Repository navigation
Expand file tree
/
Copy pathrefresh.go
More file actions
295 lines (261 loc) · 8.97 KB
/
Copy pathrefresh.go
File metadata and controls
295 lines (261 loc) · 8.97 KB
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
package seamlessauth
import (
"context"
"errors"
"fmt"
"net/http"
"sync"
"time"
)
var (
errNoRefreshCookie = errors.New("no refresh cookie")
errInvalidRefreshCookie = errors.New("invalid refresh cookie")
)
// refreshAnswered is a refresh the auth API answered without a session.
type refreshAnswered struct {
status int
body any
isJSON bool
}
func (e *refreshAnswered) Error() string { return fmt.Sprintf("refresh answered %d", e.status) }
// refreshRejected reports whether a refresh failed for good: the auth API
// refused the token, or the refresh cookie cannot be read. After a network
// failure or any other answer the token may still be good, or rotated with the
// answer lost, so the session is kept for the next attempt.
func refreshRejected(err error) bool {
var answered *refreshAnswered
if errors.As(err, &answered) {
return answered.status == http.StatusUnauthorized
}
return errors.Is(err, errInvalidRefreshCookie)
}
// refreshFailure answers a refresh that produced no session: rejected when it
// failed for good, else the auth API's answer or upstream_unavailable, with the
// cookies left alone.
func refreshFailure(err error, rejected result) result {
if refreshRejected(err) {
return rejected
}
var answered *refreshAnswered
if errors.As(err, &answered) {
return failure(answered.status, answered.body, answered.isJSON)
}
return errorResult(http.StatusBadGateway, "upstream_unavailable")
}
type refreshOutcome struct {
session map[string]any
status int
body any
isJSON bool
err error
}
type refreshFlight struct {
done chan struct{}
outcome refreshOutcome
}
// refreshKeepWindow is how long a completed cookie-transport rotation is kept
// for a tab that presents the same refresh cookie a moment later.
const refreshKeepWindow = 5 * time.Second
type keptRefresh struct {
outcome refreshOutcome
expires time.Time
}
type keptKey struct {
key string
expires time.Time
}
type refresher struct {
mu sync.Mutex
flights map[string]*refreshFlight
kept map[string]keptRefresh
// order holds kept keys by expiry, so pruning stops at the first live one.
order []keptKey
now func() time.Time
}
func newRefresher() *refresher {
return &refresher{flights: map[string]*refreshFlight{}, kept: map[string]keptRefresh{}, now: time.Now}
}
// do runs fn once per key at a time, so parallel requests from several tabs with
// one expired session share a rotation instead of tripping the auth API's reuse
// detection. Callers that arrive while fn runs share its outcome. With keep (cookie
// transport only), a successful outcome is also kept for refreshKeepWindow, for a
// tab presenting the same refresh cookie just after the rotation finished. Without
// it, a refresh token presented after its rotation finished goes to the auth API,
// which treats it as reuse.
func (f *refresher) do(key string, keep bool, fn func() refreshOutcome) refreshOutcome {
f.mu.Lock()
now := f.now()
f.prune(now)
if flight, ok := f.flights[key]; ok {
f.mu.Unlock()
<-flight.done
return flight.outcome
}
if keep {
if kept, ok := f.kept[key]; ok {
f.mu.Unlock()
return kept.outcome
}
}
flight := &refreshFlight{done: make(chan struct{})}
f.flights[key] = flight
f.mu.Unlock()
outcome := fn()
f.mu.Lock()
flight.outcome = outcome
delete(f.flights, key)
if keep && outcome.session != nil {
expires := f.now().Add(refreshKeepWindow)
f.kept[key] = keptRefresh{outcome: outcome, expires: expires}
f.order = append(f.order, keptKey{key: key, expires: expires})
}
f.mu.Unlock()
close(flight.done)
return outcome
}
// prune drops kept rotations that have expired. f.mu must be held.
func (f *refresher) prune(now time.Time) {
i := 0
for ; i < len(f.order) && !now.Before(f.order[i].expires); i++ {
if kept, ok := f.kept[f.order[i].key]; ok && kept.expires.Equal(f.order[i].expires) {
delete(f.kept, f.order[i].key)
}
}
if i > 0 {
f.order = append(f.order[:0], f.order[i:]...)
}
}
// silentRefresh rotates the session held in the refresh cookie.
func (a *Adapter) silentRefresh(r *http.Request) (map[string]any, []cookieWrite, error) {
c, err := r.Cookie(a.opts.RefreshCookieName)
if err != nil || c.Value == "" {
return nil, nil, errNoRefreshCookie
}
return a.refreshSession(r, "cookie:"+c.Value, func() (string, string) {
payload, ok := a.readCookie(r, a.opts.RefreshCookieName, kindRefresh)
if !ok {
return "", ""
}
return stringClaim(payload, "sub"), stringClaim(payload, "refreshToken")
})
}
// refreshSession rotates a cookie-transport refresh token once per key, as
// refresher.do shares and keeps it, and builds the cookies for the session it returns. held is read only by the
// caller that makes the call.
func (a *Adapter) refreshSession(r *http.Request, key string, held func() (sub, refreshToken string)) (map[string]any, []cookieWrite, error) {
outcome := a.refreshes.do(key, true, func() refreshOutcome {
sub, refreshToken := held()
if refreshToken == "" {
return refreshOutcome{err: errInvalidRefreshCookie}
}
service, err := a.tokens.sign(sub, map[string]any{"refreshToken": refreshToken})
if err != nil {
return refreshOutcome{err: err}
}
return a.rotate(r, refreshToken, "Bearer "+service)
})
if outcome.session == nil {
if outcome.err == nil {
outcome.err = &refreshAnswered{status: outcome.status, body: outcome.body, isJSON: outcome.isJSON}
}
return nil, nil, outcome.err
}
sessionID, err := a.verifySession(r.Context(), outcome.session, "access")
if err != nil {
return nil, nil, err
}
cookies, err := a.sessionCookies(outcome.session, sessionID, true)
if err != nil {
return nil, nil, err
}
return outcome.session, cookies, nil
}
// rotate runs detached from the request that leads it: callers sharing the
// rotation wait on it, and once the auth API rotates the token the old one is
// spent, so the new session must not be lost to that caller going away.
func (a *Adapter) rotate(r *http.Request, refreshToken, service string) refreshOutcome {
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), upstreamTimeout)
defer cancel()
res, err := a.call(ctx, r, upstreamCall{
method: http.MethodPost,
path: "/refresh",
authorization: "Bearer " + refreshToken,
service: service,
})
if err != nil {
return refreshOutcome{err: err}
}
data, isJSON := readJSON(res)
if res.StatusCode != http.StatusOK {
return refreshOutcome{status: res.StatusCode, body: data, isJSON: isJSON}
}
session, ok := carriesSession(data)
if !ok {
return refreshOutcome{err: errors.New("refresh returned no session")}
}
return refreshOutcome{session: session, status: http.StatusOK}
}
func (a *Adapter) refreshRoute(r *http.Request, bearer bool) result {
if bearer {
token := bearerToken(r)
if token == "" {
return errorResult(http.StatusUnauthorized, "refresh token required")
}
outcome := a.refreshes.do("bearer:"+token, false, func() refreshOutcome {
return a.rotate(r, token, a.tokens.proxyAuthorization())
})
if outcome.session == nil {
if outcome.err != nil {
return errorResult(http.StatusBadGateway, "upstream_unavailable")
}
return failure(outcome.status, outcome.body, outcome.isJSON)
}
if _, err := a.verifySession(r.Context(), outcome.session, "access"); err != nil {
return errorResult(http.StatusBadGateway, "invalid_upstream_session")
}
return result{status: http.StatusOK, body: outcome.session}
}
session, cookies, err := a.silentRefresh(r)
if errors.Is(err, errNoRefreshCookie) {
return errorResult(http.StatusUnauthorized, "refresh token required")
}
if err != nil {
rejected := errorResult(http.StatusUnauthorized, "invalid_refresh_token")
rejected.clear = []string{a.opts.AccessCookieName, a.opts.RefreshCookieName}
return refreshFailure(err, rejected)
}
return result{
status: http.StatusOK,
body: cookieTransportBody(ManifestRoute{}, session),
set: cookies,
}
}
// logoutRoute answers 204 and clears every held cookie, even when the auth API
// refuses, so a browser is never left holding a session it asked to end.
func (a *Adapter) logoutRoute(r *http.Request, bearer bool, path string) result {
clears := []string{a.opts.AccessCookieName, a.opts.RegistrationCookieName, a.opts.RefreshCookieName}
if a.opts.PreAuthCookieName != a.opts.RegistrationCookieName {
clears = append(clears, a.opts.PreAuthCookieName)
}
cred, rejected := a.credentialFor(r, "access", bearer)
if rejected != nil {
rejected.clear = clears
return *rejected
}
res, err := a.call(r.Context(), r, upstreamCall{
method: http.MethodDelete,
path: path,
authorization: cred.authorization,
service: a.tokens.proxyAuthorization(),
})
if err != nil {
a.opts.Logf("[seamless-auth] DELETE %s: %v", path, upstreamError(err))
return result{status: http.StatusBadGateway, body: map[string]any{"error": "upstream_unavailable"}, clear: clears}
}
res.Body.Close()
status := http.StatusNoContent
if res.StatusCode < 200 || res.StatusCode >= 300 {
status = res.StatusCode
}
return result{status: status, clear: clears}
}