blob: 976b0f2bbb7aaaf333073d6b6d8229e349b0f038 [file] [log] [blame]
Lorenz Brunaa6b7342019-12-12 02:55:02 +01001// 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
17package api
18
19import (
20 "context"
21 "encoding/base64"
22 "errors"
23 "fmt"
24
25 "git.monogon.dev/source/nexantic.git/core/generated/api"
26 "github.com/gogo/protobuf/proto"
27 "go.etcd.io/etcd/clientv3"
28)
29
30const enrolmentPrefix = "enrolments/"
31
32var errNotExists = errors.New("not found")
33
34type EnrolmentStore struct {
35 backend clientv3.KV
36}
37
38func (s *EnrolmentStore) GetBySecret(ctx context.Context, secret []byte) (*api.EnrolmentConfig, error) {
39
40 res, err := s.backend.Get(ctx, enrolmentPrefix+base64.RawURLEncoding.EncodeToString(secret))
41 if err != nil {
42 return nil, fmt.Errorf("failed to query consensus: %w", err)
43 }
44 if res.Count == 0 {
45 return nil, errNotExists
46 } else if res.Count > 1 {
47 panic("more than one value for the same key, bailing")
48 }
49 rawVal := res.Kvs[0].Value
50 var config *api.EnrolmentConfig
51 if err := proto.Unmarshal(rawVal, config); err != nil {
52 return nil, err
53 }
54 return config, nil
55}