-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
86 lines (74 loc) · 2.5 KB
/
store.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Copyright 2015 The LUCI Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package testsecrets provides a dumb in-memory secret store to use in unit
// tests. Use secrets.Set(c, &testsecrets.Store{...}) to inject it into
// the context.
package testsecrets
import (
"context"
"fmt"
"math/rand"
"sync"
"github.com/TriggerMail/luci-go/server/secrets"
)
// Store implements secrets.Store in the simplest way possible using memory as
// a backend and very dumb deterministic "randomness" source for secret key
// autogeneration. Useful in unit tests. Can be modified directly (use lock if
// doing it concurrently). NEVER use it outside of tests.
type Store struct {
sync.Mutex
Secrets map[secrets.Key]secrets.Secret // current map of all secrets
NoAutogenerate bool // if true, GetSecret will NOT generate secrets
SecretLen int // length of generated secret, 8 bytes default
Rand *rand.Rand // used to generate missing secrets
counter int // increased with each autogenerated key
}
// GetSecret is a part of Store interface.
func (t *Store) GetSecret(k secrets.Key) (secrets.Secret, error) {
t.Lock()
defer t.Unlock()
if s, ok := t.Secrets[k]; ok {
return s.Clone(), nil
}
if t.NoAutogenerate {
return secrets.Secret{}, secrets.ErrNoSuchSecret
}
// Initialize defaults.
if t.Secrets == nil {
t.Secrets = map[secrets.Key]secrets.Secret{}
}
if t.SecretLen == 0 {
t.SecretLen = 8
}
if t.Rand == nil {
t.Rand = rand.New(rand.NewSource(0))
}
// Generate deterministic secret.
t.counter++
secret := make([]byte, t.SecretLen)
for i := range secret {
secret[i] = byte(t.Rand.Int31n(256))
}
t.Secrets[k] = secrets.Secret{
Current: secrets.NamedBlob{
ID: fmt.Sprintf("secret_%d", t.counter),
Blob: secret,
},
}
return t.Secrets[k].Clone(), nil
}
// Use installs default testing store into the context.
func Use(c context.Context) context.Context {
return secrets.Set(c, &Store{})
}