| 1 | package server |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/sha256" |
| 7 | "encoding/base64" |
| 8 | "encoding/hex" |
| 9 | "fmt" |
| 10 | "net/http" |
| 11 | "net/http/httptest" |
| 12 | "os" |
| 13 | "path/filepath" |
| 14 | "strings" |
| 15 | "sync" |
| 16 | "sync/atomic" |
| 17 | "testing" |
| 18 | "time" |
| 19 | |
| 20 | "the-valley/web/export" |
| 21 | "the-valley/web/export/exporttest" |
| 22 | "the-valley/web/readerstate" |
| 23 | ) |
| 24 | |
| 25 | // origin is the public origin the session tests' server takes posts from. |
| 26 | const origin = "https://example.org" |
| 27 | |
| 28 | // readerLink is a read link the host issued: the credential its fragment |
| 29 | // carries, and the binding an authorization gives it. |
| 30 | type readerLink struct { |
| 31 | credential string |
| 32 | binding export.Binding |
| 33 | } |
| 34 | |
| 35 | func issue(n int, principal string) readerLink { |
| 36 | secret := bytes.Repeat([]byte{byte(n)}, 32) |
| 37 | sum := sha256.Sum256(secret) |
| 38 | id := fmt.Sprintf("lk-%016x", n) |
| 39 | return readerLink{id + "." + base64.RawURLEncoding.EncodeToString(secret), |
| 40 | export.Binding{ID: id, Principal: principal, Verifier: hex.EncodeToString(sum[:])}} |
| 41 | } |
| 42 | |
| 43 | // withReaders gives the harness a server with browser state, in a |
| 44 | // directory of its own, which takes posts from origin. Every request is |
| 45 | // read through its session. The server's log is kept, and logged reads it. |
| 46 | func (h *harness) withReaders(o readerstate.Options) *readerstate.State { |
| 47 | h.t.Helper() |
| 48 | dir := filepath.Join(h.t.TempDir(), "browser") |
| 49 | if err := os.Mkdir(dir, 0o700); err != nil { |
| 50 | h.t.Fatal(err) |
| 51 | } |
| 52 | st, err := readerstate.Open(dir, o) |
| 53 | if err != nil { |
| 54 | h.t.Fatal(err) |
| 55 | } |
| 56 | h.t.Cleanup(func() { st.Close() }) |
| 57 | h.browser = dir |
| 58 | h.srv = New(Config{Store: h.store, Now: func() time.Time { return h.now }, Log: h.keep, Readers: st, Origin: origin}) |
| 59 | return st |
| 60 | } |
| 61 | |
| 62 | func (h *harness) keep(err error) { |
| 63 | h.logMu.Lock() |
| 64 | defer h.logMu.Unlock() |
| 65 | h.kept = append(h.kept, err.Error()) |
| 66 | } |
| 67 | |
| 68 | func (h *harness) logged() string { |
| 69 | h.logMu.Lock() |
| 70 | defer h.logMu.Unlock() |
| 71 | return strings.Join(h.kept, "\n") |
| 72 | } |
| 73 | |
| 74 | // bind stores an authorization one sequence past the stored one's, with |
| 75 | // its projects, that binds the links given and no others. |
| 76 | func (h *harness) bind(links ...readerLink) { |
| 77 | h.t.Helper() |
| 78 | a, _, err := h.store.Authorization() |
| 79 | if err != nil { |
| 80 | h.t.Fatal(err) |
| 81 | } |
| 82 | next := *a |
| 83 | next.Sequence, next.Bindings = a.Sequence+1, nil |
| 84 | for _, l := range links { |
| 85 | next.Bindings = append(next.Bindings, l.binding) |
| 86 | } |
| 87 | h.authorize(&next) |
| 88 | } |
| 89 | |
| 90 | // signedIn is a server with browser state over an edge that lets anyone |
| 91 | // read app and alice read site, and a session alice redeemed from her |
| 92 | // link, which the stored authorization binds with bob's. |
| 93 | func signedIn(t *testing.T) (h *harness, alice, bob readerLink, token string) { |
| 94 | h = newHarness(t) |
| 95 | h.withReaders(readerstate.Options{}) |
| 96 | h.srv.Prepare(context.Background()) |
| 97 | h.edge(exporttest.SignedAt.Add(time.Minute), map[string][]string{"app": {export.Anyone}, "site": {"alice"}}) |
| 98 | alice, bob = issue(1, "alice"), issue(2, "bob") |
| 99 | h.bind(alice, bob) |
| 100 | w := h.redeem(alice.credential) |
| 101 | if w.Code != http.StatusNoContent { |
| 102 | t.Fatalf("redeeming alice's link answered %d: %s", w.Code, w.Body) |
| 103 | } |
| 104 | token = cookieOf(t, w) |
| 105 | return h, alice, bob, token |
| 106 | } |
| 107 | |
| 108 | // post answers a reader page's POST of body, with the headers a reader |
| 109 | // page's script sends, changed by change when it is not nil. |
| 110 | func (h *harness) post(path, body string, change func(*http.Request)) *httptest.ResponseRecorder { |
| 111 | r := httptest.NewRequest("POST", path, strings.NewReader(body)) |
| 112 | r.Header.Set("Origin", origin) |
| 113 | r.Header.Set("Content-Type", "application/json") |
| 114 | r.Header.Set("X-Valley-Reader", "1") |
| 115 | if change != nil { |
| 116 | change(r) |
| 117 | } |
| 118 | w := httptest.NewRecorder() |
| 119 | h.srv.ServeHTTP(w, r) |
| 120 | return w |
| 121 | } |
| 122 | |
| 123 | func (h *harness) redeem(credential string, cookies ...string) *httptest.ResponseRecorder { |
| 124 | return h.post("/-/redeem", `{"credential":"`+credential+`"}`, func(r *http.Request) { |
| 125 | for _, c := range cookies { |
| 126 | r.Header.Add("Cookie", cookieName+"="+c) |
| 127 | } |
| 128 | }) |
| 129 | } |
| 130 | |
| 131 | func (h *harness) logout(token string) *httptest.ResponseRecorder { |
| 132 | return h.post("/-/logout", `{}`, func(r *http.Request) { r.Header.Set("Cookie", cookieName+"="+token) }) |
| 133 | } |
| 134 | |
| 135 | // with answers method target carrying the Cookie headers given. |
| 136 | func (h *harness) with(method, target string, cookies ...string) *httptest.ResponseRecorder { |
| 137 | r := httptest.NewRequest(method, target, nil) |
| 138 | for _, c := range cookies { |
| 139 | r.Header.Add("Cookie", c) |
| 140 | } |
| 141 | w := httptest.NewRecorder() |
| 142 | h.srv.ServeHTTP(w, r) |
| 143 | return w |
| 144 | } |
| 145 | |
| 146 | func cookie(token string) string { return cookieName + "=" + token } |
| 147 | |
| 148 | // cookieOf is the session token a response sets, as sessionCookie sets it. |
| 149 | func cookieOf(t *testing.T, w *httptest.ResponseRecorder) string { |
| 150 | t.Helper() |
| 151 | set := w.Header().Values("Set-Cookie") |
| 152 | if len(set) != 1 { |
| 153 | t.Fatalf("the response sets %d cookies: %q", len(set), setting(w)) |
| 154 | } |
| 155 | token, _, _ := strings.Cut(strings.TrimPrefix(set[0], cookieName+"="), ";") |
| 156 | if set[0] != sessionCookie(token) || !strings.HasPrefix(set[0], cookieName+"=lk-") { |
| 157 | t.Fatalf("the response sets %q", setting(w)) |
| 158 | } |
| 159 | return token |
| 160 | } |
| 161 | |
| 162 | // setting is what a response's Set-Cookie headers set, for a failure's |
| 163 | // message: each cookie's value is cut to the credential ID it starts |
| 164 | // with, so no message carries a session token. |
| 165 | func setting(w *httptest.ResponseRecorder) []string { |
| 166 | var shown []string |
| 167 | for _, set := range w.Header().Values("Set-Cookie") { |
| 168 | name, rest, _ := strings.Cut(set, "=") |
| 169 | value, attributes, _ := strings.Cut(rest, ";") |
| 170 | if id, _, _ := strings.Cut(value, "."); export.ValidLinkID(id) { |
| 171 | value = id + ".<redacted>" |
| 172 | } else if value != "" { |
| 173 | value = "<redacted>" |
| 174 | } |
| 175 | shown = append(shown, name+"="+value+";"+attributes) |
| 176 | } |
| 177 | return shown |
| 178 | } |
| 179 | |
| 180 | // pending is st.Pending, with no deadline. |
| 181 | func pending(t *testing.T, st *readerstate.State) bool { |
| 182 | t.Helper() |
| 183 | p, err := st.Pending(context.Background()) |
| 184 | if err != nil { |
| 185 | t.Fatal(err) |
| 186 | } |
| 187 | return p |
| 188 | } |
| 189 | |
| 190 | func renews(w *httptest.ResponseRecorder, token string) bool { |
| 191 | set := w.Header().Values("Set-Cookie") |
| 192 | return len(set) == 1 && set[0] == sessionCookie(token) |
| 193 | } |
| 194 | |
| 195 | func TestARedeemedLinkSignsInItsReader(t *testing.T) { |
| 196 | h, alice, bob, token := signedIn(t) |
| 197 | if got := h.logged(); got != "" { |
| 198 | t.Errorf("the server logged: %s", got) |
| 199 | } |
| 200 | if w := h.with("GET", "/tools/site/"); w.Code != http.StatusNotFound { |
| 201 | t.Errorf("site answered anyone %d", w.Code) |
| 202 | } |
| 203 | w := h.with("GET", "/tools/site/", cookie(token)) |
| 204 | if w.Code != http.StatusFound || !renews(w, token) { |
| 205 | t.Errorf("site answered alice %d, setting %q", w.Code, setting(w)) |
| 206 | } |
| 207 | page := h.with("GET", w.Header().Get("Location"), cookie(token)) |
| 208 | if page.Code != http.StatusOK || !strings.Contains(page.Body.String(), `<a href="/-/logout">Sign out</a>`) || !renews(page, token) { |
| 209 | t.Errorf("site's tree answered alice %d, with no Sign out link or renewal", page.Code) |
| 210 | } |
| 211 | if strings.Contains(h.page("/-/knots"), "Sign out") { |
| 212 | t.Error("anyone's knots page links to Sign out") |
| 213 | } |
| 214 | missing, hidden := h.with("GET", "/tools/nosuch/", cookie(token)), h.with("GET", "/web/docs/", cookie(token)) |
| 215 | for _, w := range []*httptest.ResponseRecorder{missing, hidden} { |
| 216 | if w.Code != http.StatusNotFound || !bytes.Equal(w.Body.Bytes(), notFoundPage) || !renews(w, token) { |
| 217 | t.Errorf("a missing or hidden project answered alice %d, setting %q", w.Code, setting(w)) |
| 218 | } |
| 219 | } |
| 220 | head := h.with("HEAD", "/tools/site/", cookie(token)) |
| 221 | if head.Code != http.StatusFound || !renews(head, token) || head.Body.Len() != 0 { |
| 222 | t.Errorf("HEAD answered %d with %d bytes, setting %q", head.Code, head.Body.Len(), setting(head)) |
| 223 | } |
| 224 | |
| 225 | // A redeemed link redeems no more. A valid session refuses another |
| 226 | // link before it is consumed; after logout the link redeems. |
| 227 | if w := h.redeem(alice.credential); w.Code != http.StatusForbidden || w.Body.String() != refusedLink { |
| 228 | t.Errorf("a second redemption answered %d: %s", w.Code, w.Body) |
| 229 | } |
| 230 | if w := h.redeem(bob.credential, token); w.Code != http.StatusConflict || len(w.Header().Values("Set-Cookie")) != 0 { |
| 231 | t.Errorf("a redemption beside a valid session answered %d", w.Code) |
| 232 | } |
| 233 | w = h.logout(token) |
| 234 | if w.Code != http.StatusNoContent || w.Header().Get("Set-Cookie") != sessionCookie("") { |
| 235 | t.Errorf("logout answered %d, setting %q", w.Code, setting(w)) |
| 236 | } |
| 237 | if w := h.logout(token); w.Code != http.StatusNoContent { |
| 238 | t.Errorf("a second logout answered %d", w.Code) |
| 239 | } |
| 240 | if w := h.with("GET", "/tools/site/", cookie(token)); w.Code != http.StatusNotFound || len(w.Header().Values("Set-Cookie")) != 0 { |
| 241 | t.Errorf("a signed-out session answered %d, setting %q", w.Code, setting(w)) |
| 242 | } |
| 243 | if w := h.redeem(bob.credential, token); w.Code != http.StatusNoContent { |
| 244 | t.Errorf("bob's link, beside a signed-out session, answered %d", w.Code) |
| 245 | } |
| 246 | if w := h.redeem(alice.credential); w.Code != http.StatusForbidden { |
| 247 | t.Errorf("alice's link, after her logout, answered %d", w.Code) |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | func TestReaderPostsKeepTheirContract(t *testing.T) { |
| 252 | h := newHarness(t) |
| 253 | h.withReaders(readerstate.Options{}) |
| 254 | h.srv.Prepare(context.Background()) |
| 255 | alice := issue(1, "alice") |
| 256 | h.bind(alice) |
| 257 | good := `{"credential":"` + alice.credential + `"}` |
| 258 | set := func(k, v string) func(*http.Request) { return func(r *http.Request) { r.Header.Set(k, v) } } |
| 259 | add := func(k, v string) func(*http.Request) { return func(r *http.Request) { r.Header.Add(k, v) } } |
| 260 | for name, c := range map[string]struct { |
| 261 | body string |
| 262 | change func(*http.Request) |
| 263 | }{ |
| 264 | "no origin": {good, func(r *http.Request) { r.Header.Del("Origin") }}, |
| 265 | "another origin": {good, set("Origin", "https://example.org:8443")}, |
| 266 | "an http origin": {good, set("Origin", "http://example.org")}, |
| 267 | "two origins": {good, add("Origin", origin)}, |
| 268 | "no reader header": {good, func(r *http.Request) { r.Header.Del("X-Valley-Reader") }}, |
| 269 | "reader header 2": {good, set("X-Valley-Reader", "2")}, |
| 270 | "two reader header": {good, add("X-Valley-Reader", "1")}, |
| 271 | "a form": {good, set("Content-Type", "application/x-www-form-urlencoded")}, |
| 272 | "text/plain": {good, set("Content-Type", "text/plain")}, |
| 273 | "latin-1": {good, set("Content-Type", "application/json; charset=iso-8859-1")}, |
| 274 | "a parameter": {good, set("Content-Type", "application/json; v=1")}, |
| 275 | "two types": {good, add("Content-Type", "application/json")}, |
| 276 | "an encoding": {good, set("Content-Encoding", "gzip")}, |
| 277 | "a query": {good, func(r *http.Request) { r.URL.RawQuery = "x=1" }}, |
| 278 | "a bare query": {good, func(r *http.Request) { r.URL.ForceQuery = true }}, |
| 279 | "too long": {`{"credential":"` + alice.credential + strings.Repeat(" ", maxPost) + `"}`, nil}, |
| 280 | "twice": {`{"credential":"x","credential":"` + alice.credential + `"}`, nil}, |
| 281 | "unknown": {`{"credential":"` + alice.credential + `","next":"/"}`, nil}, |
| 282 | "trailing": {good + `{}`, nil}, |
| 283 | "an array": {`["` + alice.credential + `"]`, nil}, |
| 284 | "null": {`null`, nil}, |
| 285 | "cased": {`{"Credential":"` + alice.credential + `"}`, nil}, |
| 286 | "no credential": {`{}`, nil}, |
| 287 | "a null credential": {`{"credential":null}`, nil}, |
| 288 | "a number": {`{"credential":1}`, nil}, |
| 289 | } { |
| 290 | if w := h.post("/-/redeem", c.body, c.change); w.Code != http.StatusForbidden || w.Body.String() != refusedPost { |
| 291 | t.Errorf("a post with %s answered %d: %s", name, w.Code, w.Body) |
| 292 | } |
| 293 | } |
| 294 | if w := h.post("/-/logout", `{"token":"x"}`, nil); w.Code != http.StatusForbidden { |
| 295 | t.Errorf("a logout with a key answered %d", w.Code) |
| 296 | } |
| 297 | if w := h.post("/-/redeem", good, set("Content-Type", "application/json; charset=UTF-8")); w.Code != http.StatusNoContent { |
| 298 | t.Errorf("the link, after every refused post, answered %d: %s", w.Code, w.Body) |
| 299 | } |
| 300 | for _, method := range []string{"OPTIONS", "PUT", "DELETE"} { |
| 301 | w := h.with(method, "/-/redeem") |
| 302 | if w.Code != http.StatusMethodNotAllowed || w.Header().Get("Allow") != "GET, HEAD, POST" { |
| 303 | t.Errorf("%s /-/redeem answered %d, Allow %q", method, w.Code, w.Header().Get("Allow")) |
| 304 | } |
| 305 | for k := range w.Header() { |
| 306 | if strings.HasPrefix(k, "Access-Control-") { |
| 307 | t.Errorf("%s /-/redeem carries %s", method, k) |
| 308 | } |
| 309 | } |
| 310 | } |
| 311 | if w := h.post("/tools/app/", good, nil); w.Code != http.StatusMethodNotAllowed { |
| 312 | t.Errorf("a post to a content page answered %d", w.Code) |
| 313 | } |
| 314 | plain := newHarness(t) |
| 315 | if w := plain.post("/-/redeem", good, nil); w.Code != http.StatusMethodNotAllowed { |
| 316 | t.Errorf("with no browser state a redemption answered %d", w.Code) |
| 317 | } |
| 318 | if w := plain.get("/-/redeem"); w.Code != http.StatusNotFound { |
| 319 | t.Errorf("with no browser state /-/redeem answered %d", w.Code) |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | func TestEveryRefusedLinkAnswersAlike(t *testing.T) { |
| 324 | h, alice, bob, _ := signedIn(t) |
| 325 | revoked := issue(3, "carol") |
| 326 | h.bind(alice, bob) |
| 327 | secretOf := func(l readerLink) string { return strings.SplitN(l.credential, ".", 2)[1] } |
| 328 | for name, credential := range map[string]string{ |
| 329 | "malformed": "lk-0000000000000002." + secretOf(bob)[1:], |
| 330 | "unknown": issue(4, "bob").credential, |
| 331 | "wrong": bob.binding.ID + "." + secretOf(alice), |
| 332 | "revoked": revoked.credential, |
| 333 | "consumed": alice.credential, |
| 334 | "empty": "", |
| 335 | } { |
| 336 | w := h.redeem(credential) |
| 337 | if w.Code != http.StatusForbidden || w.Body.String() != refusedLink || len(w.Header().Values("Set-Cookie")) != 0 { |
| 338 | t.Errorf("a %s credential answered %d: %s", name, w.Code, w.Body) |
| 339 | } |
| 340 | } |
| 341 | if w := h.redeem(bob.credential); w.Code != http.StatusNoContent { |
| 342 | t.Errorf("bob's link answered %d", w.Code) |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | func TestSessionCookiesAreCountedAndChecked(t *testing.T) { |
| 347 | h, alice, bob, token := signedIn(t) |
| 348 | for name, cookies := range map[string][]string{ |
| 349 | "twice in one header": {cookie(token) + "; " + cookie(token)}, |
| 350 | "in two headers": {cookie(token), cookie(token)}, |
| 351 | "beside another": {"a=b; " + cookie(token) + "; " + cookie("x")}, |
| 352 | "malformed": {cookie(token + "x")}, |
| 353 | "unknown": {cookie(issue(9, "alice").credential)}, |
| 354 | "quoted": {cookieName + `="` + token + `"`}, |
| 355 | } { |
| 356 | w := h.with("GET", "/tools/site/", cookies...) |
| 357 | if w.Code != http.StatusNotFound || len(w.Header().Values("Set-Cookie")) != 0 { |
| 358 | t.Errorf("a session cookie %s answered %d, setting %q", name, w.Code, setting(w)) |
| 359 | } |
| 360 | } |
| 361 | if w := h.with("GET", "/tools/site/", "other=1; "+cookie(token)); w.Code != http.StatusFound || !renews(w, token) { |
| 362 | t.Errorf("the session beside another cookie answered %d", w.Code) |
| 363 | } |
| 364 | // The session holds only while its link is bound as it was redeemed. |
| 365 | h.bind(bob) |
| 366 | if w := h.with("GET", "/tools/site/", cookie(token)); w.Code != http.StatusNotFound || len(w.Header().Values("Set-Cookie")) != 0 { |
| 367 | t.Errorf("a revoked session answered %d", w.Code) |
| 368 | } |
| 369 | mallory := alice |
| 370 | mallory.binding.Principal = "mallory" |
| 371 | h.bind(mallory) |
| 372 | if w := h.with("GET", "/tools/site/", cookie(token)); w.Code != http.StatusNotFound { |
| 373 | t.Errorf("a session whose link is bound to another principal answered %d", w.Code) |
| 374 | } |
| 375 | h.bind(alice) |
| 376 | if w := h.with("GET", "/tools/site/", cookie(token)); w.Code != http.StatusFound || !renews(w, token) { |
| 377 | t.Errorf("a session whose link is bound again as it was answered %d", w.Code) |
| 378 | } |
| 379 | // Losing every grant leaves the session, with what anyone may see. |
| 380 | e, _ := h.buildExport(true, nil) |
| 381 | withDocs(e, map[string]string{}) |
| 382 | h.authorizeReaders(e, map[string][]string{"app": {export.Anyone}}) |
| 383 | h.bind(alice) |
| 384 | if w := h.with("GET", "/tools/site/", cookie(token)); w.Code != http.StatusNotFound || !renews(w, token) { |
| 385 | t.Errorf("a session with no grant answered %d, setting %q", w.Code, setting(w)) |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | func TestReaderPagesRenderWithTheirOwnPolicy(t *testing.T) { |
| 390 | f := exporttest.New(t) |
| 391 | store, err := export.OpenStore(exporttest.StorePath(t), nil) |
| 392 | if err != nil { |
| 393 | t.Fatal(err) |
| 394 | } |
| 395 | h := &harness{t: t, f: f, store: store, now: exporttest.Collected} |
| 396 | h.withReaders(readerstate.Options{}) |
| 397 | for _, path := range []string{"/-/redeem", "/-/logout"} { |
| 398 | w := h.with("GET", path) |
| 399 | if w.Code != http.StatusOK || w.Header().Get("Content-Security-Policy") != readerPolicy { |
| 400 | t.Errorf("%s with nothing published answered %d, policy %q", path, w.Code, w.Header().Get("Content-Security-Policy")) |
| 401 | } |
| 402 | if !strings.Contains(w.Body.String(), "<script>"+readerJS+"</script>") || strings.Contains(w.Body.String(), "Sign out</a>") { |
| 403 | t.Errorf("%s does not carry the reader script, or links to Sign out", path) |
| 404 | } |
| 405 | } |
| 406 | if !strings.Contains(readerPolicy, "script-src "+inlineHash(readerJS)+"; ") || !strings.Contains(readerPolicy, "connect-src 'self'") { |
| 407 | t.Errorf("the reader policy is %q", readerPolicy) |
| 408 | } |
| 409 | for _, p := range []string{knotsPolicy, contentPolicy} { |
| 410 | if strings.Contains(p, inlineHash(readerJS)) || !strings.Contains(p, "connect-src 'none'") { |
| 411 | t.Errorf("a content policy admits the reader script or a connection: %q", p) |
| 412 | } |
| 413 | } |
| 414 | for _, path := range []string{"/-/redeem/", "/-/redeem/x", "/-/Redeem"} { |
| 415 | if w := h.with("GET", path); w.Code == http.StatusOK { |
| 416 | t.Errorf("%s answered %d", path, w.Code) |
| 417 | } |
| 418 | } |
| 419 | if w := h.with("GET", "/"); w.Code != http.StatusServiceUnavailable { |
| 420 | t.Errorf("/ with nothing published answered %d", w.Code) |
| 421 | } |
| 422 | |
| 423 | s, _, _, token := signedIn(t) |
| 424 | w := s.with("GET", "/-/redeem", cookie(token)) |
| 425 | if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `data-session="1"`) || !strings.Contains(w.Body.String(), "Sign out</a>") || !renews(w, token) { |
| 426 | t.Errorf("/-/redeem for a signed-in reader answered %d without its session", w.Code) |
| 427 | } |
| 428 | if w := s.with("GET", "/-/redeem"); !strings.Contains(w.Body.String(), `data-session="0"`) { |
| 429 | t.Error("/-/redeem for anyone shows a session") |
| 430 | } |
| 431 | } |
| 432 | |
| 433 | func TestAnUnavailableStateServesAnyoneAlone(t *testing.T) { |
| 434 | h, _, bob, token := signedIn(t) |
| 435 | dir := h.browser |
| 436 | data, err := os.ReadFile(filepath.Join(dir, "state")) |
| 437 | if err != nil { |
| 438 | t.Fatal(err) |
| 439 | } |
| 440 | if err := os.WriteFile(filepath.Join(dir, "copy"), data, 0o600); err != nil { |
| 441 | t.Fatal(err) |
| 442 | } |
| 443 | if err := os.Rename(filepath.Join(dir, "copy"), filepath.Join(dir, "state")); err != nil { |
| 444 | t.Fatal(err) |
| 445 | } |
| 446 | for _, target := range []string{"/tools/site/", "/tools/app/", "/-/redeem"} { |
| 447 | w := h.with("GET", target, cookie(token)) |
| 448 | if w.Code != http.StatusServiceUnavailable || !bytes.Equal(w.Body.Bytes(), unavailableHTML) || len(w.Header().Values("Set-Cookie")) != 0 { |
| 449 | t.Errorf("%s with a session answered %d, setting %q", target, w.Code, setting(w)) |
| 450 | } |
| 451 | } |
| 452 | if w := h.with("GET", "/tools/app/"); w.Code != http.StatusFound { |
| 453 | t.Errorf("app answered anyone %d", w.Code) |
| 454 | } |
| 455 | if w := h.redeem(bob.credential); w.Code != http.StatusServiceUnavailable || w.Body.String() != unavailable { |
| 456 | t.Errorf("a redemption answered %d: %s", w.Code, w.Body) |
| 457 | } |
| 458 | if w := h.logout(token); w.Code != http.StatusServiceUnavailable { |
| 459 | t.Errorf("a logout answered %d", w.Code) |
| 460 | } |
| 461 | if !strings.Contains(h.logged(), "replaced or changed") { |
| 462 | t.Errorf("the server did not log why: %s", h.logged()) |
| 463 | } |
| 464 | } |
| 465 | |
| 466 | func TestNoStateIsMadeUnderABinding(t *testing.T) { |
| 467 | h := newHarness(t) |
| 468 | alice, bob := issue(1, "alice"), issue(2, "bob") |
| 469 | h.bind(alice) |
| 470 | st := h.withReaders(readerstate.Options{}) |
| 471 | h.srv.Prepare(context.Background()) |
| 472 | if !pending(t, st) { |
| 473 | t.Fatal("the state was made under a binding") |
| 474 | } |
| 475 | if w := h.redeem(alice.credential); w.Code != http.StatusServiceUnavailable { |
| 476 | t.Errorf("a redemption answered %d", w.Code) |
| 477 | } |
| 478 | if w := h.with("GET", "/tools/app/", cookie(alice.credential)); w.Code != http.StatusServiceUnavailable { |
| 479 | t.Errorf("a request with a cookie answered %d", w.Code) |
| 480 | } |
| 481 | if w := h.with("GET", "/tools/app/"); w.Code != http.StatusFound { |
| 482 | t.Errorf("a request with no cookie answered %d", w.Code) |
| 483 | } |
| 484 | // An empty binding set read by any request makes the state, with no |
| 485 | // restart, and later links redeem. |
| 486 | h.bind() |
| 487 | if w := h.with("GET", "/tools/app/"); w.Code != http.StatusFound || pending(t, st) { |
| 488 | t.Errorf("the request after the bindings were withdrawn answered %d, pending %v", w.Code, pending(t, st)) |
| 489 | } |
| 490 | h.bind(bob) |
| 491 | if w := h.redeem(bob.credential); w.Code != http.StatusNoContent { |
| 492 | t.Errorf("bob's link answered %d", w.Code) |
| 493 | } |
| 494 | } |
| 495 | |
| 496 | // A binding stored after a request read an authorization with none, and |
| 497 | // before the state is made under the serving lock, stops it. A binding the |
| 498 | // receiver stores while the state is being made waits for it. |
| 499 | func TestMakingTheStateRacesNoBinding(t *testing.T) { |
| 500 | h := newHarness(t) |
| 501 | st := h.withReaders(readerstate.Options{}) |
| 502 | stale := h.srv.readAuthorization() |
| 503 | h.bind(issue(1, "alice")) |
| 504 | h.srv.prepare(context.Background(), stale) |
| 505 | if !pending(t, st) { |
| 506 | t.Fatal("the state was made under an authorization that binds a link") |
| 507 | } |
| 508 | |
| 509 | h = newHarness(t) |
| 510 | var stored atomic.Bool |
| 511 | waited := make(chan bool, 1) |
| 512 | alice := issue(1, "alice") |
| 513 | st = h.withReaders(readerstate.Options{Fault: func(op readerstate.Op, step readerstate.Step) error { |
| 514 | if op == readerstate.Initializing && step == readerstate.Created { |
| 515 | go func() { h.bind(alice); stored.Store(true) }() |
| 516 | time.Sleep(200 * time.Millisecond) |
| 517 | waited <- !stored.Load() |
| 518 | } |
| 519 | return nil |
| 520 | }}) |
| 521 | h.srv.Prepare(context.Background()) |
| 522 | if pending(t, st) || !<-waited { |
| 523 | t.Fatal("the receiver stored a binding while the state was being made") |
| 524 | } |
| 525 | eventually(t, "the binding is stored", stored.Load) |
| 526 | if w := h.redeem(alice.credential); w.Code != http.StatusNoContent { |
| 527 | t.Errorf("alice's link answered %d", w.Code) |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | func TestAFullStateRefusesAndSignsOut(t *testing.T) { |
| 532 | h := newHarness(t) |
| 533 | one := len(readerstate.Type+"\n") + len("link lk-0000000000000001 alice ") + 64 + 1 + 64 + 1 |
| 534 | h.withReaders(readerstate.Options{Max: one}) |
| 535 | h.srv.Prepare(context.Background()) |
| 536 | alice, bob := issue(1, "alice"), issue(2, "bob") |
| 537 | h.bind(alice, bob) |
| 538 | w := h.redeem(alice.credential) |
| 539 | if w.Code != http.StatusNoContent { |
| 540 | t.Fatalf("alice's link answered %d", w.Code) |
| 541 | } |
| 542 | if w := h.redeem(bob.credential); w.Code != http.StatusServiceUnavailable { |
| 543 | t.Errorf("a redemption past the bound answered %d", w.Code) |
| 544 | } |
| 545 | if w := h.logout(cookieOf(t, w)); w.Code != http.StatusNoContent { |
| 546 | t.Errorf("a logout of a full state answered %d", w.Code) |
| 547 | } |
| 548 | } |
| 549 | |
| 550 | func TestConcurrentRedemptionsSignInOnce(t *testing.T) { |
| 551 | h, _, bob, _ := signedIn(t) |
| 552 | var wins atomic.Int32 |
| 553 | var wg sync.WaitGroup |
| 554 | for range 8 { |
| 555 | wg.Add(1) |
| 556 | go func() { |
| 557 | defer wg.Done() |
| 558 | if w := h.redeem(bob.credential); w.Code == http.StatusNoContent { |
| 559 | wins.Add(1) |
| 560 | } |
| 561 | }() |
| 562 | } |
| 563 | wg.Wait() |
| 564 | if wins.Load() != 1 { |
| 565 | t.Errorf("%d redemptions of bob's link succeeded", wins.Load()) |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | // A revocation, or a logout, that completes while a response is being |
| 570 | // rendered keeps that response from being written: it is rendered again, |
| 571 | // as anyone's, with no renewal. |
| 572 | func TestASessionResponseIsHeldToItsSession(t *testing.T) { |
| 573 | for _, mutation := range []string{"revoke", "logout"} { |
| 574 | for _, path := range []string{"/tools/site/source/blob/%s/README.md", "/tools/site/source/archive/%s.tar.gz", |
| 575 | "/tools/site/knots/oc-b000001", "/site/", "/tools/site/source/tree/%s/"} { |
| 576 | t.Run(mutation+path, func(t *testing.T) { |
| 577 | h, _, bob, token := signedIn(t) |
| 578 | target := strings.ReplaceAll(path, "%s", git(t, h.f.Repos["site"], nil, "rev-parse", export.MainRef)) |
| 579 | if w := h.with("GET", target, cookie(token)); w.Code != http.StatusOK && w.Code != http.StatusPermanentRedirect { |
| 580 | t.Fatalf("GET %s as alice answered %d", target, w.Code) |
| 581 | } |
| 582 | renders := 0 |
| 583 | h.srv.checked = func() { |
| 584 | if renders++; renders == 1 { |
| 585 | if mutation == "revoke" { |
| 586 | h.bind(bob) |
| 587 | } else if w := h.logout(token); w.Code != http.StatusNoContent { |
| 588 | t.Errorf("logout answered %d", w.Code) |
| 589 | } |
| 590 | } |
| 591 | } |
| 592 | w := h.with("GET", target, cookie(token)) |
| 593 | if w.Code != http.StatusNotFound || !bytes.Equal(w.Body.Bytes(), notFoundPage) || len(w.Header().Values("Set-Cookie")) != 0 { |
| 594 | t.Errorf("GET %s after a %s while it rendered answered %d, setting %q", target, mutation, w.Code, setting(w)) |
| 595 | } |
| 596 | if renders != 2 { |
| 597 | t.Errorf("GET %s rendered %d times, want twice", target, renders) |
| 598 | } |
| 599 | }) |
| 600 | } |
| 601 | } |
| 602 | } |
| 603 | |
| 604 | // A redemption that waits behind a slow transaction stops waiting at its |
| 605 | // deadline, and consumes nothing: its link redeems once the slow one is |
| 606 | // done. |
| 607 | func TestARedemptionPastItsDeadlineConsumesNothing(t *testing.T) { |
| 608 | h := newHarness(t) |
| 609 | reached, slow := make(chan struct{}), make(chan struct{}) |
| 610 | var once sync.Once |
| 611 | h.withReaders(readerstate.Options{Fault: func(op readerstate.Op, step readerstate.Step) error { |
| 612 | if op == readerstate.Redeeming && step == readerstate.Created { |
| 613 | once.Do(func() { close(reached); <-slow }) |
| 614 | } |
| 615 | return nil |
| 616 | }}) |
| 617 | h.srv.Prepare(context.Background()) |
| 618 | alice, bob := issue(1, "alice"), issue(2, "bob") |
| 619 | h.bind(alice, bob) |
| 620 | h.srv.timeout = 300 * time.Millisecond |
| 621 | first := make(chan int, 1) |
| 622 | go func() { first <- h.redeem(alice.credential).Code }() |
| 623 | <-reached |
| 624 | queued := make(chan *httptest.ResponseRecorder, 1) |
| 625 | go func() { queued <- h.redeem(bob.credential) }() |
| 626 | var w *httptest.ResponseRecorder |
| 627 | select { |
| 628 | case w = <-queued: |
| 629 | case <-time.After(5 * time.Second): |
| 630 | t.Error("a redemption queued behind a slow one waited past its deadline") |
| 631 | close(slow) |
| 632 | w = <-queued |
| 633 | } |
| 634 | if w.Code != http.StatusServiceUnavailable || len(w.Header().Values("Set-Cookie")) != 0 { |
| 635 | t.Errorf("the queued redemption answered %d, setting %q", w.Code, setting(w)) |
| 636 | } |
| 637 | select { |
| 638 | case <-slow: |
| 639 | default: |
| 640 | close(slow) |
| 641 | } |
| 642 | if code := <-first; code != http.StatusNoContent { |
| 643 | t.Errorf("the slow redemption answered %d", code) |
| 644 | } |
| 645 | h.srv.timeout = requestTimeout |
| 646 | if w := h.redeem(bob.credential); w.Code != http.StatusNoContent { |
| 647 | t.Errorf("bob's link, after its redemption ran out of time, answered %d: %s", w.Code, w.Body) |
| 648 | } |
| 649 | if got := h.logged(); got != "" { |
| 650 | t.Errorf("the server logged: %s", got) |
| 651 | } |
| 652 | } |
| 653 | |
| 654 | // A request that asks whether the state is still to be made waits for |
| 655 | // the read lock only until its deadline. While the state's first write, |
| 656 | // or a logout's, stalls in the filesystem under the write lock, a GET and |
| 657 | // a redemption each answer 503 at their deadline, and consume nothing. |
| 658 | func TestAStalledWriteHoldsNoRequestPastItsDeadline(t *testing.T) { |
| 659 | for _, op := range []readerstate.Op{readerstate.Initializing, readerstate.SigningOut} { |
| 660 | t.Run(op.String(), func(t *testing.T) { |
| 661 | h := newHarness(t) |
| 662 | reached, slow := make(chan struct{}), make(chan struct{}) |
| 663 | var once sync.Once |
| 664 | st := h.withReaders(readerstate.Options{Fault: func(o readerstate.Op, step readerstate.Step) error { |
| 665 | if o == op && step == readerstate.Created { |
| 666 | once.Do(func() { close(reached); <-slow }) |
| 667 | } |
| 668 | return nil |
| 669 | }}) |
| 670 | alice, bob := issue(1, "alice"), issue(2, "bob") |
| 671 | stalled := make(chan int, 1) |
| 672 | if op == readerstate.Initializing { |
| 673 | go func() { h.srv.Prepare(context.Background()); stalled <- http.StatusNoContent }() |
| 674 | } else { |
| 675 | h.srv.Prepare(context.Background()) |
| 676 | h.bind(alice) |
| 677 | token := cookieOf(t, h.redeem(alice.credential)) |
| 678 | // With no link bound, every request asks whether the |
| 679 | // state is still to be made. |
| 680 | h.bind() |
| 681 | go func() { stalled <- h.logout(token).Code }() |
| 682 | } |
| 683 | <-reached |
| 684 | h.srv.timeout = 300 * time.Millisecond |
| 685 | answered := make(chan *httptest.ResponseRecorder, 2) |
| 686 | go func() { answered <- h.with("GET", "/tools/app/") }() |
| 687 | go func() { answered <- h.redeem(bob.credential) }() |
| 688 | for range 2 { |
| 689 | select { |
| 690 | case w := <-answered: |
| 691 | if w.Code != http.StatusServiceUnavailable || len(w.Header().Values("Set-Cookie")) != 0 { |
| 692 | t.Errorf("a request behind the stalled %s answered %d, setting %q", op, w.Code, setting(w)) |
| 693 | } |
| 694 | case <-time.After(5 * time.Second): |
| 695 | t.Errorf("a request behind the stalled %s waited past its deadline", op) |
| 696 | } |
| 697 | } |
| 698 | close(slow) |
| 699 | if code := <-stalled; code != http.StatusNoContent { |
| 700 | t.Errorf("the stalled %s answered %d", op, code) |
| 701 | } |
| 702 | h.srv.timeout = requestTimeout |
| 703 | if pending(t, st) { |
| 704 | t.Error("the state was not made") |
| 705 | } |
| 706 | h.bind(bob) |
| 707 | if w := h.redeem(bob.credential); w.Code != http.StatusNoContent { |
| 708 | t.Errorf("bob's link, after its redemption ran out of time, answered %d: %s", w.Code, w.Body) |
| 709 | } |
| 710 | }) |
| 711 | } |
| 712 | } |
| 713 | |
| 714 | // A response whose deadline passes after its last check found its |
| 715 | // session valid is not written: it answers 503, and renews no session. |
| 716 | func TestAResponsePastItsDeadlineIsNotRenewed(t *testing.T) { |
| 717 | h, _, _, token := signedIn(t) |
| 718 | h.srv.timeout = time.Second |
| 719 | started := false |
| 720 | h.srv.starting = func() { |
| 721 | started = true |
| 722 | time.Sleep(h.srv.timeout + 100*time.Millisecond) |
| 723 | } |
| 724 | w := h.with("GET", "/tools/site/", cookie(token)) |
| 725 | if !started { |
| 726 | t.Fatal("the request ran out of time before its last check") |
| 727 | } |
| 728 | if w.Code != http.StatusServiceUnavailable || len(w.Header().Values("Set-Cookie")) != 0 { |
| 729 | t.Errorf("a response past its deadline answered %d, setting %q", w.Code, setting(w)) |
| 730 | } |
| 731 | h.srv.starting = nil |
| 732 | h.srv.timeout = requestTimeout |
| 733 | if w := h.with("GET", "/tools/site/", cookie(token)); w.Code != http.StatusFound || !renews(w, token) { |
| 734 | t.Errorf("the next response answered %d, setting %q", w.Code, setting(w)) |
| 735 | } |
| 736 | } |
| 737 | |
| 738 | // /-/session tells the reader page's script which link the browser's |
| 739 | // session was redeemed from, and nothing for no valid session. It |
| 740 | // answers GET and HEAD alone, and renews a valid session as every |
| 741 | // response does. |
| 742 | func TestTheSessionStateNamesItsLink(t *testing.T) { |
| 743 | h, alice, _, token := signedIn(t) |
| 744 | w := h.with("GET", "/-/session", cookie(token)) |
| 745 | if w.Code != http.StatusOK || w.Body.String() != `{"link":"`+alice.binding.ID+`"}` || !renews(w, token) { |
| 746 | t.Errorf("/-/session for alice answered %d %q, setting %q", w.Code, w.Body, setting(w)) |
| 747 | } |
| 748 | if ct, p := w.Header().Get("Content-Type"), w.Header().Get("Content-Security-Policy"); ct != "application/json" || p != readerPolicy { |
| 749 | t.Errorf("/-/session is %q under %q", ct, p) |
| 750 | } |
| 751 | for _, cookies := range [][]string{nil, {cookie(token + "x")}} { |
| 752 | if w := h.with("GET", "/-/session", cookies...); w.Code != http.StatusOK || w.Body.String() != `{"link":""}` { |
| 753 | t.Errorf("/-/session with %q answered %d %q", cookies, w.Code, w.Body) |
| 754 | } |
| 755 | } |
| 756 | for _, method := range []string{"POST", "PUT"} { |
| 757 | w := h.post("/-/session", `{}`, func(r *http.Request) { r.Method = method }) |
| 758 | if w.Code != http.StatusMethodNotAllowed || w.Header().Get("Allow") != "GET, HEAD" { |
| 759 | t.Errorf("%s /-/session answered %d, Allow %q", method, w.Code, w.Header().Get("Allow")) |
| 760 | } |
| 761 | } |
| 762 | if w := h.logout(token); w.Code != http.StatusNoContent { |
| 763 | t.Fatalf("logout answered %d", w.Code) |
| 764 | } |
| 765 | if w := h.with("GET", "/-/session", cookie(token)); w.Body.String() != `{"link":""}` || len(w.Header().Values("Set-Cookie")) != 0 { |
| 766 | t.Errorf("/-/session after logout answered %q, setting %q", w.Body, setting(w)) |
| 767 | } |
| 768 | if w := newHarness(t).get("/-/session"); w.Code != http.StatusNotFound { |
| 769 | t.Errorf("with no browser state /-/session answered %d", w.Code) |
| 770 | } |
| 771 | } |