-
Notifications
You must be signed in to change notification settings - Fork 53
/
context.go
88 lines (74 loc) · 2.27 KB
/
context.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
87
88
package challenges
import (
"context"
"encoding/base64"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
const (
// Deprecated: only used in challenge v1
ChallengeKey = "X-Challenge"
ChallengeVersionMetadataKey = "x-challenge-version"
ClientIdAssertionMetadataKey = "x-client-id-assertion"
ClientRandomMetadataKey = "x-client-random"
ChallengeV2 = "v2"
)
type ClientMetadata struct {
IdAssertion string
Random []byte
}
func ClientIdAssertionFromMetadata(md metadata.MD) (string, bool) {
ids := md.Get(ClientIdAssertionMetadataKey)
if len(ids) == 0 || len(ids[0]) == 0 {
return "", false
}
return ids[0], true
}
func ClientRandomFromMetadata(md metadata.MD) ([]byte, bool) {
v := md.Get(ClientRandomMetadataKey)
if len(v) == 0 || len(v[0]) == 0 {
return nil, false
}
data, err := base64.RawURLEncoding.DecodeString(v[0])
if err != nil {
return nil, false
}
return data, true
}
func ClientMetadataFromIncomingContext(ctx context.Context) (ClientMetadata, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return ClientMetadata{}, status.Errorf(codes.InvalidArgument, "missing metadata")
}
assertedId, ok := ClientIdAssertionFromMetadata(md)
if !ok {
return ClientMetadata{}, status.Errorf(codes.InvalidArgument, "missing id in metadata")
}
clientRandom, ok := ClientRandomFromMetadata(md)
if !ok || len(clientRandom) == 0 {
return ClientMetadata{}, status.Errorf(codes.InvalidArgument, "missing/invalid client random in metadata")
}
return ClientMetadata{
IdAssertion: assertedId,
Random: clientRandom,
}, nil
}
func ClientMetadataFromOutgoingContext(ctx context.Context) (ClientMetadata, error) {
md, ok := metadata.FromOutgoingContext(ctx)
if !ok {
return ClientMetadata{}, status.Errorf(codes.InvalidArgument, "missing metadata")
}
assertedId, ok := ClientIdAssertionFromMetadata(md)
if !ok {
return ClientMetadata{}, status.Errorf(codes.InvalidArgument, "missing id in metadata")
}
clientRandom, ok := ClientRandomFromMetadata(md)
if !ok || len(clientRandom) == 0 {
return ClientMetadata{}, status.Errorf(codes.InvalidArgument, "missing/invalid client random in metadata")
}
return ClientMetadata{
IdAssertion: assertedId,
Random: clientRandom,
}, nil
}