blob: eb892ae80ab78eb7a699d719100ef2b1bdb66ea3 [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"
Lorenz Brun878f5f92020-05-12 16:15:39 +020021 "encoding/hex"
Lorenz Brunaa6b7342019-12-12 02:55:02 +010022 "errors"
23 "fmt"
24
Lorenz Brunaa6b7342019-12-12 02:55:02 +010025 "github.com/gogo/protobuf/proto"
26 "go.etcd.io/etcd/clientv3"
Hendrik Hofstadt8efe51e2020-02-28 12:53:41 +010027
28 "git.monogon.dev/source/nexantic.git/core/generated/api"
Lorenz Brunaa6b7342019-12-12 02:55:02 +010029)
30
31const enrolmentPrefix = "enrolments/"
32
33var errNotExists = errors.New("not found")
34
35type EnrolmentStore struct {
36 backend clientv3.KV
37}
38
39func (s *EnrolmentStore) GetBySecret(ctx context.Context, secret []byte) (*api.EnrolmentConfig, error) {
40
Lorenz Brun878f5f92020-05-12 16:15:39 +020041 res, err := s.backend.Get(ctx, enrolmentPrefix+hex.EncodeToString(secret))
Lorenz Brunaa6b7342019-12-12 02:55:02 +010042 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}