1package client
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "io"
9 "log/slog"
10 "net/http"
11 "net/url"
12 "slices"
13 "strings"
14 "time"
15
16 cache "github.com/go-pkgz/expirable-cache/v3"
17 "github.com/haileyok/cocoon/internal/helpers"
18 "github.com/lestrrat-go/jwx/v2/jwk"
19)
20
21type Manager struct {
22 cli *http.Client
23 logger *slog.Logger
24 jwksCache cache.Cache[string, jwk.Key]
25 metadataCache cache.Cache[string, *Metadata]
26}
27
28type ManagerArgs struct {
29 Cli *http.Client
30 Logger *slog.Logger
31}
32
33func NewManager(args ManagerArgs) *Manager {
34 if args.Logger == nil {
35 args.Logger = slog.Default()
36 }
37
38 if args.Cli == nil {
39 args.Cli = http.DefaultClient
40 }
41
42 jwksCache := cache.NewCache[string, jwk.Key]().WithLRU().WithMaxKeys(500).WithTTL(5 * time.Minute)
43 metadataCache := cache.NewCache[string, *Metadata]().WithLRU().WithMaxKeys(500).WithTTL(5 * time.Minute)
44
45 return &Manager{
46 cli: args.Cli,
47 logger: args.Logger,
48 jwksCache: jwksCache,
49 metadataCache: metadataCache,
50 }
51}
52
53func (cm *Manager) GetClient(ctx context.Context, clientId string) (*Client, error) {
54 metadata, err := cm.getClientMetadata(ctx, clientId)
55 if err != nil {
56 return nil, err
57 }
58
59 var jwks jwk.Key
60 if metadata.TokenEndpointAuthMethod == "private_key_jwt" {
61 if metadata.JWKS != nil && len(metadata.JWKS.Keys) > 0 {
62 // TODO: this is kinda bad but whatever for now. there could obviously be more than one jwk, and we need to
63 // make sure we use the right one
64 b, err := json.Marshal(metadata.JWKS.Keys[0])
65 if err != nil {
66 return nil, err
67 }
68
69 k, err := helpers.ParseJWKFromBytes(b)
70 if err != nil {
71 return nil, err
72 }
73
74 jwks = k
75 } else if metadata.JWKS != nil {
76 } else if metadata.JWKSURI != nil {
77 maybeJwks, err := cm.getClientJwks(ctx, clientId, *metadata.JWKSURI)
78 if err != nil {
79 return nil, err
80 }
81
82 jwks = maybeJwks
83 } else {
84 return nil, fmt.Errorf("no valid jwks found in oauth client metadata")
85 }
86 }
87
88 return &Client{
89 Metadata: metadata,
90 JWKS: jwks,
91 }, nil
92}
93
94func (cm *Manager) getClientMetadata(ctx context.Context, clientId string) (*Metadata, error) {
95 cached, ok := cm.metadataCache.Get(clientId)
96 if !ok {
97 req, err := http.NewRequestWithContext(ctx, "GET", clientId, nil)
98 if err != nil {
99 return nil, err
100 }
101
102 resp, err := cm.cli.Do(req)
103 if err != nil {
104 return nil, err
105 }
106 defer resp.Body.Close()
107
108 if resp.StatusCode != http.StatusOK {
109 io.Copy(io.Discard, resp.Body)
110 return nil, fmt.Errorf("fetching client metadata returned response code %d", resp.StatusCode)
111 }
112
113 b, err := io.ReadAll(resp.Body)
114 if err != nil {
115 return nil, fmt.Errorf("error reading bytes from client response: %w", err)
116 }
117
118 validated, err := validateAndParseMetadata(clientId, b)
119 if err != nil {
120 return nil, err
121 }
122
123 cm.metadataCache.Set(clientId, validated, 10*time.Minute)
124
125 return validated, nil
126 } else {
127 return cached, nil
128 }
129}
130
131func (cm *Manager) getClientJwks(ctx context.Context, clientId, jwksUri string) (jwk.Key, error) {
132 jwks, ok := cm.jwksCache.Get(clientId)
133 if !ok {
134 req, err := http.NewRequestWithContext(ctx, "GET", jwksUri, nil)
135 if err != nil {
136 return nil, err
137 }
138
139 resp, err := cm.cli.Do(req)
140 if err != nil {
141 return nil, err
142 }
143 defer resp.Body.Close()
144
145 if resp.StatusCode != http.StatusOK {
146 io.Copy(io.Discard, resp.Body)
147 return nil, fmt.Errorf("fetching client jwks returned response code %d", resp.StatusCode)
148 }
149
150 type Keys struct {
151 Keys []map[string]any `json:"keys"`
152 }
153
154 var keys Keys
155 if err := json.NewDecoder(resp.Body).Decode(&keys); err != nil {
156 return nil, fmt.Errorf("error unmarshaling keys response: %w", err)
157 }
158
159 if len(keys.Keys) == 0 {
160 return nil, errors.New("no keys in jwks response")
161 }
162
163 // TODO: this is again bad, we should be figuring out which one we need to use...
164 b, err := json.Marshal(keys.Keys[0])
165 if err != nil {
166 return nil, fmt.Errorf("could not marshal key: %w", err)
167 }
168
169 k, err := helpers.ParseJWKFromBytes(b)
170 if err != nil {
171 return nil, err
172 }
173
174 jwks = k
175 }
176
177 return jwks, nil
178}
179
180func validateAndParseMetadata(clientId string, b []byte) (*Metadata, error) {
181 var metadataMap map[string]any
182 if err := json.Unmarshal(b, &metadataMap); err != nil {
183 return nil, fmt.Errorf("error unmarshaling metadata: %w", err)
184 }
185
186 _, jwksOk := metadataMap["jwks"].(string)
187 _, jwksUriOk := metadataMap["jwks_uri"].(string)
188 if jwksOk && jwksUriOk {
189 return nil, errors.New("jwks_uri and jwks are mutually exclusive")
190 }
191
192 for _, k := range []string{
193 "default_max_age",
194 "userinfo_signed_response_alg",
195 "id_token_signed_response_alg",
196 "userinfo_encryhpted_response_alg",
197 "authorization_encrypted_response_enc",
198 "authorization_encrypted_response_alg",
199 "tls_client_certificate_bound_access_tokens",
200 } {
201 _, kOk := metadataMap[k]
202 if kOk {
203 return nil, fmt.Errorf("unsupported `%s` parameter", k)
204 }
205 }
206
207 var metadata Metadata
208 if err := json.Unmarshal(b, &metadata); err != nil {
209 return nil, fmt.Errorf("error unmarshaling metadata: %w", err)
210 }
211
212 if metadata.ClientURI == "" {
213 u, err := url.Parse(metadata.ClientID)
214 if err != nil {
215 return nil, fmt.Errorf("unable to parse client id: %w", err)
216 }
217 u.RawPath = ""
218 u.RawQuery = ""
219 metadata.ClientURI = u.String()
220 }
221
222 u, err := url.Parse(metadata.ClientURI)
223 if err != nil {
224 return nil, fmt.Errorf("unable to parse client uri: %w", err)
225 }
226
227 if metadata.ClientName == "" {
228 metadata.ClientName = metadata.ClientURI
229 }
230
231 if isLocalHostname(u.Hostname()) {
232 return nil, fmt.Errorf("`client_uri` hostname is invalid: %s", u.Hostname())
233 }
234
235 if metadata.Scope == "" {
236 return nil, errors.New("missing `scopes` scope")
237 }
238
239 scopes := strings.Split(metadata.Scope, " ")
240 if !slices.Contains(scopes, "atproto") {
241 return nil, errors.New("missing `atproto` scope")
242 }
243
244 scopesMap := map[string]bool{}
245 for _, scope := range scopes {
246 if scopesMap[scope] {
247 return nil, fmt.Errorf("duplicate scope `%s`", scope)
248 }
249
250 // TODO: check for unsupported scopes
251
252 scopesMap[scope] = true
253 }
254
255 grantTypesMap := map[string]bool{}
256 for _, gt := range metadata.GrantTypes {
257 if grantTypesMap[gt] {
258 return nil, fmt.Errorf("duplicate grant type `%s`", gt)
259 }
260
261 switch gt {
262 case "implicit":
263 return nil, errors.New("grantg type `implicit` is not allowed")
264 case "authorization_code", "refresh_token":
265 // TODO check if this grant type is supported
266 default:
267 return nil, fmt.Errorf("grant tyhpe `%s` is not supported", gt)
268 }
269
270 grantTypesMap[gt] = true
271 }
272
273 if metadata.ClientID != clientId {
274 return nil, errors.New("`client_id` does not match")
275 }
276
277 subjectType, subjectTypeOk := metadataMap["subject_type"].(string)
278 if subjectTypeOk && subjectType != "public" {
279 return nil, errors.New("only public `subject_type` is supported")
280 }
281
282 switch metadata.TokenEndpointAuthMethod {
283 case "none":
284 if metadata.TokenEndpointAuthSigningAlg != "" {
285 return nil, errors.New("token_endpoint_auth_method `none` must not have token_endpoint_auth_signing_alg")
286 }
287 case "private_key_jwt":
288 if metadata.JWKS == nil && metadata.JWKSURI == nil {
289 return nil, errors.New("private_key_jwt auth method requires jwks or jwks_uri")
290 }
291
292 if metadata.JWKS != nil && len(metadata.JWKS.Keys) == 0 {
293 return nil, errors.New("private_key_jwt auth method requires atleast one key in jwks")
294 }
295
296 if metadata.TokenEndpointAuthSigningAlg == "" {
297 return nil, errors.New("missing token_endpoint_auth_signing_alg in client metadata")
298 }
299 default:
300 return nil, fmt.Errorf("unsupported client authentication method `%s`", metadata.TokenEndpointAuthMethod)
301 }
302
303 if !metadata.DpopBoundAccessTokens {
304 return nil, errors.New("dpop_bound_access_tokens must be true")
305 }
306
307 if !slices.Contains(metadata.ResponseTypes, "code") {
308 return nil, errors.New("response_types must inclue `code`")
309 }
310
311 if !slices.Contains(metadata.GrantTypes, "authorization_code") {
312 return nil, errors.New("the `code` response type requires that `grant_types` contains `authorization_code`")
313 }
314
315 if len(metadata.RedirectURIs) == 0 {
316 return nil, errors.New("at least one `redirect_uri` is required")
317 }
318
319 if metadata.ApplicationType == "native" && metadata.TokenEndpointAuthMethod != "none" {
320 return nil, errors.New("native clients must authenticate using `none` method")
321 }
322
323 if metadata.ApplicationType == "web" && slices.Contains(metadata.GrantTypes, "implicit") {
324 for _, ruri := range metadata.RedirectURIs {
325 u, err := url.Parse(ruri)
326 if err != nil {
327 return nil, fmt.Errorf("error parsing redirect uri: %w", err)
328 }
329
330 if u.Scheme != "https" {
331 return nil, errors.New("web clients must use https redirect uris")
332 }
333
334 if u.Hostname() == "localhost" {
335 return nil, errors.New("web clients must not use localhost as the hostname")
336 }
337 }
338 }
339
340 for _, ruri := range metadata.RedirectURIs {
341 u, err := url.Parse(ruri)
342 if err != nil {
343 return nil, fmt.Errorf("error parsing redirect uri: %w", err)
344 }
345
346 if u.User != nil {
347 if u.User.Username() != "" {
348 return nil, fmt.Errorf("redirect uri %s must not contain credentials", ruri)
349 }
350
351 if _, hasPass := u.User.Password(); hasPass {
352 return nil, fmt.Errorf("redirect uri %s must not contain credentials", ruri)
353 }
354 }
355
356 switch true {
357 case u.Hostname() == "localhost":
358 return nil, errors.New("loopback redirect uri is not allowed (use explicit ips instead)")
359 case u.Hostname() == "127.0.0.1", u.Hostname() == "[::1]":
360 if metadata.ApplicationType != "native" {
361 return nil, errors.New("loopback redirect uris are only allowed for native apps")
362 }
363
364 if u.Port() != "" {
365 // reference impl doesn't do anything with this?
366 }
367
368 if u.Scheme != "http" {
369 return nil, fmt.Errorf("loopback redirect uri %s must use http", ruri)
370 }
371 case u.Scheme == "http":
372 return nil, errors.New("only loopbvack redirect uris are allowed to use the `http` scheme")
373 case u.Scheme == "https":
374 if isLocalHostname(u.Hostname()) {
375 return nil, fmt.Errorf("redirect uri %s's domain must not be a local hostname", ruri)
376 }
377 case strings.Contains(u.Scheme, "."):
378 if metadata.ApplicationType != "native" {
379 return nil, errors.New("private-use uri scheme redirect uris are only allowed for native apps")
380 }
381
382 revdomain := reverseDomain(u.Scheme)
383
384 if isLocalHostname(revdomain) {
385 return nil, errors.New("private use uri scheme redirect uris must not be local hostnames")
386 }
387
388 if strings.HasPrefix(u.String(), fmt.Sprintf("%s://", u.Scheme)) || u.Hostname() != "" || u.Port() != "" {
389 return nil, fmt.Errorf("private use uri scheme must be in the form ")
390 }
391 default:
392 return nil, fmt.Errorf("invalid redirect uri scheme `%s`", u.Scheme)
393 }
394 }
395
396 return &metadata, nil
397}
398
399func isLocalHostname(hostname string) bool {
400 pts := strings.Split(hostname, ".")
401 if len(pts) < 2 {
402 return true
403 }
404
405 tld := strings.ToLower(pts[len(pts)-1])
406 return tld == "test" || tld == "local" || tld == "localhost" || tld == "invalid" || tld == "example"
407}
408
409func reverseDomain(domain string) string {
410 pts := strings.Split(domain, ".")
411 slices.Reverse(pts)
412 return strings.Join(pts, ".")
413}