Keep local sign-in retries on their return path
5 files changed,
+215
−18
internal/slides/app.go+18 −11internal/slides/auth.go+80 −7internal/slides/auth_test.go+49 −0internal/slides/handlers.go+7 −0internal/slides/home_test.go+61 −0
CI passed — run details
diff --git a/internal/slides/app.go b/internal/slides/app.go| index ae643e1..5fda220 100644 |
| --- a/internal/slides/app.go |
| +++ b/internal/slides/app.go |
| @@ -3,6 +3,7 @@ package slides |
| import ( |
| "context" |
| "net/http" |
| + "time" |
| "amadan.net/oficina/estilo.git/brand" |
| "amadan.net/oficina/estilo.git/chrome" |
| @@ -299,6 +300,10 @@ func newApp(d *db.DB, cfg Config) (*app, *rauth.Auth, error) { |
| if err != nil { |
| return nil, nil, err |
| } |
| + returnSeal, err := newReturnSealer(cfg.InstanceKey) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| // One Runtime for the process: it owns the compiled wasm module, |
| // which is expensive to build and cheap to instantiate, and every |
| @@ -313,17 +318,19 @@ func newApp(d *db.DB, cfg Config) (*app, *rauth.Auth, error) { |
| } |
| a := &app{ |
| - db: d, |
| - logger: logger, |
| - cfg: cfg, |
| - allowed: list, |
| - core: rt, |
| - auth: authPlugin, |
| - hub: present.New(), |
| - live: live.New(), |
| - jobs: jobs.New(logger), |
| - exports: newExportStore(), |
| - pdf: &pdfRuntime{}, |
| + db: d, |
| + logger: logger, |
| + cfg: cfg, |
| + allowed: list, |
| + returnSeal: returnSeal, |
| + returnNow: time.Now, |
| + core: rt, |
| + auth: authPlugin, |
| + hub: present.New(), |
| + live: live.New(), |
| + jobs: jobs.New(logger), |
| + exports: newExportStore(), |
| + pdf: &pdfRuntime{}, |
| } |
| // The optional session read behind every page outside the signed-in |
diff --git a/internal/slides/auth.go b/internal/slides/auth.go| index 158170a..46cada1 100644 |
| --- a/internal/slides/auth.go |
| +++ b/internal/slides/auth.go |
| @@ -18,11 +18,16 @@ |
| package slides |
| import ( |
| + "bytes" |
| "context" |
| + "crypto/sha256" |
| "database/sql" |
| + "encoding/base64" |
| + "encoding/json" |
| "errors" |
| "fmt" |
| "log/slog" |
| + "math" |
| "net/http" |
| "net/url" |
| "strings" |
| @@ -33,6 +38,7 @@ import ( |
| "amadan.net/oficina/home/connect" |
| "amadan.net/oficina/home/connect/linkstore" |
| "amadan.net/oficina/home/handoff" |
| + "amadan.net/oficina/home/handoff/seal" |
| "amadan.net/oficina/slides/internal/slides/present" |
| "amadan.net/rastrillo/rastrillo" |
| rauth "amadan.net/rastrillo/rastrillo/auth" |
| @@ -563,7 +569,7 @@ type signinView struct { |
| func (a *app) signin(w http.ResponseWriter, r *http.Request) { |
| q := r.URL.Query() |
| ret, hasReturn := safeReturn(q) |
| - if a.home == nil { |
| + if a.home == nil || r.URL.Path == "/signin/local" { |
| if s, ok := a.sessions.From(r); ok { |
| _, outcome := a.currentUser(w, sessions.WithSession(r, s)) |
| switch outcome { |
| @@ -595,6 +601,9 @@ func (a *app) signin(w http.ResponseWriter, r *http.Request) { |
| // return (spec §9.2): the remembered page, not a bare /signin, |
| // which would forget it (Astra on Docs #65, finding 2). |
| again := signinPath |
| + if a.home != nil { |
| + again = "/signin/local" |
| + } |
| if remembered, ok := a.rememberedReturn(r); ok { |
| again += "?return_to=" + url.QueryEscape(remembered) |
| } |
| @@ -712,12 +721,48 @@ func (a *app) secure() bool { return strings.HasPrefix(a.cfg.Origin, "https://") |
| // returnCookieAge is how long a remembered page lasts: a link opened |
| // after ten minutes, or in another browser, lands on the deck list. |
| -const returnCookieAge = 600 |
| +const returnCookieAge int64 = 600 |
| +const returnCookieLimit = 4096 |
| + |
| +type returnIntent struct { |
| + Path string `json:"path"` |
| + Issued int64 `json:"issued"` |
| + Expires int64 `json:"expires"` |
| +} |
| + |
| +// newReturnSealer keeps the cookie independent from any other encrypted |
| +// value. The raw instance key need not be exactly 32 bytes; its domain-bound |
| +// hash is. A changed key invalidates old return cookies, which is safe. |
| +func newReturnSealer(instanceKey string) (*seal.Sealer, error) { |
| + key := sha256.Sum256([]byte("oficina/slides return v1\x00" + instanceKey)) |
| + return seal.New(key[:], "oficina/slides") |
| +} |
| + |
| +func (a *app) returnPurpose() string { return "slides.return.v1:" + a.cfg.Origin } |
| func (a *app) rememberReturn(w http.ResponseWriter, path string) { |
| + if !handoff.SafePath(path) || a.returnSeal == nil || a.returnNow == nil { |
| + return |
| + } |
| + now := a.returnNow().Unix() |
| + if now <= 0 || now > math.MaxInt64-returnCookieAge { |
| + return |
| + } |
| + raw, err := json.Marshal(returnIntent{Path: path, Issued: now, Expires: now + returnCookieAge}) |
| + if err != nil { |
| + return |
| + } |
| + sealed, err := a.returnSeal.Seal(a.returnPurpose(), raw) |
| + if err != nil { |
| + return |
| + } |
| + value := base64.RawURLEncoding.EncodeToString(sealed) |
| + if len(value) > returnCookieLimit { |
| + return |
| + } |
| http.SetCookie(w, &http.Cookie{ |
| - Name: a.returnCookieName(), Value: url.QueryEscape(path), Path: "/", |
| - MaxAge: returnCookieAge, HttpOnly: true, Secure: a.secure(), |
| + Name: a.returnCookieName(), Value: value, Path: "/", |
| + MaxAge: int(returnCookieAge), HttpOnly: true, Secure: a.secure(), |
| SameSite: http.SameSiteLaxMode, |
| }) |
| } |
| @@ -735,15 +780,43 @@ func (a *app) forgetReturn(w http.ResponseWriter) { |
| // a same-origin path (handoff.SafePath, which also refuses /signin and |
| // /auth/*, so this can never loop). |
| func (a *app) rememberedReturn(r *http.Request) (string, bool) { |
| + if a.returnSeal == nil || a.returnNow == nil { |
| + return "", false |
| + } |
| + count := 0 |
| + for _, c := range r.Cookies() { |
| + if c.Name == a.returnCookieName() { |
| + count++ |
| + } |
| + } |
| + if count != 1 { |
| + return "", false |
| + } |
| c, err := r.Cookie(a.returnCookieName()) |
| if err != nil { |
| return "", false |
| } |
| - path, err := url.QueryUnescape(c.Value) |
| - if err != nil || !handoff.SafePath(path) { |
| + if c.Value == "" || len(c.Value) > returnCookieLimit { |
| + return "", false |
| + } |
| + sealed, err := base64.RawURLEncoding.Strict().DecodeString(c.Value) |
| + if err != nil || base64.RawURLEncoding.EncodeToString(sealed) != c.Value { |
| + return "", false |
| + } |
| + raw, err := a.returnSeal.Open(a.returnPurpose(), sealed) |
| + if err != nil || len(raw) > returnCookieLimit { |
| + return "", false |
| + } |
| + var intent returnIntent |
| + if json.Unmarshal(raw, &intent) != nil { |
| + return "", false |
| + } |
| + canonical, _ := json.Marshal(intent) |
| + now := a.returnNow().Unix() |
| + if !bytes.Equal(raw, canonical) || intent.Issued <= 0 || intent.Issued > now || intent.Expires <= now || intent.Expires <= intent.Issued || intent.Expires-intent.Issued > returnCookieAge || !handoff.SafePath(intent.Path) { |
| return "", false |
| } |
| - return path, true |
| + return intent.Path, true |
| } |
| // safeReturn is the request's return_to, when there is exactly one and |
diff --git a/internal/slides/auth_test.go b/internal/slides/auth_test.go| index 3a6a14d..3c6cb55 100644 |
| --- a/internal/slides/auth_test.go |
| +++ b/internal/slides/auth_test.go |
| @@ -1,12 +1,61 @@ |
| package slides |
| import ( |
| + "bytes" |
| "context" |
| + "encoding/base64" |
| + "net/http" |
| + "net/http/httptest" |
| "testing" |
| + "time" |
| "gorm.io/gorm" |
| ) |
| +// TestRememberedReturnRejectsTamperAndExpiry is the boundary before a return |
| +// path can become a redirect. A request cookie is attacker input: neither a |
| +// replacement path nor an expired sealed intent is allowed to select where a |
| +// completed sign-in goes. |
| +func TestRememberedReturnRejectsTamperAndExpiry(t *testing.T) { |
| + a, _, err := newApp(testDB(t), Config{Env: EnvDevelopment, Origin: "https://slides.example.test", Logger: quietLogger()}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { a.Close() }) |
| + now := time.Unix(1900000000, 0) |
| + a.returnNow = func() time.Time { return now } |
| + w := httptest.NewRecorder() |
| + a.rememberReturn(w, "/d/private?view=present") |
| + cookies := w.Result().Cookies() |
| + if len(cookies) != 1 { |
| + t.Fatalf("remembered %d cookies, want one", len(cookies)) |
| + } |
| + cookie := cookies[0] |
| + sealed, err := base64.RawURLEncoding.DecodeString(cookie.Value) |
| + if err != nil || bytes.Contains(sealed, []byte("private")) { |
| + t.Fatal("return path was not sealed") |
| + } |
| + valid := httptest.NewRequest(http.MethodGet, "https://slides.example.test/auth/landed", nil) |
| + valid.AddCookie(cookie) |
| + if got, ok := a.rememberedReturn(valid); !ok || got != "/d/private?view=present" { |
| + t.Fatalf("sealed return = %q, %v", got, ok) |
| + } |
| + |
| + sealed[len(sealed)-1] ^= 1 |
| + tampered := *cookie |
| + tampered.Value = base64.RawURLEncoding.EncodeToString(sealed) |
| + r := httptest.NewRequest(http.MethodGet, "https://slides.example.test/auth/landed", nil) |
| + r.AddCookie(&tampered) |
| + if got, ok := a.rememberedReturn(r); ok || got != "" { |
| + t.Fatalf("tampered return cookie was accepted as %q", got) |
| + } |
| + |
| + now = now.Add(time.Duration(returnCookieAge) * time.Second) |
| + if got, ok := a.rememberedReturn(valid); ok || got != "" { |
| + t.Fatalf("expired return cookie was accepted as %q", got) |
| + } |
| +} |
| + |
| // countCreates registers a GORM callback that counts INSERT statements |
| // on the handle, returning a function that reads the count. It is the |
| // only honest way to answer "did that request write?": a row's id and |
diff --git a/internal/slides/handlers.go b/internal/slides/handlers.go| index aeab57b..83fa42d 100644 |
| --- a/internal/slides/handlers.go |
| +++ b/internal/slides/handlers.go |
| @@ -3,8 +3,10 @@ package slides |
| import ( |
| "context" |
| "log/slog" |
| + "time" |
| "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/handoff/seal" |
| "amadan.net/oficina/slides/internal/slides/core" |
| "amadan.net/oficina/slides/internal/slides/live" |
| "amadan.net/oficina/slides/internal/slides/present" |
| @@ -40,6 +42,11 @@ type app struct { |
| logger *slog.Logger |
| cfg Config |
| allowed allowlist |
| + // returnSeal authenticates the short-lived return_to cookie. It is |
| + // derived from this instance's sign-in key, never from a browser |
| + // value, and the clock is a seam for expiry tests. |
| + returnSeal *seal.Sealer |
| + returnNow func() time.Time |
| // core is the compiled deck core, shared by every request. |
| // Compiling the wasm module is expensive and instantiating it is |
| // not, so there is exactly one of these per process and a Handle |
diff --git a/internal/slides/home_test.go b/internal/slides/home_test.go| index 7db78d4..79b323d 100644 |
| --- a/internal/slides/home_test.go |
| +++ b/internal/slides/home_test.go |
| @@ -215,6 +215,67 @@ func TestHomeFrontDoorLocalRecoveryAndCallbackGuard(t *testing.T) { |
| t.Fatal("Home POST continuation omitted from CSP") |
| } |
| } |
| + |
| +// TestHomeDifferentAddressStaysInLocalRecovery keeps the recovery route |
| +// separate from Home's front door. The sent page is reached at /signin, but |
| +// its retry must return to /signin/local with the same safe destination so a |
| +// second submission still completes the local recovery. |
| +func TestHomeDifferentAddressStaysInLocalRecovery(t *testing.T) { |
| + mux, _, u := homeFixture(t) |
| + jar := map[string]*http.Cookie{} |
| + do := func(method, path string, form url.Values) *httptest.ResponseRecorder { |
| + r := httptest.NewRequest(method, homeTestOrigin+path, strings.NewReader(form.Encode())) |
| + r.Header.Set("Accept", "text/html") |
| + if method == http.MethodPost { |
| + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + r.Header.Set("Origin", homeTestOrigin) |
| + r.Header.Set("Sec-Fetch-Site", "same-origin") |
| + } |
| + for _, c := range jar { |
| + r.AddCookie(c) |
| + } |
| + w := httptest.NewRecorder() |
| + mux.ServeHTTP(w, r) |
| + for _, c := range w.Result().Cookies() { |
| + if c.MaxAge < 0 { |
| + delete(jar, c.Name) |
| + } else { |
| + jar[c.Name] = c |
| + } |
| + } |
| + return w |
| + } |
| + |
| + const deep = "/d/keep-going?from=signin" |
| + if first := do(http.MethodGet, "/signin/local?return_to="+url.QueryEscape(deep), nil); first.Code != http.StatusOK { |
| + t.Fatalf("local form: %d", first.Code) |
| + } |
| + sent := do(http.MethodPost, signinPath, url.Values{"address": {u.Email}}) |
| + if sent.Code != http.StatusSeeOther || sent.Header().Get("Location") != "/signin?sent=1" { |
| + t.Fatalf("first submission: %d %q", sent.Code, sent.Header().Get("Location")) |
| + } |
| + sentPage := do(http.MethodGet, sent.Header().Get("Location"), nil) |
| + if sentPage.Code != http.StatusOK { |
| + t.Fatalf("sent page: %d", sentPage.Code) |
| + } |
| + m := regexp.MustCompile(`href="([^"]+)">slides\.signin\.again`).FindStringSubmatch(sentPage.Body.String()) |
| + if m == nil { |
| + t.Fatal("sent page has no Use a different address link") |
| + } |
| + again := strings.ReplaceAll(m[1], "&", "&") |
| + wantAgain := "/signin/local?return_to=" + url.QueryEscape(deep) |
| + if again != wantAgain { |
| + t.Fatalf("retry link = %q, want %q", again, wantAgain) |
| + } |
| + retry := do(http.MethodGet, again, nil) |
| + if retry.Code != http.StatusOK || !strings.Contains(retry.Body.String(), `name="return_to" value="`+deep+`"`) { |
| + t.Fatalf("retry form lost return_to: %d\n%s", retry.Code, retry.Body.String()) |
| + } |
| + second := do(http.MethodPost, signinPath, url.Values{"address": {u.Email}, "return_to": {deep}}) |
| + if second.Code != http.StatusSeeOther || second.Header().Get("Location") != "/signin?sent=1" { |
| + t.Fatalf("second submission did not retain the local flow: %d %q", second.Code, second.Header().Get("Location")) |
| + } |
| +} |
| func TestHomeInvalidConfigurationDoesNotMigrate(t *testing.T) { |
| d := testDB(t) |
| _, _, err := New(d, Config{Env: EnvDevelopment, Origin: homeTestOrigin, Home: &connect.Credentials{Issuer: "https://home.example.com"}}) |