Lorenz Brun | aa6b734 | 2019-12-12 02:55:02 +0100 | [diff] [blame] | 1 | // Copyright 2020 The Monogon Project Authors. |
| 2 | // |
| 3 | // SPDX-License-Identifier: Apache-2.0 |
| 4 | // |
| 5 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | // you may not use this file except in compliance with the License. |
| 7 | // You may obtain a copy of the License at |
| 8 | // |
| 9 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | // |
| 11 | // Unless required by applicable law or agreed to in writing, software |
| 12 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | // See the License for the specific language governing permissions and |
| 15 | // limitations under the License. |
| 16 | |
| 17 | package api |
| 18 | |
| 19 | import ( |
| 20 | "context" |
| 21 | "encoding/base64" |
| 22 | "errors" |
| 23 | "fmt" |
| 24 | |
Lorenz Brun | aa6b734 | 2019-12-12 02:55:02 +0100 | [diff] [blame] | 25 | "github.com/gogo/protobuf/proto" |
| 26 | "go.etcd.io/etcd/clientv3" |
Hendrik Hofstadt | 8efe51e | 2020-02-28 12:53:41 +0100 | [diff] [blame^] | 27 | |
| 28 | "git.monogon.dev/source/nexantic.git/core/generated/api" |
Lorenz Brun | aa6b734 | 2019-12-12 02:55:02 +0100 | [diff] [blame] | 29 | ) |
| 30 | |
| 31 | const enrolmentPrefix = "enrolments/" |
| 32 | |
| 33 | var errNotExists = errors.New("not found") |
| 34 | |
| 35 | type EnrolmentStore struct { |
| 36 | backend clientv3.KV |
| 37 | } |
| 38 | |
| 39 | func (s *EnrolmentStore) GetBySecret(ctx context.Context, secret []byte) (*api.EnrolmentConfig, error) { |
| 40 | |
| 41 | res, err := s.backend.Get(ctx, enrolmentPrefix+base64.RawURLEncoding.EncodeToString(secret)) |
| 42 | if err != nil { |
| 43 | return nil, fmt.Errorf("failed to query consensus: %w", err) |
| 44 | } |
| 45 | if res.Count == 0 { |
| 46 | return nil, errNotExists |
| 47 | } else if res.Count > 1 { |
| 48 | panic("more than one value for the same key, bailing") |
| 49 | } |
| 50 | rawVal := res.Kvs[0].Value |
| 51 | var config *api.EnrolmentConfig |
| 52 | if err := proto.Unmarshal(rawVal, config); err != nil { |
| 53 | return nil, err |
| 54 | } |
| 55 | return config, nil |
| 56 | } |