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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
package oauthclient
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"slices"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/bluesky-social/indigo/atproto/atcrypto"
"github.com/bluesky-social/indigo/atproto/identity"
"github.com/bluesky-social/indigo/atproto/syntax"
atprotooauth "github.com/johnandersen777/socialweb-computer-kcp/internal/atproto/oauth"
"github.com/johnandersen777/socialweb-computer-kcp/internal/atproto/pdsclient"
"github.com/johnandersen777/socialweb-computer-kcp/internal/atproto/xrpc"
)
const (
AccessSkew = 30 * time.Second
DefaultHTTPTimeout = 30 * time.Second
ServiceAuthNSID = xrpc.ServiceAuthNSID
)
type Options struct {
DID string
Handle string
RepoDID string
PDSURL string
ClientID string
Scopes []string
Directory identity.Directory
HTTPClient *http.Client
Store SessionStore
Refresher TokenRefresher
Log *slog.Logger
}
type Session struct {
mu sync.Mutex
data SessionData
key atcrypto.PrivateKeyExportable
client *http.Client
store SessionStore
refresher TokenRefresher
log *slog.Logger
did string
hostURL string
scopeAbsentLogged bool
refreshToken atomic.Pointer[string]
}
var _ pdsclient.TokenSource = (*Session)(nil)
var _ pdsclient.DPoPSource = (*Session)(nil)
func Open(ctx context.Context, opts Options) (*Session, error) {
if opts.Store == nil {
return nil, errors.New("oauthclient: no oauth session store")
}
sessions, err := opts.Store.List(ctx)
if err != nil {
return nil, err
}
if len(sessions) == 0 {
return nil, ErrNoSession
}
did, err := sessionDID(ctx, opts, sessions)
if err != nil {
return nil, err
}
session, ok := selectSession(sessions, did)
if !ok {
return nil, fmt.Errorf("oauthclient: no oauth session stored for %s", did)
}
if session.HostURL == "" {
return nil, fmt.Errorf("%w: the oauth session names no PDS", ErrInvalidSession)
}
if opts.RepoDID != "" && opts.RepoDID != did {
return nil, fmt.Errorf("%w: the oauth session is for %s, not %s", ErrInvalidSession, did, opts.RepoDID)
}
if opts.PDSURL != "" && strings.TrimRight(opts.PDSURL, "/") != strings.TrimRight(session.HostURL, "/") {
return nil, fmt.Errorf("%w: the oauth session names PDS %s, not %s", ErrInvalidSession, session.HostURL, opts.PDSURL)
}
instance, err := New(session, opts)
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrInvalidSession, err)
}
_ = instance.EnsureEndpoints(ctx)
if session.ClientID == "" && strings.TrimSpace(opts.ClientID) != "" {
_ = instance.persist(ctx)
}
if !AccessTokenLive(session.AccessToken) {
if err := instance.refreshStale(ctx); err != nil {
return nil, fmt.Errorf("oauthclient: refreshing the oauth session for %s: %w", did, err)
}
}
return instance, nil
}
func (s *Session) EnsureEndpoints(ctx context.Context) error {
if s == nil {
return errors.New("oauthclient: no oauth session")
}
s.mu.Lock()
defer s.mu.Unlock()
if s.data.AuthServerTokenEndpoint != "" {
return nil
}
if err := s.ensureEndpointsLocked(ctx); err != nil {
return err
}
return s.persistLocked(ctx)
}
func New(data SessionData, opts Options) (*Session, error) {
did, err := syntax.ParseDID(data.AccountDID)
if err != nil {
return nil, fmt.Errorf("oauthclient: the oauth session account DID: %w", err)
}
if data.SessionID == "" {
data.SessionID = SessionID(did.String(), strings.TrimRight(data.HostURL, "/"))
}
if data.HostURL == "" {
return nil, errors.New("oauthclient: the oauth session names no PDS")
}
if data.ClientID == "" {
data.ClientID = strings.TrimSpace(opts.ClientID)
}
host, err := url.Parse(data.HostURL)
if err != nil || host.Host == "" || (host.Scheme != "http" && host.Scheme != "https") {
return nil, fmt.Errorf("oauthclient: the oauth session PDS %q is not an absolute http or https URL", data.HostURL)
}
key, err := parseDPoPKey(data.DPoPPrivateKeyMultibase)
if err != nil {
return nil, err
}
client := opts.HTTPClient
if client == nil {
client = &http.Client{Timeout: DefaultHTTPTimeout}
}
log := opts.Log
if log == nil {
log = slog.New(slog.DiscardHandler)
}
session := &Session{
data: data,
key: key,
client: client,
store: opts.Store,
refresher: opts.Refresher,
log: log,
did: did.String(),
hostURL: strings.TrimRight(data.HostURL, "/"),
}
session.refreshToken.Store(&data.RefreshToken)
return session, nil
}
func sessionDID(ctx context.Context, opts Options, sessions []SessionData) (string, error) {
if opts.DID != "" {
did, err := syntax.ParseDID(opts.DID)
if err != nil {
return "", fmt.Errorf("oauthclient: oauth identity DID: %w", err)
}
return did.String(), nil
}
if opts.Handle != "" {
if opts.Directory == nil {
return "", errors.New("oauthclient: no identity directory resolves the oauth handle")
}
atid, err := syntax.ParseAtIdentifier(opts.Handle)
if err != nil {
return "", fmt.Errorf("oauthclient: oauth handle %q: %w", opts.Handle, err)
}
ident, err := opts.Directory.Lookup(ctx, atid)
if err != nil {
return "", fmt.Errorf("oauthclient: resolving the oauth handle %q: %w", opts.Handle, err)
}
return ident.DID.String(), nil
}
dids := map[string]bool{}
for _, session := range sessions {
if session.AccountDID != "" {
dids[session.AccountDID] = true
}
}
if len(dids) != 1 {
return "", errors.New("oauthclient: oauth identity mode names no DID or handle")
}
for did := range dids {
return did, nil
}
return "", errors.New("oauthclient: oauth identity mode names no DID or handle")
}
func selectSession(sessions []SessionData, did string) (SessionData, bool) {
prefix := did + "/"
keys := []string{}
byKey := map[string]SessionData{}
for _, session := range sessions {
key := SessionKey(session.AccountDID, session.SessionID)
if strings.HasPrefix(key, prefix) {
keys = append(keys, key)
byKey[key] = session
}
}
sort.Strings(keys)
if len(keys) == 0 {
return SessionData{}, false
}
return byKey[keys[0]], true
}
func (s *Session) DID() string {
if s == nil {
return ""
}
return s.did
}
func (s *Session) HostURL() string {
if s == nil {
return ""
}
return s.hostURL
}
func (s *Session) AuthServerURL() string {
if s == nil {
return ""
}
s.mu.Lock()
defer s.mu.Unlock()
return s.data.AuthServerURL
}
func (s *Session) Scopes() []string {
if s == nil {
return nil
}
s.mu.Lock()
defer s.mu.Unlock()
return append([]string(nil), s.data.Scopes...)
}
func GrantedScopes(scope string) ([]string, error) {
granted := strings.Fields(scope)
if atprotooauth.KnownGrant(granted) && !slices.Contains(granted, atprotooauth.ScopeAtproto) {
return nil, fmt.Errorf("%w (granted %q)", ErrScopeRejected, scope)
}
return granted, nil
}
func (s *Session) AccessToken(ctx context.Context) (string, error) {
if s == nil {
return "", errors.New("oauthclient: no oauth session")
}
s.mu.Lock()
token := s.data.AccessToken
s.mu.Unlock()
if AccessTokenLive(token) {
return token, nil
}
if err := s.refreshStale(ctx); err != nil {
return "", fmt.Errorf("oauthclient: refreshing the oauth session: %w", err)
}
s.mu.Lock()
token = s.data.AccessToken
s.mu.Unlock()
if token == "" {
return "", errors.New("oauthclient: the oauth session has no access token")
}
return token, nil
}
func (s *Session) RefreshAccessToken(ctx context.Context) (string, error) {
if s == nil {
return "", errors.New("oauthclient: no oauth session")
}
s.mu.Lock()
rejected := s.data.AccessToken
s.mu.Unlock()
if err := s.refreshRejected(ctx, rejected); err != nil {
return "", err
}
s.mu.Lock()
defer s.mu.Unlock()
if s.data.AccessToken == "" {
return "", errors.New("oauthclient: the oauth session has no access token")
}
return s.data.AccessToken, nil
}
func (s *Session) SetDPoPNonce(ctx context.Context, host, nonce string) error {
if s == nil {
return errors.New("oauthclient: no oauth session")
}
if strings.TrimSpace(nonce) == "" {
return nil
}
s.mu.Lock()
defer s.mu.Unlock()
if s.data.DPoPHostNonce == nonce {
return nil
}
s.data.DPoPHostNonce = nonce
return s.persistLocked(ctx)
}
func (s *Session) DPoPProof(ctx context.Context, method, target, accessToken string) (string, error) {
if s == nil {
return "", errors.New("oauthclient: no oauth session")
}
s.mu.Lock()
key := s.key
nonce := s.data.DPoPHostNonce
s.mu.Unlock()
return DPoPProof(key, method, target, accessToken, nonce)
}
func (s *Session) HTTPClient(base *http.Client) *http.Client {
var client http.Client
if base != nil {
client = *base
}
transport := client.Transport
if transport == nil {
transport = http.DefaultTransport
}
client.Transport = &httpTransport{session: s, base: transport}
return &client
}
type httpTransport struct {
session *Session
base http.RoundTripper
}
func (t *httpTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if t == nil || t.session == nil {
return nil, errors.New("oauthclient: no oauth session")
}
base := t.base
if base == nil {
base = http.DefaultTransport
}
return t.session.doAuthorized(req.Context(), &http.Client{Transport: base}, req)
}
func (s *Session) ServiceAuth(ctx context.Context, audience, lxm string, expires time.Time) (string, error) {
if s == nil {
return "", errors.New("oauthclient: no oauth session")
}
if audience == "" {
return "", errors.New("oauthclient: no service auth audience")
}
client := &xrpc.Client{Host: s.hostURL, HTTP: s.HTTPClient(s.client), Limit: ReplyLimit}
token, err := xrpc.GetServiceAuth(ctx, client, audience, lxm, expires)
if err != nil {
return "", fmt.Errorf("oauthclient: service auth: %w", err)
}
return token, nil
}
func (s *Session) doAuthorized(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
if client == nil {
client = &http.Client{Timeout: DefaultHTTPTimeout}
}
refreshed := false
for attempt := range 3 {
s.mu.Lock()
accessToken := s.data.AccessToken
nonce := s.data.DPoPHostNonce
key := s.key
s.mu.Unlock()
proof, err := DPoPProof(key, req.Method, req.URL.String(), accessToken, nonce)
if err != nil {
return nil, err
}
current := req
if attempt > 0 {
current, err = cloneRequest(req)
if err != nil {
return nil, err
}
}
current.Header.Set("Authorization", "DPoP "+accessToken)
current.Header.Set("DPoP", proof)
resp, err := client.Do(current)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusUnauthorized && resp.StatusCode != http.StatusBadRequest {
return resp, nil
}
header := resp.Header.Get("WWW-Authenticate")
nextNonce := resp.Header.Get("DPoP-Nonce")
if nextNonce != "" && (strings.Contains(header, "use_dpop_nonce") || !strings.Contains(header, "invalid_token")) {
s.mu.Lock()
s.data.DPoPHostNonce = nextNonce
err = s.persistLocked(ctx)
s.mu.Unlock()
DrainAndClose(resp.Body)
if err != nil {
return nil, err
}
continue
}
if resp.StatusCode == http.StatusUnauthorized && !refreshed {
refreshed = true
DrainAndClose(resp.Body)
if err := s.refreshRejected(ctx, accessToken); err != nil {
return nil, fmt.Errorf("oauthclient: refreshing the oauth session: %w", err)
}
continue
}
DrainAndClose(resp.Body)
return nil, fmt.Errorf("oauthclient: %s %s answered HTTP %d", req.Method, req.URL.Path, resp.StatusCode)
}
return nil, errors.New("oauthclient: the oauth session kept asking for a new DPoP nonce")
}
func cloneRequest(req *http.Request) (*http.Request, error) {
clone := req.Clone(req.Context())
if req.GetBody != nil {
body, err := req.GetBody()
if err != nil {
return nil, err
}
clone.Body = body
}
return clone, nil
}
func DrainAndClose(body io.ReadCloser) {
if body == nil {
return
}
_, _ = io.Copy(io.Discard, io.LimitReader(body, ReplyLimit))
_ = body.Close()
}
func (s *Session) persist(ctx context.Context) error {
s.mu.Lock()
defer s.mu.Unlock()
return s.persistLocked(ctx)
}
func (s *Session) persistLocked(ctx context.Context) error {
if s.store == nil {
return nil
}
return s.store.Save(ctx, s.data)
}
func (s *Session) ensureEndpointsLocked(ctx context.Context) error {
if s.data.AuthServerTokenEndpoint != "" {
return nil
}
client := s.client
if client == nil {
client = &http.Client{Timeout: DefaultHTTPTimeout}
}
authServer, tokenEndpoint, revokeEndpoint, err := DiscoverAuthServer(ctx, client, s.hostURL)
if err != nil {
return err
}
s.data.AuthServerURL = authServer
s.data.AuthServerTokenEndpoint = tokenEndpoint
if revokeEndpoint != "" {
s.data.AuthServerRevocationEndpoint = revokeEndpoint
}
return nil
}