-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeystore.go
80 lines (69 loc) · 1.9 KB
/
keystore.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
package attestation
import (
"aidanwoods.dev/go-paseto"
"errors"
"fmt"
"github.com/authenticvision/attestation-go/paserk"
"io"
"net/http"
"sync"
)
var ErrNoSuchKey = errors.New("no such SIPv4 key")
var SharedKeyStore = &KeyStore{
Client: http.DefaultClient,
Hosts: []string{"sip-keys.authenticvision.com"},
keys: make(map[string]paseto.V4AsymmetricPublicKey),
}
type KeyStore struct {
Client *http.Client
Hosts []string
keys map[string]paseto.V4AsymmetricPublicKey
mutex sync.RWMutex
}
func (ks *KeyStore) AddPublicKey(key paseto.V4AsymmetricPublicKey) {
ks.mutex.Lock()
defer ks.mutex.Unlock()
ks.keys[paserk.KeyID(key)] = key
}
func (ks *KeyStore) getPublicKeyIfExists(id string) (key paseto.V4AsymmetricPublicKey, ok bool) {
ks.mutex.RLock()
defer ks.mutex.RUnlock()
key, ok = ks.keys[id]
return
}
func (ks *KeyStore) GetPublicKey(id string) (key paseto.V4AsymmetricPublicKey, err error) {
var keyPresent bool
key, keyPresent = ks.getPublicKeyIfExists(id)
if keyPresent {
return
}
for _, host := range ks.Hosts {
if key, err = ks.getPublicKeyForHost(id, host); err == nil {
ks.AddPublicKey(key)
return
}
}
return
}
func (ks *KeyStore) getPublicKeyForHost(id, host string) (key paseto.V4AsymmetricPublicKey, err error) {
if resp, err := ks.Client.Get("https://" + host + "/v4/" + id); err != nil {
return key, fmt.Errorf("failed to get key: %w", err)
} else {
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return key, ErrNoSuchKey
}
if resp.StatusCode != http.StatusOK {
return key, fmt.Errorf("non-ok HTTP response code %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return key, fmt.Errorf("failed to read key request body: %w", err)
}
if key, err := paserk.ParsePublic(string(body)); err != nil {
return key, fmt.Errorf("failed to parse public key: %w", err)
} else {
return key, nil
}
}
}