-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
77 lines (65 loc) · 2.02 KB
/
service.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
package keyfob
import (
"github.com/golang/protobuf/ptypes/empty"
"github.com/google/uuid"
"github.com/sakjur/keyfob/proto"
"golang.org/x/net/context"
)
// KeyFobService implements the KeyFob gRPC service. All keys which are
// returned are derived from both the key stored in the vault and the provided
// service key.
type KeyFobService struct {
Vault KeyVault
}
// GenerateKey fetches a key from the vault matching the key in the request,
// creating it if it doesn't exist.
func (s KeyFobService) GenerateKey(ctx context.Context, req *proto.GenerateKeyRequest) (*proto.EncryptionKey, error) {
userid, err := uuid.FromBytes(req.UserUuid)
if err != nil {
return nil, err
}
userKey := UserKeyPointer{UserID: userid, Category: req.Category, ServiceKey: req.ServiceKey}
key, err := userKey.DeriveKey(s.Vault)
if err != nil {
_ = userKey.CreateKey(s.Vault)
key, err = userKey.DeriveKey(s.Vault)
if err != nil {
return nil, err
}
}
return &proto.EncryptionKey{
Category: req.Category,
Key: key,
}, nil
}
// DeleteKey permanently deletes a key from the vault.
func (s KeyFobService) DeleteKey(ctx context.Context, req *proto.DeleteKeyRequest) (*empty.Empty, error) {
userid, err := uuid.FromBytes(req.UserUuid)
if err != nil {
return nil, err
}
userKey := UserKeyPointer{UserID: userid, Category: req.Category}
return &empty.Empty{}, userKey.DeleteKey(s.Vault)
}
// ListKeys returns all the keys which exists for a user in a vault.
func (s KeyFobService) ListKeys(ctx context.Context, req *proto.ListKeysRequest) (*proto.ListKeysResponse, error) {
userid, err := uuid.FromBytes(req.UserUuid)
if err != nil {
return nil, err
}
userKey := UserKeyPointer{UserID: userid, ServiceKey: req.ServiceKey}
stored, err := userKey.ListUserKeys(s.Vault)
if err != nil {
return nil, err
}
keys := make([]*proto.EncryptionKey, len(stored))
for i, key := range stored {
keys[i] = &proto.EncryptionKey{
Key: key.Key,
Category: key.Category,
}
}
return &proto.ListKeysResponse{
Keys: keys,
}, nil
}