-
Notifications
You must be signed in to change notification settings - Fork 53
/
ephemeral.go
66 lines (58 loc) · 1.17 KB
/
ephemeral.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
package ephemeral
import (
"crypto/rand"
"encoding/json"
"fmt"
"io"
"github.com/rancher/opni/pkg/validation"
)
type (
KeyUsageType string
)
const (
Authentication KeyUsageType = "auth"
)
type Key struct {
Labels map[string]string `json:"labels"`
Usage KeyUsageType `json:"usage"`
Secret []byte `json:"sec,omitempty"`
}
func (e *Key) Validate() error {
if err := validation.ValidateLabels(e.Labels); err != nil {
return err
}
switch e.Usage {
case Authentication:
default:
return validation.Errorf("invalid usage type: %s", e.Usage)
}
if len(e.Secret) < 16 {
return validation.Errorf("secret key must be at least 128 bits")
}
return nil
}
func LoadKey(r io.Reader) (*Key, error) {
var key Key
if err := json.NewDecoder(r).Decode(&key); err != nil {
return nil, err
}
if err := key.Validate(); err != nil {
return nil, err
}
return &key, nil
}
func NewKey(usage KeyUsageType, labels map[string]string) *Key {
ek := &Key{
Usage: usage,
Labels: labels,
}
switch usage {
case Authentication:
var key [32]byte
rand.Read(key[:])
ek.Secret = key[:]
default:
panic(fmt.Errorf("unknown usage type: %s", usage))
}
return ek
}