-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
200 lines (163 loc) · 4.97 KB
/
common.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package authcontrol
import (
"cmp"
"context"
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"github.com/0xsequence/authcontrol/proto"
"github.com/go-chi/jwtauth/v5"
"github.com/lestrrat-go/jwx/v2/jwa"
"github.com/lestrrat-go/jwx/v2/jwt"
)
const (
HeaderAccessKey = "X-Access-Key"
)
type AccessKeyFunc func(*http.Request) string
func AccessKeyFromHeader(r *http.Request) string {
return r.Header.Get(HeaderAccessKey)
}
type ErrHandler func(r *http.Request, w http.ResponseWriter, err error)
func errHandler(r *http.Request, w http.ResponseWriter, err error) {
rpcErr, ok := err.(proto.WebRPCError)
if !ok {
rpcErr = proto.ErrWebrpcEndpoint.WithCause(err)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(rpcErr.HTTPStatus)
respBody, _ := json.Marshal(rpcErr)
w.Write(respBody)
}
// UserStore is a pluggable backend that verifies if a user exists.
// If the account doesn't exist, it should return nil, false, nil.
type UserStore interface {
GetUser(ctx context.Context, address string) (user any, isAdmin bool, err error)
}
// ProjectStore is a pluggable backend that verifies if a project exists.
// If the project does not exist, it should return nil, nil, nil.
// The optional Auth, when returned, will be used for instead of the standard one.
type ProjectStore interface {
GetProject(ctx context.Context, id uint64) (project any, auth *Auth, err error)
}
// Config is a generic map of services/methods to a config value.
// map[service]map[method]T
type Config[T any] map[string]map[string]T
// Get returns the config value for the given request.
func (c Config[T]) Get(_ context.Context, path string) (v T, err error) {
if c == nil {
return v, fmt.Errorf("config is nil")
}
p := strings.Split(path, "/")
if len(p) < 4 {
return v, fmt.Errorf("path has not enough parts: %s", path)
}
var (
packageName = p[len(p)-3]
serviceName = p[len(p)-2]
methodName = p[len(p)-1]
)
if packageName != "rpc" {
return v, fmt.Errorf("path doesn't include rpc: %s", path)
}
v, ok := c[serviceName][methodName]
if !ok {
return v, fmt.Errorf("acl not defined for path: %s", path)
}
return v, nil
}
// Verify checks that the given config is valid for the given service.
// It can be used in unit tests to ensure that all methods are covered.
func (c Config[any]) Verify(webrpcServices map[string][]string) error {
var errList []error
for service, methods := range webrpcServices {
for _, method := range methods {
if _, ok := c[service][method]; !ok {
errList = append(errList, fmt.Errorf("%s.%s not found", service, method))
}
}
}
return errors.Join(errList...)
}
// ACL is a list of session types, encoded as a bitfield.
// SessionType(n) is represented by n=-the bit.
type ACL uint64
// NewACL returns a new ACL with the given session types.
func NewACL(sessions ...proto.SessionType) ACL {
var acl ACL
for _, v := range sessions {
acl = acl.And(v)
}
return acl
}
// And returns a new ACL with the given session types added.
func (a ACL) And(session ...proto.SessionType) ACL {
for _, v := range session {
a |= 1 << v
}
return a
}
// Includes returns true if the ACL includes the given session type.
func (t ACL) Includes(session proto.SessionType) bool {
return t&ACL(1<<session) != 0
}
// NewAuth creates a new Auth HS256 with the given secret.
func NewAuth(secret string) *Auth {
return &Auth{Algorithm: jwa.HS256, Private: []byte(secret)}
}
// Auth is a struct that holds the private and public keys for JWT signing and verification.
type Auth struct {
Algorithm jwa.SignatureAlgorithm
Private []byte
Public []byte
}
// GetVerifier returns a JWTAuth using the private secret when available, otherwise the public key
func (a Auth) GetVerifier(options ...jwt.ValidateOption) (*jwtauth.JWTAuth, error) {
if a.Algorithm == "" {
return nil, fmt.Errorf("missing algorithm")
}
if a.Private != nil {
return jwtauth.New(string(a.Algorithm), a.Private, a.Private, options...), nil
}
if a.Public == nil {
return nil, fmt.Errorf("missing public key")
}
block, _ := pem.Decode(a.Public)
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("parse public key: %w", err)
}
return jwtauth.New(a.Algorithm.String(), nil, pub, options...), nil
}
// findProjectClaim looks for the project_id/project claim in the JWT
func findProjectClaim(r *http.Request) (uint64, error) {
raw := jwtauth.TokenFromHeader(r)
if raw == "" {
return 0, nil
}
token, err := jwt.ParseString(raw, jwt.WithVerify(false))
if err != nil {
return 0, fmt.Errorf("parse token: %w", err)
}
claims := token.PrivateClaims()
claim := cmp.Or(claims["project_id"], claims["project"])
if claim == nil {
return 0, nil
}
switch val := claim.(type) {
case float64:
return uint64(val), nil
case string:
v, err := strconv.ParseUint(val, 10, 64)
if err != nil {
return 0, fmt.Errorf("invalid value")
}
return v, nil
default:
return 0, fmt.Errorf("invalid type: %T", val)
}
}