Docs: move onto home/connect, migrate links with Adopt. Docs drops its private homeBridge and signs in through Home's shared connect package (Finish plus the Unlinked/HomeOnly hooks), pinned with teammode and roster at Home main 602f513. Existing docs_identity_links rows move into connect's home_identity_links at boot in one transaction via linkstore.Adopt (binding computed as Confirm would), the link clock carried with MAX, the disjointness triggers re-pointed and the old table, triggers, flows and clock dropped in the same transaction; any refusal aborts boot and drops nothing; a rerun is a no-op. Existing sessions survive (same __Host-rastrillo_session cookie and sessions table, method connect.HomeMethod, mount refuses a mismatch). Request Access is carried with teammode.WithAccess so Guard sees real standing. One-way: the previous build cannot boot on a moved database, so deploy with a snapshot first. Reviewed by Claude Fable 5.1 (claude-fable-5-1) on oficina/docs #101, APPROVED at de26fd8; CI green. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Squashed from home-connect into main.
41 files changed,
+2,048
−3,139
go.mod+3 −2go.sum+6 −0internal/docs/app.go+38 −19internal/docs/auth.go+2 −1internal/docs/auth_navigation.go+14 −0internal/docs/dashboard.go+3 −3internal/docs/errors_test.go+23 −24internal/docs/home_config.go+3 −2internal/docs/home_connect.go+415 −0internal/docs/home_connect_linked_test.go+21 −60internal/docs/home_connect_test.go+102 −0internal/docs/home_exchange.go+0 −314internal/docs/home_exchange_test.go+0 −437internal/docs/home_link_handlers.go+0 −194internal/docs/home_links_move.go+165 −0internal/docs/home_links_move_test.go+631 −0internal/docs/home_local_navigation.go+0 −212internal/docs/home_local_navigation_test.go+0 −321internal/docs/home_return.go+53 −8internal/docs/home_router_integration_test.go+11 −11internal/docs/home_routes.go+0 −215internal/docs/identity.go+65 −50internal/docs/identity_test.go+36 −14internal/docs/linkstore/flows.go+0 −314internal/docs/linkstore/principals/migrations/0001_old_link_table.sql+7 −0internal/docs/linkstore/schema.go+44 −0internal/docs/linkstore/store.go+0 −217internal/docs/linkstore/store_test.go+0 −534internal/docs/principalstore/store.go+35 −4internal/docs/principalstore/store_test.go+50 −11internal/docs/signin_return.go+16 −26internal/docs/team_access.go+16 −4internal/docs/team_access_test.go+57 −5internal/docs/team_config.go+10 −6internal/docs/team_home.go+0 −62internal/docs/team_home_test.go+148 −37internal/docs/team_identity_test.go+5 −7internal/docs/team_session_reader_test.go+16 −16internal/docs/team_state_test.go+49 −6internal/docs/team_stream.go+3 −3internal/shipped/shipped.go+1 −0
CI passed — run details
diff --git a/go.mod b/go.mod| index c50c4d4..31ed322 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -6,8 +6,8 @@ require ( |
| amadan.net/oficina/estilo.git v0.0.0-20261026205409-aa90aaceb796 |
| amadan.net/oficina/home/dashboard v0.0.0-20261024235511-baa2503c7064 |
| amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 |
| - amadan.net/oficina/home/roster v0.0.0-20261028171508-67c12e39a9d2 |
| - amadan.net/oficina/home/teammode v0.0.0-20261028171508-67c12e39a9d2 |
| + amadan.net/oficina/home/roster v0.0.0-20261030153823-602f5136f9af |
| + amadan.net/oficina/home/teammode v0.0.0-20261030153823-602f5136f9af |
| amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3 |
| amadan.net/rastrillo/rastrillo v0.29.1-0.20261027164201-054787952dd2 |
| github.com/carlosframework/rastrillo v0.23.0 |
| @@ -26,6 +26,7 @@ require ( |
| ) |
| require ( |
| + amadan.net/oficina/home/connect v0.0.0-20261030153823-602f5136f9af // indirect |
| amadan.net/rastrillo/rastrillo/money v0.1.0 // indirect |
| github.com/BurntSushi/toml v1.6.0 // indirect |
| github.com/chromedp/sysutil v1.1.0 // indirect |
diff --git a/go.sum b/go.sum| index 248ac38..4f51c46 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -2,14 +2,20 @@ amadan.net/oficina/estilo.git v0.0.0-20261026205409-aa90aaceb796 h1:yj3d1pKgMbZ3 |
| amadan.net/oficina/estilo.git v0.0.0-20261026205409-aa90aaceb796/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw= |
| amadan.net/oficina/home/connect v0.0.0-20261028165624-d942439ac4e4 h1:WQ4irMKZerybbbccJblyukiloZZ9zfIxcay4vVyVowU= |
| amadan.net/oficina/home/connect v0.0.0-20261028165624-d942439ac4e4/go.mod h1:ix81eFV87yE9f2SXiRuxYCVM4lAgTRC5YoQMiH3+TDk= |
| +amadan.net/oficina/home/connect v0.0.0-20261030153823-602f5136f9af h1:jAQ3F8iqqR+z3dnkzmcMmPadX6vZ82adqGlGQMh0GkM= |
| +amadan.net/oficina/home/connect v0.0.0-20261030153823-602f5136f9af/go.mod h1:ix81eFV87yE9f2SXiRuxYCVM4lAgTRC5YoQMiH3+TDk= |
| amadan.net/oficina/home/dashboard v0.0.0-20261024235511-baa2503c7064 h1:2YbDksZDxpY9khlhXmTeiM89yze7w2XfYSumtrzH4tc= |
| amadan.net/oficina/home/dashboard v0.0.0-20261024235511-baa2503c7064/go.mod h1:+7xsX+QyVFrKy5gDAGh+FZ5+75z4CibWTL0wl9DWAw0= |
| amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 h1:RPKtyry/71i06o8L+gjAaUyexbmG56kO1YPs601URAM= |
| amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k= |
| amadan.net/oficina/home/roster v0.0.0-20261028171508-67c12e39a9d2 h1:yKUTS0nOiVw7ktHpTin0bCcUDLFjmMjpW6CsHIZzZKk= |
| amadan.net/oficina/home/roster v0.0.0-20261028171508-67c12e39a9d2/go.mod h1:gqshuXyDtFZUCYbhuZyV3Epc51pUcsLbpqAqiA5UiXg= |
| +amadan.net/oficina/home/roster v0.0.0-20261030153823-602f5136f9af h1:YtDEq1YUm87/v6XtP6+V32g9U3KDvKos1SdXsnOxA6A= |
| +amadan.net/oficina/home/roster v0.0.0-20261030153823-602f5136f9af/go.mod h1:gqshuXyDtFZUCYbhuZyV3Epc51pUcsLbpqAqiA5UiXg= |
| amadan.net/oficina/home/teammode v0.0.0-20261028171508-67c12e39a9d2 h1:0PQiRUkC+9cbTHE67Y4/SmW1sPH1NNWNwTceNFyMjTY= |
| amadan.net/oficina/home/teammode v0.0.0-20261028171508-67c12e39a9d2/go.mod h1:dXBZeB2ic33SIZiGUCzafmviUT8TYWgzSYZvo2rM6zA= |
| +amadan.net/oficina/home/teammode v0.0.0-20261030153823-602f5136f9af h1:QsC+WKvYxiKipS3+J4D9YWRmKQ+cJJTevlH6kP8UVhA= |
| +amadan.net/oficina/home/teammode v0.0.0-20261030153823-602f5136f9af/go.mod h1:dXBZeB2ic33SIZiGUCzafmviUT8TYWgzSYZvo2rM6zA= |
| amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3 h1:5EFx7BLJj/+G/rt8bTmeyMWVfF5s5Sns7ajTvX4w/I8= |
| amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3/go.mod h1:ZaaxeE278dJltdrLwmwpxUjQ5wuKzqDAVSNRet+WupY= |
| amadan.net/rastrillo/rastrillo v0.29.1-0.20261027164201-054787952dd2 h1:ybFov1+wRduFtkxTn44QnzCKTDhyjfFWxWsW+cKaAyk= |
diff --git a/internal/docs/app.go b/internal/docs/app.go| index 23f20c9..9b65167 100644 |
| --- a/internal/docs/app.go |
| +++ b/internal/docs/app.go |
| @@ -12,6 +12,7 @@ package docs |
| import ( |
| "amadan.net/oficina/estilo.git/sky" |
| + connectlinks "amadan.net/oficina/home/connect/linkstore" |
| "context" |
| "errors" |
| "fmt" |
| @@ -299,7 +300,11 @@ func (a *App) Drain() { a.handlers.hub.drain() } |
| // §2): sessions.Schema before auth.Schema — auth's own backfill |
| // migration reads the sessions table — before this app's own Schema |
| // (models.go). |
| -var BootSchema = migrate.Merge(migrate.MustFromFS(dashboard.Migrations, "oficina_dashboard"), sessions.Schema, authSchema, Schema, linkstore.Schema, migrate.MustFromFS(handoff.Migrations, "oficina_handoff")) |
| +// |
| +// linkstore.Schema is Docs' retired link table, which every database has |
| +// applied; connect's link schema follows the handoff's. Docs' rows move |
| +// into connect's table at boot (home_links_move.go). |
| +var BootSchema = migrate.Merge(migrate.MustFromFS(dashboard.Migrations, "oficina_dashboard"), sessions.Schema, authSchema, Schema, linkstore.Schema, migrate.MustFromFS(handoff.Migrations, "oficina_handoff"), migrate.MustFromFS(connectlinks.Migrations, connectlinks.SchemaNamespace)) |
| // New opens the database, applies migrations and wires the router. It |
| // is rastrillo SKILL.md's app.go shape: db.Open for the SQLite handle, |
| @@ -444,6 +449,21 @@ func New(cfg Config) (*App, error) { |
| // The sample library is for members. A guest admitted by a grant is |
| // visiting, not moving in. |
| store.seedOnlyMembers = list.configured |
| + // Home: connect's Bridge, then the one-time move of Docs' own links |
| + // into connect's table (home_links_move.go). connect.New has swept |
| + // already, nothing else is running, and the team census below reads |
| + // the moved table. |
| + var home *homeRoutes |
| + if homeSettings != nil { |
| + if home, err = newHome(homeSettings, cfg.Origin, d.Writer(), store, teamSettings != nil); err == nil { |
| + err = moveLinksOntoConnect(context.Background(), d.Writer(), home.bridge) |
| + } |
| + if err != nil { |
| + rt.Close(context.Background()) |
| + d.Close() |
| + return nil, err |
| + } |
| + } |
| if teamSettings != nil { |
| store.team, err = newTeamRuntime(context.Background(), teamSettings, d.Writer(), homeSettings) |
| if err != nil { |
| @@ -513,34 +533,33 @@ func New(cfg Config) (*App, error) { |
| return id.Address, ok |
| } |
| - var home *homeRoutes |
| - if homeSettings != nil { |
| - home, err = newHomeRoutes(homeSettings, cfg.Origin, d.Writer(), authPlugin, h) |
| - if err != nil { |
| + if home != nil { |
| + if err = home.mount(h, authPlugin); err != nil { |
| rt.Close(context.Background()) |
| d.Close() |
| return nil, err |
| } |
| h.homeEnabled = true |
| - h.homeLinked = home.bridge.links.Linked |
| + h.homeLinked = home.bridge.Linked |
| h.peek = func(r *http.Request) (string, bool) { |
| - s, ok := home.bridge.sessions.From(r) |
| + s, ok := home.sessions.From(r) |
| if !ok || s.Subject == "" { |
| return "", false |
| } |
| if s.Method == "magiclink" || s.Method == "keymail" { |
| return s.Subject, true |
| } |
| - id, err := home.bridge.resolver.resolve(sessions.WithSession(r, s)) |
| + id, err := home.resolver.resolve(sessions.WithSession(r, s)) |
| if err != nil { |
| return "", false |
| } |
| return actorAddress(id.Actor), true |
| } |
| if store.team != nil { |
| - store.team.bridge = home.bridge |
| - home.bridge.resolver.team = store.team |
| - store.team.readSession, err = newTeamSessionReader(d.Writer(), cfg.Origin, home.bridge.sessionCookie, logger) |
| + store.team.home = home |
| + home.team = store.team |
| + home.resolver.team = store.team |
| + store.team.readSession, err = newTeamSessionReader(d.Writer(), cfg.Origin, home.sessionCookie, logger) |
| if err != nil { |
| rt.Close(context.Background()) |
| d.Close() |
| @@ -559,11 +578,11 @@ func New(cfg Config) (*App, error) { |
| if home == nil { |
| return authPlugin.RequireSession(next) |
| } |
| - current := home.bridge.sessions.Require(home.bridge.resolver.middleware("/signin/local")(next)) |
| + current := home.sessions.Require(home.resolver.middleware("/signin/local")(next)) |
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| // A live stream retains its opening context. Require trusts that cached |
| // session, so re-read the cookie before admitting each stream write. |
| - session, ok := home.bridge.sessions.From(r) |
| + session, ok := home.sessions.From(r) |
| if !ok { |
| http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusUnauthorized) |
| return |
| @@ -578,7 +597,7 @@ func New(cfg Config) (*App, error) { |
| return nil, err |
| } |
| native := nativeauth.New(nativeSessions, cfg.Origin, "Docs", h.requireCurrent) |
| - var standalone *localLinkNavigation |
| + var standalone *returnMemory |
| if home == nil { |
| if standalone, err = standaloneReturn(instanceKey, cfg.Origin); err != nil { |
| rt.Close(context.Background()) |
| @@ -589,7 +608,7 @@ func New(cfg Config) (*App, error) { |
| if home == nil { |
| h.remembered = standalone.returnPath |
| } else { |
| - h.remembered = home.navigation.returnPath |
| + h.remembered = home.returns.returnPath |
| } |
| r := chi.NewRouter() |
| // Every route that is not a route is the 404 page for a browser, and a |
| @@ -685,8 +704,8 @@ func New(cfg Config) (*App, error) { |
| if store.team != nil { |
| r.Group(func(r chi.Router) { |
| - r.Use(home.bridge.sessions.Require) |
| - r.Use(home.bridge.resolver.middleware("/signin/local")) |
| + r.Use(home.sessions.Require) |
| + r.Use(home.resolver.middleware("/signin/local")) |
| r.Use(requireTeamAccountAdmission(list)) |
| home.mountAccount(r) |
| }) |
| @@ -695,8 +714,8 @@ func New(cfg Config) (*App, error) { |
| if home == nil { |
| r.Use(requireSessionReturning(authPlugin)) |
| } else { |
| - r.Use(home.bridge.sessions.Require) |
| - r.Use(home.bridge.resolver.middleware("/signin/local")) |
| + r.Use(home.sessions.Require) |
| + r.Use(home.resolver.middleware("/signin/local")) |
| } |
| // After the session middleware, so a 500 page shows the viewer's |
| // own chrome (errors.go). |
diff --git a/internal/docs/auth.go b/internal/docs/auth.go| index 5fc609b..689eb69 100644 |
| --- a/internal/docs/auth.go |
| +++ b/internal/docs/auth.go |
| @@ -552,7 +552,8 @@ func (h *handlers) signin(w http.ResponseWriter, r *http.Request) { |
| // signedOut is GET /signed-out, where Sign out lands: "You’re signed out", |
| // and a Sign in button (spec §9.2). With Home configured it is the same |
| -// page (home_routes.go), which is why it takes the path to sign in at. |
| +// page (connect's SignedOut, drawn by home_connect.go's render), which is |
| +// why it takes the path to sign in at. |
| func (h *handlers) signedOut(w http.ResponseWriter, r *http.Request) { |
| h.render.homeLink(w, r, "signedout", "", http.StatusOK) |
| } |
diff --git a/internal/docs/auth_navigation.go b/internal/docs/auth_navigation.go| index 707069b..d8af473 100644 |
| --- a/internal/docs/auth_navigation.go |
| +++ b/internal/docs/auth_navigation.go |
| @@ -97,6 +97,20 @@ func (w *signinResponse) Write(p []byte) (int, error) { |
| return w.body.Write(p) |
| } |
| +// replay writes the captured response to w. |
| +func (w *signinResponse) replay(to http.ResponseWriter) { |
| + for name, values := range w.header { |
| + for _, value := range values { |
| + to.Header().Add(name, value) |
| + } |
| + } |
| + if w.status == 0 { |
| + w.status = http.StatusOK |
| + } |
| + to.WriteHeader(w.status) |
| + _, _ = to.Write(w.body.Bytes()) |
| +} |
| + |
| // signinDoor is what rastrillo/auth calls back into for the two pages it |
| // hands to the app (newAuthPlugin). The plugin is built before the |
| // handlers, so these are bound late, by New. |
diff --git a/internal/docs/dashboard.go b/internal/docs/dashboard.go| index 21f5c31..667f325 100644 |
| --- a/internal/docs/dashboard.go |
| +++ b/internal/docs/dashboard.go |
| @@ -23,7 +23,7 @@ func (h *handlers) dashboardProvider(home *homeRoutes, c *homeSettings, list all |
| // local account or calling EnsureHome. The token itself confers no access. |
| resolve := func(ctx context.Context, subject string) (requestIdentity, error) { |
| r, _ := http.NewRequestWithContext(ctx, http.MethodGet, h.origin+"/", nil) |
| - id, e := home.bridge.resolver.resolve(sessions.WithSession(r, sessions.Session{Subject: subject, Method: homeAssertionMethod})) |
| + id, e := home.resolver.resolve(sessions.WithSession(r, sessions.Session{Subject: subject, Method: homeAssertionMethod})) |
| if e != nil { |
| return requestIdentity{}, e |
| } |
| @@ -49,7 +49,7 @@ func (h *handlers) dashboardProvider(home *homeRoutes, c *homeSettings, list all |
| var access *requestAccess |
| if h.store.team != nil { |
| access = h.store.team.resolveAccess(ctx, id) |
| - ctx = context.WithValue(ctx, accessContextKey{}, access) |
| + ctx = withAccess(ctx, access) |
| ctx.Value(dashboardAccessKey{}).(*dashboardAccess).access = access |
| } |
| rows, e := h.store.listForLimited(ctx, id.Actor, dashboard.MaxItems+1) |
| @@ -77,7 +77,7 @@ func (h *handlers) dashboardProvider(home *homeRoutes, c *homeSettings, list all |
| http.Error(w, "Dashboard unavailable", 503) |
| return |
| } |
| - r = r.WithContext(context.WithValue(r.Context(), accessContextKey{}, access)) |
| + r = r.WithContext(withAccess(r.Context(), access)) |
| } |
| _ = writeGuardedBody(w, r, 200, body) |
| }}) |
diff --git a/internal/docs/errors_test.go b/internal/docs/errors_test.go| index 06bced7..9cce5a9 100644 |
| --- a/internal/docs/errors_test.go |
| +++ b/internal/docs/errors_test.go |
| @@ -236,30 +236,29 @@ func TestEveryPlainTextErrorIsClassified(t *testing.T) { |
| why string |
| }{ |
| "dashboard.go:handlers.dashboardProvider": {1, "private server-to-server dashboard JSON; missing response authorization fails closed"}, |
| - "app.go:New": {1, "live stream re-check: an EventSource, never a page"}, |
| - "assets.go:serveIcon": {1, "static asset 404"}, |
| - "assets.go:serveBundle": {1, "static asset 404"}, |
| - "auth.go:requireAdmissionOf": {2, "shared guard in front of page and fetch routes; its non-GET 403 must stay text for save-queue.mjs, and a GET never reaches the 503 without a database stall (R3)"}, |
| - "errors.go:handlers.fail": {1, "the non-HTML half of the negotiated answer"}, |
| - "errors.go:handlers.errorPage": {1, "the error page itself could not render"}, |
| - "errors.go:handlers.methodNotAllowed": {1, "405 for a non-GET method, which no navigation sends"}, |
| - "errors.go:handlers.recoverToErrorPage": {1, "the non-HTML half of a recovered panic"}, |
| - "errors.go:App.ErrorPage": {1, "the non-HTML half of rastrillo's recovered panic"}, |
| - "handlers.go:handlers.updatesGet": {3, "the update log, fetched by the editor"}, |
| - "handlers.go:handlers.updatesPost": {9, "the update log, posted by the editor"}, |
| - "handlers.go:parseSince": {1, "the update log's cursor"}, |
| - "home_local_navigation.go:localLinkNavigation.guard": {1, "405 for a non-GET method"}, |
| - "home_local_navigation.go:localLinkNavigation.Begin": {1, "Home link start, sealing failure (R3: moves with home/connect)"}, |
| - "home_render.go:renderer.homeLinkBack": {1, "the page itself could not render"}, |
| - "home_routes.go:homeCSRF": {1, "unknown Host: not a page anyone navigates to"}, |
| - "identity.go:identityResolver.middleware": {1, "shared guard in front of page and fetch routes (R3)"}, |
| - "identity.go:refuseIdentity": {1, "non-GET refusal; a GET redirects to sign-in"}, |
| - "native.go:nativeJSON": {1, "native API JSON"}, |
| - "native.go:handlers.nativeList": {2, "native API JSON"}, |
| - "search.go:handlers.searchJSON": {3, "jump-to palette JSON"}, |
| - "stream.go:handlers.stream": {7, "live update stream"}, |
| - "team_access.go:teamRuntime.admission": {1, "shared guard, identity missing: a wiring failure, not a page state"}, |
| - "team_emission.go:writeGuardedBody": {1, "response already guarded"}, |
| + "app.go:New": {1, "live stream re-check: an EventSource, never a page"}, |
| + "assets.go:serveIcon": {1, "static asset 404"}, |
| + "assets.go:serveBundle": {1, "static asset 404"}, |
| + "auth.go:requireAdmissionOf": {2, "shared guard in front of page and fetch routes; its non-GET 403 must stay text for save-queue.mjs, and a GET never reaches the 503 without a database stall (R3)"}, |
| + "errors.go:handlers.fail": {1, "the non-HTML half of the negotiated answer"}, |
| + "errors.go:handlers.errorPage": {1, "the error page itself could not render"}, |
| + "errors.go:handlers.methodNotAllowed": {1, "405 for a non-GET method, which no navigation sends"}, |
| + "errors.go:handlers.recoverToErrorPage": {1, "the non-HTML half of a recovered panic"}, |
| + "errors.go:App.ErrorPage": {1, "the non-HTML half of rastrillo's recovered panic"}, |
| + "handlers.go:handlers.updatesGet": {3, "the update log, fetched by the editor"}, |
| + "handlers.go:handlers.updatesPost": {9, "the update log, posted by the editor"}, |
| + "handlers.go:parseSince": {1, "the update log's cursor"}, |
| + "home_return.go:returnMemory.guard": {1, "405 for a non-GET method"}, |
| + "home_connect.go:homeRoutes.render": {1, "connect's page before the handlers exist: unreachable once New returns"}, |
| + "home_render.go:renderer.homeLinkBack": {1, "the page itself could not render"}, |
| + "identity.go:identityResolver.middleware": {1, "shared guard in front of page and fetch routes (R3)"}, |
| + "identity.go:refuseIdentity": {1, "non-GET refusal; a GET redirects to sign-in"}, |
| + "native.go:nativeJSON": {1, "native API JSON"}, |
| + "native.go:handlers.nativeList": {2, "native API JSON"}, |
| + "search.go:handlers.searchJSON": {3, "jump-to palette JSON"}, |
| + "stream.go:handlers.stream": {7, "live update stream"}, |
| + "team_access.go:teamRuntime.admission": {1, "shared guard, identity missing: a wiring failure, not a page state"}, |
| + "team_emission.go:writeGuardedBody": {1, "response already guarded"}, |
| } |
| got := httpErrorSites(t) |
| var problems []string |
diff --git a/internal/docs/home_config.go b/internal/docs/home_config.go| index 796a0fd..bf6b67b 100644 |
| --- a/internal/docs/home_config.go |
| +++ b/internal/docs/home_config.go |
| @@ -100,8 +100,9 @@ var errDirectoryConfig = errors.New("docs: invalid $HOME_DIRECTORY_ORIGIN") |
| // links to, by Home's own originHost rules (home internal/home/origins.go): |
| // https, a lower-case DNS name of at least two labels, no IP address, no |
| // port, userinfo, path, query or fragment. Empty is allowed and means no |
| -// switcher. Docs reads it itself because it is not on home/connect, where |
| -// it would be connect.Credentials.Directory (spec §6.2); that move is R3. |
| +// switcher. Docs reads it itself rather than through |
| +// connect.Credentials.Directory (spec §6.2), as it reads the rest of its |
| +// Home configuration; moving the configuration onto connect is R3. |
| func validatedDirectory(origin string) (string, error) { |
| if origin == "" { |
| return "", nil |
diff --git a/internal/docs/home_connect.go b/internal/docs/home_connect.go| new file mode 100644 |
| index 0000000..7490a50 |
| --- /dev/null |
| +++ b/internal/docs/home_connect.go |
| @@ -0,0 +1,415 @@ |
| +package docs |
| + |
| +// Docs on Home's shared account connection, home/connect. |
| +// |
| +// connect owns the Home exchange (Start, Callback, Finish), the link flow |
| +// (local reauthentication, a fresh Home assertion, an explicit confirm), |
| +// the sealed navigation that resumes a link after a local sign-in, and the |
| +// link table, home_identity_links. Docs supplies its people, its sessions |
| +// and its pages, and in team mode the Unlinked and HomeOnly hooks over |
| +// principalstore (team_access.go's roster decides standing on every |
| +// request; the hooks only decide who a Home subject is). |
| +// |
| +// What stays Docs' own, and why: |
| +// - GET /signin skips the form only for a session the signed-in routes |
| +// would admit (h.handlers.admitted), not merely one that exists, or a |
| +// guest whose last share was revoked loops between / and /signin |
| +// (Astra, #65). |
| +// - A local sign-in lands on the page it began from (spec §9.4). connect |
| +// lands it on LocalLandingPath, so Docs keeps its own sealed return |
| +// memory (home_return.go) beside connect's and substitutes it there. |
| +// - The pages are Docs' (home_render.go), in Docs' catalog. |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "encoding/base64" |
| + "errors" |
| + "net/http" |
| + "net/url" |
| + |
| + "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/home/teammode" |
| + "amadan.net/rastrillo/rastrillo" |
| + rauth "amadan.net/rastrillo/rastrillo/auth" |
| + "amadan.net/rastrillo/rastrillo/csrf" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + "github.com/carlosframework/docs/internal/docs/principalstore" |
| + "github.com/go-chi/chi/v5" |
| + "gorm.io/gorm" |
| +) |
| + |
| +// homeNamespace seals connect's handoff and link state, Docs' return |
| +// memory and the roster evidence. It is the namespace Docs' own bridge |
| +// used, so pending handoff rows survive the move onto connect. |
| +const homeNamespace = "oficina/docs" |
| + |
| +// homeRoutes is Docs' side of home/connect. |
| +type homeRoutes struct { |
| + bridge *connect.Bridge |
| + // routes is connect's navigation and route handlers, built by mount |
| + // once the handlers exist. |
| + routes *connect.Routes |
| + // sessions is rastrillo's session store, the one rastrillo/auth uses: |
| + // the same cookie and the same rows, so sessions minted before Docs |
| + // moved onto connect are still read (mount checks the cookie name). |
| + sessions *sessions.Sessions |
| + sessionCookie string |
| + issuer string |
| + origin string |
| + dek []byte |
| + resolver identityResolver |
| + // returns is the page a sign-in began from, for the local landing and |
| + // "Use a different address" (home_return.go). |
| + returns *returnMemory |
| + // team is set after the move, in team mode only; the hooks read it. |
| + team *teamRuntime |
| + // handlers is set by mount; render reads it. |
| + handlers *handlers |
| +} |
| + |
| +// newHome builds connect's Bridge over Docs' people and sessions. New calls |
| +// it after the migrations and before the link move (home_links_move.go), |
| +// the team runtime and the handlers, so the pages and the team hooks are |
| +// bound late; no request is served before mount. |
| +func newHome(settings *homeSettings, origin string, db *sql.DB, store *Store, team bool) (*homeRoutes, error) { |
| + if settings == nil || db == nil || store == nil { |
| + return nil, errHomeConfig |
| + } |
| + sess, err := sessions.New(sessions.Config{DB: db, Origin: origin}) |
| + if err != nil { |
| + return nil, errHomeConfig |
| + } |
| + sealer, err := seal.New(settings.dek, homeNamespace) |
| + if err != nil { |
| + return nil, errHomeConfig |
| + } |
| + returns := newReturnMemory(sealer, origin) |
| + if returns == nil { |
| + return nil, errHomeConfig |
| + } |
| + h := &homeRoutes{sessions: sess, sessionCookie: sess.CookieName(), issuer: settings.issuer, origin: origin, dek: settings.dek, returns: returns} |
| + cfg := connect.Config{ |
| + DB: db, Origin: origin, Issuer: settings.issuer, ConsumerID: settings.consumerID, Namespace: homeNamespace, |
| + Keys: settings.keys, DEK: settings.dek, SessionCookie: h.sessionCookie, |
| + ReadSession: h.readSession, |
| + MintHomeSession: func(w http.ResponseWriter, r *http.Request, s connect.Session) error { |
| + return sess.SignIn(w, r, sessions.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime}) |
| + }, |
| + LookupPerson: linkedAddress, |
| + LookupLocalSession: localPerson(store), |
| + Render: h.render, |
| + } |
| + if team { |
| + // Team mode only. With both nil, connect refuses a Home subject with |
| + // no link as "unknown", as Docs always has outside team mode. |
| + cfg.HomeOnly, cfg.Unlinked = h.homeOnly, h.unlinked |
| + } |
| + if h.bridge, err = connect.New(cfg); err != nil { |
| + return nil, errHomeConfig |
| + } |
| + h.resolver = identityResolver{store: store, issuer: settings.issuer, links: h.bridge} |
| + return h, nil |
| +} |
| + |
| +// mount builds connect's routes once the handlers exist. rastrillo/auth's |
| +// cookie must be the session store's, or a local sign-in would mint a |
| +// session connect cannot read. |
| +func (h *homeRoutes) mount(handlers *handlers, auth *rauth.Auth) error { |
| + if handlers == nil || auth == nil || auth.SessionCookie() != h.sessionCookie { |
| + return errHomeConfig |
| + } |
| + routes, err := connect.NewRoutes(h.bridge, connect.RoutesConfig{ |
| + LocalLandingPath: "/", Namespace: homeNamespace, Origin: h.origin, Issuer: h.issuer, SessionCookie: h.sessionCookie, |
| + FormPolicy: homeFormPolicy(h.issuer), DEK: h.dek, ReadSession: h.readSession, SignOut: h.sessions.SignOut, |
| + LocalSignin: handlers.signin, Protect: csrf.Protect(h.origin), Render: h.render, |
| + }) |
| + if err != nil { |
| + return errHomeConfig |
| + } |
| + h.routes, h.handlers = routes, handlers |
| + return nil |
| +} |
| + |
| +// readSession is the actual cookie-backed session, never a supplied one. |
| +func (h *homeRoutes) readSession(r *http.Request) (*connect.Session, error) { |
| + s, ok := h.sessions.From(r) |
| + if !ok { |
| + return nil, nil |
| + } |
| + return &connect.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime, At: s.At}, nil |
| +} |
| + |
| +// linkedAddress is connect's LookupPerson: a person's address, read through |
| +// q (connect's transaction when it has one). It is a plain read of people, |
| +// as Docs' own link store's was. It never consults the roster or the |
| +// allowlist: a link names who somebody is, and admission is asked on every |
| +// request. A roster-consulting lookup would also refuse every member's |
| +// link at boot, while the roster is still Unknown (Fable, oficina/home #99 |
| +// note 9), and the move would abort. |
| +func linkedAddress(ctx context.Context, q linkstore.Queryer, id int64) (string, error) { |
| + if id <= 0 { |
| + return "", sql.ErrNoRows |
| + } |
| + var email string |
| + if err := q.QueryRowContext(ctx, "SELECT email FROM people WHERE id = ?", id).Scan(&email); err != nil { |
| + return "", err |
| + } |
| + if email == "" { |
| + return "", sql.ErrNoRows |
| + } |
| + return email, nil |
| +} |
| + |
| +// localPerson is connect's LookupLocalSession: the existing person a local |
| +// (magic link or Keymail) session's verified address names. It never |
| +// creates one; resolve's EnsurePerson does that, on the signed-in routes. |
| +func localPerson(store *Store) func(context.Context, connect.Session) (connect.Person, error) { |
| + return func(ctx context.Context, s connect.Session) (connect.Person, error) { |
| + var person Person |
| + err := store.db.WithContext(ctx).Where("email = ?", subjectOf(s.Subject)).First(&person).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return connect.Person{}, errIdentityRefused |
| + } |
| + if err != nil { |
| + return connect.Person{}, errIdentityStorage |
| + } |
| + if person.ID <= 0 || subjectOf(person.Email) == "" { |
| + return connect.Person{}, errIdentityRefused |
| + } |
| + return connect.Person{ID: person.ID, Label: person.Email}, nil |
| + } |
| +} |
| + |
| +// homeOnly is connect's HomeOnly: the Home-only principal unlinked gave a |
| +// subject, read and never created. connect asks it only after the link |
| +// table refused the subject, so a principal principalstore resolves |
| +// through a link row (one whose binding connect no longer accepts) is not |
| +// one: answering with it would sign the subject in as that local account. |
| +func (h *homeRoutes) homeOnly(ctx context.Context, issuer, subject string) (connect.Person, error) { |
| + t := h.team |
| + if t == nil { |
| + return connect.Person{}, errTeamUnavailable |
| + } |
| + p, err := t.principals.Resolve(ctx, issuer, subject) |
| + switch { |
| + case errors.Is(err, principalstore.ErrRefused): |
| + return connect.Person{}, connect.ErrNoPerson |
| + case err != nil: |
| + return connect.Person{}, errTeamUnavailable |
| + case p.Kind != principalstore.Home: |
| + return connect.Person{}, connect.ErrNoPerson |
| + } |
| + return connect.Person{ID: p.ID}, nil |
| +} |
| + |
| +// unlinked is connect's Unlinked, asked only when nobody is signed in here |
| +// and the subject has neither a link nor a Home-only principal. It creates |
| +// one only for a subject the roster says is a Member now, under a valid |
| +// lease (Runtime.AdmitUnlinked). principalstore's EnsureHome asks the same |
| +// gate again inside (RequireMembership), so the allocation condition holds |
| +// for every caller of EnsureHome, not only this one. A stranger is |
| +// connect's "unknown"; an undecidable roster is a 503. |
| +func (h *homeRoutes) unlinked(ctx context.Context, issuer, subject string) (connect.Person, error) { |
| + t := h.team |
| + if t == nil { |
| + return connect.Person{}, errTeamUnavailable |
| + } |
| + if err := t.cache.AdmitUnlinked(ctx, issuer, subject); err != nil { |
| + if errors.Is(err, teammode.ErrNotMember) { |
| + return connect.Person{}, connect.ErrNoPerson |
| + } |
| + return connect.Person{}, errTeamUnavailable |
| + } |
| + p, err := t.principals.EnsureHome(ctx, principalstore.HomeIdentity{Issuer: issuer, Subject: subject}) |
| + switch { |
| + case errors.Is(err, principalstore.ErrRefused): |
| + // Not a member after all, or linked to a local account in the |
| + // meantime: that person signs in as that account, not a new one. |
| + return connect.Person{}, connect.ErrNoPerson |
| + case err != nil: |
| + return connect.Person{}, errTeamUnavailable |
| + } |
| + return connect.Person{ID: p.ID}, nil |
| +} |
| + |
| +// render draws connect's states as Docs' own pages. |
| +func (h *homeRoutes) render(w http.ResponseWriter, r *http.Request, state, label string, status int) { |
| + if h.handlers == nil { |
| + w.Header().Set("Cache-Control", "no-store") |
| + http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusServiceUnavailable) |
| + return |
| + } |
| + back := "" |
| + if state == "success" { |
| + // The page the link began from, as connect validated it. |
| + back = connect.PageFor(r, state, label).Action |
| + } |
| + h.handlers.render.homeLinkBack(w, r, state, label, back, status) |
| +} |
| + |
| +func (h *homeRoutes) mountPublic(r chi.Router) { |
| + r.Get("/signin", h.signin) |
| + r.Get("/signed-out", h.routes.SignedOut) |
| + r.Get("/signin/local", h.handlers.signin) |
| + r.Get(localLinkCompletePath, h.localComplete) |
| + r.Get(handoff.StartPath, h.bridge.Start) |
| + r.Post(handoff.CallbackPath, h.bridge.Callback) |
| + r.Get(handoff.FinishPath, h.bridge.Finish) |
| +} |
| + |
| +// mountAccount is connecting an Oficina account: connect's link flow, |
| +// behind the caller's session, identity and admission middleware. Linking |
| +// needs a local sign-in no older than five minutes (connect.FreshLocal, |
| +// the rule Docs' own bridge had); without one, GET /account/home sends the |
| +// person to sign in locally first. |
| +func (h *homeRoutes) mountAccount(r chi.Router) { |
| + r.Get("/account/home", h.routes.Account) |
| + r.Post("/account/home", h.routes.LinkStart) |
| + r.Get("/account/home/confirm", h.bridge.ConfirmPage) |
| + r.Post("/account/home/confirm", h.routes.ConfirmPost) |
| +} |
| + |
| +// signin is GET /signin with Home configured. |
| +func (h *homeRoutes) signin(w http.ResponseWriter, r *http.Request) { |
| + q, err := url.ParseQuery(r.URL.RawQuery) |
| + if err != nil { |
| + h.render(w, r, "failed", "", http.StatusBadRequest) |
| + return |
| + } |
| + // These are outcomes from the existing local email flow. Keep its form |
| + // available even when the browser already has a Home session. |
| + if q.Has("sent") || q.Has("err") || q.Has("force") { |
| + h.handlers.signin(w, r) |
| + return |
| + } |
| + // Already signed in to Docs: straight back, with no form and no new |
| + // Home exchange (spec §9.2). Admitted, not merely holding a session: a |
| + // refused identity must be able to reach sign-in, or the guard and |
| + // this shortcut redirect to each other forever (h.handlers.admitted). |
| + _, signedIn := h.sessions.From(r) |
| + if signedIn && h.handlers.admitted(r) { |
| + alreadySignedIn(w, r) |
| + return |
| + } |
| + path, ok := requestedReturn(r) |
| + if !ok { |
| + path = "/" |
| + } |
| + if !h.returns.rememberReturn(w, path) { |
| + h.render(w, r, "failed", "", http.StatusServiceUnavailable) |
| + return |
| + } |
| + // connect remembers the page for the link flow and starts the Home |
| + // exchange. Its own shortcut skips to the page for any live session, |
| + // which for a session admission refuses is the loop above, so it is |
| + // not shown that one. |
| + if signedIn { |
| + r = withoutCookie(r, h.sessionCookie) |
| + } |
| + h.routes.Signin(w, r) |
| +} |
| + |
| +// localComplete is where a local sign-in lands. connect resumes a link from |
| +// here, or goes to /account/home; otherwise it lands on "/", and Docs lands |
| +// on the page the sign-in began from instead, as it always has. |
| +func (h *homeRoutes) localComplete(w http.ResponseWriter, r *http.Request) { |
| + rec := &signinResponse{header: make(http.Header)} |
| + h.routes.LocalComplete(rec, r) |
| + if rec.status == http.StatusSeeOther && rec.header.Get("Location") == "/" { |
| + rec.header.Set("Location", h.returns.returnPath(r)) |
| + } |
| + rec.replay(w) |
| +} |
| + |
| +// signout is connect's, which ends the session, clears the hand-off |
| +// cookies and chains to {issuer}/signout (spec shared-chrome §9.5), plus |
| +// Docs' own return memory. |
| +func (h *homeRoutes) signout(w http.ResponseWriter, r *http.Request) { |
| + localNavigationCookie(w, homeReturnCookie, "", -1) |
| + h.routes.Signout(w, r) |
| +} |
| + |
| +// Only the assertion callback crosses origins (connect's Middleware). |
| +func homeCSRF(origin string, home *homeRoutes) func(http.Handler) http.Handler { |
| + if home == nil { |
| + return csrf.Protect(origin) |
| + } |
| + return home.routes.Middleware |
| +} |
| + |
| +// The local plugin resolves the first pending cookie, so reject ambiguity |
| +// before it can verify a gesture or rotate the existing session. |
| +func localAuthGuard(home *homeRoutes, next http.HandlerFunc) http.HandlerFunc { |
| + if home == nil { |
| + return next |
| + } |
| + return home.routes.LocalGuard(next) |
| +} |
| + |
| +// homeLinkLabel is the account menu's "Connect your Oficina account", or "" |
| +// when there is nothing to connect: offered only to a local person with no |
| +// stored link, whichever way this session signed in. Before, it was offered |
| +// to every session that had not come from a Home assertion, so a linked |
| +// person who used the email link still saw it (Paul, as paul@tito.io). |
| +// A team instance already resolved the link with the identity; otherwise |
| +// it is one indexed lookup per menu render. Not knowing offers nothing. |
| +func (h *handlers) homeLinkLabel(r *http.Request) string { |
| + if !h.homeEnabled || h.homeLinked == nil { |
| + return "" |
| + } |
| + id, ok := currentIdentity(r) |
| + if !ok || id.Session.Method == homeAssertionMethod || id.HomeSubject != "" { |
| + return "" |
| + } |
| + if linked, err := h.homeLinked(r.Context(), id.Actor.PersonID); err != nil || linked { |
| + return "" |
| + } |
| + return rastrillo.T(r, "docs.home.menu_action") |
| +} |
| + |
| +func cookieCount(r *http.Request, name string) int { |
| + n := 0 |
| + for _, c := range r.Cookies() { |
| + if c.Name == name { |
| + n++ |
| + } |
| + } |
| + return n |
| +} |
| + |
| +// homeCookie distinguishes absent cookies from malformed or duplicate values. |
| +// Neither a duplicate nor an invalid cookie may select ordinary sign-in. |
| +func homeCookie(r *http.Request, name string) (value string, present, valid bool) { |
| + count := 0 |
| + for _, c := range r.Cookies() { |
| + if c.Name == name { |
| + count++ |
| + value = c.Value |
| + } |
| + } |
| + if count == 0 { |
| + return "", false, true |
| + } |
| + if count != 1 || len(value) != 43 { |
| + return "", true, false |
| + } |
| + raw, err := base64.RawURLEncoding.Strict().DecodeString(value) |
| + return value, true, err == nil && len(raw) == 32 && base64.RawURLEncoding.EncodeToString(raw) == value |
| +} |
| + |
| +// withoutCookie is r, as seen by a handler that must not see the named |
| +// cookie. Only Docs' /signin uses it, on connect's Signin. |
| +func withoutCookie(r *http.Request, name string) *http.Request { |
| + c := r.Clone(r.Context()) |
| + c.Header.Del("Cookie") |
| + for _, cookie := range r.Cookies() { |
| + if cookie.Name != name { |
| + c.AddCookie(cookie) |
| + } |
| + } |
| + return c |
| +} |
diff --git a/internal/docs/home_connect_linked_test.go b/internal/docs/home_connect_linked_test.go| index ddd78dc..f27f631 100644 |
| --- a/internal/docs/home_connect_linked_test.go |
| +++ b/internal/docs/home_connect_linked_test.go |
| @@ -1,14 +1,13 @@ |
| package docs |
| import ( |
| - "net/http" |
| "net/http/httptest" |
| + "net/url" |
| "strings" |
| "testing" |
| "time" |
| "amadan.net/rastrillo/rastrillo" |
| - "amadan.net/rastrillo/rastrillo/sessions" |
| ) |
| const connectItem = `href="/account/home"` |
| @@ -45,7 +44,7 @@ func TestHomeMenuOffersConnectOnlyWithoutAStoredLink(t *testing.T) { |
| } |
| b.linkProof(t, "opaque-alice", "alice@example.com") |
| b.confirmLink(t, "/") |
| - if routerRows(t, f, "docs_identity_links") != 1 { |
| + if routerRows(t, f, "home_identity_links") != 1 { |
| t.Fatal("Connect accounts did not store the link") |
| } |
| if b.menuOffersConnect(t) { |
| @@ -105,7 +104,7 @@ func TestHomeUnknownArrivalResumesLinkAfterLocalSignIn(t *testing.T) { |
| } |
| nonce = b.start(t, next, "300") |
| routerRedirect(t, b.exchange(t, nonce, "opaque-alice", time.Now().Add(-time.Minute)), "/account/home/confirm") |
| - if routerRows(t, f, "docs_identity_links") != 0 { |
| + if routerRows(t, f, "home_identity_links") != 0 { |
| t.Fatal("linked before the explicit confirm") |
| } |
| confirm := b.do("GET", "/account/home/confirm", "") |
| @@ -113,66 +112,11 @@ func TestHomeUnknownArrivalResumesLinkAfterLocalSignIn(t *testing.T) { |
| t.Fatalf("confirm step not shown: %d", confirm.Code) |
| } |
| b.confirmLink(t, "/") |
| - if routerRows(t, f, "docs_identity_links") != 1 || b.menuOffersConnect(t) { |
| + if routerRows(t, f, "home_identity_links") != 1 || b.menuOffersConnect(t) { |
| t.Fatal("resumed link not stored, or the menu still offers it") |
| } |
| } |
| -// TestLocalNavigationUnknownMarkerExpiresToTheMenuPath: a remembered |
| -// arrival older than the marker is ignored, and the person lands as from |
| -// any sign-in, with the menu item still on offer. |
| -func TestLocalNavigationUnknownMarkerExpiresToTheMenuPath(t *testing.T) { |
| - app, n := navigationFixture(t) |
| - resumed := 0 |
| - n.resume = func(w http.ResponseWriter, r *http.Request) bool { |
| - resumed++ |
| - http.Redirect(w, r, "/resumed", http.StatusSeeOther) |
| - return true |
| - } |
| - now := time.Now().Truncate(time.Second) |
| - n.now = func() time.Time { return now } |
| - remember := httptest.NewRecorder() |
| - n.rememberUnknown(remember) |
| - var marker *http.Cookie |
| - for _, c := range remember.Result().Cookies() { |
| - if c.Name == localLinkNavigationCookie && c.MaxAge > 0 { |
| - marker = c |
| - } |
| - } |
| - if marker == nil { |
| - t.Fatal("unknown arrival not remembered") |
| - } |
| - session := navigationSession(t, n, sessions.Session{Subject: "local@example.com", Method: "magiclink"}) |
| - request := func() *http.Request { |
| - r := navigationRequest(localLinkCompletePath) |
| - r.AddCookie(marker) |
| - r.AddCookie(session) |
| - return r |
| - } |
| - assertNavigation(t, n, request(), "/resumed") |
| - later := now.Add(time.Duration(localLinkNavigationLifetime) * time.Second) |
| - n.now = func() time.Time { return later } |
| - // The local sign-in is fresh at the later time too, so only the |
| - // marker's own expiry can decide. |
| - if _, err := app.db.Writer().Exec(`UPDATE sessions SET created_at=? WHERE token_hash=?`, later.Add(-time.Minute).UTC().Format(time.RFC3339), sessions.HashToken(session.Value)); err != nil { |
| - t.Fatal(err) |
| - } |
| - n.resume = func(w http.ResponseWriter, r *http.Request) bool { |
| - resumed++ |
| - http.Redirect(w, r, "/resumed", http.StatusSeeOther) |
| - return true |
| - } |
| - menu := navigationMarker(t, n) |
| - r := navigationRequest(localLinkCompletePath) |
| - r.AddCookie(menu) |
| - r.AddCookie(session) |
| - assertNavigation(t, n, r, "/account/home") |
| - assertNavigation(t, n, request(), "/") |
| - if resumed != 1 { |
| - t.Fatal("expired marker resumed", resumed) |
| - } |
| -} |
| - |
| // TestHomeLinkActionsShareOneRow: Connect and Back to Docs sat stacked |
| // flush; they share the door's form-foot row, primary first. |
| func TestHomeLinkActionsShareOneRow(t *testing.T) { |
| @@ -186,3 +130,20 @@ func TestHomeLinkActionsShareOneRow(t *testing.T) { |
| t.Fatalf("actions are not one row with primary first:\n%s", html) |
| } |
| } |
| + |
| +// With Home, a deep link opened signed out and finished by a local |
| +// sign-in still lands on the deep link (spec §9.4). connect lands a local |
| +// sign-in on "/"; Docs puts its own remembered page there. |
| +func TestHomeLocalSignInReturnsToTheDeepLink(t *testing.T) { |
| + f := newRouterHomeFixture(t) |
| + owner := f.browser() |
| + owner.localSignin(t, "alice@example.com") |
| + deep := routerRedirect(t, owner.do("POST", "/documents", "title=Minutes"), "") + "?view=1" |
| + b := f.browser() |
| + signin := routerRedirect(t, b.do("GET", deep, ""), "/signin?return_to="+url.QueryEscape(deep)) |
| + routerRedirect(t, b.do("GET", signin, ""), "/auth/start?return_to="+url.QueryEscape(deep)) |
| + if b.cookies[homeReturnCookie] == nil || b.cookies[connectReturnCookie] == nil { |
| + t.Fatal("the deep link was not remembered for both landings") |
| + } |
| + b.localSignin(t, "alice@example.com", deep) |
| +} |
diff --git a/internal/docs/home_connect_test.go b/internal/docs/home_connect_test.go| new file mode 100644 |
| index 0000000..ea0a04c |
| --- /dev/null |
| +++ b/internal/docs/home_connect_test.go |
| @@ -0,0 +1,102 @@ |
| +package docs |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "testing" |
| + |
| + "amadan.net/oficina/home/handoff/seal" |
| + assertioncrypto "amadan.net/rastrillo/rastrillo/crypto" |
| +) |
| + |
| +const bridgeOrigin = "https://blue.docs.oficina.works" |
| +const bridgeIssuer = "https://id.oficina.works" |
| + |
| +// connect's cookies, as a browser holds them. |
| +const ( |
| + homeInitCookie = "__Host-oficina-home-init" |
| + homeProofCookie = "__Host-oficina-home-proof" |
| + localLinkNavigationCookie = "__Host-oficina-local-link-navigation" |
| + connectReturnCookie = "__Host-oficina-home-return" |
| +) |
| + |
| +// connectedURL is where connect sends a confirmed link: "Accounts |
| +// connected", with the page the link began from. |
| +func connectedURL(path string) string { |
| + return "/account/home/confirm?" + url.Values{"connected": {"1"}, "return_to": {path}}.Encode() |
| +} |
| + |
| +type navigationMail struct{} |
| + |
| +func (navigationMail) Send(context.Context, string, string, string) error { return nil } |
| + |
| +// homeFixture is Docs' side of connect (newHome) over a test App's database, |
| +// not mounted on its router. |
| +type homeFixture struct { |
| + h *homeRoutes |
| + app *App |
| + key *assertioncrypto.Keypair |
| +} |
| + |
| +func newBridgeFixture(t *testing.T) *homeFixture { |
| + t.Helper() |
| + app, err := NewForTestWith(t, Config{Origin: bridgeOrigin, SampleDocuments: "false"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + key, err := assertioncrypto.Generate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + settings := &homeSettings{issuer: bridgeIssuer, consumerID: "blue-docs", keys: map[string][]byte{"key": key.SignPub()}, dek: bytes.Repeat([]byte{41}, 32)} |
| + h, err := newHome(settings, bridgeOrigin, app.db.Writer(), app.store, false) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return &homeFixture{h: h, app: app, key: key} |
| +} |
| + |
| +func bridgeRequest(method, path string, cookies []*http.Cookie) *http.Request { |
| + r := httptest.NewRequest(method, bridgeOrigin+path, nil) |
| + for _, cookie := range cookies { |
| + r.AddCookie(cookie) |
| + } |
| + return r |
| +} |
| + |
| +func bridgeCookie(t *testing.T, w *httptest.ResponseRecorder, name string) *http.Cookie { |
| + t.Helper() |
| + for _, cookie := range w.Result().Cookies() { |
| + if cookie.Name == name && cookie.MaxAge >= 0 { |
| + if !cookie.Secure || !cookie.HttpOnly || cookie.Domain != "" || cookie.Path != "/" || cookie.SameSite != http.SameSiteLaxMode { |
| + t.Fatal("unsafe cookie attributes") |
| + } |
| + return cookie |
| + } |
| + } |
| + t.Fatalf("missing cookie %s; status=%d", name, w.Code) |
| + return nil |
| +} |
| + |
| +const navigationOrigin = "https://docs.example.com" |
| + |
| +// navigationFixture is Docs' return memory, sealed as a Home instance's is. |
| +func navigationFixture(t *testing.T) (*App, *returnMemory) { |
| + t.Helper() |
| + app, err := NewForTestWith(t, Config{Origin: navigationOrigin, SampleDocuments: "0", Mailer: navigationMail{}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + sealer, err := seal.New(bytes.Repeat([]byte{19}, 32), homeNamespace) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + n := newReturnMemory(sealer, navigationOrigin) |
| + if n == nil { |
| + t.Fatal("return memory refused") |
| + } |
| + return app, n |
| +} |
diff --git a/internal/docs/home_exchange.go b/internal/docs/home_exchange.go| deleted file mode 100644 |
| index 5bd4f71..0000000 |
| --- a/internal/docs/home_exchange.go |
| +++ /dev/null |
| @@ -1,314 +0,0 @@ |
| -package docs |
| - |
| -import ( |
| - "context" |
| - "database/sql" |
| - "encoding/base64" |
| - "errors" |
| - "net/http" |
| - "strings" |
| - "time" |
| - |
| - "amadan.net/oficina/home/handoff" |
| - "amadan.net/oficina/home/handoff/seal" |
| - "amadan.net/rastrillo/rastrillo/assertion" |
| - rauth "amadan.net/rastrillo/rastrillo/auth" |
| - "amadan.net/rastrillo/rastrillo/sessions" |
| - "github.com/carlosframework/docs/internal/docs/linkstore" |
| - "gorm.io/gorm" |
| -) |
| - |
| -const homeInitCookie = "__Host-docs-home-init" |
| -const homeProofCookie = "__Host-docs-home-proof" |
| - |
| -var errHomeBridge = errors.New("docs: Home exchange unavailable") |
| - |
| -type homeBridge struct { |
| - origin string |
| - sessionCookie string |
| - sessions *sessions.Sessions |
| - links *linkstore.Store |
| - resolver identityResolver |
| - ordinary, fresh *handoff.Consumer |
| - render *renderer |
| - store *Store |
| - now func() time.Time |
| - // returnPath reads separate sealed navigation state; it carries no identity. |
| - returnPath func(*http.Request) string |
| - // rememberUnknown leaves the sealed navigation marker that resumes |
| - // linking after the person signs in locally (newHomeRoutes). |
| - rememberUnknown func(http.ResponseWriter) |
| -} |
| -type homeFinishKey struct{} |
| -type homeFinishResult struct { |
| - session *sessions.Session |
| - init string |
| - state string |
| - status int |
| -} |
| - |
| -// Both subsystem schemas must be migrated before construction. The consumers |
| -// share one replay store; choosing a different Finish cannot weaken freshness. |
| -func newHomeBridge(settings *homeSettings, origin string, db *sql.DB, auth *rauth.Auth, render *renderer, store *Store) (*homeBridge, error) { |
| - if settings == nil || db == nil || auth == nil || render == nil || store == nil { |
| - return nil, errHomeBridge |
| - } |
| - sealer, err := seal.New(settings.dek, "oficina/docs") |
| - if err != nil { |
| - return nil, errHomeBridge |
| - } |
| - exchange, err := handoff.NewStore(db, sealer, settings.issuer, origin, settings.keys) |
| - if err != nil { |
| - return nil, errHomeBridge |
| - } |
| - linker, err := linkstore.New(db, settings.dek, origin, settings.issuer) |
| - if err != nil { |
| - return nil, errHomeBridge |
| - } |
| - sessionStore, err := sessions.New(sessions.Config{DB: db, Origin: origin}) |
| - if err != nil { |
| - return nil, errHomeBridge |
| - } |
| - if auth.SessionCookie() != sessionStore.CookieName() { |
| - return nil, errHomeBridge |
| - } |
| - b := &homeBridge{origin: origin, sessionCookie: auth.SessionCookie(), sessions: sessionStore, links: linker, render: render, store: store, now: time.Now} |
| - b.resolver = identityResolver{store: store, issuer: settings.issuer, linkedPerson: func(ctx context.Context, issuer, subject string) (int64, error) { |
| - id, _, err := linker.Resolve(ctx, issuer, subject) |
| - if errors.Is(err, linkstore.ErrRefused) { |
| - return 0, nil |
| - } |
| - if err != nil { |
| - return 0, errIdentityStorage |
| - } |
| - return id, nil |
| - }} |
| - cfg := handoff.ConsumerConfig{Store: exchange, ConsumerID: settings.consumerID, Complete: b.complete, Fail: b.fail, Now: func() time.Time { return b.now() }, CurrentSubject: func(r *http.Request) string { |
| - result, _ := r.Context().Value(homeFinishKey{}).(*homeFinishResult) |
| - if result != nil && result.session != nil && result.session.Method == homeAssertionMethod { |
| - return result.session.Subject |
| - } |
| - return "" |
| - }} |
| - b.ordinary, err = handoff.NewConsumer(cfg) |
| - if err != nil { |
| - return nil, errHomeBridge |
| - } |
| - cfg.RequireFreshAuth = true |
| - cfg.BindStart = func(r *http.Request, nonce string) error { |
| - secret, present, ok := homeCookie(r, homeInitCookie) |
| - if !present || !ok { |
| - return errIdentityRefused |
| - } |
| - local, _, err := b.localBinding(r) |
| - if err != nil { |
| - return err |
| - } |
| - return b.links.BindNonce(r.Context(), secret, local, nonce, b.now()) |
| - } |
| - b.fresh, err = handoff.NewConsumer(cfg) |
| - if err != nil { |
| - return nil, errHomeBridge |
| - } |
| - if exchange.Sweep(context.Background(), b.now()) != nil || linker.Sweep(context.Background(), b.now()) != nil { |
| - return nil, errHomeBridge |
| - } |
| - return b, nil |
| -} |
| - |
| -// homeCookie distinguishes absent cookies from malformed or duplicate values. |
| -// Neither a duplicate nor an invalid link cookie may select ordinary sign-in. |
| -func homeCookie(r *http.Request, name string) (value string, present, valid bool) { |
| - count := 0 |
| - for _, c := range r.Cookies() { |
| - if c.Name == name { |
| - count++ |
| - value = c.Value |
| - } |
| - } |
| - if count == 0 { |
| - return "", false, true |
| - } |
| - if count != 1 || len(value) != 43 { |
| - return "", true, false |
| - } |
| - raw, err := base64.RawURLEncoding.Strict().DecodeString(value) |
| - return value, true, err == nil && len(raw) == 32 && base64.RawURLEncoding.EncodeToString(raw) == value |
| -} |
| -func setHomeCookie(w http.ResponseWriter, name, value string, seconds int) { |
| - http.SetCookie(w, &http.Cookie{Name: name, Value: value, Path: "/", MaxAge: seconds, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode}) |
| -} |
| -func (b *homeBridge) actualSession(r *http.Request) (*sessions.Session, error) { |
| - _, present, ok := homeCookie(r, b.sessionCookie) |
| - if !ok { |
| - return nil, errIdentityRefused |
| - } |
| - if !present { |
| - return nil, nil |
| - } |
| - session, ok := b.sessions.From(r) |
| - if !ok { |
| - return nil, errIdentityRefused |
| - } |
| - return &session, nil |
| -} |
| -func (b *homeBridge) Start(w http.ResponseWriter, r *http.Request) { |
| - _, present, ok := homeCookie(r, homeInitCookie) |
| - if !ok { |
| - b.fail(w, r, http.StatusBadRequest) |
| - return |
| - } |
| - // Duplicate auth cookies must fail before a fresh hook or future mint. |
| - if _, err := b.actualSession(r); err != nil { |
| - b.fail(w, r, http.StatusForbidden) |
| - return |
| - } |
| - if present { |
| - b.fresh.Start(w, r) |
| - } else { |
| - b.ordinary.Start(w, r) |
| - } |
| -} |
| -func (b *homeBridge) Callback(w http.ResponseWriter, r *http.Request) { b.ordinary.Callback(w, r) } |
| -func (b *homeBridge) Finish(w http.ResponseWriter, r *http.Request) { |
| - init, _, ok := homeCookie(r, homeInitCookie) |
| - if !ok { |
| - b.fail(w, r, http.StatusBadRequest) |
| - return |
| - } |
| - _, _, ok = homeCookie(r, homeProofCookie) |
| - if !ok { |
| - b.fail(w, r, http.StatusBadRequest) |
| - return |
| - } |
| - session, err := b.actualSession(r) |
| - if err != nil { |
| - b.fail(w, r, http.StatusForbidden) |
| - return |
| - } |
| - result := &homeFinishResult{session: session, init: init} |
| - b.ordinary.Finish(w, r.WithContext(context.WithValue(r.Context(), homeFinishKey{}, result))) |
| -} |
| -func (b *homeBridge) fail(w http.ResponseWriter, r *http.Request, status int) { |
| - state := "failed" |
| - if result, ok := r.Context().Value(homeFinishKey{}).(*homeFinishResult); ok && result.state != "" { |
| - state, status = result.state, result.status |
| - } |
| - b.render.homeLink(w, r, state, "", status) |
| -} |
| -func rejectHome(r *http.Request, state string, status int) error { |
| - if result, ok := r.Context().Value(homeFinishKey{}).(*homeFinishResult); ok { |
| - result.state, result.status = state, status |
| - } |
| - return errIdentityRefused |
| -} |
| -func (b *homeBridge) complete(w http.ResponseWriter, r *http.Request, claims assertion.Claims) error { |
| - result, ok := r.Context().Value(homeFinishKey{}).(*homeFinishResult) |
| - if !ok { |
| - return errHomeBridge |
| - } |
| - if result.init != "" { |
| - setHomeCookie(w, homeInitCookie, "", -1) |
| - local, _, err := b.localBinding(r) |
| - if err != nil { |
| - return rejectHome(r, "failed", http.StatusForbidden) |
| - } |
| - secret, err := b.links.Complete(r.Context(), result.init, local, linkstore.Home{Issuer: claims.Issuer, Subject: claims.Subject, Nonce: claims.Nonce, AuthTime: time.Unix(claims.AuthTime, 0)}, b.now()) |
| - if errors.Is(err, linkstore.ErrRefused) { |
| - return rejectHome(r, "failed", http.StatusForbidden) |
| - } |
| - if err != nil { |
| - return errHomeBridge |
| - } |
| - setHomeCookie(w, homeProofCookie, secret, 300) |
| - return nil |
| - } |
| - if b.store.team != nil { |
| - if err := b.completeTeamPrincipal(r, claims, result.session); err != nil { |
| - return err |
| - } |
| - } else { |
| - id, _, err := b.links.Resolve(r.Context(), claims.Issuer, claims.Subject) |
| - if errors.Is(err, linkstore.ErrRefused) { |
| - if b.rememberUnknown != nil { |
| - b.rememberUnknown(w) |
| - } |
| - return rejectHome(r, "unknown", http.StatusForbidden) |
| - } |
| - if err != nil { |
| - return errHomeBridge |
| - } |
| - if result.session != nil { |
| - person, err := b.existingPerson(r, *result.session) |
| - if err != nil || person.ID != id { |
| - return rejectHome(r, "failed", http.StatusForbidden) |
| - } |
| - } |
| - } |
| - if err := b.sessions.SignIn(w, r, sessions.Session{Subject: claims.Subject, Method: homeAssertionMethod, AuthTime: time.Unix(claims.AuthTime, 0)}); err != nil { |
| - return errHomeBridge |
| - } |
| - return nil |
| -} |
| - |
| -// existingPerson never creates a person or samples, even during ordinary SSO. |
| -func (b *homeBridge) existingPerson(r *http.Request, session sessions.Session) (Person, error) { |
| - var person Person |
| - if session.Method == homeAssertionMethod { |
| - id, _, err := b.links.Resolve(r.Context(), b.resolver.issuer, session.Subject) |
| - if err != nil { |
| - return person, errIdentityRefused |
| - } |
| - if err := b.store.db.WithContext(r.Context()).First(&person, id).Error; err != nil { |
| - return Person{}, errIdentityRefused |
| - } |
| - } else { |
| - if session.Method != "magiclink" && session.Method != "keymail" { |
| - return person, errIdentityRefused |
| - } |
| - err := b.store.db.WithContext(r.Context()).Where("email = ?", subjectOf(session.Subject)).First(&person).Error |
| - if errors.Is(err, gorm.ErrRecordNotFound) { |
| - return Person{}, errIdentityRefused |
| - } |
| - if err != nil { |
| - return Person{}, errIdentityStorage |
| - } |
| - } |
| - if person.ID <= 0 || subjectOf(person.Email) == "" { |
| - return Person{}, errIdentityRefused |
| - } |
| - return person, nil |
| -} |
| -func (b *homeBridge) localBinding(r *http.Request) (linkstore.Local, Person, error) { |
| - session, err := b.actualSession(r) |
| - if err != nil || session == nil { |
| - return linkstore.Local{}, Person{}, errIdentityRefused |
| - } |
| - at, fresh := freshLocalAuthentication(*session, b.now()) |
| - if !fresh { |
| - return linkstore.Local{}, Person{}, errIdentityRefused |
| - } |
| - person, err := b.existingPerson(r, *session) |
| - if err != nil { |
| - return linkstore.Local{}, Person{}, err |
| - } |
| - token, _, _ := homeCookie(r, b.sessionCookie) |
| - return linkstore.Local{PersonID: person.ID, SessionToken: token, AuthTime: at}, person, nil |
| -} |
| -func (b *homeBridge) guard(w http.ResponseWriter, r *http.Request, method, path string) bool { |
| - w.Header().Set("Cache-Control", "no-store") |
| - if r.Host != strings.TrimPrefix(b.origin, "https://") || r.URL.Path != path { |
| - b.fail(w, r, http.StatusNotFound) |
| - return false |
| - } |
| - if r.Method != method { |
| - w.Header().Set("Allow", method) |
| - b.fail(w, r, http.StatusMethodNotAllowed) |
| - return false |
| - } |
| - if r.URL.RawQuery != "" { |
| - b.fail(w, r, http.StatusBadRequest) |
| - return false |
| - } |
| - return true |
| -} |
diff --git a/internal/docs/home_exchange_test.go b/internal/docs/home_exchange_test.go| deleted file mode 100644 |
| index f60d295..0000000 |
| --- a/internal/docs/home_exchange_test.go |
| +++ /dev/null |
| @@ -1,437 +0,0 @@ |
| -package docs |
| - |
| -import ( |
| - "bytes" |
| - "context" |
| - "net/http" |
| - "net/http/httptest" |
| - "net/url" |
| - "strings" |
| - "testing" |
| - "time" |
| - |
| - "amadan.net/oficina/home/handoff" |
| - "amadan.net/rastrillo/rastrillo/assertion" |
| - rauth "amadan.net/rastrillo/rastrillo/auth" |
| - assertioncrypto "amadan.net/rastrillo/rastrillo/crypto" |
| - "amadan.net/rastrillo/rastrillo/csrf" |
| - "amadan.net/rastrillo/rastrillo/migrate" |
| - "amadan.net/rastrillo/rastrillo/sessions" |
| - "github.com/carlosframework/docs/internal/docs/linkstore" |
| -) |
| - |
| -const bridgeOrigin = "https://blue.docs.oficina.works" |
| -const bridgeIssuer = "https://id.oficina.works" |
| - |
| -type bridgeFixture struct { |
| - b *homeBridge |
| - app *App |
| - key *assertioncrypto.Keypair |
| -} |
| - |
| -func newBridgeFixture(t *testing.T) *bridgeFixture { |
| - t.Helper() |
| - app, err := NewForTestWith(t, Config{Origin: bridgeOrigin, SampleDocuments: "false"}) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - schema := migrate.Merge(linkstore.Schema, migrate.MustFromFS(handoff.Migrations, "oficina_handoff")) |
| - if _, err := migrate.Apply(context.Background(), app.db, schema); err != nil { |
| - t.Fatal(err) |
| - } |
| - key, err := assertioncrypto.Generate() |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - settings := &homeSettings{issuer: bridgeIssuer, consumerID: "blue-docs", keys: map[string][]byte{"key": key.SignPub()}, dek: bytes.Repeat([]byte{41}, 32)} |
| - auth, err := rauth.New(rauth.Config{DB: app.db.Writer(), Origin: bridgeOrigin, InstanceKey: devInstanceKey, Logger: app.logger, ProofOff: true}) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - b, err := newHomeBridge(settings, bridgeOrigin, app.db.Writer(), auth, app.handlers.render, app.store) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - return &bridgeFixture{b: b, app: app, key: key} |
| -} |
| -func bridgeRequest(method, path string, cookies []*http.Cookie) *http.Request { |
| - r := httptest.NewRequest(method, bridgeOrigin+path, nil) |
| - for _, cookie := range cookies { |
| - r.AddCookie(cookie) |
| - } |
| - return r |
| -} |
| -func bridgeCookie(t *testing.T, w *httptest.ResponseRecorder, name string) *http.Cookie { |
| - t.Helper() |
| - for _, cookie := range w.Result().Cookies() { |
| - if cookie.Name == name && cookie.MaxAge >= 0 { |
| - if !cookie.Secure || !cookie.HttpOnly || cookie.Domain != "" || cookie.Path != "/" || cookie.SameSite != http.SameSiteLaxMode { |
| - t.Fatal("unsafe cookie attributes") |
| - } |
| - return cookie |
| - } |
| - } |
| - t.Fatalf("missing cookie %s; status=%d", name, w.Code) |
| - return nil |
| -} |
| -func bridgeNoSession(t *testing.T, b *homeBridge, w *httptest.ResponseRecorder) { |
| - t.Helper() |
| - for _, c := range w.Result().Cookies() { |
| - if c.Name == b.sessionCookie { |
| - t.Fatal("unexpected app session mutation") |
| - } |
| - } |
| -} |
| -func (f *bridgeFixture) local(t *testing.T, address, method string, authTime time.Time) *http.Cookie { |
| - t.Helper() |
| - if _, err := f.app.store.EnsurePerson(context.Background(), address); err != nil { |
| - t.Fatal(err) |
| - } |
| - token, err := f.b.sessions.Mint(sessions.Session{Subject: address, Method: method, AuthTime: authTime}) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - return &http.Cookie{Name: f.b.sessionCookie, Value: token} |
| -} |
| -func (f *bridgeFixture) start(t *testing.T, cookies []*http.Cookie, path string) (*http.Cookie, string) { |
| - t.Helper() |
| - w := httptest.NewRecorder() |
| - f.b.Start(w, bridgeRequest(http.MethodGet, "/auth/start?return_to="+url.QueryEscape(path), cookies)) |
| - if w.Code != 303 { |
| - t.Fatalf("start=%d body=%s", w.Code, w.Body.String()) |
| - } |
| - target, err := url.Parse(w.Header().Get("Location")) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - return bridgeCookie(t, w, "__Host-oficina-assertion-pending"), target.Query().Get("nonce") |
| -} |
| -func (f *bridgeFixture) callback(t *testing.T, subject, nonce string, authTime time.Time) *http.Cookie { |
| - t.Helper() |
| - now := time.Now().Unix() |
| - id, err := assertion.RandomID() |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - token, err := assertion.Sign(f.key, assertion.Claims{Version: 1, Issuer: bridgeIssuer, Audience: bridgeOrigin, Subject: subject, KeyID: "key", ID: id, Nonce: nonce, IssuedAt: now, ExpiresAt: now + 90, AuthTime: authTime.Unix()}) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - form := url.Values{"assertion": {token}} |
| - r := httptest.NewRequest(http.MethodPost, bridgeOrigin+"/auth/assertion", strings.NewReader(form.Encode())) |
| - r.Header.Set("Origin", bridgeIssuer) |
| - r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| - w := httptest.NewRecorder() |
| - f.b.Callback(w, r) |
| - if w.Code != 303 { |
| - t.Fatalf("callback=%d", w.Code) |
| - } |
| - bridgeNoSession(t, f.b, w) |
| - return bridgeCookie(t, w, "__Host-oficina-assertion-inbox") |
| -} |
| -func (f *bridgeFixture) linkProof(t *testing.T, local *http.Cookie, subject string) (*http.Cookie, []*http.Cookie) { |
| - t.Helper() |
| - w := httptest.NewRecorder() |
| - f.b.LinkStart(w, bridgeRequest(http.MethodPost, "/account/home", []*http.Cookie{local})) |
| - if w.Code != 303 { |
| - t.Fatalf("link start=%d", w.Code) |
| - } |
| - init := bridgeCookie(t, w, homeInitCookie) |
| - cookies := []*http.Cookie{local, init} |
| - start := httptest.NewRecorder() |
| - f.b.Start(start, bridgeRequest(http.MethodGet, w.Header().Get("Location"), cookies)) |
| - if start.Code != 303 { |
| - t.Fatalf("fresh start=%d", start.Code) |
| - } |
| - target, _ := url.Parse(start.Header().Get("Location")) |
| - if target.Query().Get("max_age") != "300" { |
| - t.Fatal("link exchange did not request fresh authentication") |
| - } |
| - pending := bridgeCookie(t, start, "__Host-oficina-assertion-pending") |
| - inbox := f.callback(t, subject, target.Query().Get("nonce"), time.Now().Add(-30*time.Second)) |
| - finish := httptest.NewRecorder() |
| - f.b.Finish(finish, bridgeRequest(http.MethodGet, "/auth/finish", append(cookies, pending, inbox))) |
| - if finish.Code != 303 || finish.Header().Get("Location") != "/account/home/confirm" { |
| - t.Fatalf("link finish=%d location=%q", finish.Code, finish.Header().Get("Location")) |
| - } |
| - bridgeNoSession(t, f.b, finish) |
| - return bridgeCookie(t, finish, homeProofCookie), []*http.Cookie{local} |
| -} |
| -func (f *bridgeFixture) link(t *testing.T, local *http.Cookie, subject string) { |
| - t.Helper() |
| - proof, cookies := f.linkProof(t, local, subject) |
| - cookies = append(cookies, proof) |
| - page := httptest.NewRecorder() |
| - f.b.ConfirmPage(page, bridgeRequest(http.MethodGet, "/account/home/confirm", cookies)) |
| - if page.Code != 200 { |
| - t.Fatalf("confirm page=%d", page.Code) |
| - } |
| - w := httptest.NewRecorder() |
| - f.b.ConfirmPost(w, bridgeRequest(http.MethodPost, "/account/home/confirm", cookies)) |
| - if w.Code != 303 || w.Header().Get("Location") != connectedURL("/") { |
| - t.Fatalf("confirm=%d %q", w.Code, w.Header().Get("Location")) |
| - } |
| - bridgeNoSession(t, f.b, w) |
| -} |
| - |
| -func TestHomeBridgeLinkThenOrdinarySignInPreservesIdentity(t *testing.T) { |
| - f := newBridgeFixture(t) |
| - local := f.local(t, "one@example.com", "magiclink", time.Time{}) |
| - person, err := f.app.store.EnsurePerson(context.Background(), "one@example.com") |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - doc, err := f.app.store.Create(context.Background(), person, "Existing document") |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - f.link(t, local, "opaque-subject-one") |
| - if _, ok := f.b.sessions.From(bridgeRequest(http.MethodGet, "/", []*http.Cookie{local})); !ok { |
| - t.Fatal("linking replaced local session") |
| - } |
| - pending, nonce := f.start(t, nil, "/d/"+doc.Sqid) |
| - original := time.Now().Add(-time.Hour).Truncate(time.Second) |
| - inbox := f.callback(t, "opaque-subject-one", nonce, original) |
| - finish := httptest.NewRecorder() |
| - f.b.Finish(finish, bridgeRequest(http.MethodGet, "/auth/finish", []*http.Cookie{pending, inbox})) |
| - if finish.Code != 303 || finish.Header().Get("Location") != "/d/"+doc.Sqid { |
| - t.Fatalf("ordinary finish=%d %q", finish.Code, finish.Header().Get("Location")) |
| - } |
| - cookie := bridgeCookie(t, finish, f.b.sessionCookie) |
| - r := bridgeRequest(http.MethodGet, "/", []*http.Cookie{cookie}) |
| - session, ok := f.b.sessions.From(r) |
| - if !ok || session.Method != homeAssertionMethod || session.Subject != "opaque-subject-one" || !session.AuthTime.Equal(original) { |
| - t.Fatalf("wrong Home session: %+v", session) |
| - } |
| - identity, err := f.b.resolver.resolve(sessions.WithSession(r, session)) |
| - if err != nil || identity.Actor.PersonID != person || (identity.Actor.VerifiedAddress == nil || *identity.Actor.VerifiedAddress != "one@example.com") { |
| - t.Fatalf("identity=%+v %v", identity, err) |
| - } |
| - if _, err := f.app.store.Get(context.Background(), person, doc.Sqid); err != nil { |
| - t.Fatal("existing ownership changed", err) |
| - } |
| - var count int |
| - if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM people").Scan(&count); err != nil || count != 1 { |
| - t.Fatal("SSO created an extra person", count, err) |
| - } |
| - replay := httptest.NewRecorder() |
| - f.b.Finish(replay, bridgeRequest(http.MethodGet, "/auth/finish", []*http.Cookie{pending, inbox})) |
| - if replay.Code == 303 { |
| - t.Fatal("assertion replay minted session") |
| - } |
| - bridgeNoSession(t, f.b, replay) |
| -} |
| - |
| -func TestHomeBridgeUnknownAndDifferentCurrentAccountNeverMint(t *testing.T) { |
| - f := newBridgeFixture(t) |
| - local := f.local(t, "one@example.com", "magiclink", time.Now().Add(-time.Minute)) |
| - other := f.local(t, "two@example.com", "magiclink", time.Now().Add(-time.Minute)) |
| - f.link(t, local, "linked-subject") |
| - for _, tc := range []struct { |
| - name, subject string |
| - cookies []*http.Cookie |
| - }{{"unknown", "unknown-private-subject", nil}, {"different-local", "linked-subject", []*http.Cookie{other}}} { |
| - t.Run(tc.name, func(t *testing.T) { |
| - pending, n := f.start(t, tc.cookies, "/") |
| - inbox := f.callback(t, tc.subject, n, time.Now().Add(-time.Minute)) |
| - w := httptest.NewRecorder() |
| - f.b.Finish(w, bridgeRequest(http.MethodGet, "/auth/finish", append(tc.cookies, pending, inbox))) |
| - if w.Code != 403 { |
| - t.Fatalf("rejected exchange=%d", w.Code) |
| - } |
| - bridgeNoSession(t, f.b, w) |
| - if tc.name == "unknown" && !strings.Contains(w.Body.String(), "/signin/local") { |
| - t.Fatal("unknown identity lacks local continuation") |
| - } |
| - if strings.Contains(w.Body.String(), tc.subject) { |
| - t.Fatal("opaque identity leaked into response") |
| - } |
| - retry := httptest.NewRecorder() |
| - f.b.Finish(retry, bridgeRequest(http.MethodGet, "/auth/finish", []*http.Cookie{pending, inbox})) |
| - if retry.Code == 303 { |
| - t.Fatal("rejected completion remained reusable") |
| - } |
| - }) |
| - } |
| -} |
| - |
| -func TestHomeBridgeChangedLocalSessionAndProofReplayRefused(t *testing.T) { |
| - f := newBridgeFixture(t) |
| - authTime := time.Now().Add(-time.Minute) |
| - original := f.local(t, "one@example.com", "magiclink", authTime) |
| - proof, cookies := f.linkProof(t, original, "opaque") |
| - rotated := f.local(t, "one@example.com", "magiclink", authTime) |
| - w := httptest.NewRecorder() |
| - f.b.ConfirmPost(w, bridgeRequest(http.MethodPost, "/account/home/confirm", []*http.Cookie{rotated, proof})) |
| - if w.Code != 403 { |
| - t.Fatal("different session linked proof", w.Code) |
| - } |
| - retry := httptest.NewRecorder() |
| - f.b.ConfirmPost(retry, bridgeRequest(http.MethodPost, "/account/home/confirm", append(cookies, proof))) |
| - if retry.Code != 403 { |
| - t.Fatal("rejected proof reusable", retry.Code) |
| - } |
| -} |
| - |
| -func TestHomeBridgeStrictCookiesAndStaleLocalRefusal(t *testing.T) { |
| - f := newBridgeFixture(t) |
| - local := f.local(t, "one@example.com", "magiclink", time.Now().Add(-time.Minute)) |
| - for _, cookies := range [][]*http.Cookie{{{Name: homeInitCookie, Value: "bad"}}, {{Name: homeInitCookie, Value: strings.Repeat("A", 43)}, {Name: homeInitCookie, Value: strings.Repeat("A", 43)}}, {local, local}, {{Name: f.b.sessionCookie, Value: strings.Repeat("A", 43)}}} { |
| - w := httptest.NewRecorder() |
| - f.b.Start(w, bridgeRequest(http.MethodGet, "/auth/start", cookies)) |
| - if w.Code == 303 { |
| - t.Fatal("malformed/duplicate/unresolved cookie downgraded into ordinary sign-in") |
| - } |
| - } |
| - for _, method := range []string{"magiclink", "keymail", homeAssertionMethod} { |
| - cookie := f.local(t, "one@example.com", method, time.Now().Add(-6*time.Minute)) |
| - w := httptest.NewRecorder() |
| - f.b.LinkStart(w, bridgeRequest(http.MethodPost, "/account/home", []*http.Cookie{cookie})) |
| - if w.Code != 403 { |
| - t.Fatal("stale or Home method began linking", method, w.Code) |
| - } |
| - } |
| - pending, n := f.start(t, nil, "/") |
| - inbox := f.callback(t, "unknown", n, time.Now().Add(-time.Minute)) |
| - for _, cookies := range [][]*http.Cookie{{pending, inbox, local, local}, {pending, inbox, {Name: f.b.sessionCookie, Value: strings.Repeat("A", 43)}}} { |
| - w := httptest.NewRecorder() |
| - f.b.Finish(w, bridgeRequest(http.MethodGet, "/auth/finish", cookies)) |
| - if w.Code != 403 { |
| - t.Fatal("unresolved/ambiguous current account accepted", w.Code) |
| - } |
| - bridgeNoSession(t, f.b, w) |
| - } |
| -} |
| - |
| -func TestHomeBridgeCallbackHasNoSessionDependencyAndExactOrigin(t *testing.T) { |
| - f := newBridgeFixture(t) |
| - _, n := f.start(t, nil, "/") |
| - id, _ := assertion.RandomID() |
| - now := time.Now().Unix() |
| - token, err := assertion.Sign(f.key, assertion.Claims{Version: 1, Issuer: bridgeIssuer, Audience: bridgeOrigin, Subject: "opaque", KeyID: "key", ID: id, Nonce: n, IssuedAt: now, ExpiresAt: now + 90, AuthTime: now}) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - for _, origin := range []string{"", "https://evil.example", bridgeIssuer} { |
| - r := httptest.NewRequest(http.MethodPost, bridgeOrigin+"/auth/assertion", strings.NewReader(url.Values{"assertion": {token}}.Encode())) |
| - r.Header.Set("Origin", origin) |
| - r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| - // Even malformed duplicate app cookies cannot affect the issuer callback. |
| - r.AddCookie(&http.Cookie{Name: f.b.sessionCookie, Value: "bad"}) |
| - r.AddCookie(&http.Cookie{Name: f.b.sessionCookie, Value: "bad"}) |
| - w := httptest.NewRecorder() |
| - f.b.Callback(w, r) |
| - bridgeNoSession(t, f.b, w) |
| - if origin == bridgeIssuer && w.Code != 303 { |
| - t.Fatal("callback resolved local session", w.Code) |
| - } |
| - if origin != bridgeIssuer && w.Code == 303 { |
| - t.Fatal("callback accepted different origin") |
| - } |
| - } |
| -} |
| - |
| -func TestHomeBridgeLinkMutationsRemainBehindCSRF(t *testing.T) { |
| - f := newBridgeFixture(t) |
| - local := f.local(t, "one@example.com", "magiclink", time.Now().Add(-time.Minute)) |
| - protected := csrf.Protect(bridgeOrigin)(http.HandlerFunc(f.b.LinkStart)) |
| - r := bridgeRequest(http.MethodPost, "/account/home", []*http.Cookie{local}) |
| - r.Header.Set("Origin", "https://evil.example") |
| - r.Header.Set("Sec-Fetch-Site", "cross-site") |
| - w := httptest.NewRecorder() |
| - protected.ServeHTTP(w, r) |
| - if w.Code != 403 { |
| - t.Fatal("cross-site link initiation accepted", w.Code) |
| - } |
| - var count int |
| - if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM docs_link_flows").Scan(&count); err != nil || count != 0 { |
| - t.Fatal("cross-site initiation retained state", count, err) |
| - } |
| -} |
| - |
| -func TestHomeBridgeOrdinaryProofCannotBecomeLinkProof(t *testing.T) { |
| - f := newBridgeFixture(t) |
| - local := f.local(t, "one@example.com", "magiclink", time.Now().Add(-time.Minute)) |
| - w := httptest.NewRecorder() |
| - f.b.LinkStart(w, bridgeRequest(http.MethodPost, "/account/home", []*http.Cookie{local})) |
| - init := bridgeCookie(t, w, homeInitCookie) |
| - // Bind an explicit link to its own generated nonce. |
| - f.start(t, []*http.Cookie{local, init}, "/account/home/confirm") |
| - // A separate ordinary sign-in produces a valid assertion with another nonce. |
| - pending, n := f.start(t, []*http.Cookie{local}, "/") |
| - inbox := f.callback(t, "opaque", n, time.Now().Add(-time.Minute)) |
| - finish := httptest.NewRecorder() |
| - f.b.Finish(finish, bridgeRequest(http.MethodGet, "/auth/finish", []*http.Cookie{local, init, pending, inbox})) |
| - if finish.Code != 403 { |
| - t.Fatal("ordinary exchange reused for linking", finish.Code) |
| - } |
| - bridgeNoSession(t, f.b, finish) |
| - for _, cookie := range finish.Result().Cookies() { |
| - if cookie.Name == homeProofCookie && cookie.MaxAge > 0 { |
| - t.Fatal("wrong nonce created proof") |
| - } |
| - } |
| - var rows int |
| - if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM docs_link_flows").Scan(&rows); err != nil || rows != 0 { |
| - t.Fatal("failed link initiation not burned", rows, err) |
| - } |
| -} |
| - |
| -func TestHomeBridgeStaleFreshExchangeCannotMintOrCreateProof(t *testing.T) { |
| - f := newBridgeFixture(t) |
| - local := f.local(t, "one@example.com", "magiclink", time.Now().Add(-time.Minute)) |
| - w := httptest.NewRecorder() |
| - f.b.LinkStart(w, bridgeRequest(http.MethodPost, "/account/home", []*http.Cookie{local})) |
| - init := bridgeCookie(t, w, homeInitCookie) |
| - pending, n := f.start(t, []*http.Cookie{local, init}, "/account/home/confirm") |
| - inbox := f.callback(t, "opaque", n, time.Now().Add(-6*time.Minute)) |
| - for i := 0; i < 2; i++ { |
| - finish := httptest.NewRecorder() |
| - f.b.Finish(finish, bridgeRequest(http.MethodGet, "/auth/finish", []*http.Cookie{local, init, pending, inbox})) |
| - if finish.Code == 303 { |
| - t.Fatal("stale Home proof accepted or revived") |
| - } |
| - bridgeNoSession(t, f.b, finish) |
| - } |
| - var rows int |
| - if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM docs_link_flows WHERE stage = 'pending'").Scan(&rows); err != nil || rows != 0 { |
| - t.Fatal("stale Home gesture created a pending link", rows, err) |
| - } |
| -} |
| - |
| -func TestHomeBridgeCurrentHomeSubjectIsCheckedByConsumer(t *testing.T) { |
| - f := newBridgeFixture(t) |
| - local := f.local(t, "one@example.com", "magiclink", time.Now().Add(-time.Minute)) |
| - f.link(t, local, "subject-one") |
| - other := f.local(t, "two@example.com", "magiclink", time.Now().Add(-time.Minute)) |
| - f.link(t, other, "subject-two") |
| - homeToken, err := f.b.sessions.Mint(sessions.Session{Subject: "subject-one", Method: homeAssertionMethod, AuthTime: time.Now().Add(-time.Minute)}) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - current := &http.Cookie{Name: f.b.sessionCookie, Value: homeToken} |
| - pending, n := f.start(t, []*http.Cookie{current}, "/") |
| - inbox := f.callback(t, "subject-two", n, time.Now().Add(-time.Minute)) |
| - w := httptest.NewRecorder() |
| - f.b.Finish(w, bridgeRequest(http.MethodGet, "/auth/finish", []*http.Cookie{current, pending, inbox})) |
| - if w.Code == 303 { |
| - t.Fatal("signed-in Home identity silently replaced") |
| - } |
| - bridgeNoSession(t, f.b, w) |
| -} |
| - |
| -func TestHomeBridgeReturnPathCallbackRemainsSafe(t *testing.T) { |
| - for _, tc := range []struct{ input, want string }{{"/d/existing-document?view=reading", "/d/existing-document?view=reading"}, {"https://evil.example/private", "/"}, {"//evil.example", "/"}, {"/auth/finish", "/"}, {"/%2fhost", "/"}, {"", "/"}} { |
| - t.Run(tc.input, func(t *testing.T) { |
| - f := newBridgeFixture(t) |
| - f.b.returnPath = func(*http.Request) string { return tc.input } |
| - local := f.local(t, "one@example.com", "magiclink", time.Now().Add(-time.Minute)) |
| - proof, cookies := f.linkProof(t, local, "opaque") |
| - w := httptest.NewRecorder() |
| - f.b.ConfirmPost(w, bridgeRequest(http.MethodPost, "/account/home/confirm", append(cookies, proof))) |
| - if w.Code != 303 || w.Header().Get("Location") != connectedURL(tc.want) { |
| - t.Fatalf("return location=%q status=%d", w.Header().Get("Location"), w.Code) |
| - } |
| - }) |
| - } |
| -} |
diff --git a/internal/docs/home_link_handlers.go b/internal/docs/home_link_handlers.go| deleted file mode 100644 |
| index 3eef44c..0000000 |
| --- a/internal/docs/home_link_handlers.go |
| +++ /dev/null |
| @@ -1,194 +0,0 @@ |
| -package docs |
| - |
| -import ( |
| - "errors" |
| - "net/http" |
| - "net/url" |
| - "strings" |
| - |
| - "amadan.net/oficina/home/handoff" |
| - "github.com/carlosframework/docs/internal/docs/linkstore" |
| -) |
| - |
| -// Link routes belong behind the app's CSRF, session, identity and admission |
| -// middleware. They recheck the actual cookie at each sensitive transition. |
| -func (b *homeBridge) LinkPage(w http.ResponseWriter, r *http.Request) { |
| - if !b.guard(w, r, http.MethodGet, "/account/home") { |
| - return |
| - } |
| - session, err := b.actualSession(r) |
| - if err != nil || session == nil { |
| - b.fail(w, r, http.StatusForbidden) |
| - return |
| - } |
| - person, err := b.existingPerson(r, *session) |
| - if err != nil { |
| - b.fail(w, r, http.StatusForbidden) |
| - return |
| - } |
| - b.render.homeLink(w, r, "start", person.Email, http.StatusOK) |
| -} |
| -func (b *homeBridge) LinkStart(w http.ResponseWriter, r *http.Request) { |
| - if !b.guard(w, r, http.MethodPost, "/account/home") { |
| - return |
| - } |
| - if status, err := b.startLink(w, r); err != nil { |
| - if status == 0 { |
| - b.linkFailure(w, r, err) |
| - } else { |
| - b.fail(w, r, status) |
| - } |
| - } |
| -} |
| - |
| -// resumeLink is LinkStart for a person who just signed in locally after an |
| -// Oficina assertion with no link arrived: the same checks, the same flow. |
| -// It reports false having written nothing when the link cannot begin. |
| -func (b *homeBridge) resumeLink(w http.ResponseWriter, r *http.Request) bool { |
| - _, err := b.startLink(w, r) |
| - return err == nil |
| -} |
| - |
| -// startLink begins a link for the actual fresh local session and sends the |
| -// browser to the Home freshness check. It writes nothing unless it succeeds; |
| -// on failure it returns the status to show, or 0 for linkFailure's. |
| -func (b *homeBridge) startLink(w http.ResponseWriter, r *http.Request) (int, error) { |
| - for _, name := range []string{homeInitCookie, homeProofCookie} { |
| - if _, _, ok := homeCookie(r, name); !ok { |
| - return http.StatusBadRequest, errIdentityRefused |
| - } |
| - } |
| - local, _, err := b.localBinding(r) |
| - // The reviewed local reauthentication continuation is wired separately. |
| - // Stale local authentication cannot begin or reuse a linking initiation. |
| - if err != nil { |
| - return http.StatusForbidden, err |
| - } |
| - path := "/" |
| - if b.returnPath != nil { |
| - if candidate := b.returnPath(r); handoff.SafePath(candidate) { |
| - path = candidate |
| - } |
| - } |
| - secret, err := b.links.Start(r.Context(), local, path, b.now()) |
| - if err != nil { |
| - return 0, err |
| - } |
| - setHomeCookie(w, homeInitCookie, secret, 300) |
| - setHomeCookie(w, homeProofCookie, "", -1) |
| - http.Redirect(w, r, "/auth/start?return_to=%2Faccount%2Fhome%2Fconfirm", http.StatusSeeOther) |
| - return 0, nil |
| -} |
| - |
| -// connectedQuery marks the confirm page's GET after a successful confirm. |
| -// It shows "Accounts connected" only to a person whose link is stored, so |
| -// a crafted URL can show nothing that is not already true. return_to is |
| -// the page the link began from, revalidated before it becomes the page's |
| -// way back. |
| -const connectedQuery = "connected" |
| - |
| -func connectedURL(path string) string { |
| - return "/account/home/confirm?" + url.Values{connectedQuery: {"1"}, "return_to": {path}}.Encode() |
| -} |
| - |
| -func (b *homeBridge) ConfirmPage(w http.ResponseWriter, r *http.Request) { |
| - if q, err := url.ParseQuery(r.URL.RawQuery); err == nil && q.Has(connectedQuery) { |
| - b.connectedPage(w, r, q) |
| - return |
| - } |
| - if !b.guard(w, r, http.MethodGet, "/account/home/confirm") { |
| - return |
| - } |
| - secret, present, ok := homeCookie(r, homeProofCookie) |
| - if !ok || !present { |
| - b.fail(w, r, http.StatusBadRequest) |
| - return |
| - } |
| - local, person, err := b.localBinding(r) |
| - if err != nil { |
| - b.fail(w, r, http.StatusForbidden) |
| - return |
| - } |
| - if _, err := b.links.Pending(r.Context(), secret, local, b.now()); err != nil { |
| - if errors.Is(err, linkstore.ErrRefused) { |
| - setHomeCookie(w, homeProofCookie, "", -1) |
| - } |
| - b.linkFailure(w, r, err) |
| - return |
| - } |
| - b.render.homeLink(w, r, "confirm", person.Email, http.StatusOK) |
| -} |
| -func (b *homeBridge) ConfirmPost(w http.ResponseWriter, r *http.Request) { |
| - if !b.guard(w, r, http.MethodPost, "/account/home/confirm") { |
| - return |
| - } |
| - secret, present, ok := homeCookie(r, homeProofCookie) |
| - if !ok || !present { |
| - b.fail(w, r, http.StatusBadRequest) |
| - return |
| - } |
| - local, _, err := b.localBinding(r) |
| - if err != nil { |
| - b.fail(w, r, http.StatusForbidden) |
| - return |
| - } |
| - pending, err := b.links.Confirm(r.Context(), secret, local, b.now()) |
| - if err == nil || errors.Is(err, linkstore.ErrRefused) { |
| - setHomeCookie(w, homeProofCookie, "", -1) |
| - } |
| - if err != nil { |
| - b.linkFailure(w, r, err) |
| - return |
| - } |
| - // Say that it worked (Paul, 2026-10-24: landing back on the list with |
| - // the menu unchanged left him unable to tell). A GET, so a reload |
| - // repeats the page rather than the POST. |
| - http.Redirect(w, r, connectedURL(pending.ReturnPath), http.StatusSeeOther) |
| -} |
| - |
| -// connectedPage is "Accounts connected", for the signed-in person whose |
| -// account now has a stored link. Its way back is the page the link began |
| -// from. |
| -func (b *homeBridge) connectedPage(w http.ResponseWriter, r *http.Request, q url.Values) { |
| - w.Header().Set("Cache-Control", "no-store") |
| - if r.Host != strings.TrimPrefix(b.origin, "https://") || r.URL.Path != "/account/home/confirm" { |
| - b.fail(w, r, http.StatusNotFound) |
| - return |
| - } |
| - if r.Method != http.MethodGet { |
| - w.Header().Set("Allow", http.MethodGet) |
| - b.fail(w, r, http.StatusMethodNotAllowed) |
| - return |
| - } |
| - session, err := b.actualSession(r) |
| - if err != nil || session == nil { |
| - b.fail(w, r, http.StatusForbidden) |
| - return |
| - } |
| - person, err := b.existingPerson(r, *session) |
| - if err != nil { |
| - b.fail(w, r, http.StatusForbidden) |
| - return |
| - } |
| - linked, err := b.links.Linked(r.Context(), person.ID) |
| - if err != nil { |
| - b.fail(w, r, http.StatusServiceUnavailable) |
| - return |
| - } |
| - if !linked { |
| - b.fail(w, r, http.StatusForbidden) |
| - return |
| - } |
| - back := "/" |
| - if v, ok := q["return_to"]; ok && len(v) == 1 && handoff.SafePath(v[0]) { |
| - back = v[0] |
| - } |
| - b.render.homeLinkBack(w, r, "success", person.Email, back, http.StatusOK) |
| -} |
| -func (b *homeBridge) linkFailure(w http.ResponseWriter, r *http.Request, err error) { |
| - status := http.StatusServiceUnavailable |
| - if errors.Is(err, linkstore.ErrRefused) { |
| - status = http.StatusForbidden |
| - } |
| - b.fail(w, r, status) |
| -} |
diff --git a/internal/docs/home_links_move.go b/internal/docs/home_links_move.go| new file mode 100644 |
| index 0000000..577f35d |
| --- /dev/null |
| +++ b/internal/docs/home_links_move.go |
| @@ -0,0 +1,165 @@ |
| +package docs |
| + |
| +// Moving Docs' Home links onto home/connect, once, at boot. |
| +// |
| +// Before this branch Docs linked a local person to a Home identity in its |
| +// own docs_identity_links (issuer, subject, person_id). home/connect keeps |
| +// links in home_identity_links, where every row also carries |
| +// person_binding, a keyed hash of the person's address that Resolve checks. |
| +// A SQL copy would make rows connect refuses, so each row is carried with |
| +// connect's Bridge.Adopt, which writes exactly the row linking through |
| +// connect would have written (Home's implementation/linkstore-adopt.md). |
| +// |
| +// The move is one transaction, run in New after the migrations and |
| +// connect.New (whose Sweep has already committed) and before the team |
| +// runtime's census or any request: nothing else holds the single writer |
| +// connection while it runs. |
| +// |
| +// 1. In a team database, principalstore's link triggers are re-pointed |
| +// at home_identity_links first, so the disjointness trigger guards |
| +// every adopted row. Its refusal is a RAISE(ABORT), which Adopt |
| +// reports as ErrStorage, not ErrRefused (Fable, oficina/home #99 note |
| +// 7); either one aborts. |
| +// 2. Every row is adopted. ErrRefused aborts the whole move: a dropped |
| +// row would be a link lost for good (#99 note 9). Nothing is skipped. |
| +// 3. docs_link_clock's high-water mark is carried with MAX, so connect's |
| +// rollback guard does not restart at 0. |
| +// 4. The old table, its append-only triggers, and the flow and clock |
| +// tables are dropped. In-flight link flows (five minutes long) are not |
| +// carried; whoever was mid-link starts again. |
| +// |
| +// Commit makes all of it visible at once. A crash or a refusal leaves the |
| +// old table exactly as it was, for a full redo on the next boot, and a |
| +// boot after a successful move finds no old table and does nothing. |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "fmt" |
| + |
| + "amadan.net/oficina/home/connect/linkstore" |
| + "github.com/carlosframework/docs/internal/docs/principalstore" |
| +) |
| + |
| +var ( |
| + // errLinksRefused: some row cannot be carried as it stands (connect's |
| + // ErrRefused: another issuer, a malformed subject, a person who no |
| + // longer has an address). Nothing moved; Docs does not start. |
| + errLinksRefused = errors.New("docs: an existing Home link cannot move onto home/connect; nothing was moved, docs_identity_links is intact") |
| + // errLinksUnavailable: storage failed, or a trigger refused a row. |
| + errLinksUnavailable = errors.New("docs: moving Home links onto home/connect failed; nothing was moved, docs_identity_links is intact") |
| +) |
| + |
| +// linkAdopter is connect.Bridge's Adopt (a seam for the move's tests). |
| +type linkAdopter interface { |
| + Adopt(ctx context.Context, tx *sql.Tx, issuer, subject string, person int64) error |
| +} |
| + |
| +type oldLink struct { |
| + issuer, subject string |
| + person int64 |
| +} |
| + |
| +// moveLinksOntoConnect carries docs_identity_links into connect's table and |
| +// retires it, all in one transaction on db (the writer). See the file |
| +// comment for the order and why. |
| +func moveLinksOntoConnect(ctx context.Context, db *sql.DB, links linkAdopter) error { |
| + if db == nil || links == nil { |
| + return errLinksUnavailable |
| + } |
| + tx, err := db.BeginTx(ctx, nil) |
| + if err != nil { |
| + return errLinksUnavailable |
| + } |
| + defer tx.Rollback() |
| + old, err := tableExists(ctx, tx, "docs_identity_links") |
| + if err != nil { |
| + return errLinksUnavailable |
| + } |
| + if !old { |
| + // Moved already (or never created): nothing to do, nothing written. |
| + return nil |
| + } |
| + principals, err := tableExists(ctx, tx, "docs_home_identities") |
| + if err != nil { |
| + return errLinksUnavailable |
| + } |
| + if principals { |
| + if err := principalstore.RepointLinks(ctx, tx); err != nil { |
| + return errLinksUnavailable |
| + } |
| + } |
| + rows, err := readOldLinks(ctx, tx) |
| + if err != nil { |
| + return errLinksUnavailable |
| + } |
| + for _, row := range rows { |
| + switch err := links.Adopt(ctx, tx, row.issuer, row.subject, row.person); { |
| + case err == nil: |
| + case errors.Is(err, linkstore.ErrRefused): |
| + // The person ID locates the row for an operator; the subject |
| + // and the address are left out of the log. |
| + return fmt.Errorf("%w (person %d)", errLinksRefused, row.person) |
| + default: |
| + return errLinksUnavailable |
| + } |
| + } |
| + clock, err := tableExists(ctx, tx, "docs_link_clock") |
| + if err != nil { |
| + return errLinksUnavailable |
| + } |
| + if clock { |
| + var high int64 |
| + if err := tx.QueryRowContext(ctx, "SELECT high_water FROM docs_link_clock WHERE id = 1").Scan(&high); err != nil && !errors.Is(err, sql.ErrNoRows) { |
| + return errLinksUnavailable |
| + } |
| + res, err := tx.ExecContext(ctx, "UPDATE home_link_clock SET high_water = MAX(high_water, ?) WHERE id = 1", high) |
| + if err != nil { |
| + return errLinksUnavailable |
| + } |
| + if n, err := res.RowsAffected(); err != nil || n != 1 { |
| + return errLinksUnavailable |
| + } |
| + } |
| + for _, q := range []string{ |
| + "DROP TRIGGER IF EXISTS docs_identity_links_keep_update", |
| + "DROP TRIGGER IF EXISTS docs_identity_links_keep_delete", |
| + "DROP TABLE docs_identity_links", |
| + "DROP TABLE IF EXISTS docs_link_flows", |
| + "DROP TABLE IF EXISTS docs_link_clock", |
| + } { |
| + if _, err := tx.ExecContext(ctx, q); err != nil { |
| + return errLinksUnavailable |
| + } |
| + } |
| + if err := tx.Commit(); err != nil { |
| + return errLinksUnavailable |
| + } |
| + return nil |
| +} |
| + |
| +// readOldLinks reads every row before adopting any, so no cursor is open |
| +// on the transaction's one connection while Adopt uses it. |
| +func readOldLinks(ctx context.Context, tx *sql.Tx) ([]oldLink, error) { |
| + rows, err := tx.QueryContext(ctx, "SELECT issuer, subject, person_id FROM docs_identity_links ORDER BY issuer, subject") |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []oldLink |
| + for rows.Next() { |
| + var l oldLink |
| + if err := rows.Scan(&l.issuer, &l.subject, &l.person); err != nil { |
| + return nil, err |
| + } |
| + out = append(out, l) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +func tableExists(ctx context.Context, tx *sql.Tx, name string) (bool, error) { |
| + var n int |
| + err := tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = ?", name).Scan(&n) |
| + return n == 1, err |
| +} |
diff --git a/internal/docs/home_links_move_test.go b/internal/docs/home_links_move_test.go| new file mode 100644 |
| index 0000000..f580716 |
| --- /dev/null |
| +++ b/internal/docs/home_links_move_test.go |
| @@ -0,0 +1,631 @@ |
| +package docs |
| + |
| +// The one-time move of Docs' own Home links onto home/connect |
| +// (home_links_move.go), against databases as main (7c9122f) left them: |
| +// team mode off, as on docs.oficina.works, and on, as on a team instance. |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "path/filepath" |
| + "reflect" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + connectlinks "amadan.net/oficina/home/connect/linkstore" |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + "github.com/carlosframework/docs/internal/docs/principalstore" |
| +) |
| + |
| +// legacyLinks is a database main left behind, holding links, and the |
| +// configuration to boot it with. |
| +type legacyLinks struct { |
| + t *testing.T |
| + cfg Config |
| + team bool |
| + fix *teamRouterFixture // the keys that sign assertions for cfg |
| + ledger []ledgerRow |
| + high int64 // docs_link_clock's high-water mark |
| + // People: Paul (linked, owns "Paul's plan"), Bob (linked, owns "Bob's |
| + // notes"), Carol (local only). In team mode also a Home-only member |
| + // (owns "Home-only notes"), which main made through principalstore. |
| + paul, bob, carol, homeOnly int64 |
| + // tokens are sessions main minted, by who holds them. |
| + tokens map[string]string |
| +} |
| + |
| +var ( |
| + paulSubject = teamSubject('a') |
| + bobSubject = teamSubject('b') |
| + homeOnlySubject = teamSubject('c') |
| +) |
| + |
| +// newLegacyLinks builds the database at a fresh path. Team mode on, it is |
| +// legacyTeamDatabase (main's schema, the old team set and its marker); |
| +// off, main's schema alone. Either way the rows are written as main's code |
| +// wrote them, with SQL, since that code is gone. |
| +func newLegacyLinks(t *testing.T, team bool) *legacyLinks { |
| + t.Helper() |
| + f := newTeamRouterFixture(t) |
| + l := &legacyLinks{t: t, cfg: f.cfg, team: team, fix: f, tokens: map[string]string{}} |
| + l.cfg.DBPath = filepath.Join(t.TempDir(), "legacy.db") |
| + if team { |
| + legacyTeamDatabase(t, l.cfg.DBPath, "", roster.Bindings{Issuer: bridgeIssuer, Directory: "https://home.example", Consumer: "router-docs", App: "docs", Team: "TeamA", Audience: bridgeOrigin}) |
| + } else { |
| + l.cfg.Team = nil |
| + l.cfg.AllowedAddresses = "paul@tito.io,bob@example.com,carol@example.com" |
| + } |
| + d, err := db.Open(l.cfg.DBPath, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer d.Close() |
| + if !team { |
| + if _, err = migrate.Apply(t.Context(), d, mainBootSchema); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + w := d.Writer() |
| + person := func(address string) int64 { |
| + r, err := w.Exec(`INSERT INTO people(email,created_at) VALUES(?,CURRENT_TIMESTAMP)`, address) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + id, _ := r.LastInsertId() |
| + return id |
| + } |
| + document := func(owner int64, sqid, title string) { |
| + if _, err := w.Exec(`INSERT INTO documents(sqid,title,guid,client_id,created_at,updated_at,owner_id) VALUES(?,?,?,1,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,?)`, sqid, title, "guid-"+sqid, owner); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + l.paul, l.bob, l.carol = person("paul@tito.io"), person("bob@example.com"), person("carol@example.com") |
| + document(l.paul, "paulplan", "Paul's plan") |
| + document(l.bob, "bobnotes", "Bob's notes") |
| + for subject, id := range map[string]int64{paulSubject: l.paul, bobSubject: l.bob} { |
| + if _, err = w.Exec(`INSERT INTO docs_identity_links VALUES(?,?,?)`, bridgeIssuer, subject, id); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + // Ahead of now, within connect's 30-second tolerance: the carried mark |
| + // is then visible, since connect's own Sweep at boot writes now. |
| + l.high = time.Now().Unix() + 20 |
| + if _, err = w.Exec(`UPDATE docs_link_clock SET high_water=? WHERE id=1`, l.high); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = w.Exec(`INSERT INTO docs_link_flows VALUES('in-flight','init',?,x'00')`, time.Now().Unix()+300); err != nil { |
| + t.Fatal(err) |
| + } |
| + if team { |
| + // principalstore.EnsureHome, as main ran it. |
| + l.homeOnly = principalstore.HomeIDMin |
| + for _, q := range []string{ |
| + fmt.Sprintf(`UPDATE docs_home_allocator SET high_water=%d WHERE singleton=1`, l.homeOnly), |
| + fmt.Sprintf(`INSERT INTO docs_principals VALUES(%d,'home',CURRENT_TIMESTAMP)`, l.homeOnly), |
| + fmt.Sprintf(`INSERT INTO docs_home_identities VALUES('%s','%s',%d)`, bridgeIssuer, homeOnlySubject, l.homeOnly), |
| + } { |
| + if _, err = w.Exec(q); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + document(l.homeOnly, "homeonly", "Home-only notes") |
| + } |
| + store, err := sessions.New(sessions.Config{DB: w, Origin: bridgeOrigin}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + mint := func(name, subject, method string) { |
| + token, err := store.Mint(sessions.Session{Subject: subject, Method: method, AuthTime: time.Now().Add(-time.Hour)}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + l.tokens[name] = token |
| + } |
| + mint("paul", paulSubject, "home-assertion") |
| + mint("bob", bobSubject, "home-assertion") |
| + mint("carol", "carol@example.com", "magiclink") |
| + if team { |
| + mint("homeOnly", homeOnlySubject, "home-assertion") |
| + } |
| + l.ledger = readLedger(t, w) |
| + return l |
| +} |
| + |
| +// boot is New on the database, as a fixture whose browsers sign |
| +// assertions with the configured key. |
| +func (l *legacyLinks) boot() *routerHomeFixture { |
| + l.t.Helper() |
| + app, err := New(l.cfg) |
| + if err != nil { |
| + l.t.Fatal("a database main left behind did not boot:", err) |
| + } |
| + l.t.Cleanup(func() { app.Close() }) |
| + sess, err := sessions.New(sessions.Config{DB: app.db.Writer(), Origin: bridgeOrigin}) |
| + if err != nil { |
| + l.t.Fatal(err) |
| + } |
| + return &routerHomeFixture{app: app, key: l.fix.key, keyID: l.fix.keyID, sessions: sess} |
| +} |
| + |
| +// holding is a browser holding a session main minted. |
| +func (l *legacyLinks) holding(f *routerHomeFixture, name string) *routerBrowser { |
| + b := f.browser() |
| + b.cookies[f.sessions.CookieName()] = &http.Cookie{Name: f.sessions.CookieName(), Value: l.tokens[name]} |
| + return b |
| +} |
| + |
| +func tableNamed(t *testing.T, q *sql.DB, name string) bool { |
| + t.Helper() |
| + var n int |
| + if err := q.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE name=?`, name).Scan(&n); err != nil { |
| + t.Fatal(err) |
| + } |
| + return n == 1 |
| +} |
| + |
| +type linkRow struct { |
| + Issuer, Subject string |
| + Person int64 |
| + Binding string |
| +} |
| + |
| +func connectLinks(t *testing.T, q *sql.DB) []linkRow { |
| + t.Helper() |
| + rows, err := q.Query(`SELECT issuer, subject, person_id, person_binding FROM home_identity_links ORDER BY subject`) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer rows.Close() |
| + var out []linkRow |
| + for rows.Next() { |
| + var r linkRow |
| + if err := rows.Scan(&r.Issuer, &r.Subject, &r.Person, &r.Binding); err != nil { |
| + t.Fatal(err) |
| + } |
| + out = append(out, r) |
| + } |
| + return out |
| +} |
| + |
| +func oldLinks(t *testing.T, q *sql.DB) []linkRow { |
| + t.Helper() |
| + rows, err := q.Query(`SELECT issuer, subject, person_id FROM docs_identity_links ORDER BY subject`) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer rows.Close() |
| + var out []linkRow |
| + for rows.Next() { |
| + var r linkRow |
| + if err := rows.Scan(&r.Issuer, &r.Subject, &r.Person); err != nil { |
| + t.Fatal(err) |
| + } |
| + out = append(out, r) |
| + } |
| + return out |
| +} |
| + |
| +func linkClock(t *testing.T, q *sql.DB, table string) int64 { |
| + t.Helper() |
| + var high int64 |
| + if err := q.QueryRow(`SELECT high_water FROM ` + table + ` WHERE id=1`).Scan(&high); err != nil { |
| + t.Fatal(err) |
| + } |
| + return high |
| +} |
| + |
| +// schemaDump is every object in the database, as SQLite stores it. |
| +func schemaDump(t *testing.T, q *sql.DB) []string { |
| + t.Helper() |
| + rows, err := q.Query(`SELECT type||' '||name||' ON '||tbl_name||': '||COALESCE(sql,'') FROM sqlite_master ORDER BY type, name`) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer rows.Close() |
| + var out []string |
| + for rows.Next() { |
| + var s string |
| + if err := rows.Scan(&s); err != nil { |
| + t.Fatal(err) |
| + } |
| + out = append(out, s) |
| + } |
| + return out |
| +} |
| + |
| +// requireMoved: the old tables are gone, every link is in connect's table |
| +// with a binding, for the same person, the clock is carried, and the |
| +// ledger is main's plus only what is new. |
| +func (l *legacyLinks) requireMoved(f *routerHomeFixture) { |
| + t := l.t |
| + t.Helper() |
| + w := f.app.db.Writer() |
| + for _, table := range []string{"docs_identity_links", "docs_link_flows", "docs_link_clock"} { |
| + if tableNamed(t, w, table) { |
| + t.Fatal("the old table is still there:", table) |
| + } |
| + } |
| + got := connectLinks(t, w) |
| + if len(got) != 2 || got[0].Subject != paulSubject || got[0].Person != l.paul || got[1].Subject != bobSubject || got[1].Person != l.bob { |
| + t.Fatalf("links not carried: %+v", got) |
| + } |
| + for _, r := range got { |
| + if r.Issuer != bridgeIssuer || len(r.Binding) != 64 { |
| + t.Fatalf("link carried without a binding: %+v", r) |
| + } |
| + } |
| + if high := linkClock(t, w, "home_link_clock"); high != l.high { |
| + t.Fatal("the link clock was not carried", high, l.high) |
| + } |
| + schema, mainSchema := BootSchema, mainBootSchema |
| + if l.team { |
| + schema, mainSchema = TeamBootSchema, migrate.Merge(mainBootSchema, principalstore.Schema, teamState.Schema()) |
| + } |
| + requireLedgerKept(t, l.ledger, readLedger(t, w), schema, mainSchema) |
| +} |
| + |
| +// requireSignsIn: the session main minted for name still signs in, as the |
| +// same person, and sees their document. |
| +func (l *legacyLinks) requireSignsIn(f *routerHomeFixture, name, title string) { |
| + l.t.Helper() |
| + page := l.holding(f, name).do("GET", "/", "") |
| + if page.Code != 200 || !strings.Contains(page.Body.String(), title) { |
| + l.t.Fatalf("%s's session did not survive the move: %d", name, page.Code) |
| + } |
| +} |
| + |
| +// Paul's docs.oficina.works: Home sign-in, team mode off. His account and |
| +// Bob's are linked; Carol's is local. After the move every link resolves, |
| +// every session main minted still signs in as the same person, and a new |
| +// Home sign-in reaches the same account. |
| +func TestLinksMoveOntoConnectWithTeamModeOff(t *testing.T) { |
| + l := newLegacyLinks(t, false) |
| + f := l.boot() |
| + l.requireMoved(f) |
| + l.requireSignsIn(f, "paul", "Paul's plan") |
| + l.requireSignsIn(f, "bob", "Bob's notes") |
| + l.requireSignsIn(f, "carol", "") |
| + if page := l.holding(f, "paul").do("GET", "/", ""); strings.Contains(page.Body.String(), "Bob's notes") { |
| + t.Fatal("Paul's session reached Bob's document") |
| + } |
| + fresh := f.browser() |
| + nonce := fresh.start(t, "/auth/start?return_to=%2F", "") |
| + routerRedirect(t, fresh.exchange(t, nonce, paulSubject, time.Now().Add(-time.Minute)), "/") |
| + if page := fresh.do("GET", "/", ""); page.Code != 200 || !strings.Contains(page.Body.String(), "Paul's plan") { |
| + t.Fatal("a new Home sign-in did not reach Paul's account", page.Code) |
| + } |
| + // The menu still knows Paul is linked when he signs in by email. |
| + local := f.browser() |
| + local.localSignin(t, "paul@tito.io") |
| + if local.menuOffersConnect(t) { |
| + t.Fatal("a linked account is offered Connect again") |
| + } |
| +} |
| + |
| +// A team instance: links, a Home-only member, the marker. The disjointness |
| +// triggers now name connect's table, and the Home-only member still signs |
| +// in through connect's HomeOnly hook. |
| +func TestLinksMoveOntoConnectWithTeamModeOn(t *testing.T) { |
| + l := newLegacyLinks(t, true) |
| + f := l.boot() |
| + l.requireMoved(f) |
| + l.requireSignsIn(f, "paul", "Paul's plan") |
| + l.requireSignsIn(f, "bob", "Bob's notes") |
| + l.requireSignsIn(f, "homeOnly", "Home-only notes") |
| + w := f.app.db.Writer() |
| + triggers := map[string]string{} |
| + rows, err := w.Query(`SELECT name, tbl_name, sql FROM sqlite_master WHERE type='trigger' AND (sql LIKE '%identity_links%')`) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for rows.Next() { |
| + var name, table, body string |
| + if err := rows.Scan(&name, &table, &body); err != nil { |
| + t.Fatal(err) |
| + } |
| + if strings.Contains(body, "docs_identity_links") { |
| + t.Fatal("a trigger still names the old table:", name) |
| + } |
| + triggers[name] = table |
| + } |
| + rows.Close() |
| + want := map[string]string{"docs_home_identity_unique": "docs_home_identities", "docs_local_identity_unique": "home_identity_links", "docs_home_links_keep_update": "home_identity_links", "docs_home_links_keep_delete": "home_identity_links"} |
| + if !reflect.DeepEqual(triggers, want) { |
| + t.Fatalf("triggers not re-pointed: %v", triggers) |
| + } |
| + // They hold: a Home-only subject cannot be linked, nor a linked one |
| + // become Home-only, and a link cannot change. |
| + for _, q := range []string{ |
| + fmt.Sprintf(`INSERT INTO home_identity_links(issuer,subject,person_id) VALUES('%s','%s',%d)`, bridgeIssuer, homeOnlySubject, l.carol), |
| + fmt.Sprintf(`INSERT INTO docs_home_identities VALUES('%s','%s',%d)`, bridgeIssuer, paulSubject, l.homeOnly), |
| + `UPDATE home_identity_links SET person_id=person_id`, |
| + `DELETE FROM home_identity_links`, |
| + } { |
| + if _, err := w.Exec(q); err == nil { |
| + t.Fatal("accepted:", q) |
| + } |
| + } |
| + // Bob's link gives his local sign-in his team standing, as before. |
| + local := f.browser() |
| + local.localSignin(t, "bob@example.com") |
| + if page := local.do("POST", "/documents", "title=Made+by+a+member"); page.Code != 303 { |
| + t.Fatal("a linked member signing in by email lost the team rung", page.Code) |
| + } |
| +} |
| + |
| +// A second boot finds nothing to move and changes nothing. |
| +func TestLinksMoveIsANoOpOnceDone(t *testing.T) { |
| + for _, team := range []bool{false, true} { |
| + t.Run(fmt.Sprint("team=", team), func(t *testing.T) { |
| + l := newLegacyLinks(t, team) |
| + f := l.boot() |
| + w := f.app.db.Writer() |
| + schema, links, high, ledger := schemaDump(t, w), connectLinks(t, w), linkClock(t, w, "home_link_clock"), readLedger(t, w) |
| + if err := f.app.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + again := l.boot() |
| + w = again.app.db.Writer() |
| + if !reflect.DeepEqual(schema, schemaDump(t, w)) || !reflect.DeepEqual(links, connectLinks(t, w)) || high != linkClock(t, w, "home_link_clock") || !reflect.DeepEqual(ledger, readLedger(t, w)) { |
| + t.Fatal("a second boot changed the database") |
| + } |
| + if err := moveLinksOntoConnect(t.Context(), w, adoptFunc(func(context.Context, *sql.Tx, string, string, int64) error { |
| + t.Fatal("a move with nothing to move adopted a row") |
| + return nil |
| + })); err != nil { |
| + t.Fatal(err) |
| + } |
| + l.requireSignsIn(again, "paul", "Paul's plan") |
| + }) |
| + } |
| +} |
| + |
| +type adoptFunc func(ctx context.Context, tx *sql.Tx, issuer, subject string, person int64) error |
| + |
| +func (f adoptFunc) Adopt(ctx context.Context, tx *sql.Tx, issuer, subject string, person int64) error { |
| + return f(ctx, tx, issuer, subject, person) |
| +} |
| + |
| +// openLegacy is the database with this code's schema applied and connect's |
| +// Bridge over it, the move not yet run: the state New is in just before it. |
| +func (l *legacyLinks) openLegacy() (*db.DB, *homeRoutes) { |
| + l.t.Helper() |
| + d, err := db.Open(l.cfg.DBPath, nil) |
| + if err != nil { |
| + l.t.Fatal(err) |
| + } |
| + l.t.Cleanup(func() { d.Close() }) |
| + schema := BootSchema |
| + if l.team { |
| + schema = TeamBootSchema |
| + } |
| + if _, err = migrate.Apply(l.t.Context(), d, schema); err != nil { |
| + l.t.Fatal(err) |
| + } |
| + settings, err := validatedHomeConfig(l.cfg.Home, bridgeOrigin) |
| + if err != nil { |
| + l.t.Fatal(err) |
| + } |
| + h, err := newHome(settings, bridgeOrigin, d.Writer(), &Store{db: d.G}, l.team) |
| + if err != nil { |
| + l.t.Fatal(err) |
| + } |
| + return d, h |
| +} |
| + |
| +// A move that stops partway, by an error or a cancelled context, leaves |
| +// the database as it found it, and the next attempt redoes all of it. |
| +func TestLinksMoveThatStopsPartwayLeavesTheOldState(t *testing.T) { |
| + l := newLegacyLinks(t, true) |
| + d, h := l.openLegacy() |
| + w := d.Writer() |
| + before, rows, clock := schemaDump(t, w), oldLinks(t, w), linkClock(t, w, "docs_link_clock") |
| + newClock := linkClock(t, w, "home_link_clock") |
| + for _, name := range []string{"storage", "cancelled"} { |
| + ctx, cancel := context.WithCancel(t.Context()) |
| + defer cancel() |
| + stop := func(context.Context, *sql.Tx, string, string, int64) error { return connectlinks.ErrStorage } |
| + if name == "cancelled" { |
| + stop = func(context.Context, *sql.Tx, string, string, int64) error { |
| + cancel() |
| + return context.Canceled |
| + } |
| + } |
| + adopted := 0 |
| + err := moveLinksOntoConnect(ctx, w, adoptFunc(func(ctx context.Context, tx *sql.Tx, issuer, subject string, person int64) error { |
| + if adopted++; adopted == 2 { |
| + return stop(ctx, tx, issuer, subject, person) |
| + } |
| + return h.bridge.Adopt(ctx, tx, issuer, subject, person) |
| + })) |
| + if !errors.Is(err, errLinksUnavailable) || adopted != 2 { |
| + t.Fatal(name, "move did not stop", err, adopted) |
| + } |
| + if !reflect.DeepEqual(before, schemaDump(t, w)) || !reflect.DeepEqual(rows, oldLinks(t, w)) || clock != linkClock(t, w, "docs_link_clock") || newClock != linkClock(t, w, "home_link_clock") || len(connectLinks(t, w)) != 0 { |
| + t.Fatal(name, "a stopped move left a half state") |
| + } |
| + } |
| + if err := moveLinksOntoConnect(t.Context(), w, h.bridge); err != nil { |
| + t.Fatal("the redo failed", err) |
| + } |
| + if got := connectLinks(t, w); len(got) != 2 || tableNamed(t, w, "docs_identity_links") { |
| + t.Fatal("the redo did not move everything", got) |
| + } |
| +} |
| + |
| +// A link connect refuses (here, from an issuer Docs no longer trusts) |
| +// aborts the whole move: Docs does not start, and no row is dropped. |
| +func TestLinksMoveAbortsOnARefusedLink(t *testing.T) { |
| + for _, team := range []bool{false, true} { |
| + t.Run(fmt.Sprint("team=", team), func(t *testing.T) { |
| + l := newLegacyLinks(t, team) |
| + d, err := db.Open(l.cfg.DBPath, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = d.Writer().Exec(`INSERT INTO docs_identity_links VALUES('https://old-id.example',?,?)`, "opaque-carol", l.carol); err != nil { |
| + t.Fatal(err) |
| + } |
| + rows := oldLinks(t, d.Writer()) |
| + d.Close() |
| + if app, err := New(l.cfg); !errors.Is(err, errLinksRefused) { |
| + if app != nil { |
| + app.Close() |
| + } |
| + t.Fatal("a refused link did not stop the boot", err) |
| + } |
| + d, h := l.openLegacy() |
| + w := d.Writer() |
| + if !reflect.DeepEqual(rows, oldLinks(t, w)) || len(rows) != 3 || len(connectLinks(t, w)) != 0 || !tableNamed(t, w, "docs_link_clock") { |
| + t.Fatal("a refused move dropped or moved rows") |
| + } |
| + if err := moveLinksOntoConnect(t.Context(), w, h.bridge); !errors.Is(err, errLinksRefused) || !strings.Contains(err.Error(), fmt.Sprintf("person %d", l.carol)) { |
| + t.Fatal("the refusal does not name the person", err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// In a team database the re-pointed disjointness trigger guards every |
| +// adopted row, inside Adopt's own insert. A subject that is both linked |
| +// and Home-only (main's triggers forbade it; here it is forced) is a |
| +// RAISE, which connect reports as ErrStorage, not ErrRefused (Fable, home |
| +// #99 note 7): the move still aborts and leaves everything as it was. |
| +func TestLinksMoveAbortsWhenTheDisjointnessTriggerRefuses(t *testing.T) { |
| + l := newLegacyLinks(t, true) |
| + d, err := db.Open(l.cfg.DBPath, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var trigger string |
| + if err = d.Writer().QueryRow(`SELECT sql FROM sqlite_master WHERE name='docs_home_identity_unique'`).Scan(&trigger); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, q := range []string{ |
| + `DROP TRIGGER docs_home_identity_unique`, |
| + fmt.Sprintf(`UPDATE docs_home_allocator SET high_water=%d WHERE singleton=1`, l.homeOnly+1), |
| + fmt.Sprintf(`INSERT INTO docs_principals VALUES(%d,'home',CURRENT_TIMESTAMP)`, l.homeOnly+1), |
| + fmt.Sprintf(`INSERT INTO docs_home_identities VALUES('%s','%s',%d)`, bridgeIssuer, bobSubject, l.homeOnly+1), |
| + trigger, |
| + } { |
| + if _, err = d.Writer().Exec(q); err != nil { |
| + t.Fatal(q, err) |
| + } |
| + } |
| + d.Close() |
| + if app, err := New(l.cfg); err == nil || errors.Is(err, errLinksRefused) || !errors.Is(err, errLinksUnavailable) { |
| + if app != nil { |
| + app.Close() |
| + } |
| + t.Fatal("the trigger's refusal did not abort as a storage failure", err) |
| + } |
| + d, h := l.openLegacy() |
| + w := d.Writer() |
| + var refusal error |
| + err = moveLinksOntoConnect(t.Context(), w, adoptFunc(func(ctx context.Context, tx *sql.Tx, issuer, subject string, person int64) error { |
| + err := h.bridge.Adopt(ctx, tx, issuer, subject, person) |
| + if subject == bobSubject { |
| + refusal = err |
| + } |
| + return err |
| + })) |
| + if !errors.Is(refusal, connectlinks.ErrStorage) || !errors.Is(err, errLinksUnavailable) { |
| + t.Fatal("the re-pointed trigger did not fire inside Adopt", refusal, err) |
| + } |
| + if len(oldLinks(t, w)) != 2 || len(connectLinks(t, w)) != 0 { |
| + t.Fatal("an aborted move changed the links") |
| + } |
| + var table string |
| + if err = w.QueryRow(`SELECT tbl_name FROM sqlite_master WHERE name='docs_local_identity_unique'`).Scan(&table); err != nil || table != "docs_identity_links" { |
| + t.Fatal("an aborted move kept the re-pointed triggers", table, err) |
| + } |
| +} |
| + |
| +// LookupPerson is a plain read of people: it neither asks the roster nor |
| +// the allowlist, so the move succeeds with the roster unknown (the |
| +// directory down from the first fetch) and with an empty allowlist. |
| +func TestLinksMoveNeedsNeitherTheRosterNorTheAllowlist(t *testing.T) { |
| + l := newLegacyLinks(t, true) |
| + l.fix.directory.change(nil, true) |
| + l.cfg.AllowedAddresses = "nobody@example.com" |
| + f := l.boot() |
| + l.requireMoved(f) |
| + for _, id := range []int64{l.paul, l.bob} { |
| + if _, err := linkedAddress(t.Context(), f.app.db.Writer(), id); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if _, err := linkedAddress(t.Context(), f.app.db.Writer(), l.homeOnly); !errors.Is(err, sql.ErrNoRows) { |
| + t.Fatal("a Home-only principal has an address", err) |
| + } |
| +} |
| + |
| +// A database that moved its links with team mode off can still turn team |
| +// mode on later: principalstore's first migration needs the old table, so |
| +// linkstore.ForPrincipals puts it back, empty, and the move re-points the |
| +// triggers and drops it again. The links and Paul's session survive. |
| +func TestTeamModeTurnedOnAfterTheMove(t *testing.T) { |
| + l := newLegacyLinks(t, false) |
| + f := l.boot() |
| + l.requireMoved(f) |
| + links := connectLinks(t, f.app.db.Writer()) |
| + if err := f.app.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + l.cfg.Team = l.fix.cfg.Team |
| + l.team = true |
| + team := l.boot() |
| + w := team.app.db.Writer() |
| + if tableNamed(t, w, "docs_identity_links") || !reflect.DeepEqual(links, connectLinks(t, w)) { |
| + t.Fatal("turning team mode on lost or kept the wrong tables") |
| + } |
| + var table string |
| + if err := w.QueryRow(`SELECT tbl_name FROM sqlite_master WHERE name='docs_local_identity_unique'`).Scan(&table); err != nil || table != "home_identity_links" { |
| + t.Fatal("the triggers were not re-pointed", table, err) |
| + } |
| + l.requireSignsIn(team, "paul", "Paul's plan") |
| +} |
| + |
| +// The resolver gives team standing only for a link connect would resolve: |
| +// one made for another address (its binding no longer matches) signs |
| +// nobody in, so it is not a Home identity for the local account either. |
| +func TestTeamStandingNeedsALinkConnectResolves(t *testing.T) { |
| + f := newTeamRouterFixture(t) |
| + w := f.app.db.Writer() |
| + if _, err := w.Exec(`INSERT INTO home_identity_links(issuer,subject,person_id,person_binding) VALUES(?,?,?,?)`, bridgeIssuer, teamSubject('a'), f.alice, strings.Repeat("0", 64)); err != nil { |
| + t.Fatal(err) |
| + } |
| + b := f.browser() |
| + b.localSignin(t, "alice@example.com") |
| + if page := b.do("POST", "/documents", "title=Team+rung"); page.Code == 303 { |
| + t.Fatal("a link connect refuses gave team standing") |
| + } |
| + if _, err := f.app.store.team.home.bridge.Resolve(t.Context(), teamSubject('a')); !errors.Is(err, connectlinks.ErrRefused) { |
| + t.Fatal("fixture: connect resolved the stale link", err) |
| + } |
| + // Nor does a Home session for that subject sign in as Alice. |
| + token, err := f.sessions.Mint(sessions.Session{Subject: teamSubject('a'), Method: "home-assertion", AuthTime: time.Now()}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + home := f.browser() |
| + home.cookies[f.sessions.CookieName()] = &http.Cookie{Name: f.sessions.CookieName(), Value: token} |
| + if page := home.do("GET", "/", ""); page.Code == 200 { |
| + t.Fatal("a Home session signed in through a link connect refuses") |
| + } |
| + // The control: a link connect made does give standing. |
| + other := f.browser() |
| + other.localSignin(t, "bob@example.com") |
| + other.linkProof(t, teamSubject('b'), "bob@example.com") |
| + routerRedirect(t, other.do("POST", "/account/home/confirm", ""), connectedURL("/")) |
| + if page := other.do("POST", "/documents", "title=Team+rung"); page.Code != 303 { |
| + t.Fatal("a link connect made gave no team standing", page.Code) |
| + } |
| +} |
diff --git a/internal/docs/home_local_navigation.go b/internal/docs/home_local_navigation.go| deleted file mode 100644 |
| index f797b5b..0000000 |
| --- a/internal/docs/home_local_navigation.go |
| +++ /dev/null |
| @@ -1,212 +0,0 @@ |
| -package docs |
| - |
| -import ( |
| - "bytes" |
| - "encoding/base64" |
| - "encoding/json" |
| - "errors" |
| - "math" |
| - "net/http" |
| - "net/url" |
| - "time" |
| - |
| - "amadan.net/oficina/home/handoff" |
| - "amadan.net/rastrillo/rastrillo" |
| - "amadan.net/rastrillo/rastrillo/sessions" |
| -) |
| - |
| -const localLinkNavigationCookie = "__Host-oficina-docs-local-link-navigation" |
| -const localLinkNavigationLifetime = int64(600) |
| -const localLinkNavigationLimit = 1024 |
| -const localLinkCompletePath = "/auth/local/complete" |
| - |
| -type localLinkMarker struct { |
| - Version int `json:"v"` |
| - Action string `json:"action"` |
| - Issued int64 `json:"issued"` |
| - Expires int64 `json:"expires"` |
| -} |
| - |
| -type localLinkNavigation struct { |
| - sealer handoff.Sealer |
| - sess *sessions.Sessions |
| - origin, host string |
| - now func() time.Time |
| - // resume begins the link for the actual fresh local session and |
| - // redirects to the Home freshness check, or reports false having |
| - // written nothing (homeBridge.resumeLink). |
| - resume func(http.ResponseWriter, *http.Request) bool |
| -} |
| - |
| -// The marker's two actions. linkStart is the account menu's: after local |
| -// sign-in, show the Connect page. linkResume is remembered when an Oficina |
| -// assertion arrived that Docs has no link for: after local sign-in, begin |
| -// the link at once, so the person lands on the confirm step rather than |
| -// hunting for the menu item. |
| -const ( |
| - linkStart = "link-start" |
| - linkResume = "link-resume" |
| -) |
| - |
| -var ( |
| - errNavigationClock = errors.New("docs: navigation clock unusable") |
| - errNavigationSeal = errors.New("docs: navigation marker unavailable") |
| -) |
| - |
| -// newLocalLinkNavigation takes the already validated suite origin and the same |
| -// session store used by local auth. The marker conveys navigation only. |
| -func newLocalLinkNavigation(sealer handoff.Sealer, sess *sessions.Sessions, origin string) *localLinkNavigation { |
| - u, err := url.Parse(origin) |
| - if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" || sealer == nil || sess == nil { |
| - return nil |
| - } |
| - return &localLinkNavigation{sealer: sealer, sess: sess, origin: origin, host: u.Host, now: time.Now} |
| -} |
| - |
| -func localNavigationCookie(w http.ResponseWriter, name, value string, age int) { |
| - http.SetCookie(w, &http.Cookie{Name: name, Value: value, Path: "/", Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode, MaxAge: age}) |
| -} |
| - |
| -func (n *localLinkNavigation) purpose() string { return "docs.local-link-navigation.v1:" + n.origin } |
| - |
| -func (n *localLinkNavigation) guard(w http.ResponseWriter, r *http.Request, path string) bool { |
| - w.Header().Set("Cache-Control", "no-store") |
| - if r.Method != http.MethodGet { |
| - w.Header().Set("Allow", http.MethodGet) |
| - http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusMethodNotAllowed) |
| - return false |
| - } |
| - if r.Host != n.host || r.URL.Path != path || r.URL.RawQuery != "" { |
| - http.Redirect(w, r, "/", http.StatusSeeOther) |
| - return false |
| - } |
| - return true |
| -} |
| - |
| -// Begin abandons browser pointers to an old link. Rotation and freshness also |
| -// invalidate its binding; clearing cookies does not consume database rows. |
| -// A cross-site top-level GET may abandon a flow, but cannot create a link. |
| -func (n *localLinkNavigation) Begin(w http.ResponseWriter, r *http.Request) { |
| - localNavigationCookie(w, localLinkNavigationCookie, "", -1) |
| - if !n.guard(w, r, "/account/home") { |
| - return |
| - } |
| - localNavigationCookie(w, "__Host-docs-home-init", "", -1) |
| - localNavigationCookie(w, "__Host-docs-home-proof", "", -1) |
| - encoded, err := n.seal(linkStart) |
| - if errors.Is(err, errNavigationClock) { |
| - http.Redirect(w, r, "/", http.StatusSeeOther) |
| - return |
| - } |
| - if err != nil { |
| - http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusServiceUnavailable) |
| - return |
| - } |
| - localNavigationCookie(w, localLinkNavigationCookie, encoded, int(localLinkNavigationLifetime)) |
| - http.Redirect(w, r, "/signin/local", http.StatusSeeOther) |
| -} |
| - |
| -// seal returns the encoded marker for action. |
| -func (n *localLinkNavigation) seal(action string) (string, error) { |
| - now := n.now().Unix() |
| - if now <= 0 || now > math.MaxInt64-localLinkNavigationLifetime { |
| - return "", errNavigationClock |
| - } |
| - payload, _ := json.Marshal(localLinkMarker{Version: 1, Action: action, Issued: now, Expires: now + localLinkNavigationLifetime}) |
| - sealed, err := n.sealer.Seal(n.purpose(), payload) |
| - if err != nil { |
| - return "", errNavigationSeal |
| - } |
| - encoded := base64.RawURLEncoding.EncodeToString(sealed) |
| - if len(encoded) > localLinkNavigationLimit { |
| - return "", errNavigationSeal |
| - } |
| - return encoded, nil |
| -} |
| - |
| -// rememberUnknown records, in the same sealed short-lived marker, that an |
| -// Oficina assertion arrived with no link here. It carries no identity: the |
| -// link is still bound to a fresh Home assertion and an explicit confirm, as |
| -// from the menu. Failing to seal costs only the shortcut. |
| -func (n *localLinkNavigation) rememberUnknown(w http.ResponseWriter) { |
| - if encoded, err := n.seal(linkResume); err == nil { |
| - localNavigationCookie(w, localLinkNavigationCookie, encoded, int(localLinkNavigationLifetime)) |
| - } |
| -} |
| - |
| -// marker returns the action of the one valid, unexpired marker, or "". |
| -func (n *localLinkNavigation) marker(r *http.Request, now int64) string { |
| - value := "" |
| - count := 0 |
| - for _, c := range r.Cookies() { |
| - if c.Name == localLinkNavigationCookie { |
| - count++ |
| - value = c.Value |
| - } |
| - } |
| - if count != 1 || value == "" || len(value) > localLinkNavigationLimit { |
| - return "" |
| - } |
| - sealed, err := base64.RawURLEncoding.Strict().DecodeString(value) |
| - if err != nil || base64.RawURLEncoding.EncodeToString(sealed) != value { |
| - return "" |
| - } |
| - payload, err := n.sealer.Open(n.purpose(), sealed) |
| - if err != nil || len(payload) > localLinkNavigationLimit { |
| - return "" |
| - } |
| - var marker localLinkMarker |
| - if json.Unmarshal(payload, &marker) != nil { |
| - return "" |
| - } |
| - // Only this helper writes the payload. Exact re-encoding excludes duplicate |
| - // and unknown fields, alternate numbers, and any trailing JSON value. |
| - canonical, _ := json.Marshal(marker) |
| - if !bytes.Equal(payload, canonical) { |
| - return "" |
| - } |
| - if marker.Version == 1 && (marker.Action == linkStart || marker.Action == linkResume) && marker.Issued > 0 && marker.Issued <= now && now < marker.Expires && marker.Expires > marker.Issued && marker.Expires-marker.Issued <= localLinkNavigationLifetime { |
| - return marker.Action |
| - } |
| - return "" |
| -} |
| - |
| -// Complete reads the newly presented session after local verification. It |
| -// never confirms a link, and never treats a Home mint as local proof. With |
| -// a remembered unknown assertion it begins one, exactly as the Connect |
| -// button would, which is bound to this fresh session and still needs a |
| -// fresh Home assertion and an explicit same-origin confirm. A copied marker |
| -// can at most repeat that navigation. An expired marker is ignored: the |
| -// person lands as from any sign-in, with the menu item still on offer. |
| -func (n *localLinkNavigation) Complete(w http.ResponseWriter, r *http.Request) { |
| - localNavigationCookie(w, localLinkNavigationCookie, "", -1) |
| - if !n.guard(w, r, localLinkCompletePath) { |
| - return |
| - } |
| - now := n.now() |
| - // The page the person was sent to sign in from (spec §9.4), or the |
| - // list. The Home link-start marker still wins: that flow resumes at |
| - // /account/home. The remembered page is left in place, as it always |
| - // was: LinkStart reads it too, so connecting accounts right after |
| - // signing in still returns to the same document. |
| - target := n.returnPath(r) |
| - if action := n.marker(r, now.Unix()); action != "" { |
| - count := 0 |
| - for _, c := range r.Cookies() { |
| - if c.Name == n.sess.CookieName() { |
| - count++ |
| - } |
| - } |
| - if count == 1 { |
| - if session, ok := n.sess.From(r); ok { |
| - if _, fresh := freshLocalAuthentication(session, now); fresh { |
| - if action == linkResume && n.resume != nil && n.resume(w, r) { |
| - return |
| - } |
| - target = "/account/home" |
| - } |
| - } |
| - } |
| - } |
| - http.Redirect(w, r, target, http.StatusSeeOther) |
| -} |
diff --git a/internal/docs/home_local_navigation_test.go b/internal/docs/home_local_navigation_test.go| deleted file mode 100644 |
| index c9a6d1a..0000000 |
| --- a/internal/docs/home_local_navigation_test.go |
| +++ /dev/null |
| @@ -1,321 +0,0 @@ |
| -package docs |
| - |
| -import ( |
| - "bytes" |
| - "context" |
| - "encoding/base64" |
| - "encoding/json" |
| - "errors" |
| - "net/http" |
| - "net/http/httptest" |
| - "strings" |
| - "testing" |
| - "time" |
| - |
| - "amadan.net/oficina/home/handoff/seal" |
| - rauth "amadan.net/rastrillo/rastrillo/auth" |
| - "amadan.net/rastrillo/rastrillo/sessions" |
| -) |
| - |
| -const navigationOrigin = "https://docs.example.com" |
| - |
| -type navigationMail struct{} |
| - |
| -func (navigationMail) Send(context.Context, string, string, string) error { return nil } |
| - |
| -func navigationFixture(t *testing.T) (*App, *localLinkNavigation) { |
| - t.Helper() |
| - app, err := NewForTestWith(t, Config{Origin: navigationOrigin, SampleDocuments: "0", Mailer: navigationMail{}}) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - sess, err := sessions.New(sessions.Config{DB: app.db.Writer(), Origin: navigationOrigin}) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - sealer, err := seal.New(bytes.Repeat([]byte{19}, 32), "oficina/docs") |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - n := newLocalLinkNavigation(sealer, sess, navigationOrigin) |
| - if n == nil { |
| - t.Fatal("navigation config refused") |
| - } |
| - return app, n |
| -} |
| -func navigationRequest(path string) *http.Request { |
| - return httptest.NewRequest("GET", navigationOrigin+path, nil) |
| -} |
| -func navigationMarker(t *testing.T, n *localLinkNavigation) *http.Cookie { |
| - t.Helper() |
| - rec := httptest.NewRecorder() |
| - n.Begin(rec, navigationRequest("/account/home")) |
| - if rec.Code != 303 || rec.Header().Get("Location") != "/signin/local" { |
| - t.Fatal("local navigation did not begin") |
| - } |
| - var marker *http.Cookie |
| - for _, c := range rec.Result().Cookies() { |
| - if c.Name == localLinkNavigationCookie && c.MaxAge > 0 { |
| - marker = c |
| - } |
| - } |
| - if marker == nil { |
| - t.Fatal("navigation marker missing") |
| - } |
| - return marker |
| -} |
| -func navigationSession(t *testing.T, n *localLinkNavigation, s sessions.Session) *http.Cookie { |
| - t.Helper() |
| - rec := httptest.NewRecorder() |
| - if err := n.sess.SignIn(rec, navigationRequest("/"), s); err != nil { |
| - t.Fatal(err) |
| - } |
| - for _, c := range rec.Result().Cookies() { |
| - if c.Name == n.sess.CookieName() { |
| - return c |
| - } |
| - } |
| - t.Fatal("session cookie missing") |
| - return nil |
| -} |
| -func assertNavigation(t *testing.T, n *localLinkNavigation, r *http.Request, want string) { |
| - t.Helper() |
| - rec := httptest.NewRecorder() |
| - n.Complete(rec, r) |
| - if rec.Code != 303 || rec.Header().Get("Location") != want || rec.Header().Get("Cache-Control") != "no-store" { |
| - t.Fatalf("navigation status=%d target=%q wanted%q", rec.Code, rec.Header().Get("Location"), want) |
| - } |
| - cleared := false |
| - for _, c := range rec.Result().Cookies() { |
| - if c.Name == localLinkNavigationCookie && c.MaxAge < 0 { |
| - cleared = true |
| - } |
| - } |
| - if !cleared { |
| - t.Fatal("marker not cleared") |
| - } |
| -} |
| - |
| -func TestLocalNavigationBeginIsBoundedFixedAndClearsOldPointers(t *testing.T) { |
| - _, n := navigationFixture(t) |
| - now := time.Now().Truncate(time.Second) |
| - n.now = func() time.Time { return now } |
| - rec := httptest.NewRecorder() |
| - n.Begin(rec, navigationRequest("/account/home")) |
| - cleared := map[string]bool{} |
| - for _, c := range rec.Result().Cookies() { |
| - if !c.Secure || !c.HttpOnly || c.Domain != "" || c.Path != "/" || c.SameSite != http.SameSiteLaxMode { |
| - t.Fatal("cookie policy weakened") |
| - } |
| - if c.MaxAge < 0 { |
| - cleared[c.Name] = true |
| - } |
| - } |
| - if !cleared["__Host-docs-home-init"] || !cleared["__Host-docs-home-proof"] { |
| - t.Fatal("old link browser pointers retained") |
| - } |
| - marker := navigationMarker(t, n) |
| - if marker.MaxAge != 600 || len(marker.Value) > 1024 { |
| - t.Fatal("unbounded navigation") |
| - } |
| - encrypted, err := base64.RawURLEncoding.DecodeString(marker.Value) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - plain, err := n.sealer.Open(n.purpose(), encrypted) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - want, _ := json.Marshal(localLinkMarker{1, "link-start", now.Unix(), now.Unix() + 600}) |
| - if !bytes.Equal(plain, want) { |
| - t.Fatal("navigation carries something beyond fixed action/time") |
| - } |
| - for _, path := range []string{"/account/home?return_to=%2Fsecret", "/account/home?next=https://evil.example", "/other"} { |
| - rec = httptest.NewRecorder() |
| - n.Begin(rec, navigationRequest(path)) |
| - if rec.Code != 303 || rec.Header().Get("Location") != "/" { |
| - t.Fatal("caller selected navigation") |
| - } |
| - for _, c := range rec.Result().Cookies() { |
| - if c.MaxAge > 0 { |
| - t.Fatal("bad path set marker") |
| - } |
| - } |
| - } |
| -} |
| - |
| -func TestLocalNavigationUsesActualFreshSessionMethod(t *testing.T) { |
| - app, n := navigationFixture(t) |
| - now := time.Now().Truncate(time.Second) |
| - n.now = func() time.Time { return now } |
| - for _, tc := range []struct { |
| - name, method string |
| - auth, created time.Time |
| - want string |
| - }{ |
| - {"magic zero", "magiclink", time.Time{}, now, "/account/home"}, |
| - {"magic old stored At", "magiclink", time.Time{}, now.Add(-301 * time.Second), "/"}, |
| - {"magic future stored At", "magiclink", time.Time{}, now.Add(time.Second), "/"}, |
| - {"magic actual boundary", "magiclink", now.Add(-300 * time.Second), now, "/account/home"}, |
| - {"magic old original", "magiclink", now.Add(-301 * time.Second), now, "/"}, |
| - {"magic future original", "magiclink", now.Add(time.Second), now, "/"}, |
| - {"Home remint", "home-assertion", time.Time{}, now, "/"}, |
| - {"Home fresh claim", "home-assertion", now, now, "/"}, |
| - {"keymail zero", "keymail", time.Time{}, now, "/"}, |
| - {"keymail fresh", "keymail", now.Add(-time.Minute), now, "/account/home"}, |
| - {"keymail stale", "keymail", now.Add(-301 * time.Second), now, "/"}, |
| - {"unknown", "password", now, now, "/"}, |
| - } { |
| - t.Run(tc.name, func(t *testing.T) { |
| - cookie := navigationSession(t, n, sessions.Session{Subject: "local@example.com", Method: tc.method, AuthTime: tc.auth}) |
| - if _, err := app.db.Writer().Exec(`UPDATE sessions SET created_at=? WHERE token_hash=?`, tc.created.UTC().Format(time.RFC3339), sessions.HashToken(cookie.Value)); err != nil { |
| - t.Fatal(err) |
| - } |
| - r := navigationRequest(localLinkCompletePath) |
| - r.AddCookie(navigationMarker(t, n)) |
| - r.AddCookie(cookie) |
| - assertNavigation(t, n, r, tc.want) |
| - }) |
| - } |
| -} |
| - |
| -func TestLocalNavigationRealEmailRotationAndChangedAccount(t *testing.T) { |
| - app, n := navigationFixture(t) |
| - // This plugin differs only in its configured successful local landing. |
| - plugin, err := rauth.New(rauth.Config{DB: app.db.Writer(), Origin: navigationOrigin, InstanceKey: devInstanceKey, Mailer: app.mailRecorder, SignedInPath: localLinkCompletePath, ProofOff: true}) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - first := app.TestRequest(t, "first@example.com", "GET", "/", nil) |
| - old, err := first.Cookie(n.sess.CookieName()) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - marker := navigationMarker(t, n) |
| - // The newly verified account may differ: only the displayed initiation page |
| - // is reached. No old account proof or local person is carried by the marker. |
| - link, err := app.TestSignIn(t, "second@example.com") |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - verify := confirmRequest(link) |
| - verify.AddCookie(old) |
| - rec := httptest.NewRecorder() |
| - plugin.Verify(rec, verify) |
| - if rec.Code != 303 || rec.Header().Get("Location") != localLinkCompletePath { |
| - t.Fatal("actual plugin did not use fixed landing") |
| - } |
| - if _, ok := n.sess.From(first); ok { |
| - t.Fatal("old actual session survived rotation") |
| - } |
| - complete := navigationRequest(localLinkCompletePath) |
| - complete.AddCookie(marker) |
| - for _, c := range rec.Result().Cookies() { |
| - complete.AddCookie(c) |
| - } |
| - actual, ok := n.sess.From(complete) |
| - if !ok || actual.Subject != "second@example.com" || actual.Method != "magiclink" || !actual.AuthTime.IsZero() { |
| - t.Fatal("real email verification identity wrong") |
| - } |
| - assertNavigation(t, n, complete, "/account/home") |
| - // Ordinary local verification has no continuation marker and still lands /. |
| - ordinary := navigationRequest(localLinkCompletePath) |
| - for _, c := range rec.Result().Cookies() { |
| - ordinary.AddCookie(c) |
| - } |
| - assertNavigation(t, n, ordinary, "/") |
| - failed := httptest.NewRecorder() |
| - plugin.Verify(failed, verify) |
| - if failed.Header().Get("Location") == localLinkCompletePath { |
| - t.Fatal("failed replayed verification reached bridge") |
| - } |
| -} |
| - |
| -func TestLocalNavigationRejectsAmbiguousCookies(t *testing.T) { |
| - _, n := navigationFixture(t) |
| - marker := navigationMarker(t, n) |
| - cookie := navigationSession(t, n, sessions.Session{Subject: "local@example.com", Method: "magiclink"}) |
| - for _, cookies := range [][]*http.Cookie{nil, {marker}, {cookie}, {marker, marker, cookie}, {marker, cookie, cookie}, {marker, {Name: n.sess.CookieName(), Value: "unknown"}}, {marker, cookie, {Name: n.sess.CookieName(), Value: "unknown"}}} { |
| - r := navigationRequest(localLinkCompletePath) |
| - for _, c := range cookies { |
| - r.AddCookie(c) |
| - } |
| - assertNavigation(t, n, r, "/") |
| - } |
| -} |
| - |
| -func TestLocalNavigationRejectsInvalidMarkersAndOtherHosts(t *testing.T) { |
| - _, n := navigationFixture(t) |
| - now := time.Now().Truncate(time.Second) |
| - n.now = func() time.Time { return now } |
| - cookie := navigationSession(t, n, sessions.Session{Subject: "local@example.com", Method: "magiclink"}) |
| - valid := navigationMarker(t, n).Value |
| - plain := func(m localLinkMarker) string { b, _ := json.Marshal(m); return string(b) } |
| - base := localLinkMarker{1, "link-start", now.Unix(), now.Unix() + 600} |
| - badJSON := []string{ |
| - "{}", `{"v":1,"v":1,"action":"link-start","issued":1,"expires":2}`, |
| - plain(base) + " {}", strings.TrimSuffix(plain(base), "}") + `,"unknown":true}`, |
| - } |
| - for _, m := range []localLinkMarker{{2, "link-start", now.Unix(), now.Unix() + 600}, {1, "other", now.Unix(), now.Unix() + 600}, {1, "link-start", 0, now.Unix() + 600}, {1, "link-start", now.Unix() + 1, now.Unix() + 600}, {1, "link-start", now.Unix() - 600, now.Unix()}, {1, "link-start", now.Unix(), now.Unix() + 601}} { |
| - badJSON = append(badJSON, plain(m)) |
| - } |
| - badValues := []string{"", strings.Repeat("a", 1025), valid + "=", "%" + valid, valid[:len(valid)-2]} |
| - for _, p := range badJSON { |
| - sealed, err := n.sealer.Seal(n.purpose(), []byte(p)) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - badValues = append(badValues, base64.RawURLEncoding.EncodeToString(sealed)) |
| - } |
| - otherPurpose, err := n.sealer.Seal("docs.local-link-navigation.v1:https://other.example", []byte(plain(base))) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - badValues = append(badValues, base64.RawURLEncoding.EncodeToString(otherPurpose)) |
| - for _, value := range badValues { |
| - r := navigationRequest(localLinkCompletePath) |
| - r.AddCookie(cookie) |
| - r.AddCookie(&http.Cookie{Name: localLinkNavigationCookie, Value: value}) |
| - assertNavigation(t, n, r, "/") |
| - } |
| - for _, change := range []func(*http.Request){func(r *http.Request) { r.Host = "other.example" }, func(r *http.Request) { r.URL.RawQuery = "return_to=https://evil.example" }, func(r *http.Request) { r.URL.Path = "/wrong" }} { |
| - r := navigationRequest(localLinkCompletePath) |
| - r.AddCookie(cookie) |
| - r.AddCookie(&http.Cookie{Name: localLinkNavigationCookie, Value: valid}) |
| - change(r) |
| - assertNavigation(t, n, r, "/") |
| - } |
| - // A valid marker expires independently of the browser cookie's MaxAge. |
| - n.now = func() time.Time { return now.Add(600 * time.Second) } |
| - r := navigationRequest(localLinkCompletePath) |
| - r.AddCookie(cookie) |
| - r.AddCookie(&http.Cookie{Name: localLinkNavigationCookie, Value: valid}) |
| - assertNavigation(t, n, r, "/") |
| -} |
| - |
| -type navigationBrokenSealer struct{} |
| - |
| -func (navigationBrokenSealer) Seal(string, []byte) ([]byte, error) { |
| - return nil, errors.New("private failure") |
| -} |
| -func (navigationBrokenSealer) Open(string, []byte) ([]byte, error) { |
| - return nil, errors.New("private failure") |
| -} |
| -func TestLocalNavigationStorageFailureAndMethod(t *testing.T) { |
| - _, n := navigationFixture(t) |
| - n.sealer = navigationBrokenSealer{} |
| - rec := httptest.NewRecorder() |
| - n.Begin(rec, navigationRequest("/account/home")) |
| - if rec.Code != 503 || strings.Contains(rec.Body.String(), "private") || rec.Header().Get("Location") != "" { |
| - t.Fatal("storage failure published/leaked navigation") |
| - } |
| - for _, fn := range []http.HandlerFunc{n.Begin, n.Complete} { |
| - rec = httptest.NewRecorder() |
| - r := navigationRequest(localLinkCompletePath) |
| - r.Method = "POST" |
| - fn(rec, r) |
| - if rec.Code != 405 || rec.Header().Get("Allow") != "GET" || rec.Header().Get("Cache-Control") != "no-store" { |
| - t.Fatal("wrong method accepted") |
| - } |
| - } |
| -} |
diff --git a/internal/docs/home_return.go b/internal/docs/home_return.go| index 71962e5..f43f61d 100644 |
| --- a/internal/docs/home_return.go |
| +++ b/internal/docs/home_return.go |
| @@ -6,12 +6,57 @@ import ( |
| "encoding/json" |
| "math" |
| "net/http" |
| + "net/url" |
| + "time" |
| + "amadan.net/oficina/home/connect" |
| "amadan.net/oficina/home/handoff" |
| + "amadan.net/rastrillo/rastrillo" |
| ) |
| const homeReturnCookie = "__Host-oficina-docs-home-return" |
| const homeReturnLimit = 4096 |
| +const returnLifetime = int64(600) |
| + |
| +// localLinkCompletePath is where a local sign-in lands (rastrillo/auth's |
| +// SignedInPath), connect's path with Home and Docs' own without. |
| +const localLinkCompletePath = connect.LocalCompletePath |
| + |
| +// returnMemory is the page a sign-in began from (spec §9.4), in a sealed, |
| +// ten-minute cookie: Docs' own, beside connect's, because connect lands a |
| +// local sign-in on a fixed path and keeps its memory to itself |
| +// (home_connect.go). Standalone Docs uses it too (signin_return.go). |
| +type returnMemory struct { |
| + sealer handoff.Sealer |
| + origin, host string |
| + now func() time.Time |
| +} |
| + |
| +func newReturnMemory(sealer handoff.Sealer, origin string) *returnMemory { |
| + u, err := url.Parse(origin) |
| + if err != nil || u.Host == "" || u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" || sealer == nil { |
| + return nil |
| + } |
| + return &returnMemory{sealer: sealer, origin: origin, host: u.Host, now: time.Now} |
| +} |
| + |
| +func localNavigationCookie(w http.ResponseWriter, name, value string, age int) { |
| + http.SetCookie(w, &http.Cookie{Name: name, Value: value, Path: "/", Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode, MaxAge: age}) |
| +} |
| + |
| +func (n *returnMemory) guard(w http.ResponseWriter, r *http.Request, path string) bool { |
| + w.Header().Set("Cache-Control", "no-store") |
| + if r.Method != http.MethodGet { |
| + w.Header().Set("Allow", http.MethodGet) |
| + http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusMethodNotAllowed) |
| + return false |
| + } |
| + if r.Host != n.host || r.URL.Path != path || r.URL.RawQuery != "" { |
| + http.Redirect(w, r, "/", http.StatusSeeOther) |
| + return false |
| + } |
| + return true |
| +} |
| type homeReturnIntent struct { |
| Path string `json:"path"` |
| @@ -19,17 +64,17 @@ type homeReturnIntent struct { |
| Expires int64 `json:"expires"` |
| } |
| -// Resource navigation is separate from the fixed-action local reauth marker. |
| -// Neither cookie authorizes linking or access to the requested document. |
| -func (n *localLinkNavigation) rememberReturn(w http.ResponseWriter, path string) bool { |
| +// The remembered page authorizes nothing: not linking, and not access to |
| +// the document it names. |
| +func (n *returnMemory) rememberReturn(w http.ResponseWriter, path string) bool { |
| if !handoff.SafePath(path) { |
| path = "/" |
| } |
| now := n.now().Unix() |
| - if now <= 0 || now > math.MaxInt64-localLinkNavigationLifetime { |
| + if now <= 0 || now > math.MaxInt64-returnLifetime { |
| return false |
| } |
| - raw, err := json.Marshal(homeReturnIntent{path, now, now + localLinkNavigationLifetime}) |
| + raw, err := json.Marshal(homeReturnIntent{path, now, now + returnLifetime}) |
| if err != nil { |
| return false |
| } |
| @@ -41,11 +86,11 @@ func (n *localLinkNavigation) rememberReturn(w http.ResponseWriter, path string) |
| if len(value) > homeReturnLimit { |
| return false |
| } |
| - localNavigationCookie(w, homeReturnCookie, value, int(localLinkNavigationLifetime)) |
| + localNavigationCookie(w, homeReturnCookie, value, int(returnLifetime)) |
| return true |
| } |
| -func (n *localLinkNavigation) returnPath(r *http.Request) string { |
| +func (n *returnMemory) returnPath(r *http.Request) string { |
| value := "" |
| if cookieCount(r, homeReturnCookie) != 1 { |
| return "/" |
| @@ -72,7 +117,7 @@ func (n *localLinkNavigation) returnPath(r *http.Request) string { |
| } |
| canonical, _ := json.Marshal(intent) |
| now := n.now().Unix() |
| - if !bytes.Equal(raw, canonical) || intent.Issued <= 0 || intent.Issued > now || intent.Expires <= now || intent.Expires <= intent.Issued || intent.Expires-intent.Issued > localLinkNavigationLifetime || !handoff.SafePath(intent.Path) { |
| + if !bytes.Equal(raw, canonical) || intent.Issued <= 0 || intent.Issued > now || intent.Expires <= now || intent.Expires <= intent.Issued || intent.Expires-intent.Issued > returnLifetime || !handoff.SafePath(intent.Path) { |
| return "/" |
| } |
| return intent.Path |
diff --git a/internal/docs/home_router_integration_test.go b/internal/docs/home_router_integration_test.go| index 4cfc169..b737b96 100644 |
| --- a/internal/docs/home_router_integration_test.go |
| +++ b/internal/docs/home_router_integration_test.go |
| @@ -269,7 +269,7 @@ func TestHomeRouterExistingAccountRoundTripPreservesOwnedAndSharedContent(t *tes |
| if unknown.Code != 403 || !strings.Contains(unknown.Body.String(), "/signin/local") { |
| t.Fatal("unknown Home subject did not show local guidance", unknown.Code) |
| } |
| - if routerRows(t, f, "people") != 2 || routerRows(t, f, "documents") != 3 || routerRows(t, f, "docs_identity_links") != 0 || b.cookies[f.sessions.CookieName()] != nil { |
| + if routerRows(t, f, "people") != 2 || routerRows(t, f, "documents") != 3 || routerRows(t, f, "home_identity_links") != 0 || b.cookies[f.sessions.CookieName()] != nil { |
| t.Fatal("unknown Home subject created an account or session") |
| } |
| // The unknown arrival is remembered, so signing in locally resumes the |
| @@ -283,11 +283,11 @@ func TestHomeRouterExistingAccountRoundTripPreservesOwnedAndSharedContent(t *tes |
| if confirm := b.do("GET", "/account/home/confirm", ""); confirm.Code != 200 || !strings.Contains(confirm.Body.String(), "alice@example.com") { |
| t.Fatal("confirmation did not identify local account", confirm.Code) |
| } |
| - if b.cookies[f.sessions.CookieName()].Value != localCookie || routerRows(t, f, "docs_identity_links") != 0 { |
| + if b.cookies[f.sessions.CookieName()].Value != localCookie || routerRows(t, f, "home_identity_links") != 0 { |
| t.Fatal("proof replaced local session or linked before confirmation") |
| } |
| routerRedirect(t, b.do("POST", "/account/home/confirm", ""), connectedURL(resource)) |
| - if b.cookies[f.sessions.CookieName()].Value != localCookie || routerRows(t, f, "docs_identity_links") != 1 { |
| + if b.cookies[f.sessions.CookieName()].Value != localCookie || routerRows(t, f, "home_identity_links") != 1 { |
| t.Fatal("confirmation failed local session retention") |
| } |
| if rec := b.do("GET", resource, ""); rec.Code != 200 { |
| @@ -366,7 +366,7 @@ func TestHomeRouterCSRFGuardsBothLinkMutations(t *testing.T) { |
| r.Header.Set("Origin", "https://evil.example") |
| r.Header.Set("Sec-Fetch-Site", fetch) |
| rec := b.serve(r) |
| - if rec.Code != 403 || routerRows(t, f, "docs_link_flows") != 0 { |
| + if rec.Code != 403 || routerRows(t, f, "home_link_flows") != 0 { |
| t.Fatal("actual router permitted foreign link initiation", rec.Code) |
| } |
| } |
| @@ -376,12 +376,12 @@ func TestHomeRouterCSRFGuardsBothLinkMutations(t *testing.T) { |
| r.Header.Set("Origin", "https://evil.example") |
| r.Header.Set("Sec-Fetch-Site", fetch) |
| rec := b.serve(r) |
| - if rec.Code != 403 || routerRows(t, f, "docs_identity_links") != 0 || routerRows(t, f, "docs_link_flows") != 1 { |
| + if rec.Code != 403 || routerRows(t, f, "home_identity_links") != 0 || routerRows(t, f, "home_link_flows") != 1 { |
| t.Fatal("actual router permitted foreign confirmation or consumed valid proof", rec.Code) |
| } |
| } |
| routerRedirect(t, b.do("POST", "/account/home/confirm", ""), connectedURL("/")) |
| - if routerRows(t, f, "docs_identity_links") != 1 { |
| + if routerRows(t, f, "home_identity_links") != 1 { |
| t.Fatal("valid same-origin confirmation failed after refusal") |
| } |
| } |
| @@ -433,7 +433,7 @@ func TestHomeRouterStaleLocalGestureRestartsWithoutResumingProof(t *testing.T) { |
| b.linkProof(t, "opaque-alice", "alice@example.com") |
| oldProof := b.cookies[homeProofCookie] |
| oldSession := b.cookies[f.sessions.CookieName()] |
| - if oldProof == nil || routerRows(t, f, "docs_link_flows") != 1 { |
| + if oldProof == nil || routerRows(t, f, "home_link_flows") != 1 { |
| t.Fatal("pending proof fixture missing") |
| } |
| // Move only the actual stored local verification time into the past. The |
| @@ -452,7 +452,7 @@ func TestHomeRouterStaleLocalGestureRestartsWithoutResumingProof(t *testing.T) { |
| verifyPath, verifyForm := confirmForm(path) |
| routerRedirect(t, b.do("POST", verifyPath, verifyForm), localLinkCompletePath) |
| routerRedirect(t, b.do("GET", localLinkCompletePath, ""), "/account/home") |
| - if b.cookies[f.sessions.CookieName()].Value == oldSession.Value || b.cookies[homeProofCookie] != nil || b.cookies[homeInitCookie] != nil || routerRows(t, f, "docs_identity_links") != 0 { |
| + if b.cookies[f.sessions.CookieName()].Value == oldSession.Value || b.cookies[homeProofCookie] != nil || b.cookies[homeInitCookie] != nil || routerRows(t, f, "home_identity_links") != 0 { |
| t.Fatal("navigation minted or resumed link authority") |
| } |
| if rec := b.do("GET", "/account/home", ""); rec.Code != 200 { |
| @@ -463,7 +463,7 @@ func TestHomeRouterStaleLocalGestureRestartsWithoutResumingProof(t *testing.T) { |
| if rec := b.do("POST", "/account/home/confirm", ""); rec.Code != 403 { |
| t.Fatal("old proof resumed after actual session rotation", rec.Code) |
| } |
| - if routerRows(t, f, "docs_identity_links") != 0 || routerRows(t, f, "docs_link_flows") != 0 { |
| + if routerRows(t, f, "home_identity_links") != 0 || routerRows(t, f, "home_link_flows") != 0 { |
| t.Fatal("old proof failure created link or retained reusable proof") |
| } |
| oldRequest := httptest.NewRequest("GET", bridgeOrigin+"/", nil) |
| @@ -473,7 +473,7 @@ func TestHomeRouterStaleLocalGestureRestartsWithoutResumingProof(t *testing.T) { |
| } |
| // Only this new explicit POST creates a new initiation, not the email or GET. |
| routerRedirect(t, b.do("POST", "/account/home", ""), "/auth/start?return_to=%2Faccount%2Fhome%2Fconfirm") |
| - if routerRows(t, f, "docs_link_flows") != 1 || routerRows(t, f, "docs_identity_links") != 0 || b.cookies[homeProofCookie] != nil { |
| + if routerRows(t, f, "home_link_flows") != 1 || routerRows(t, f, "home_identity_links") != 0 || b.cookies[homeProofCookie] != nil { |
| t.Fatal("new explicit initiation state wrong") |
| } |
| } |
| @@ -516,7 +516,7 @@ func TestHomeRouterCallbackChecksExactOriginIssuerAndAudience(t *testing.T) { |
| if rec := b.do("GET", "/auth/finish", ""); rec.Code != 403 || !strings.Contains(rec.Body.String(), "/signin/local") { |
| t.Fatal("unknown verified identity not guided after valid callback") |
| } |
| - if routerRows(t, f, "people") != 0 || routerRows(t, f, "docs_identity_links") != 0 { |
| + if routerRows(t, f, "people") != 0 || routerRows(t, f, "home_identity_links") != 0 { |
| t.Fatal("unknown callback created person/link") |
| } |
| } |
diff --git a/internal/docs/home_routes.go b/internal/docs/home_routes.go| deleted file mode 100644 |
| index 0fe4dac..0000000 |
| --- a/internal/docs/home_routes.go |
| +++ /dev/null |
| @@ -1,215 +0,0 @@ |
| -package docs |
| - |
| -import ( |
| - "database/sql" |
| - "net/http" |
| - "net/url" |
| - "strings" |
| - "time" |
| - |
| - "amadan.net/oficina/home/handoff" |
| - "amadan.net/oficina/home/handoff/seal" |
| - "amadan.net/rastrillo/rastrillo" |
| - rauth "amadan.net/rastrillo/rastrillo/auth" |
| - "amadan.net/rastrillo/rastrillo/csrf" |
| - "amadan.net/rastrillo/rastrillo/sessions" |
| - "github.com/go-chi/chi/v5" |
| -) |
| - |
| -type homeRoutes struct { |
| - bridge *homeBridge |
| - navigation *localLinkNavigation |
| - handlers *handlers |
| - formPolicy string |
| - issuer string |
| -} |
| - |
| -func newHomeRoutes(settings *homeSettings, origin string, db *sql.DB, auth *rauth.Auth, h *handlers) (*homeRoutes, error) { |
| - b, err := newHomeBridge(settings, origin, db, auth, h.render, h.store) |
| - if err != nil { |
| - return nil, err |
| - } |
| - sealer, err := seal.New(settings.dek, "oficina/docs") |
| - if err != nil { |
| - return nil, errHomeConfig |
| - } |
| - navigation := newLocalLinkNavigation(sealer, b.sessions, origin) |
| - if navigation == nil { |
| - return nil, errHomeConfig |
| - } |
| - b.returnPath = navigation.returnPath |
| - b.rememberUnknown = navigation.rememberUnknown |
| - navigation.resume = b.resumeLink |
| - return &homeRoutes{bridge: b, navigation: navigation, handlers: h, formPolicy: homeFormPolicy(settings.issuer), issuer: settings.issuer}, nil |
| -} |
| - |
| -func cookieCount(r *http.Request, name string) int { |
| - n := 0 |
| - for _, c := range r.Cookies() { |
| - if c.Name == name { |
| - n++ |
| - } |
| - } |
| - return n |
| -} |
| - |
| -// Only the assertion callback crosses origins. Its shared consumer validates |
| -// the exact issuer without consulting the browser's local session. |
| -func homeCSRF(origin string, home *homeRoutes) func(http.Handler) http.Handler { |
| - protect := csrf.Protect(origin) |
| - if home == nil { |
| - return protect |
| - } |
| - return func(next http.Handler) http.Handler { |
| - checked := protect(next) |
| - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| - w.Header().Set("Content-Security-Policy", home.formPolicy) |
| - if r.Host != strings.TrimPrefix(origin, "https://") { |
| - http.NotFound(w, r) |
| - return |
| - } |
| - if r.Method == http.MethodPost && r.URL.Path == handoff.CallbackPath { |
| - next.ServeHTTP(w, r) |
| - return |
| - } |
| - if cookieCount(r, home.bridge.sessionCookie) > 1 { |
| - home.bridge.fail(w, r, http.StatusBadRequest) |
| - return |
| - } |
| - checked.ServeHTTP(w, r) |
| - }) |
| - } |
| -} |
| - |
| -// The local plugin resolves the first pending cookie, so reject ambiguity |
| -// before it can verify a gesture or rotate the existing session. |
| -func localAuthGuard(home *homeRoutes, next http.HandlerFunc) http.HandlerFunc { |
| - if home == nil { |
| - return next |
| - } |
| - return func(w http.ResponseWriter, r *http.Request) { |
| - if cookieCount(r, home.bridge.sessionCookie) > 1 || cookieCount(r, "__Host-rastrillo_pending") > 1 { |
| - home.bridge.fail(w, r, http.StatusBadRequest) |
| - return |
| - } |
| - next(w, r) |
| - } |
| -} |
| - |
| -func (h *homeRoutes) mountPublic(r chi.Router) { |
| - r.Get("/signin", h.signin) |
| - r.Get("/signed-out", func(w http.ResponseWriter, r *http.Request) { |
| - h.handlers.render.homeLink(w, r, "signedout", "", http.StatusOK) |
| - }) |
| - r.Get("/signin/local", h.handlers.signin) |
| - r.Get(localLinkCompletePath, h.navigation.Complete) |
| - r.Get(handoff.StartPath, h.bridge.Start) |
| - r.Post(handoff.CallbackPath, h.bridge.Callback) |
| - r.Get(handoff.FinishPath, h.bridge.Finish) |
| -} |
| - |
| -func (h *homeRoutes) signin(w http.ResponseWriter, r *http.Request) { |
| - q, err := url.ParseQuery(r.URL.RawQuery) |
| - if err != nil { |
| - h.bridge.fail(w, r, http.StatusBadRequest) |
| - return |
| - } |
| - // These are outcomes from the existing local email flow. Keep its form |
| - // available even when the browser already has a Home session. |
| - if q.Has("sent") || q.Has("err") || q.Has("force") { |
| - h.handlers.signin(w, r) |
| - return |
| - } |
| - // Already signed in to Docs: straight back, with no form and no new |
| - // Home exchange (spec §9.2). A person with no session goes on to Home |
| - // as before. |
| - // Admitted, not merely holding a session: a refused identity must be |
| - // able to reach sign-in, or the guard and this shortcut redirect to |
| - // each other forever (h.handlers.admitted). |
| - if _, ok := h.bridge.sessions.From(r); ok && h.handlers.admitted(r) { |
| - alreadySignedIn(w, r) |
| - return |
| - } |
| - path := "/" |
| - if values, ok := q["return_to"]; ok && len(values) == 1 && handoff.SafePath(values[0]) { |
| - path = values[0] |
| - } |
| - if !h.navigation.rememberReturn(w, path) { |
| - h.bridge.fail(w, r, http.StatusServiceUnavailable) |
| - return |
| - } |
| - w.Header().Set("Cache-Control", "no-store") |
| - http.Redirect(w, r, handoff.StartPath+"?"+url.Values{"return_to": {path}}.Encode(), http.StatusSeeOther) |
| -} |
| - |
| -func (h *homeRoutes) mountAccount(r chi.Router) { |
| - r.Get("/account/home", func(w http.ResponseWriter, r *http.Request) { |
| - s, ok := sessions.Current(r) |
| - if _, fresh := freshLocalAuthentication(s, time.Now()); !ok || !fresh { |
| - h.navigation.Begin(w, r) |
| - return |
| - } |
| - h.bridge.LinkPage(w, r) |
| - }) |
| - r.Post("/account/home", func(w http.ResponseWriter, r *http.Request) { |
| - s, ok := sessions.Current(r) |
| - if _, fresh := freshLocalAuthentication(s, time.Now()); !ok || !fresh { |
| - w.Header().Set("Cache-Control", "no-store") |
| - http.Redirect(w, r, "/account/home", http.StatusSeeOther) |
| - return |
| - } |
| - h.bridge.LinkStart(w, r) |
| - }) |
| - r.Get("/account/home/confirm", h.bridge.ConfirmPage) |
| - r.Post("/account/home/confirm", func(w http.ResponseWriter, r *http.Request) { |
| - localNavigationCookie(w, homeReturnCookie, "", -1) |
| - h.bridge.ConfirmPost(w, r) |
| - }) |
| -} |
| - |
| -// homeLinkLabel is the account menu's "Connect your Oficina account", or "" |
| -// when there is nothing to connect: offered only to a local person with no |
| -// stored link, whichever way this session signed in. Before, it was offered |
| -// to every session that had not come from a Home assertion, so a linked |
| -// person who used the email link still saw it (Paul, as paul@tito.io). |
| -// A team instance already resolved the link with the identity; otherwise |
| -// it is one indexed lookup per menu render. Not knowing offers nothing. |
| -func (h *handlers) homeLinkLabel(r *http.Request) string { |
| - if !h.homeEnabled || h.homeLinked == nil { |
| - return "" |
| - } |
| - id, ok := currentIdentity(r) |
| - if !ok || id.Session.Method == homeAssertionMethod || id.HomeSubject != "" { |
| - return "" |
| - } |
| - if linked, err := h.homeLinked(r.Context(), id.Actor.PersonID); err != nil || linked { |
| - return "" |
| - } |
| - return rastrillo.T(r, "docs.home.menu_action") |
| -} |
| - |
| -// signout ends the Docs session and clears the hand-off cookies, then hands |
| -// the same POST on to {issuer}/signout, which ends the id.* session too and |
| -// returns the browser to this origin's /signed-out (spec shared-chrome §9.5; |
| -// connect.Routes.Signout does the same for every other app). Ending only the |
| -// Docs session left "Sign in" on the signed-out page passing silently |
| -// through the live 30-day id.* session. |
| -// |
| -// - 307, not 303, so the hop stays a POST. id.* ignores a GET sign-out, |
| -// because any link or <img> can trigger one. |
| -// - The browser sends "Origin: null" on the redirected POST, so id.* admits |
| -// it by Referer. strict-origin-when-cross-origin makes the Referer |
| -// exactly this origin, which id.* checks against HOME_CONSUMERS. |
| -// - homeFormPolicy already names the issuer in form-action, which browsers |
| -// enforce on the redirect target of a form submission. |
| -// |
| -// /signed-out itself still never starts another exchange. |
| -func (h *homeRoutes) signout(w http.ResponseWriter, r *http.Request) { |
| - h.bridge.sessions.SignOut(w, r) |
| - for _, name := range []string{homeInitCookie, homeProofCookie, localLinkNavigationCookie, homeReturnCookie, "__Host-oficina-assertion-pending", "__Host-oficina-assertion-inbox"} { |
| - localNavigationCookie(w, name, "", -1) |
| - } |
| - w.Header().Set("Cache-Control", "no-store") |
| - w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin") |
| - http.Redirect(w, r, h.issuer+"/signout", http.StatusTemporaryRedirect) |
| -} |
diff --git a/internal/docs/identity.go b/internal/docs/identity.go| index 95a5a9c..3afa353 100644 |
| --- a/internal/docs/identity.go |
| +++ b/internal/docs/identity.go |
| @@ -4,16 +4,19 @@ import ( |
| "context" |
| "database/sql" |
| "errors" |
| - "github.com/carlosframework/docs/internal/docs/principalstore" |
| "net/http" |
| - "time" |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/connect/linkstore" |
| "amadan.net/rastrillo/rastrillo" |
| "amadan.net/rastrillo/rastrillo/sessions" |
| - "gorm.io/gorm" |
| + "github.com/carlosframework/docs/internal/docs/principalstore" |
| ) |
| -const homeAssertionMethod = "home-assertion" |
| +// homeAssertionMethod is the session method of a Home sign-in. It is |
| +// connect's, and was Docs' own string before Docs used connect, so sessions |
| +// minted then are still Home sessions now. |
| +const homeAssertionMethod = connect.HomeMethod |
| var ( |
| errIdentityRefused = errors.New("docs: identity refused") |
| @@ -38,8 +41,31 @@ type identityResolver struct { |
| team *teamRuntime |
| store *Store |
| issuer string |
| - // Return zero for an unknown link. Errors must not contain identity values. |
| - linkedPerson func(context.Context, string, string) (int64, error) |
| + // links resolves a Home subject: connect's account link (its binding |
| + // checked against the person's current address), then in team mode the |
| + // Home-only principal. Its errors are linkstore's and carry no identity |
| + // values. It is the connect.Bridge. |
| + links homeSubjects |
| +} |
| + |
| +// homeSubjects is connect.Bridge's Resolve. |
| +type homeSubjects interface { |
| + Resolve(ctx context.Context, subject string) (connect.Person, error) |
| +} |
| + |
| +// homePerson is links.Resolve as an identity error. |
| +func (v identityResolver) homePerson(ctx context.Context, subject string) (connect.Person, error) { |
| + if v.links == nil { |
| + return connect.Person{}, errIdentityRefused |
| + } |
| + p, err := v.links.Resolve(ctx, subject) |
| + switch { |
| + case errors.Is(err, linkstore.ErrRefused): |
| + return connect.Person{}, errIdentityRefused |
| + case err != nil: |
| + return connect.Person{}, errIdentityStorage |
| + } |
| + return p, nil |
| } |
| func (v identityResolver) resolve(r *http.Request) (requestIdentity, error) { |
| @@ -51,8 +77,12 @@ func (v identityResolver) resolve(r *http.Request) (requestIdentity, error) { |
| return requestIdentity{}, errIdentityRefused |
| } |
| if session.Method == homeAssertionMethod { |
| + person, err := v.homePerson(r.Context(), session.Subject) |
| + if err != nil { |
| + return requestIdentity{}, err |
| + } |
| if v.team != nil { |
| - p, err := v.team.principals.Resolve(r.Context(), v.team.bindings.Issuer, session.Subject) |
| + p, err := v.team.principals.Person(r.Context(), person.ID) |
| if errors.Is(err, principalstore.ErrRefused) { |
| return requestIdentity{}, errIdentityRefused |
| } |
| @@ -61,31 +91,11 @@ func (v identityResolver) resolve(r *http.Request) (requestIdentity, error) { |
| } |
| return requestIdentity{Actor: Actor{PersonID: p.ID, VerifiedAddress: p.VerifiedAddress}, Session: session, HomeSubject: session.Subject}, nil |
| } |
| - if v.issuer == "" || v.linkedPerson == nil { |
| + address := subjectOf(person.Label) |
| + if person.ID <= 0 || address == "" { |
| return requestIdentity{}, errIdentityRefused |
| } |
| - person, err := v.linkedPerson(r.Context(), v.issuer, session.Subject) |
| - if errors.Is(err, errIdentityRefused) { |
| - return requestIdentity{}, errIdentityRefused |
| - } |
| - if err != nil { |
| - return requestIdentity{}, errIdentityStorage |
| - } |
| - if person <= 0 { |
| - return requestIdentity{}, errIdentityRefused |
| - } |
| - var p Person |
| - if err = v.store.db.WithContext(r.Context()).First(&p, person).Error; err != nil { |
| - if errors.Is(err, gorm.ErrRecordNotFound) { |
| - return requestIdentity{}, errIdentityRefused |
| - } |
| - return requestIdentity{}, errIdentityStorage |
| - } |
| - address := subjectOf(p.Email) |
| - if address == "" { |
| - return requestIdentity{}, errIdentityRefused |
| - } |
| - return requestIdentity{Actor: localActor(p.ID, address), Session: session}, nil |
| + return requestIdentity{Actor: localActor(person.ID, address), Session: session}, nil |
| } |
| if v.team != nil && session.Method != "magiclink" && session.Method != "keymail" { |
| return requestIdentity{}, errIdentityRefused |
| @@ -106,14 +116,36 @@ func (v identityResolver) resolve(r *http.Request) (requestIdentity, error) { |
| return requestIdentity{}, errIdentityRefused |
| } |
| id.Actor = Actor{PersonID: p.ID, VerifiedAddress: p.VerifiedAddress} |
| - err = v.team.db.QueryRowContext(r.Context(), "SELECT subject FROM docs_identity_links WHERE issuer=? AND person_id=?", v.team.bindings.Issuer, p.ID).Scan(&id.HomeSubject) |
| - if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| - return requestIdentity{}, errIdentityStorage |
| + if id.HomeSubject, err = v.linkedSubject(r.Context(), p.ID); err != nil { |
| + return requestIdentity{}, err |
| } |
| } |
| return id, nil |
| } |
| +// linkedSubject is the Home subject a local person is linked to, for team |
| +// standing, or "" for none. The link counts only if connect resolves it |
| +// back to the same person: a link whose binding no longer matches the |
| +// person's address signs nobody in, so it gives no standing either. |
| +func (v identityResolver) linkedSubject(ctx context.Context, person int64) (string, error) { |
| + var subject string |
| + err := v.team.db.QueryRowContext(ctx, "SELECT subject FROM home_identity_links WHERE issuer=? AND person_id=?", v.team.bindings.Issuer, person).Scan(&subject) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return "", nil |
| + } |
| + if err != nil { |
| + return "", errIdentityStorage |
| + } |
| + linked, err := v.homePerson(ctx, subject) |
| + if errors.Is(err, errIdentityRefused) || (err == nil && linked.ID != person) { |
| + return "", nil |
| + } |
| + if err != nil { |
| + return "", err |
| + } |
| + return subject, nil |
| +} |
| + |
| // middleware belongs after RequireSession and before admission. A verified |
| // Home subject with no local link must never reach an app handler. |
| func (v identityResolver) middleware(signinPath string) func(http.Handler) http.Handler { |
| @@ -153,20 +185,3 @@ func requestActor(r *http.Request, store *Store) (Actor, error) { |
| id, err := (identityResolver{store: store}).resolve(r) |
| return id.Actor, err |
| } |
| - |
| -// freshLocalAuthentication accepts only an independent local verification. |
| -// Rastrillo stores zero AuthTime for completed magic links; only that method |
| -// can use the persisted session creation time as verification evidence. |
| -func freshLocalAuthentication(s sessions.Session, now time.Time) (time.Time, bool) { |
| - if s.Subject == "" || (s.Method != "magiclink" && s.Method != "keymail") { |
| - return time.Time{}, false |
| - } |
| - at := s.AuthTime |
| - if at.IsZero() && s.Method == "magiclink" { |
| - at = s.At |
| - } |
| - if at.IsZero() || at.After(now) || now.Sub(at) > 5*time.Minute { |
| - return time.Time{}, false |
| - } |
| - return at, true |
| -} |
diff --git a/internal/docs/identity_test.go b/internal/docs/identity_test.go| index ea5a9a2..19fc08a 100644 |
| --- a/internal/docs/identity_test.go |
| +++ b/internal/docs/identity_test.go |
| @@ -2,15 +2,30 @@ package docs |
| import ( |
| "context" |
| - "errors" |
| "net/http" |
| "net/http/httptest" |
| "testing" |
| "time" |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/connect/linkstore" |
| "amadan.net/rastrillo/rastrillo/sessions" |
| ) |
| +// subjectsFunc stands in for connect's Resolve. |
| +type subjectsFunc func(ctx context.Context, subject string) (connect.Person, error) |
| + |
| +func (f subjectsFunc) Resolve(ctx context.Context, subject string) (connect.Person, error) { |
| + return f(ctx, subject) |
| +} |
| + |
| +// freshLocalAuthentication is connect's rule before linking |
| +// (connect.FreshLocal, the rule Docs' own bridge had), over the sessions |
| +// Docs actually mints. |
| +func freshLocalAuthentication(s sessions.Session, now time.Time) (time.Time, bool) { |
| + return connect.FreshLocal(connect.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime, At: s.At}, now) |
| +} |
| + |
| func identityRequest(method, subject, authMethod string) *http.Request { |
| return sessions.WithSession(httptest.NewRequest(method, "https://docs.example/", nil), sessions.Session{Subject: subject, Method: authMethod}) |
| } |
| @@ -30,13 +45,16 @@ func TestHomeIdentityNeverCreatesPersonOrSamples(t *testing.T) { |
| if h.member(r) { |
| t.Fatal("unconfigured Home identity gained membership") |
| } |
| - for _, id := range []int64{0, 999999} { |
| - v := identityResolver{store: store, issuer: "https://id.example", linkedPerson: func(ctx context.Context, issuer, got string) (int64, error) { |
| - if issuer != "https://id.example" || got != subject { |
| - t.Fatal("issuer/subject changed") |
| + for _, answer := range []struct { |
| + p connect.Person |
| + err error |
| + }{{connect.Person{}, linkstore.ErrRefused}, {connect.Person{ID: 0, Label: "x@example.com"}, nil}, {connect.Person{ID: 999999}, nil}} { |
| + v := identityResolver{store: store, issuer: "https://id.example", links: subjectsFunc(func(ctx context.Context, got string) (connect.Person, error) { |
| + if got != subject { |
| + t.Fatal("subject changed") |
| } |
| - return id, nil |
| - }} |
| + return answer.p, answer.err |
| + })} |
| reached := false |
| rec := httptest.NewRecorder() |
| v.middleware("/signin")(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { reached = true })).ServeHTTP(rec, r) |
| @@ -84,12 +102,14 @@ func TestLinkedHomeIdentityPreservesOwnersAndAddressGrants(t *testing.T) { |
| if err = store.Grant(ctx, bob, shared.Sqid, "alice@example.com", RoleWriter); err != nil { |
| t.Fatal(err) |
| } |
| - v := identityResolver{store: store, issuer: "https://id.example", linkedPerson: func(ctx context.Context, issuer, subject string) (int64, error) { |
| - if issuer != "https://id.example" || subject != "opaque_alice" { |
| - return 0, nil |
| + v := identityResolver{store: store, issuer: "https://id.example", links: subjectsFunc(func(ctx context.Context, subject string) (connect.Person, error) { |
| + if subject != "opaque_alice" { |
| + return connect.Person{}, linkstore.ErrRefused |
| } |
| - return alice, nil |
| - }} |
| + // connect reads the person's current address on every Resolve. |
| + address, err := linkedAddress(ctx, app.db.Writer(), alice) |
| + return connect.Person{ID: alice, Label: address}, err |
| + })} |
| memberAddresses := []string{} |
| h := &handlers{store: store, isMember: func(address string) bool { |
| memberAddresses = append(memberAddresses, address) |
| @@ -156,7 +176,9 @@ func TestHomeAdmissionRequiresAdapterAndCurrentAddress(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - v := identityResolver{store: store, issuer: "https://id.example", linkedPerson: func(context.Context, string, string) (int64, error) { return person, nil }} |
| + v := identityResolver{store: store, issuer: "https://id.example", links: subjectsFunc(func(context.Context, string) (connect.Person, error) { |
| + return connect.Person{ID: person, Label: "local@example.com"}, nil |
| + })} |
| reached := false |
| next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) { reached = true }) |
| for _, method := range []string{"GET", "POST"} { |
| @@ -182,7 +204,7 @@ func TestHomeAdmissionRequiresAdapterAndCurrentAddress(t *testing.T) { |
| if reached || rec.Code != 403 { |
| t.Fatal("link bypassed changed admission") |
| } |
| - v.linkedPerson = func(context.Context, string, string) (int64, error) { return 0, errors.New("fixture storage failure") } |
| + v.links = subjectsFunc(func(context.Context, string) (connect.Person, error) { return connect.Person{}, linkstore.ErrStorage }) |
| rec = httptest.NewRecorder() |
| v.middleware("/signin")(next).ServeHTTP(rec, identityRequest("POST", "opaque", homeAssertionMethod)) |
| if reached || rec.Code != 503 { |
diff --git a/internal/docs/linkstore/flows.go b/internal/docs/linkstore/flows.go| deleted file mode 100644 |
| index 2fbee38..0000000 |
| --- a/internal/docs/linkstore/flows.go |
| +++ /dev/null |
| @@ -1,314 +0,0 @@ |
| -package linkstore |
| - |
| -import ( |
| - "bytes" |
| - "context" |
| - "database/sql" |
| - "encoding/json" |
| - "errors" |
| - "io" |
| - "time" |
| - |
| - "amadan.net/oficina/home/handoff" |
| -) |
| - |
| -type flow struct { |
| - Version int `json:"v"` |
| - PersonID int64 `json:"person"` |
| - SessionHash string `json:"session"` |
| - LocalAuth int64 `json:"local_auth"` |
| - Issuer string `json:"issuer"` |
| - NonceHash string `json:"nonce,omitempty"` |
| - Subject string `json:"subject,omitempty"` |
| - HomeAuth int64 `json:"home_auth,omitempty"` |
| - ReturnPath string `json:"return"` |
| - Expires int64 `json:"expires"` |
| -} |
| - |
| -func (s *Store) purpose(stage, id string) string { |
| - return "identity-link/v1/" + stage + "/" + id + "/" + s.origin |
| -} |
| -func (s *Store) put(ctx context.Context, tx *sql.Tx, stage, id string, f flow) error { |
| - raw, err := json.Marshal(f) |
| - if err != nil { |
| - return ErrStorage |
| - } |
| - sealed, err := s.seal.Seal(s.purpose(stage, id), raw) |
| - if err != nil { |
| - return ErrStorage |
| - } |
| - _, err = tx.ExecContext(ctx, "INSERT INTO docs_link_flows (id_hash, stage, expires_at, payload) VALUES (?, ?, ?, ?)", id, stage, f.Expires, sealed) |
| - if err != nil { |
| - return ErrStorage |
| - } |
| - return nil |
| -} |
| - |
| -// load deletes a presented row before interpreting it when consume is true. |
| -// Callers commit refusals, so a rejected conflict or mixed-up browser cannot |
| -// reuse its proof. Storage failures roll back and never install a mapping. |
| -func (s *Store) load(ctx context.Context, tx *sql.Tx, stage, id string, high int64, consume bool) (flow, error) { |
| - var raw []byte |
| - var expires int64 |
| - err := tx.QueryRowContext(ctx, "SELECT expires_at, payload FROM docs_link_flows WHERE id_hash = ? AND stage = ?", id, stage).Scan(&expires, &raw) |
| - if errors.Is(err, sql.ErrNoRows) { |
| - return flow{}, ErrRefused |
| - } |
| - if err != nil { |
| - return flow{}, ErrStorage |
| - } |
| - if consume { |
| - if _, err := tx.ExecContext(ctx, "DELETE FROM docs_link_flows WHERE id_hash = ? AND stage = ?", id, stage); err != nil { |
| - return flow{}, ErrStorage |
| - } |
| - } |
| - if len(raw) > 8192 || expires <= high { |
| - return flow{}, ErrRefused |
| - } |
| - opened, err := s.seal.Open(s.purpose(stage, id), raw) |
| - if err != nil { |
| - return flow{}, ErrRefused |
| - } |
| - var f flow |
| - dec := json.NewDecoder(bytes.NewReader(opened)) |
| - dec.DisallowUnknownFields() |
| - if dec.Decode(&f) != nil || dec.Decode(new(any)) != io.EOF { |
| - return flow{}, ErrRefused |
| - } |
| - if f.Version != 1 || f.Expires != expires || f.Issuer != s.issuer || !handoff.SafePath(f.ReturnPath) { |
| - return flow{}, ErrRefused |
| - } |
| - return f, nil |
| -} |
| -func (s *Store) matches(f flow, local Local, now, high int64) bool { |
| - return validLocal(local, now, high) && f.PersonID == local.PersonID && f.SessionHash == hash(local.SessionToken) && f.LocalAuth == local.AuthTime.Unix() && fresh(f.LocalAuth, now, high) |
| -} |
| -func personExists(ctx context.Context, tx *sql.Tx, id int64) (bool, error) { |
| - var found int |
| - err := tx.QueryRowContext(ctx, "SELECT 1 FROM people WHERE id = ? AND email <> ''", id).Scan(&found) |
| - if errors.Is(err, sql.ErrNoRows) { |
| - return false, nil |
| - } |
| - if err != nil { |
| - return false, ErrStorage |
| - } |
| - return true, nil |
| -} |
| - |
| -// Start is called only by an explicit same-origin local-account link POST. |
| -// The returned secret belongs in a host-only Secure/HttpOnly/Lax cookie. |
| -func (s *Store) Start(ctx context.Context, local Local, returnPath string, now time.Time) (string, error) { |
| - tx, high, err := s.begin(ctx, now) |
| - if err != nil { |
| - return "", err |
| - } |
| - defer tx.Rollback() |
| - if err = sweep(ctx, tx, high); err != nil { |
| - return "", err |
| - } |
| - if !validLocal(local, now.Unix(), high) { |
| - return "", refuse(tx) |
| - } |
| - exists, err := personExists(ctx, tx, local.PersonID) |
| - if err != nil { |
| - return "", err |
| - } |
| - if !exists { |
| - return "", refuse(tx) |
| - } |
| - var count int |
| - if err := tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM docs_link_flows").Scan(&count); err != nil { |
| - return "", ErrStorage |
| - } |
| - if count >= maxFlows { |
| - return "", refuse(tx) |
| - } |
| - secret, err := newSecret() |
| - if err != nil { |
| - return "", err |
| - } |
| - expires := min(now.Unix()+maxAge, local.AuthTime.Unix()+maxAge) |
| - if expires <= high { |
| - return "", refuse(tx) |
| - } |
| - f := flow{Version: 1, PersonID: local.PersonID, SessionHash: hash(local.SessionToken), LocalAuth: local.AuthTime.Unix(), Issuer: s.issuer, ReturnPath: safePath(returnPath), Expires: expires} |
| - if err := s.put(ctx, tx, "init", hash(secret), f); err != nil { |
| - return "", err |
| - } |
| - if err := commit(tx); err != nil { |
| - return "", err |
| - } |
| - return secret, nil |
| -} |
| - |
| -// BindNonce is the shared consumer's start hook. It accepts one generated |
| -// nonce exactly once, before that consumer sets its cookie or redirects. |
| -func (s *Store) BindNonce(ctx context.Context, secret string, local Local, nonce string, now time.Time) error { |
| - id, ok := secretHash(secret) |
| - if !ok { |
| - return ErrRefused |
| - } |
| - tx, high, err := s.begin(ctx, now) |
| - if err != nil { |
| - return err |
| - } |
| - defer tx.Rollback() |
| - f, err := s.load(ctx, tx, "init", id, high, true) |
| - if errors.Is(err, ErrRefused) { |
| - return refuse(tx) |
| - } |
| - if err != nil { |
| - return err |
| - } |
| - if !s.matches(f, local, now.Unix(), high) || !handoff.ValidNonce(nonce) || f.NonceHash != "" { |
| - return refuse(tx) |
| - } |
| - f.NonceHash = hash(nonce) |
| - if err := s.put(ctx, tx, "init", id, f); err != nil { |
| - return err |
| - } |
| - return commit(tx) |
| -} |
| - |
| -// Complete consumes the initiation after the shared consumer has consumed and |
| -// verified the Home assertion. It keeps the local Docs session intact. |
| -func (s *Store) Complete(ctx context.Context, secret string, local Local, home Home, now time.Time) (string, error) { |
| - id, ok := secretHash(secret) |
| - if !ok { |
| - return "", ErrRefused |
| - } |
| - tx, high, err := s.begin(ctx, now) |
| - if err != nil { |
| - return "", err |
| - } |
| - defer tx.Rollback() |
| - f, err := s.load(ctx, tx, "init", id, high, true) |
| - if errors.Is(err, ErrRefused) { |
| - return "", refuse(tx) |
| - } |
| - if err != nil { |
| - return "", err |
| - } |
| - if !s.matches(f, local, now.Unix(), high) || !handoff.ValidNonce(home.Nonce) || f.NonceHash != hash(home.Nonce) || home.Issuer != s.issuer || !validSubject(home.Subject) || !fresh(home.AuthTime.Unix(), now.Unix(), high) { |
| - return "", refuse(tx) |
| - } |
| - exists, err := personExists(ctx, tx, local.PersonID) |
| - if err != nil { |
| - return "", err |
| - } |
| - if !exists { |
| - return "", refuse(tx) |
| - } |
| - pending, err := newSecret() |
| - if err != nil { |
| - return "", err |
| - } |
| - f.Subject, f.HomeAuth = home.Subject, home.AuthTime.Unix() |
| - f.Expires = min(f.Expires, f.HomeAuth+maxAge) |
| - if f.Expires <= high { |
| - return "", refuse(tx) |
| - } |
| - if err := s.put(ctx, tx, "pending", hash(pending), f); err != nil { |
| - return "", err |
| - } |
| - if err := commit(tx); err != nil { |
| - return "", err |
| - } |
| - return pending, nil |
| -} |
| - |
| -func validPending(f flow, now, high int64) bool { |
| - return f.NonceHash != "" && validSubject(f.Subject) && fresh(f.HomeAuth, now, high) |
| -} |
| -func pendingView(f flow) Pending { |
| - return Pending{PersonID: f.PersonID, ReturnPath: f.ReturnPath, HomeAuthTime: time.Unix(f.HomeAuth, 0)} |
| -} |
| - |
| -// Pending reads a still-valid continuation for its current local session. |
| -// Invalid presented state is consumed; reading valid state creates no link. |
| -func (s *Store) Pending(ctx context.Context, secret string, local Local, now time.Time) (Pending, error) { |
| - id, ok := secretHash(secret) |
| - if !ok { |
| - return Pending{}, ErrRefused |
| - } |
| - tx, high, err := s.begin(ctx, now) |
| - if err != nil { |
| - return Pending{}, err |
| - } |
| - defer tx.Rollback() |
| - f, err := s.load(ctx, tx, "pending", id, high, true) |
| - if errors.Is(err, ErrRefused) { |
| - return Pending{}, refuse(tx) |
| - } |
| - if err != nil { |
| - return Pending{}, err |
| - } |
| - if !s.matches(f, local, now.Unix(), high) || !validPending(f, now.Unix(), high) { |
| - return Pending{}, refuse(tx) |
| - } |
| - exists, err := personExists(ctx, tx, local.PersonID) |
| - if err != nil { |
| - return Pending{}, err |
| - } |
| - if !exists { |
| - return Pending{}, refuse(tx) |
| - } |
| - if err := s.put(ctx, tx, "pending", id, f); err != nil { |
| - return Pending{}, err |
| - } |
| - if err := commit(tx); err != nil { |
| - return Pending{}, err |
| - } |
| - return pendingView(f), nil |
| -} |
| - |
| -// Confirm requires an explicit same-origin POST. The proof deletion and unique |
| -// mapping write commit together. A separate proof for the same mapping is |
| -// idempotent; a reused cookie or conflicting mapping is consumed and refused. |
| -func (s *Store) Confirm(ctx context.Context, secret string, local Local, now time.Time) (Pending, error) { |
| - id, ok := secretHash(secret) |
| - if !ok { |
| - return Pending{}, ErrRefused |
| - } |
| - tx, high, err := s.begin(ctx, now) |
| - if err != nil { |
| - return Pending{}, err |
| - } |
| - defer tx.Rollback() |
| - f, err := s.load(ctx, tx, "pending", id, high, true) |
| - if errors.Is(err, ErrRefused) { |
| - return Pending{}, refuse(tx) |
| - } |
| - if err != nil { |
| - return Pending{}, err |
| - } |
| - if !s.matches(f, local, now.Unix(), high) || !validPending(f, now.Unix(), high) { |
| - return Pending{}, refuse(tx) |
| - } |
| - exists, err := personExists(ctx, tx, local.PersonID) |
| - if err != nil { |
| - return Pending{}, err |
| - } |
| - if !exists { |
| - return Pending{}, refuse(tx) |
| - } |
| - _, err = tx.ExecContext(ctx, "INSERT INTO docs_identity_links (issuer, subject, person_id) VALUES (?, ?, ?) ON CONFLICT DO NOTHING", s.issuer, f.Subject, f.PersonID) |
| - if err != nil { |
| - return Pending{}, ErrStorage |
| - } |
| - var person int64 |
| - err = tx.QueryRowContext(ctx, "SELECT person_id FROM docs_identity_links WHERE issuer = ? AND subject = ?", s.issuer, f.Subject).Scan(&person) |
| - if errors.Is(err, sql.ErrNoRows) { |
| - return Pending{}, refuse(tx) |
| - } |
| - if err != nil { |
| - return Pending{}, ErrStorage |
| - } |
| - if person != f.PersonID { |
| - return Pending{}, refuse(tx) |
| - } |
| - if err := commit(tx); err != nil { |
| - return Pending{}, err |
| - } |
| - return pendingView(f), nil |
| -} |
diff --git a/internal/docs/linkstore/principals/migrations/0001_old_link_table.sql b/internal/docs/linkstore/principals/migrations/0001_old_link_table.sql| new file mode 100644 |
| index 0000000..7d406b9 |
| --- /dev/null |
| +++ b/internal/docs/linkstore/principals/migrations/0001_old_link_table.sql |
| @@ -0,0 +1,7 @@ |
| +CREATE TABLE IF NOT EXISTS docs_identity_links ( |
| + issuer TEXT NOT NULL, |
| + subject TEXT NOT NULL, |
| + person_id INTEGER NOT NULL REFERENCES people(id), |
| + PRIMARY KEY (issuer, subject), |
| + UNIQUE (issuer, person_id) |
| +); |
diff --git a/internal/docs/linkstore/schema.go b/internal/docs/linkstore/schema.go| new file mode 100644 |
| index 0000000..0a103a6 |
| --- /dev/null |
| +++ b/internal/docs/linkstore/schema.go |
| @@ -0,0 +1,44 @@ |
| +// Package linkstore is what is left of Docs' own Home link store: the |
| +// migrations every Docs database has already applied. Docs links Home |
| +// identities through home/connect now, in connect's home_identity_links, |
| +// and moves this package's rows there once, at boot |
| +// (internal/docs/home_links_move.go), dropping these tables as it does. |
| +// |
| +// The migrations stay because they are in every database's ledger |
| +// (migrations are immutable once applied), and because a new database |
| +// still creates docs_identity_links on the way: principalstore's first |
| +// migration puts a trigger on it, which the move then re-points. |
| +package linkstore |
| + |
| +import ( |
| + "embed" |
| + "io/fs" |
| + |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| +) |
| + |
| +//go:embed migrations/*.sql |
| +var migrations embed.FS |
| + |
| +// Schema is the applied docs_identity_link set, unchanged. |
| +var Schema = migrate.MustFromFS(migrations, "docs_identity_link") |
| + |
| +//go:embed principals/migrations/*.sql |
| +var forPrincipals embed.FS |
| + |
| +// ForPrincipals goes immediately before principalstore.Schema, and only in |
| +// the team schema. A database that moved its links onto connect while team |
| +// mode was off has no docs_identity_links, and principalstore's first |
| +// migration cannot create its trigger on a missing table, so turning team |
| +// mode on later would refuse to boot. This puts the old table back, empty, |
| +// for that one migration; the move at boot re-points the trigger and drops |
| +// it again. Wherever the table still exists it does nothing. |
| +var ForPrincipals = migrate.MustFromFS(mustSub(forPrincipals, "principals"), "docs_identity_link_principals") |
| + |
| +func mustSub(f fs.FS, dir string) fs.FS { |
| + sub, err := fs.Sub(f, dir) |
| + if err != nil { |
| + panic(err) |
| + } |
| + return sub |
| +} |
diff --git a/internal/docs/linkstore/store.go b/internal/docs/linkstore/store.go| deleted file mode 100644 |
| index 2f469ec..0000000 |
| --- a/internal/docs/linkstore/store.go |
| +++ /dev/null |
| @@ -1,217 +0,0 @@ |
| -// Package linkstore binds an existing Docs person to an independently verified |
| -// Home identity. It creates no people, sessions, membership or document grants. |
| -package linkstore |
| - |
| -import ( |
| - "context" |
| - "crypto/rand" |
| - "crypto/sha256" |
| - "database/sql" |
| - "embed" |
| - "encoding/base64" |
| - "encoding/hex" |
| - "errors" |
| - "net/url" |
| - "strings" |
| - "time" |
| - "unicode/utf8" |
| - |
| - "amadan.net/oficina/home/handoff" |
| - "amadan.net/oficina/home/handoff/seal" |
| - "amadan.net/rastrillo/rastrillo/migrate" |
| -) |
| - |
| -//go:embed migrations/*.sql |
| -var migrations embed.FS |
| - |
| -// Schema follows the Docs people schema in the application's BootSchema. |
| -var Schema = migrate.MustFromFS(migrations, "docs_identity_link") |
| - |
| -var ( |
| - ErrRefused = errors.New("docs link: refused") |
| - ErrStorage = errors.New("docs link: storage unavailable") |
| -) |
| - |
| -const maxFlows = 10000 |
| -const maxAge = 300 |
| - |
| -// Local is supplied only after the caller verifies the actual local session |
| -// and its method-aware authentication time. Home assertions cannot supply it. |
| -// SessionToken is the actual cookie value, never a subject or a minted alias. |
| -type Local struct { |
| - PersonID int64 |
| - SessionToken string |
| - AuthTime time.Time |
| -} |
| - |
| -// Home contains already verified, consumed shared-handoff claims. The caller |
| -// must not construct it from query parameters or an unverified assertion. |
| -type Home struct { |
| - Issuer, Subject, Nonce string |
| - AuthTime time.Time |
| -} |
| - |
| -// Pending is safe server-side continuation state, not an authentication token. |
| -type Pending struct { |
| - PersonID int64 |
| - ReturnPath string |
| - HomeAuthTime time.Time |
| -} |
| - |
| -type Store struct { |
| - db *sql.DB |
| - seal *seal.Sealer |
| - origin, issuer string |
| -} |
| - |
| -// New uses a dedicated handoff/storage DEK, never the document content key. |
| -// Apply Schema first, then call Sweep at boot before accepting requests. |
| -func New(db *sql.DB, dek []byte, origin, issuer string) (*Store, error) { |
| - if db == nil || !validOrigin(origin) || !validOrigin(issuer) { |
| - return nil, ErrRefused |
| - } |
| - sealer, err := seal.New(dek, "oficina/docs") |
| - if err != nil { |
| - return nil, ErrRefused |
| - } |
| - return &Store{db: db, seal: sealer, origin: origin, issuer: issuer}, nil |
| -} |
| - |
| -func validOrigin(v string) bool { |
| - u, err := url.Parse(v) |
| - return err == nil && len(v) <= 2048 && u.Scheme == "https" && u.Host != "" && u.Hostname() != "" && u.User == nil && u.Path == "" && u.RawQuery == "" && !u.ForceQuery && u.Fragment == "" && u.Opaque == "" && u.String() == v && !strings.ContainsAny(v, "\\\r\n\t ") |
| -} |
| - |
| -func hash(v string) string { sum := sha256.Sum256([]byte(v)); return hex.EncodeToString(sum[:]) } |
| -func secretHash(v string) (string, bool) { |
| - if len(v) != 43 { |
| - return "", false |
| - } |
| - b, err := base64.RawURLEncoding.Strict().DecodeString(v) |
| - return hash(v), err == nil && len(b) == 32 && base64.RawURLEncoding.EncodeToString(b) == v |
| -} |
| -func newSecret() (string, error) { |
| - b := make([]byte, 32) |
| - if _, err := rand.Read(b); err != nil { |
| - return "", ErrStorage |
| - } |
| - return base64.RawURLEncoding.EncodeToString(b), nil |
| -} |
| -func fresh(at int64, now, high int64) bool { return at > 0 && at <= now && high-at <= maxAge } |
| -func validLocal(local Local, now, high int64) bool { |
| - return local.PersonID > 0 && local.SessionToken != "" && len(local.SessionToken) <= 4096 && fresh(local.AuthTime.Unix(), now, high) |
| -} |
| -func validSubject(v string) bool { |
| - if v == "" || len(v) > 512 || !utf8.ValidString(v) { |
| - return false |
| - } |
| - for _, r := range v { |
| - if r <= 32 || r == 127 { |
| - return false |
| - } |
| - } |
| - return true |
| -} |
| - |
| -// begin obtains the write lock before any reads, including capacity checks. |
| -// A persisted clock prevents stale evidence becoming fresh after a restart or |
| -// a clock rollback. Match the shared handoff's 30-second rollback tolerance. |
| -func (s *Store) begin(ctx context.Context, now time.Time) (*sql.Tx, int64, error) { |
| - if now.Unix() <= 0 { |
| - return nil, 0, ErrRefused |
| - } |
| - tx, err := s.db.BeginTx(ctx, nil) |
| - if err != nil { |
| - return nil, 0, ErrStorage |
| - } |
| - if _, err = tx.ExecContext(ctx, "UPDATE docs_link_clock SET high_water = MAX(high_water, ?) WHERE id = 1", now.Unix()); err != nil { |
| - tx.Rollback() |
| - return nil, 0, ErrStorage |
| - } |
| - var high int64 |
| - if err = tx.QueryRowContext(ctx, "SELECT high_water FROM docs_link_clock WHERE id = 1").Scan(&high); err != nil { |
| - tx.Rollback() |
| - return nil, 0, ErrStorage |
| - } |
| - if now.Unix() < high-30 { |
| - tx.Rollback() |
| - return nil, 0, ErrRefused |
| - } |
| - return tx, high, nil |
| -} |
| -func refuse(tx *sql.Tx) error { |
| - if err := tx.Commit(); err != nil { |
| - return ErrStorage |
| - } |
| - return ErrRefused |
| -} |
| -func commit(tx *sql.Tx) error { |
| - if err := tx.Commit(); err != nil { |
| - return ErrStorage |
| - } |
| - return nil |
| -} |
| -func sweep(ctx context.Context, tx *sql.Tx, high int64) error { |
| - if _, err := tx.ExecContext(ctx, "DELETE FROM docs_link_flows WHERE expires_at <= ?", high); err != nil { |
| - return ErrStorage |
| - } |
| - return nil |
| -} |
| -func (s *Store) Sweep(ctx context.Context, now time.Time) error { |
| - tx, high, err := s.begin(ctx, now) |
| - if err != nil { |
| - return err |
| - } |
| - defer tx.Rollback() |
| - if err := sweep(ctx, tx, high); err != nil { |
| - return err |
| - } |
| - return commit(tx) |
| -} |
| - |
| -// Resolve reads the current existing person, never EnsurePerson or a cached |
| -// address. A deleted or unlinked person is refused without creating anything. |
| -func (s *Store) Resolve(ctx context.Context, issuer, subject string) (int64, string, error) { |
| - if issuer != s.issuer || !validSubject(subject) { |
| - return 0, "", ErrRefused |
| - } |
| - var id int64 |
| - var address string |
| - err := s.db.QueryRowContext(ctx, `SELECT p.id, p.email FROM docs_identity_links l JOIN people p ON p.id = l.person_id WHERE l.issuer = ? AND l.subject = ?`, issuer, subject).Scan(&id, &address) |
| - if errors.Is(err, sql.ErrNoRows) { |
| - return 0, "", ErrRefused |
| - } |
| - if err != nil { |
| - return 0, "", ErrStorage |
| - } |
| - if id <= 0 || address == "" { |
| - return 0, "", ErrRefused |
| - } |
| - return id, address, nil |
| -} |
| - |
| -// Linked reports whether the person has a stored link to an identity at |
| -// this issuer, whichever way the current session signed in. It is one |
| -// lookup on the UNIQUE (issuer, person_id) index, cheap enough for every |
| -// page that draws the account menu. |
| -func (s *Store) Linked(ctx context.Context, person int64) (bool, error) { |
| - if person <= 0 { |
| - return false, nil |
| - } |
| - var one int |
| - err := s.db.QueryRowContext(ctx, "SELECT 1 FROM docs_identity_links WHERE issuer = ? AND person_id = ?", s.issuer, person).Scan(&one) |
| - if errors.Is(err, sql.ErrNoRows) { |
| - return false, nil |
| - } |
| - if err != nil { |
| - return false, ErrStorage |
| - } |
| - return true, nil |
| -} |
| - |
| -func safePath(v string) string { |
| - if handoff.SafePath(v) { |
| - return v |
| - } |
| - return "/" |
| -} |
diff --git a/internal/docs/linkstore/store_test.go b/internal/docs/linkstore/store_test.go| deleted file mode 100644 |
| index 0faf240..0000000 |
| --- a/internal/docs/linkstore/store_test.go |
| +++ /dev/null |
| @@ -1,534 +0,0 @@ |
| -package linkstore |
| - |
| -import ( |
| - "bytes" |
| - "context" |
| - "database/sql" |
| - "encoding/base64" |
| - "errors" |
| - "net/url" |
| - "os" |
| - "path/filepath" |
| - "strings" |
| - "sync" |
| - "sync/atomic" |
| - "testing" |
| - "time" |
| - |
| - _ "modernc.org/sqlite" |
| -) |
| - |
| -var ctx = context.Background() |
| -var testNow = time.Unix(1788865200, 0) |
| - |
| -const origin = "https://test.docs.oficina.works" |
| -const issuer = "https://id.oficina.works" |
| - |
| -func fixture(t *testing.T) (*Store, string) { |
| - t.Helper() |
| - path := filepath.Join(t.TempDir(), "docs.db") |
| - d, err := sql.Open("sqlite", (&url.URL{Scheme: "file", Path: path}).String()+"?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=foreign_keys(1)") |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - t.Cleanup(func() { d.Close() }) |
| - _, err = d.Exec(`CREATE TABLE people (id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE); INSERT INTO people VALUES (1,'one@example.com'),(2,'two@example.com'); CREATE TABLE old_content (owner_id INTEGER, bytes BLOB); INSERT INTO old_content VALUES (1,x'00010203'),(2,x'04050607')`) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - migration, err := migrations.ReadFile("migrations/0001_links.sql") |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if _, err := d.Exec(string(migration)); err != nil { |
| - t.Fatal(err) |
| - } |
| - s, err := New(d, bytes.Repeat([]byte{42}, 32), origin, issuer) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := s.Sweep(ctx, testNow); err != nil { |
| - t.Fatal(err) |
| - } |
| - return s, path |
| -} |
| -func local(id int64) Local { |
| - return Local{PersonID: id, SessionToken: strings.Repeat(string(rune('a'+id)), 43), AuthTime: testNow.Add(-time.Minute)} |
| -} |
| -func nonce(n byte) string { return base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{n}, 16)) } |
| -func start(t *testing.T, s *Store, l Local, n string) string { |
| - t.Helper() |
| - secret, err := s.Start(ctx, l, "/d/private-document?view=reading", testNow) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := s.BindNonce(ctx, secret, l, n, testNow); err != nil { |
| - t.Fatal(err) |
| - } |
| - return secret |
| -} |
| -func complete(t *testing.T, s *Store, l Local, subject string, n byte) string { |
| - t.Helper() |
| - secret := start(t, s, l, nonce(n)) |
| - pending, err := s.Complete(ctx, secret, l, Home{Issuer: issuer, Subject: subject, Nonce: nonce(n), AuthTime: testNow.Add(-30 * time.Second)}, testNow) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - return pending |
| -} |
| -func refused(t *testing.T, err error) { |
| - t.Helper() |
| - if !errors.Is(err, ErrRefused) { |
| - t.Fatalf("error = %v, want generic refusal", err) |
| - } |
| -} |
| -func flowCount(t *testing.T, s *Store) int { |
| - t.Helper() |
| - var count int |
| - if err := s.db.QueryRow("SELECT COUNT(*) FROM docs_link_flows").Scan(&count); err != nil { |
| - t.Fatal(err) |
| - } |
| - return count |
| -} |
| - |
| -func TestExplicitLinkPreservesPeopleAndContent(t *testing.T) { |
| - s, _ := fixture(t) |
| - for _, id := range []int64{1, 2} { |
| - l := local(id) |
| - subject := "opaque-home-" + string(rune('a'+id)) |
| - cookie := complete(t, s, l, subject, byte(id)) |
| - p, err := s.Pending(ctx, cookie, l, testNow) |
| - if err != nil || p.PersonID != id || p.ReturnPath != "/d/private-document?view=reading" { |
| - t.Fatalf("pending=%+v error=%v", p, err) |
| - } |
| - _, _, err = s.Resolve(ctx, issuer, subject) |
| - refused(t, err) |
| - got, err := s.Confirm(ctx, cookie, l, testNow) |
| - if err != nil || got.PersonID != id { |
| - t.Fatalf("confirm=%+v error=%v", got, err) |
| - } |
| - linked, address, err := s.Resolve(ctx, issuer, subject) |
| - if err != nil || linked != id || address == "" { |
| - t.Fatalf("resolve=%d,%q,%v", linked, address, err) |
| - } |
| - _, err = s.Confirm(ctx, cookie, l, testNow) |
| - refused(t, err) |
| - } |
| - var count int |
| - if err := s.db.QueryRow("SELECT COUNT(*) FROM people").Scan(&count); err != nil || count != 2 { |
| - t.Fatalf("people changed: %d %v", count, err) |
| - } |
| - var content string |
| - if err := s.db.QueryRow("SELECT group_concat(hex(bytes), ',') FROM old_content ORDER BY owner_id").Scan(&content); err != nil || content != "00010203,04050607" { |
| - t.Fatalf("legacy content changed: %q %v", content, err) |
| - } |
| - if _, err := s.db.Exec("UPDATE people SET email = 'new@example.com' WHERE id = 1"); err != nil { |
| - t.Fatal(err) |
| - } |
| - _, address, err := s.Resolve(ctx, issuer, "opaque-home-b") |
| - if err != nil || address != "new@example.com" { |
| - t.Fatalf("stale address %q %v", address, err) |
| - } |
| - _, _, err = s.Resolve(ctx, "https://other.example", "opaque-home-b") |
| - refused(t, err) |
| - if flowCount(t, s) != 0 { |
| - t.Fatal("consumed rows remain") |
| - } |
| -} |
| - |
| -func TestInitiationAndCompletionBindingsBurnFailures(t *testing.T) { |
| - for _, which := range []string{"missing-init", "unbound-nonce", "nonce", "person", "session", "local-auth", "issuer", "home-stale", "home-future", "local-stale", "local-future"} { |
| - t.Run(which, func(t *testing.T) { |
| - s, _ := fixture(t) |
| - l := local(1) |
| - n := nonce(1) |
| - secret, err := s.Start(ctx, l, "/", testNow) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if which != "unbound-nonce" { |
| - if err := s.BindNonce(ctx, secret, l, n, testNow); err != nil { |
| - t.Fatal(err) |
| - } |
| - } |
| - home := Home{Issuer: issuer, Subject: "opaque", Nonce: n, AuthTime: testNow} |
| - switch which { |
| - case "missing-init": |
| - secret = base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{80}, 32)) |
| - case "nonce": |
| - home.Nonce = nonce(2) |
| - case "person": |
| - l.PersonID = 2 |
| - case "session": |
| - l.SessionToken = "different-actual-cookie" |
| - case "local-auth": |
| - l.AuthTime = testNow |
| - case "issuer": |
| - home.Issuer = "https://evil.example" |
| - case "home-stale": |
| - home.AuthTime = testNow.Add(-301 * time.Second) |
| - case "home-future": |
| - home.AuthTime = testNow.Add(time.Second) |
| - case "local-stale": |
| - l.AuthTime = testNow.Add(-301 * time.Second) |
| - case "local-future": |
| - l.AuthTime = testNow.Add(time.Second) |
| - } |
| - got, err := s.Complete(ctx, secret, l, home, testNow) |
| - refused(t, err) |
| - if got != "" { |
| - t.Fatal("rejected completion returned cookie") |
| - } |
| - _, err = s.Complete(ctx, secret, local(1), Home{Issuer: issuer, Subject: "opaque", Nonce: n, AuthTime: testNow}, testNow) |
| - refused(t, err) |
| - if which != "missing-init" && flowCount(t, s) != 0 { |
| - t.Fatal("failed initiation was reusable") |
| - } |
| - }) |
| - } |
| -} |
| - |
| -func TestBindNonceOnceAndExactLocalSession(t *testing.T) { |
| - for _, which := range []string{"duplicate", "person", "session", "invalid-nonce"} { |
| - t.Run(which, func(t *testing.T) { |
| - s, _ := fixture(t) |
| - l := local(1) |
| - secret, err := s.Start(ctx, l, "/", testNow) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - n := nonce(1) |
| - if which == "duplicate" { |
| - if err := s.BindNonce(ctx, secret, l, n, testNow); err != nil { |
| - t.Fatal(err) |
| - } |
| - } |
| - if which == "person" { |
| - l.PersonID = 2 |
| - } |
| - if which == "session" { |
| - l.SessionToken = "changed" |
| - } |
| - if which == "invalid-nonce" { |
| - n += "=" |
| - } |
| - refused(t, s.BindNonce(ctx, secret, l, n, testNow)) |
| - refused(t, s.BindNonce(ctx, secret, local(1), nonce(2), testNow)) |
| - }) |
| - } |
| -} |
| - |
| -func TestConfirmationFreshnessAndLocalBinding(t *testing.T) { |
| - for _, which := range []string{"person", "session", "auth-time", "expired", "future-after-rollback"} { |
| - t.Run(which, func(t *testing.T) { |
| - s, _ := fixture(t) |
| - l := local(1) |
| - cookie := complete(t, s, l, "opaque", 1) |
| - now := testNow |
| - switch which { |
| - case "person": |
| - l.PersonID = 2 |
| - case "session": |
| - l.SessionToken = "new-cookie" |
| - case "auth-time": |
| - l.AuthTime = testNow |
| - case "expired": |
| - now = now.Add(241 * time.Second) |
| - case "future-after-rollback": |
| - // Complete a proof with a genuinely current Home gesture, then roll back |
| - // within the accepted clock tolerance. It must not earn future credit. |
| - init := start(t, s, l, nonce(2)) |
| - var err error |
| - cookie, err = s.Complete(ctx, init, l, Home{Issuer: issuer, Subject: "opaque", Nonce: nonce(2), AuthTime: testNow}, testNow) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - now = now.Add(-time.Second) |
| - } |
| - _, err := s.Confirm(ctx, cookie, l, now) |
| - refused(t, err) |
| - _, err = s.Confirm(ctx, cookie, local(1), now) |
| - refused(t, err) |
| - _, _, err = s.Resolve(ctx, issuer, "opaque") |
| - refused(t, err) |
| - }) |
| - } |
| -} |
| - |
| -func TestConflictConsumedWithoutReplacingEitherMapping(t *testing.T) { |
| - s, _ := fixture(t) |
| - l1, l2 := local(1), local(2) |
| - first := complete(t, s, l1, "subject-one", 1) |
| - if _, err := s.Confirm(ctx, first, l1, testNow); err != nil { |
| - t.Fatal(err) |
| - } |
| - identical := complete(t, s, l1, "subject-one", 2) |
| - if _, err := s.Confirm(ctx, identical, l1, testNow); err != nil { |
| - t.Fatal("separate identical proof should be idempotent", err) |
| - } |
| - for _, tc := range []struct { |
| - local Local |
| - sub string |
| - }{{l2, "subject-one"}, {l1, "subject-two"}} { |
| - cookie := complete(t, s, tc.local, tc.sub, 3) |
| - _, err := s.Confirm(ctx, cookie, tc.local, testNow) |
| - refused(t, err) |
| - // Remove the competing mapping only in the fixture: an unconsumed failed |
| - // proof would now succeed, making this a direct replay regression test. |
| - if _, err := s.db.Exec("DELETE FROM docs_identity_links"); err != nil { |
| - t.Fatal(err) |
| - } |
| - _, err = s.Confirm(ctx, cookie, tc.local, testNow) |
| - refused(t, err) |
| - if _, err := s.db.Exec("INSERT INTO docs_identity_links VALUES (?,?,?)", issuer, "subject-one", 1); err != nil { |
| - t.Fatal(err) |
| - } |
| - } |
| - id, _, err := s.Resolve(ctx, issuer, "subject-one") |
| - if err != nil || id != 1 { |
| - t.Fatalf("mapping replaced: %d %v", id, err) |
| - } |
| -} |
| - |
| -func TestConcurrentConfirmationAndCapacity(t *testing.T) { |
| - s, _ := fixture(t) |
| - l := local(1) |
| - cookie := complete(t, s, l, "subject", 1) |
| - var winners atomic.Int32 |
| - var wg sync.WaitGroup |
| - for i := 0; i < 12; i++ { |
| - wg.Add(1) |
| - go func() { |
| - defer wg.Done() |
| - _, err := s.Confirm(ctx, cookie, l, testNow) |
| - if err == nil { |
| - winners.Add(1) |
| - } else if !errors.Is(err, ErrRefused) { |
| - t.Errorf("unexpected concurrent failure: %v", err) |
| - } |
| - }() |
| - } |
| - wg.Wait() |
| - if winners.Load() != 1 { |
| - t.Fatalf("winners=%d", winners.Load()) |
| - } |
| - _, err := s.db.Exec(`WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n WHERE x < 9999) INSERT INTO docs_link_flows SELECT printf('%064d',x),'init',?,x'00' FROM n`, testNow.Unix()+300) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - winners.Store(0) |
| - for i := 0; i < 8; i++ { |
| - wg.Add(1) |
| - go func() { |
| - defer wg.Done() |
| - _, err := s.Start(ctx, l, "/", testNow) |
| - if err == nil { |
| - winners.Add(1) |
| - } else if !errors.Is(err, ErrRefused) { |
| - t.Errorf("unexpected capacity failure: %v", err) |
| - } |
| - }() |
| - } |
| - wg.Wait() |
| - if winners.Load() != 1 || flowCount(t, s) != 10000 { |
| - t.Fatalf("capacity winners=%d count=%d", winners.Load(), flowCount(t, s)) |
| - } |
| - if err := s.Sweep(ctx, testNow.Add(301*time.Second)); err != nil { |
| - t.Fatal(err) |
| - } |
| - if flowCount(t, s) != 0 { |
| - t.Fatal("expired rows survived sweep") |
| - } |
| -} |
| - |
| -func TestSealedPendingAndTamperRefusal(t *testing.T) { |
| - for _, which := range []string{"ciphertext", "row", "origin", "expiry", "key"} { |
| - t.Run(which, func(t *testing.T) { |
| - s, _ := fixture(t) |
| - l := local(1) |
| - cookie := complete(t, s, l, "private-subject", 1) |
| - switch which { |
| - case "ciphertext": |
| - if _, err := s.db.Exec("UPDATE docs_link_flows SET payload = zeroblob(length(payload))"); err != nil { |
| - t.Fatal(err) |
| - } |
| - case "row": |
| - replacement, _ := newSecret() |
| - if _, err := s.db.Exec("UPDATE docs_link_flows SET id_hash = ?", hash(replacement)); err != nil { |
| - t.Fatal(err) |
| - } |
| - cookie = replacement |
| - case "origin": |
| - s.origin = "https://other.docs.oficina.works" |
| - case "expiry": |
| - if _, err := s.db.Exec("UPDATE docs_link_flows SET expires_at = expires_at + 300"); err != nil { |
| - t.Fatal(err) |
| - } |
| - case "key": |
| - var err error |
| - s, err = New(s.db, bytes.Repeat([]byte{43}, 32), origin, issuer) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - } |
| - _, err := s.Confirm(ctx, cookie, l, testNow) |
| - refused(t, err) |
| - if flowCount(t, s) != 0 { |
| - t.Fatal("tampered row remains reusable") |
| - } |
| - }) |
| - } |
| -} |
| - |
| -func TestNoPendingSecretsInSQLiteOrWAL(t *testing.T) { |
| - s, path := fixture(t) |
| - l := local(1) |
| - n := nonce(8) |
| - init := start(t, s, l, n) |
| - cookie, err := s.Complete(ctx, init, l, Home{Issuer: issuer, Subject: "private-subject-should-be-sealed", Nonce: n, AuthTime: testNow}, testNow) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - for _, file := range []string{path, path + "-wal"} { |
| - raw, err := os.ReadFile(file) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - for _, secret := range []string{init, cookie, l.SessionToken, n, "private-subject-should-be-sealed", "/d/private-document?view=reading"} { |
| - if bytes.Contains(raw, []byte(secret)) { |
| - t.Fatalf("plaintext in %s", filepath.Base(file)) |
| - } |
| - } |
| - } |
| - reopened, err := New(s.db, bytes.Repeat([]byte{42}, 32), origin, issuer) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if _, err := reopened.Confirm(ctx, cookie, l, testNow); err != nil { |
| - t.Fatal("sealed pending must survive store restart", err) |
| - } |
| -} |
| - |
| -func TestClockHighWaterPreventsRevivedAuthentication(t *testing.T) { |
| - s, _ := fixture(t) |
| - l := local(1) |
| - cookie := complete(t, s, l, "subject", 1) |
| - if err := s.Sweep(ctx, testNow.Add(241*time.Second)); err != nil { |
| - t.Fatal(err) |
| - } |
| - _, err := s.Confirm(ctx, cookie, l, testNow.Add(220*time.Second)) |
| - refused(t, err) |
| - if err := s.Sweep(ctx, testNow); !errors.Is(err, ErrRefused) { |
| - t.Fatalf("large clock rollback=%v", err) |
| - } |
| -} |
| - |
| -func TestSafePathsAndInvalidInputs(t *testing.T) { |
| - for _, path := range []string{"", "https://evil.example", "//evil.example", "/auth/finish", "/%2fhost", "/d/../auth/finish", "/d\\evil", "/d/x\n"} { |
| - t.Run(path, func(t *testing.T) { |
| - s, _ := fixture(t) |
| - l := local(1) |
| - init, err := s.Start(ctx, l, path, testNow) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := s.BindNonce(ctx, init, l, nonce(1), testNow); err != nil { |
| - t.Fatal(err) |
| - } |
| - cookie, err := s.Complete(ctx, init, l, Home{Issuer: issuer, Subject: "subject", Nonce: nonce(1), AuthTime: testNow}, testNow) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - p, err := s.Pending(ctx, cookie, l, testNow) |
| - if err != nil || p.ReturnPath != "/" { |
| - t.Fatalf("unsafe return=%q %v", p.ReturnPath, err) |
| - } |
| - }) |
| - } |
| - s, _ := fixture(t) |
| - for _, l := range []Local{{}, {PersonID: 99, SessionToken: "actual", AuthTime: testNow}, {PersonID: 1, SessionToken: "actual", AuthTime: testNow.Add(time.Second)}, {PersonID: 1, SessionToken: "actual", AuthTime: testNow.Add(-301 * time.Second)}} { |
| - _, err := s.Start(ctx, l, "/", testNow) |
| - refused(t, err) |
| - } |
| - for _, cookie := range []string{"", "short", strings.Repeat("A", 43) + "=", strings.Repeat("A", 42) + "B"} { |
| - _, err := s.Confirm(ctx, cookie, local(1), testNow) |
| - refused(t, err) |
| - } |
| -} |
| - |
| -func TestMappingStorageFailureRollsBackProofConsumption(t *testing.T) { |
| - s, _ := fixture(t) |
| - l := local(1) |
| - cookie := complete(t, s, l, "subject", 1) |
| - if _, err := s.db.Exec(`CREATE TRIGGER block_link BEFORE INSERT ON docs_identity_links BEGIN SELECT RAISE(ABORT, 'private internal storage detail'); END`); err != nil { |
| - t.Fatal(err) |
| - } |
| - _, err := s.Confirm(ctx, cookie, l, testNow) |
| - if !errors.Is(err, ErrStorage) || strings.Contains(err.Error(), "private") { |
| - t.Fatalf("storage error = %v", err) |
| - } |
| - if flowCount(t, s) != 1 { |
| - t.Fatal("storage failure consumed proof without mapping") |
| - } |
| - if _, err := s.db.Exec("DROP TRIGGER block_link"); err != nil { |
| - t.Fatal(err) |
| - } |
| - if _, err := s.Confirm(ctx, cookie, l, testNow); err != nil { |
| - t.Fatal("retry after storage recovery", err) |
| - } |
| -} |
| - |
| -func TestConcurrentConflictingSubjectsCannotReplacePersonLink(t *testing.T) { |
| - s, _ := fixture(t) |
| - l := local(1) |
| - a, b := complete(t, s, l, "subject-a", 1), complete(t, s, l, "subject-b", 2) |
| - var winners atomic.Int32 |
| - var wg sync.WaitGroup |
| - for _, cookie := range []string{a, b} { |
| - wg.Add(1) |
| - go func() { |
| - defer wg.Done() |
| - _, err := s.Confirm(ctx, cookie, l, testNow) |
| - if err == nil { |
| - winners.Add(1) |
| - } else if !errors.Is(err, ErrRefused) { |
| - t.Errorf("conflicting confirmation: %v", err) |
| - } |
| - }() |
| - } |
| - wg.Wait() |
| - if winners.Load() != 1 || flowCount(t, s) != 0 { |
| - t.Fatalf("conflict winners=%d remaining=%d", winners.Load(), flowCount(t, s)) |
| - } |
| - for _, cookie := range []string{a, b} { |
| - _, err := s.Confirm(ctx, cookie, l, testNow) |
| - refused(t, err) |
| - } |
| -} |
| - |
| -func TestPendingReadConsumesChangedSession(t *testing.T) { |
| - s, _ := fixture(t) |
| - l := local(1) |
| - cookie := complete(t, s, l, "subject", 1) |
| - changed := l |
| - changed.SessionToken = "rotated-cookie" |
| - _, err := s.Pending(ctx, cookie, changed, testNow) |
| - refused(t, err) |
| - _, err = s.Confirm(ctx, cookie, l, testNow) |
| - refused(t, err) |
| -} |
| - |
| -func TestFreshnessBoundaryProducesNoExpiredNewRows(t *testing.T) { |
| - s, _ := fixture(t) |
| - l := local(1) |
| - l.AuthTime = testNow.Add(-300 * time.Second) |
| - _, err := s.Start(ctx, l, "/", testNow) |
| - refused(t, err) |
| - l = local(1) |
| - init := start(t, s, l, nonce(1)) |
| - _, err = s.Complete(ctx, init, l, Home{Issuer: issuer, Subject: "subject", Nonce: nonce(1), AuthTime: testNow.Add(-300 * time.Second)}, testNow) |
| - refused(t, err) |
| - if flowCount(t, s) != 0 { |
| - t.Fatal("expired state minted at exact five-minute boundary") |
| - } |
| -} |
diff --git a/internal/docs/principalstore/store.go b/internal/docs/principalstore/store.go| index b913833..2d4e8ef 100644 |
| --- a/internal/docs/principalstore/store.go |
| +++ b/internal/docs/principalstore/store.go |
| @@ -18,10 +18,41 @@ import ( |
| //go:embed migrations/*.sql |
| var migrations embed.FS |
| -// Schema follows Docs and linkstore schemas. It remains unmounted until the |
| -// combined migration, admission and rollback release has been reviewed. |
| +// Schema follows Docs and linkstore schemas, in the team schema only. Its |
| +// link triggers name Docs' retired docs_identity_links, as applied; the |
| +// move onto home/connect re-points them (RepointLinks). |
| var Schema = migrate.MustFromFS(migrations, "docs_principal") |
| +// repointLinks is 0001_principals.sql's four link triggers, naming |
| +// home/connect's home_identity_links instead of docs_identity_links. Links |
| +// and Home-only identities stay disjoint in both directions, and a link, |
| +// once made, is never changed or removed: connect only inserts. |
| +const repointLinks = ` |
| +DROP TRIGGER IF EXISTS docs_home_identity_unique; |
| +DROP TRIGGER IF EXISTS docs_local_identity_unique; |
| +DROP TRIGGER IF EXISTS docs_identity_links_keep_update; |
| +DROP TRIGGER IF EXISTS docs_identity_links_keep_delete; |
| +DROP TRIGGER IF EXISTS docs_home_links_keep_update; |
| +DROP TRIGGER IF EXISTS docs_home_links_keep_delete; |
| +CREATE TRIGGER docs_home_identity_unique BEFORE INSERT ON docs_home_identities WHEN EXISTS(SELECT 1 FROM home_identity_links WHERE issuer=NEW.issuer AND subject=NEW.subject) BEGIN SELECT RAISE(ABORT,'docs principal: refused'); END; |
| +CREATE TRIGGER docs_local_identity_unique BEFORE INSERT ON home_identity_links WHEN EXISTS(SELECT 1 FROM docs_home_identities WHERE issuer=NEW.issuer AND subject=NEW.subject) BEGIN SELECT RAISE(ABORT,'docs principal: refused'); END; |
| +CREATE TRIGGER docs_home_links_keep_update BEFORE UPDATE ON home_identity_links BEGIN SELECT RAISE(ABORT,'docs principal: refused'); END; |
| +CREATE TRIGGER docs_home_links_keep_delete BEFORE DELETE ON home_identity_links BEGIN SELECT RAISE(ABORT,'docs principal: refused'); END; |
| +` |
| + |
| +// RepointLinks moves the link triggers onto home_identity_links inside the |
| +// caller's transaction, which must also retire docs_identity_links (the |
| +// move at boot does both). It never commits. |
| +func RepointLinks(ctx context.Context, tx *sql.Tx) error { |
| + if tx == nil { |
| + return ErrUnavailable |
| + } |
| + if _, err := tx.ExecContext(ctx, repointLinks); err != nil { |
| + return ErrUnavailable |
| + } |
| + return nil |
| +} |
| + |
| const HomeIDMin int64 = 1 << 52 |
| const HomeIDMax int64 = 1<<53 - 1 |
| @@ -120,7 +151,7 @@ func (s *Store) Resolve(ctx context.Context, issuer, subject string) (Principal, |
| } |
| var id int64 |
| var count int |
| - err := s.db.QueryRowContext(ctx, `SELECT COALESCE(MIN(id),0),COUNT(*) FROM (SELECT person_id AS id FROM docs_identity_links WHERE issuer=? AND subject=? UNION ALL SELECT principal_id AS id FROM docs_home_identities WHERE issuer=? AND subject=?)`, issuer, subject, issuer, subject).Scan(&id, &count) |
| + err := s.db.QueryRowContext(ctx, `SELECT COALESCE(MIN(id),0),COUNT(*) FROM (SELECT person_id AS id FROM home_identity_links WHERE issuer=? AND subject=? UNION ALL SELECT principal_id AS id FROM docs_home_identities WHERE issuer=? AND subject=?)`, issuer, subject, issuer, subject).Scan(&id, &count) |
| if err != nil { |
| return Principal{}, ErrUnavailable |
| } |
| @@ -153,7 +184,7 @@ func (s *Store) EnsureHome(ctx context.Context, identity HomeIdentity) (Principa |
| return Principal{}, ErrUnavailable |
| } |
| var local int |
| - if err = tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM docs_identity_links WHERE issuer=? AND subject=?`, identity.Issuer, identity.Subject).Scan(&local); err != nil { |
| + if err = tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM home_identity_links WHERE issuer=? AND subject=?`, identity.Issuer, identity.Subject).Scan(&local); err != nil { |
| return Principal{}, ErrUnavailable |
| } |
| if local != 0 { |
diff --git a/internal/docs/principalstore/store_test.go b/internal/docs/principalstore/store_test.go| index c3786b4..5e548db 100644 |
| --- a/internal/docs/principalstore/store_test.go |
| +++ b/internal/docs/principalstore/store_test.go |
| @@ -8,6 +8,7 @@ import ( |
| "sync" |
| "testing" |
| + connectlinks "amadan.net/oficina/home/connect/linkstore" |
| "amadan.net/rastrillo/rastrillo/db" |
| "amadan.net/rastrillo/rastrillo/migrate" |
| "github.com/carlosframework/docs/internal/docs" |
| @@ -17,6 +18,34 @@ import ( |
| const issuer = "https://id.oficina.works" |
| +// base is the schema principalstore follows: Docs', its retired link table |
| +// (still applied in every database) and connect's. |
| +var base = migrate.Merge(docs.Schema, linkstore.Schema, migrate.MustFromFS(connectlinks.Migrations, connectlinks.SchemaNamespace)) |
| + |
| +// applyPrincipals applies Schema and then does what Docs' boot does next, |
| +// in one transaction: re-point the link triggers at home_identity_links |
| +// and drop docs_identity_links. |
| +func applyPrincipals(t *testing.T, d *db.DB) { |
| + t.Helper() |
| + if _, e := migrate.Apply(context.Background(), d, p.Schema); e != nil { |
| + t.Fatal(e) |
| + } |
| + tx, e := d.Writer().Begin() |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer tx.Rollback() |
| + if e = p.RepointLinks(context.Background(), tx); e != nil { |
| + t.Fatal(e) |
| + } |
| + if _, e = tx.Exec(`DROP TABLE docs_identity_links`); e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = tx.Commit(); e != nil { |
| + t.Fatal(e) |
| + } |
| +} |
| + |
| func fixture(t *testing.T, apply bool) (*db.DB, *p.Store) { |
| t.Helper() |
| d, e := db.Open(filepath.Join(t.TempDir(), "docs.db"), nil) |
| @@ -24,13 +53,11 @@ func fixture(t *testing.T, apply bool) (*db.DB, *p.Store) { |
| t.Fatal(e) |
| } |
| t.Cleanup(func() { d.Close() }) |
| - if _, e = migrate.Apply(context.Background(), d, migrate.Merge(docs.Schema, linkstore.Schema)); e != nil { |
| + if _, e = migrate.Apply(context.Background(), d, base); e != nil { |
| t.Fatal(e) |
| } |
| if apply { |
| - if _, e = migrate.Apply(context.Background(), d, p.Schema); e != nil { |
| - t.Fatal(e) |
| - } |
| + applyPrincipals(t, d) |
| } |
| s, e := p.New(d.Writer(), p.Config{Issuer: issuer, Team: "A1", RequireMembership: func(_ context.Context, r p.MembershipRequest) error { |
| if r.Issuer != issuer || r.Team != "A1" || r.Subject == "absent" { |
| @@ -64,10 +91,8 @@ func local(t *testing.T, d *db.DB, address string) int64 { |
| func TestAllocationIsolationAddressAbsenceAndNoSamples(t *testing.T) { |
| d, s := fixture(t, false) |
| a := local(t, d, "alice@example.invalid") |
| - exec(t, d, `INSERT INTO docs_identity_links VALUES(?,?,?)`, issuer, "alice", a) |
| - if _, e := migrate.Apply(context.Background(), d, p.Schema); e != nil { |
| - t.Fatal(e) |
| - } |
| + exec(t, d, `INSERT INTO home_identity_links(issuer,subject,person_id) VALUES(?,?,?)`, issuer, "alice", a) |
| + applyPrincipals(t, d) |
| old, e := s.Resolve(context.Background(), issuer, "alice") |
| if e != nil || old.ID != a || old.Kind != p.Local || old.VerifiedAddress == nil || *old.VerifiedAddress != "alice@example.invalid" { |
| t.Fatal(old, e) |
| @@ -97,9 +122,23 @@ func TestAllocationIsolationAddressAbsenceAndNoSamples(t *testing.T) { |
| if _, e = s.EnsureHome(context.Background(), p.HomeIdentity{Issuer: issuer, Subject: "alice"}); !errors.Is(e, p.ErrRefused) { |
| t.Fatal("merged local account", e) |
| } |
| - if _, e = d.Writer().Exec(`INSERT INTO docs_identity_links VALUES(?,?,?)`, issuer, "new-home", b); e == nil { |
| + if _, e = d.Writer().Exec(`INSERT INTO home_identity_links(issuer,subject,person_id) VALUES(?,?,?)`, issuer, "new-home", b); e == nil { |
| t.Fatal("cross-table collision accepted") |
| } |
| + if _, e = d.Writer().Exec(`INSERT INTO home_identity_links(issuer,subject,person_id) VALUES(?,?,?)`, issuer, "bob-home", b); e != nil { |
| + t.Fatal("a link without a collision refused", e) |
| + } |
| + if _, e = s.EnsureHome(context.Background(), p.HomeIdentity{Issuer: issuer, Subject: "bob-home"}); !errors.Is(e, p.ErrRefused) { |
| + t.Fatal("allocated beside a link", e) |
| + } |
| + if _, e = d.Writer().Exec(`INSERT INTO docs_home_identities VALUES(?,?,?)`, issuer, "bob-home", p.HomeIDMin); e == nil { |
| + t.Fatal("reverse cross-table collision accepted") |
| + } |
| + for _, q := range []string{`UPDATE home_identity_links SET person_id=person_id`, `DELETE FROM home_identity_links`} { |
| + if _, e = d.Writer().Exec(q); e == nil { |
| + t.Fatal("a link changed:", q) |
| + } |
| + } |
| } |
| func TestMembershipSeamAndIdentityOnlyResolve(t *testing.T) { |
| d, s := fixture(t, true) |
| @@ -177,7 +216,7 @@ func TestConcurrentCreationAndImmutableIDs(t *testing.T) { |
| `DELETE FROM docs_home_identities`, `UPDATE docs_home_identities SET subject='other'`, `UPDATE docs_home_allocator SET high_water=high_water-1`, |
| fmt.Sprintf(`INSERT INTO people(id,email,created_at) VALUES(%d,'collision@example.invalid',CURRENT_TIMESTAMP)`, p.HomeIDMin), |
| fmt.Sprintf(`INSERT INTO docs_home_identities VALUES('%s','wrong-kind',%d)`, issuer, a), |
| - `INSERT INTO docs_identity_links VALUES('https://id.oficina.works','missing',12345)`, |
| + fmt.Sprintf(`INSERT INTO home_identity_links(issuer,subject,person_id) VALUES('%s','same',%d)`, issuer, a), |
| } { |
| if _, e := d.Writer().Exec(q); e == nil { |
| t.Fatalf("accepted mutation: %s", q) |
| @@ -186,7 +225,7 @@ func TestConcurrentCreationAndImmutableIDs(t *testing.T) { |
| if _, e := migrate.Apply(ctx, d, p.Schema); e != nil { |
| t.Fatal(e) |
| } |
| - if _, e := migrate.Apply(ctx, d, migrate.Merge(docs.Schema, linkstore.Schema)); e != nil { |
| + if _, e := migrate.Apply(ctx, d, base); e != nil { |
| t.Fatal("older known migration set rejected newer ledger", e) |
| } |
| rows, e := d.Writer().Query(`PRAGMA foreign_key_check`) |
diff --git a/internal/docs/signin_return.go b/internal/docs/signin_return.go| index d4a0047..c4d6427 100644 |
| --- a/internal/docs/signin_return.go |
| +++ b/internal/docs/signin_return.go |
| @@ -5,12 +5,12 @@ package docs |
| // GET /signin goes straight back, and signing out lands on a page that |
| // says so. |
| // |
| -// With Home configured, the return path already rode the Home hand-off |
| -// (home_routes.go's signin remembers it in __Host-oficina-docs-home- |
| -// return). What did not honour it was the local email link: rastrillo's |
| -// auth.Verify always lands on its fixed SignedInPath, so the value cannot |
| -// ride the emailed link and lives in that same sealed, 600-second cookie |
| -// instead, read at /auth/local/complete. |
| +// With Home configured, the return path rides the Home hand-off, and |
| +// home_connect.go's signin also remembers it in Docs' own |
| +// __Host-oficina-docs-home-return. What would not honour it is the local |
| +// email link: rastrillo's auth.Verify always lands on its fixed |
| +// SignedInPath, so the value cannot ride the emailed link and lives in |
| +// that sealed, 600-second cookie instead, read at /auth/local/complete. |
| // |
| // Standalone Docs (no Home) had nothing: rastrillo's RequireSession drops |
| // the path (its refuseSession redirects to a bare /signin) and its |
| @@ -32,7 +32,6 @@ import ( |
| "net/http" |
| "net/url" |
| "strings" |
| - "time" |
| "amadan.net/oficina/home/handoff" |
| "amadan.net/oficina/home/handoff/seal" |
| @@ -40,19 +39,19 @@ import ( |
| ) |
| // standaloneReturn builds the standalone instance's return memory: the |
| -// same sealed cookie localLinkNavigation keeps for Home instances, keyed |
| +// same sealed cookie returnMemory keeps for Home instances, keyed |
| // from the instance key rather than Home's DEK (standalone has none). |
| -func standaloneReturn(instanceKey, origin string) (*localLinkNavigation, error) { |
| +func standaloneReturn(instanceKey, origin string) (*returnMemory, error) { |
| key := sha256.Sum256([]byte("oficina/docs standalone return v1\x00" + instanceKey)) |
| sealer, err := seal.New(key[:], "oficina/docs") |
| if err != nil { |
| return nil, err |
| } |
| - u, err := url.Parse(origin) |
| - if err != nil { |
| - return nil, err |
| + n := newReturnMemory(sealer, origin) |
| + if n == nil { |
| + return nil, errHomeConfig |
| } |
| - return &localLinkNavigation{sealer: sealer, origin: origin, host: u.Host, now: time.Now}, nil |
| + return n, nil |
| } |
| // requestedReturn is the return_to a sign-in GET carries, when it is |
| @@ -110,7 +109,7 @@ func (h *handlers) admitted(r *http.Request) bool { |
| // standaloneSignin is GET /signin without Home: already signed in (and |
| // admitted) goes back; a return_to is remembered for the landing; then |
| // the form. |
| -func (h *handlers) standaloneSignin(n *localLinkNavigation) http.HandlerFunc { |
| +func (h *handlers) standaloneSignin(n *returnMemory) http.HandlerFunc { |
| return func(w http.ResponseWriter, r *http.Request) { |
| if !signinOutcome(r) && h.admitted(r) { |
| alreadySignedIn(w, r) |
| @@ -120,7 +119,7 @@ func (h *handlers) standaloneSignin(n *localLinkNavigation) http.HandlerFunc { |
| // /signin remembers the list: a page remembered by an earlier, |
| // abandoned attempt must not win over the one being made now. The |
| // email flow's own outcomes (?sent, ?err) leave it alone. Home's |
| - // /signin does the same (home_routes.go). |
| + // /signin does the same (home_connect.go). |
| if !signinOutcome(r) { |
| path, ok := requestedReturn(r) |
| if !ok { |
| @@ -134,7 +133,7 @@ func (h *handlers) standaloneSignin(n *localLinkNavigation) http.HandlerFunc { |
| // completeStandalone is the standalone SignedInPath: land on the |
| // remembered page, once, or on the list. |
| -func (n *localLinkNavigation) completeStandalone(w http.ResponseWriter, r *http.Request) { |
| +func (n *returnMemory) completeStandalone(w http.ResponseWriter, r *http.Request) { |
| if !n.guard(w, r, localLinkCompletePath) { |
| return |
| } |
| @@ -172,15 +171,6 @@ func signoutToSignedOut(signout http.HandlerFunc) http.HandlerFunc { |
| if result.status == http.StatusSeeOther && strings.HasPrefix(result.header.Get("Location"), "/signin") { |
| result.header.Set("Location", "/signed-out") |
| } |
| - for name, values := range result.header { |
| - for _, value := range values { |
| - w.Header().Add(name, value) |
| - } |
| - } |
| - if result.status == 0 { |
| - result.status = http.StatusOK |
| - } |
| - w.WriteHeader(result.status) |
| - _, _ = w.Write(result.body.Bytes()) |
| + result.replay(w) |
| } |
| } |
diff --git a/internal/docs/team_access.go b/internal/docs/team_access.go| index 9713204..d1cf512 100644 |
| --- a/internal/docs/team_access.go |
| +++ b/internal/docs/team_access.go |
| @@ -52,6 +52,17 @@ func (s *Store) access(ctx context.Context, actor Actor) (*requestAccess, bool) |
| a, ok := ctx.Value(accessContextKey{}).(*requestAccess) |
| return a, ok && a != nil && a.runtime == s.team && sameActor(a.actor, actor) |
| } |
| + |
| +// withAccess carries a request's standing to the store: Docs' own key, for |
| +// permissionScope and the emission checks, and teammode's, so Guard is |
| +// handed the same latched Access rather than Unknown. |
| +func withAccess(ctx context.Context, a *requestAccess) context.Context { |
| + ctx = context.WithValue(ctx, accessContextKey{}, a) |
| + if a != nil { |
| + ctx = teammode.WithAccess(ctx, a.Access) |
| + } |
| + return ctx |
| +} |
| func (t *teamRuntime) resolveAccess(ctx context.Context, id requestIdentity) *requestAccess { |
| return &requestAccess{Access: t.cache.Access(ctx, id.HomeSubject), runtime: t, actor: id.Actor} |
| } |
| @@ -63,7 +74,7 @@ func (t *teamRuntime) admission(next http.Handler) http.Handler { |
| return |
| } |
| a := t.resolveAccess(r.Context(), id) |
| - next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), accessContextKey{}, a))) |
| + next.ServeHTTP(w, r.WithContext(withAccess(r.Context(), a))) |
| }) |
| } |
| @@ -168,9 +179,10 @@ func (s *Store) snapshotPermission(ctx context.Context, db *gorm.DB, docID int64 |
| // ownerMutation authorizes, mutates and authorizes again inside one writer |
| // transaction, so it commits only if the standing that admitted it still |
| -// holds. The rule reads the standing in permissionScope, from the request's |
| -// own latched Access matched to the actor, rather than from Guard's |
| -// argument; with team mode off it is ownership alone. |
| +// holds. Guard is handed the request's standing (admission carries its |
| +// Access with withAccess), and the rule, in permissionScope, reads that |
| +// same latched Access matched to the actor; with team mode off it is |
| +// ownership alone. |
| func (s *Store) ownerMutation(ctx context.Context, owner, docID int64, mutate func(*gorm.DB) error) error { |
| actor := s.ownerActor(ctx, owner) |
| return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
diff --git a/internal/docs/team_access_test.go b/internal/docs/team_access_test.go| index 5c9fb77..72729c5 100644 |
| --- a/internal/docs/team_access_test.go |
| +++ b/internal/docs/team_access_test.go |
| @@ -1,6 +1,7 @@ |
| package docs |
| import ( |
| + connectlinks "amadan.net/oficina/home/connect/linkstore" |
| "amadan.net/oficina/home/handoff/seal" |
| "amadan.net/oficina/home/roster" |
| "amadan.net/oficina/home/teammode" |
| @@ -9,6 +10,7 @@ import ( |
| "amadan.net/rastrillo/rastrillo/sessions" |
| "bytes" |
| "context" |
| + "database/sql" |
| "encoding/base64" |
| "errors" |
| "github.com/carlosframework/docs/internal/docs/principalstore" |
| @@ -16,6 +18,7 @@ import ( |
| "gorm.io/gorm" |
| "io" |
| "net/http" |
| + "net/http/httptest" |
| "strings" |
| "sync" |
| "testing" |
| @@ -147,6 +150,25 @@ type teamTestTransport func(*http.Request) (*http.Response, error) |
| func (f teamTestTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } |
| +// migrateTeam applies the team schema to a team-off test App's database |
| +// and moves its (empty) link table onto connect's, as New would at boot. |
| +func migrateTeam(t *testing.T, app *App) { |
| + t.Helper() |
| + if _, e := migrate.Apply(t.Context(), app.db, TeamBootSchema); e != nil { |
| + t.Fatal(e) |
| + } |
| + if e := moveLinksOntoConnect(t.Context(), app.db.Writer(), refuseAdopt{}); e != nil { |
| + t.Fatal(e) |
| + } |
| +} |
| + |
| +// refuseAdopt is an adopter for a move that must carry no rows. |
| +type refuseAdopt struct{} |
| + |
| +func (refuseAdopt) Adopt(context.Context, *sql.Tx, string, string, int64) error { |
| + return connectlinks.ErrRefused |
| +} |
| + |
| func testTeamRoster(t *testing.T, s *Store, app *App) (*teamRuntime, *teamTestClock, string) { |
| t.Helper() |
| op, e := family.Generate() |
| @@ -168,9 +190,7 @@ func testTeamRoster(t *testing.T, s *Store, app *App) (*teamRuntime, *teamTestCl |
| if e != nil { |
| t.Fatal(e) |
| } |
| - if _, e = migrate.Apply(t.Context(), app.db, TeamBootSchema); e != nil { |
| - t.Fatal(e) |
| - } |
| + migrateTeam(t, app) |
| clock := &teamTestClock{} |
| subject := "pr_" + strings.Repeat("a", 26) |
| transport := teamTestTransport(func(r *http.Request) (*http.Response, error) { |
| @@ -195,7 +215,7 @@ func testTeamRoster(t *testing.T, s *Store, app *App) (*teamRuntime, *teamTestCl |
| if e != nil { |
| t.Fatal(e) |
| } |
| - cache, e := teammode.Open(t.Context(), teammode.RuntimeConfig{Settings: settings, State: teamState, DB: app.db.Writer(), Sealer: sealer, IssuerTables: []string{"docs_identity_links", "docs_home_identities"}, Clock: clock, Transport: transport}) |
| + cache, e := teammode.Open(t.Context(), teammode.RuntimeConfig{Settings: settings, State: teamState, DB: app.db.Writer(), Sealer: sealer, IssuerTables: []string{"home_identity_links", "docs_home_identities"}, Clock: clock, Transport: transport}) |
| if e != nil { |
| t.Fatal(e) |
| } |
| @@ -423,7 +443,7 @@ func TestTeamPermissionContentionCannotRecoverIntoPermanentDenial(t *testing.T) |
| t.Fatal("session") |
| } |
| request := sessions.WithSession(b.request("GET", "/", ""), session) |
| - id, e := f.app.store.team.bridge.resolver.resolve(request) |
| + id, e := f.app.store.team.home.resolver.resolve(request) |
| if e != nil { |
| t.Fatal(e) |
| } |
| @@ -469,3 +489,35 @@ func TestTeamPermissionContentionCannotRecoverIntoPermanentDenial(t *testing.T) |
| t.Fatal("uncertainty leaked into a new request") |
| } |
| } |
| + |
| +// Admission carries the request's Access to teammode as well as to Docs' |
| +// own key, so Guard, inside ownerMutation's transaction, is handed the |
| +// real latched standing rather than Unknown. |
| +func TestTeamAdmissionCarriesTheAccessToGuard(t *testing.T) { |
| + app := newSampleDocumentsInternalTestApp(t, "0") |
| + s := app.Store() |
| + person, e := s.EnsurePerson(t.Context(), "member@example.com") |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + rt, _, subject := testTeamRoster(t, s, app) |
| + id := requestIdentity{Actor: localActor(person, "member@example.com"), HomeSubject: subject} |
| + r := httptest.NewRequest("GET", "https://docs.example/", nil) |
| + r = r.WithContext(context.WithValue(r.Context(), identityContextKey{}, id)) |
| + reached := false |
| + rt.admission(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + reached = true |
| + a, ok := r.Context().Value(accessContextKey{}).(*requestAccess) |
| + carried, found := teammode.FromContext(r.Context()) |
| + if !ok || !found || carried != a.Access || teammode.Standing(r.Context()) != roster.Member { |
| + t.Fatal("Guard would not see the request's standing", teammode.Standing(r.Context())) |
| + } |
| + var standing roster.State |
| + if e := teammode.Guard(r.Context(), func(st roster.State) error { standing = st; return nil }, func() error { return nil }); e != nil || standing != roster.Member { |
| + t.Fatal("Guard was handed", standing, e) |
| + } |
| + })).ServeHTTP(httptest.NewRecorder(), r) |
| + if !reached { |
| + t.Fatal("admission refused a member") |
| + } |
| +} |
diff --git a/internal/docs/team_config.go b/internal/docs/team_config.go| index cf7edb0..d4caedd 100644 |
| --- a/internal/docs/team_config.go |
| +++ b/internal/docs/team_config.go |
| @@ -11,6 +11,7 @@ import ( |
| "amadan.net/oficina/home/roster" |
| "amadan.net/oficina/home/teammode" |
| "amadan.net/rastrillo/rastrillo/migrate" |
| + "github.com/carlosframework/docs/internal/docs/linkstore" |
| "github.com/carlosframework/docs/internal/docs/principalstore" |
| ) |
| @@ -44,7 +45,9 @@ type teamSettings struct { |
| clock roster.Clock |
| } |
| -var TeamBootSchema = migrate.Merge(BootSchema, principalstore.Schema, teamState.Schema()) |
| +// TeamBootSchema is BootSchema and the team sets. linkstore.ForPrincipals |
| +// sits just before principalstore.Schema: see its comment. |
| +var TeamBootSchema = migrate.Merge(BootSchema, linkstore.ForPrincipals, principalstore.Schema, teamState.Schema()) |
| func validatedTeamConfig(cfg *TeamConfig, home *homeSettings, origin string) (*teamSettings, error) { |
| if cfg == nil { |
| @@ -64,7 +67,7 @@ type teamRuntime struct { |
| // cache is the roster cache, behind teammode's runtime: its Check is |
| // the only way Docs asks it, and Access the only way a request does. |
| cache *teammode.Runtime |
| - bridge *homeBridge |
| + home *homeRoutes |
| readSession func(context.Context, *http.Request) (sessions.Session, bool) |
| principals *principalstore.Store |
| bindings roster.Bindings |
| @@ -79,7 +82,7 @@ func newTeamRuntime(ctx context.Context, settings *teamSettings, db *sql.DB, hom |
| if e != nil { |
| return nil, errTeamConfig |
| } |
| - cache, e := teammode.Open(ctx, teammode.RuntimeConfig{Settings: settings.Settings, State: teamState, DB: db, Sealer: sealer, IssuerTables: []string{"docs_identity_links", "docs_home_identities"}, Transport: settings.transport, Clock: settings.clock}) |
| + cache, e := teammode.Open(ctx, teammode.RuntimeConfig{Settings: settings.Settings, State: teamState, DB: db, Sealer: sealer, IssuerTables: []string{"home_identity_links", "docs_home_identities"}, Transport: settings.transport, Clock: settings.clock}) |
| if e != nil { |
| if errors.Is(e, teammode.ErrConfig) { |
| return nil, errTeamConfig |
| @@ -88,9 +91,10 @@ func newTeamRuntime(ctx context.Context, settings *teamSettings, db *sql.DB, hom |
| } |
| b := cache.Bindings() |
| runtime := &teamRuntime{cache: cache, bindings: b, db: db} |
| - // The allocation gate until Docs moves onto home/connect, whose |
| - // Unlinked hook takes AdmitUnlinked directly: a Home-only principal |
| - // is created only while the roster says Member under a valid lease. |
| + // The allocation gate: a Home-only principal is created only while the |
| + // roster says Member under a valid lease. connect's Unlinked hook asks |
| + // AdmitUnlinked first (home_connect.go); this is the second gate, |
| + // inside EnsureHome, so it holds for every caller. |
| principals, e := principalstore.New(db, principalstore.Config{Issuer: b.Issuer, Team: b.Team, RequireMembership: func(ctx context.Context, request principalstore.MembershipRequest) error { |
| if request.Team != b.Team { |
| return principalstore.ErrUnavailable |
diff --git a/internal/docs/team_home.go b/internal/docs/team_home.go| deleted file mode 100644 |
| index 682fe4d..0000000 |
| --- a/internal/docs/team_home.go |
| +++ /dev/null |
| @@ -1,62 +0,0 @@ |
| -package docs |
| - |
| -import ( |
| - "errors" |
| - "net/http" |
| - |
| - "amadan.net/rastrillo/rastrillo/assertion" |
| - "amadan.net/rastrillo/rastrillo/sessions" |
| - "github.com/carlosframework/docs/internal/docs/principalstore" |
| -) |
| - |
| -// existingPrincipal is read-only; an existing browser session cannot cause an |
| -// unknown incoming identity to allocate a second account during completion. |
| -func (b *homeBridge) existingPrincipal(r *http.Request, session sessions.Session) (principalstore.Principal, error) { |
| - t := b.store.team |
| - if t == nil { |
| - return principalstore.Principal{}, errIdentityRefused |
| - } |
| - if session.Method == homeAssertionMethod { |
| - return t.principals.Resolve(r.Context(), t.bindings.Issuer, session.Subject) |
| - } |
| - person, e := b.existingPerson(r, session) |
| - if e != nil { |
| - return principalstore.Principal{}, e |
| - } |
| - p, e := t.principals.Person(r.Context(), person.ID) |
| - if e == nil && p.Kind != principalstore.Local { |
| - return principalstore.Principal{}, errIdentityRefused |
| - } |
| - return p, e |
| -} |
| -func (b *homeBridge) completeTeamPrincipal(r *http.Request, claims assertion.Claims, current *sessions.Session) error { |
| - t := b.store.team |
| - p, e := t.principals.Resolve(r.Context(), claims.Issuer, claims.Subject) |
| - if e != nil && !errors.Is(e, principalstore.ErrRefused) { |
| - return rejectHome(r, "failed", http.StatusServiceUnavailable) |
| - } |
| - if current != nil { |
| - if e != nil { |
| - return rejectHome(r, "failed", http.StatusForbidden) |
| - } |
| - existing, err := b.existingPrincipal(r, *current) |
| - if errors.Is(err, principalstore.ErrUnavailable) || errors.Is(err, errIdentityStorage) { |
| - return rejectHome(r, "failed", http.StatusServiceUnavailable) |
| - } |
| - if err != nil || existing.ID != p.ID { |
| - return rejectHome(r, "failed", http.StatusForbidden) |
| - } |
| - return nil |
| - } |
| - if e == nil { |
| - return nil |
| - } |
| - _, e = t.principals.EnsureHome(r.Context(), principalstore.HomeIdentity{Issuer: claims.Issuer, Subject: claims.Subject}) |
| - if errors.Is(e, principalstore.ErrRefused) { |
| - return rejectHome(r, "unknown", http.StatusForbidden) |
| - } |
| - if e != nil { |
| - return rejectHome(r, "failed", http.StatusServiceUnavailable) |
| - } |
| - return nil |
| -} |
diff --git a/internal/docs/team_home_test.go b/internal/docs/team_home_test.go| index d55595d..6ebac9d 100644 |
| --- a/internal/docs/team_home_test.go |
| +++ b/internal/docs/team_home_test.go |
| @@ -3,32 +3,47 @@ package docs |
| import ( |
| "context" |
| "errors" |
| - "net/http/httptest" |
| - "strings" |
| "testing" |
| "time" |
| + "amadan.net/oficina/home/connect" |
| + connectlinks "amadan.net/oficina/home/connect/linkstore" |
| "amadan.net/oficina/home/roster" |
| - "amadan.net/rastrillo/rastrillo/assertion" |
| - "amadan.net/rastrillo/rastrillo/sessions" |
| "github.com/carlosframework/docs/internal/docs/principalstore" |
| ) |
| -func TestTeamCompletionCannotAllocateAroundCurrentAccount(t *testing.T) { |
| +// teamHooksFixture is connect's two team-mode hooks over a team runtime |
| +// whose roster lists one member, with principalstore's allocation gate |
| +// (the second gate, inside EnsureHome) counted and switchable. |
| +type teamHooksFixture struct { |
| + app *App |
| + rt *teamRuntime |
| + clock *teamTestClock |
| + member string |
| + h *homeRoutes |
| + calls int |
| + refuse bool |
| + persons func() (people, docs int64) |
| +} |
| + |
| +func newTeamHooksFixture(t *testing.T) *teamHooksFixture { |
| + t.Helper() |
| app := newSampleDocumentsInternalTestApp(t, "0") |
| s := app.Store() |
| - ctx := t.Context() |
| - local, e := s.EnsurePerson(ctx, "local@example.com") |
| + local, e := s.EnsurePerson(t.Context(), "local@example.com") |
| if e != nil { |
| t.Fatal(e) |
| } |
| - if _, e = s.Create(ctx, local, "existing"); e != nil { |
| + if _, e = s.Create(t.Context(), local, "existing"); e != nil { |
| t.Fatal(e) |
| } |
| rt, clock, subject := testTeamRoster(t, s, app) |
| - calls := 0 |
| + f := &teamHooksFixture{app: app, rt: rt, clock: clock, member: subject, h: &homeRoutes{team: rt}} |
| rt.principals, e = principalstore.New(app.db.Writer(), principalstore.Config{Issuer: rt.bindings.Issuer, Team: rt.bindings.Team, RequireMembership: func(ctx context.Context, q principalstore.MembershipRequest) error { |
| - calls++ |
| + f.calls++ |
| + if f.refuse { |
| + return principalstore.ErrRefused |
| + } |
| d := rt.cache.Check(ctx, q.Subject) |
| if d.State == roster.Member && d.Lease.Valid() { |
| return nil |
| @@ -41,39 +56,135 @@ func TestTeamCompletionCannotAllocateAroundCurrentAccount(t *testing.T) { |
| if e != nil { |
| t.Fatal(e) |
| } |
| - b := &homeBridge{store: s, resolver: identityResolver{store: s, team: rt}} |
| - result := &homeFinishResult{} |
| - r := httptest.NewRequest("GET", "https://docs.example/auth/home/finish", nil).WithContext(context.WithValue(ctx, homeFinishKey{}, result)) |
| - claims := assertion.Claims{Issuer: rt.bindings.Issuer, Subject: subject} |
| - current := &sessions.Session{Subject: "local@example.com", Method: "magiclink", At: time.Now()} |
| - if e = b.completeTeamPrincipal(r, claims, current); e == nil || calls != 0 { |
| - t.Fatal("current account conflict reached allocation", e) |
| + f.persons = func() (people, docs int64) { |
| + s.db.Model(&Person{}).Count(&people) |
| + s.db.Model(&Document{}).Count(&docs) |
| + return |
| + } |
| + return f |
| +} |
| + |
| +func (f *teamHooksFixture) allocated(t *testing.T, subject string) bool { |
| + t.Helper() |
| + _, e := f.rt.principals.Resolve(t.Context(), f.rt.bindings.Issuer, subject) |
| + if e != nil && !errors.Is(e, principalstore.ErrRefused) { |
| + t.Fatal(e) |
| + } |
| + return e == nil |
| +} |
| + |
| +// Unlinked creates a Home-only principal for a roster Member, and for |
| +// nobody else: the roster's gate first, principalstore's again inside |
| +// EnsureHome. It never creates a local person or sample documents. |
| +func TestTeamUnlinkedAllocatesOnlyForAMemberThroughBothGates(t *testing.T) { |
| + f := newTeamHooksFixture(t) |
| + ctx, issuer := t.Context(), f.rt.bindings.Issuer |
| + stranger := "pr_" + "bbbbbbbbbbbbbbbbbbbbbbbbbb" |
| + if _, e := f.h.unlinked(ctx, issuer, stranger); !errors.Is(e, connect.ErrNoPerson) || f.calls != 0 || f.allocated(t, stranger) { |
| + t.Fatal("a stranger reached allocation", e, f.calls) |
| + } |
| + if _, e := f.h.unlinked(ctx, "https://other.example", f.member); !errors.Is(e, connect.ErrNoPerson) || f.calls != 0 { |
| + t.Fatal("another issuer reached allocation", e) |
| + } |
| + f.refuse = true |
| + if _, e := f.h.unlinked(ctx, issuer, f.member); !errors.Is(e, connect.ErrNoPerson) || f.calls != 1 || f.allocated(t, f.member) { |
| + t.Fatal("the second gate did not hold", e, f.calls) |
| } |
| - if _, e = rt.principals.Resolve(ctx, claims.Issuer, subject); !errors.Is(e, principalstore.ErrRefused) { |
| - t.Fatal("conflict allocated principal", e) |
| + f.refuse = false |
| + p, e := f.h.unlinked(ctx, issuer, f.member) |
| + if e != nil || p.ID != principalstore.HomeIDMin || p.Label != "" || f.calls != 2 { |
| + t.Fatal("a member was not given a Home-only principal", p, e, f.calls) |
| } |
| - if e = b.completeTeamPrincipal(r, claims, nil); e != nil || calls != 1 { |
| - t.Fatal("verified fresh member could not create stable identity", e) |
| + if again, e := f.h.unlinked(ctx, issuer, f.member); e != nil || again.ID != p.ID { |
| + t.Fatal("a second arrival allocated again", again, e) |
| } |
| - p, e := rt.principals.Resolve(ctx, claims.Issuer, subject) |
| - if e != nil || p.ID != principalstore.HomeIDMin || p.VerifiedAddress != nil { |
| - t.Fatal("Home principal changed address or allocation", e) |
| + if people, docs := f.persons(); people != 1 || docs != 1 { |
| + t.Fatal("allocation fabricated a local person or samples", people, docs) |
| } |
| - var people, docs int64 |
| - s.db.Model(&Person{}).Count(&people) |
| - s.db.Model(&Document{}).Count(&docs) |
| - if people != 1 || docs != 1 { |
| - t.Fatal("Home completion fabricated local person or sample documents") |
| + // The lease lapses and the directory is down: undecided, which connect |
| + // answers 503, never "unknown", and nothing is allocated. |
| + f.clock.step(61 * time.Second) |
| + other := "pr_" + "cccccccccccccccccccccccccc" |
| + if _, e := f.h.unlinked(ctx, issuer, other); e == nil || errors.Is(e, connect.ErrNoPerson) || f.allocated(t, other) { |
| + t.Fatal("an undecided roster was not retryable", e) |
| } |
| - clock.step(60 * time.Second) |
| - if e = b.completeTeamPrincipal(r, claims, &sessions.Session{Subject: subject, Method: homeAssertionMethod}); e != nil || calls != 1 { |
| - t.Fatal("known identity requires no new allocation or standing", e) |
| + if _, e := (&homeRoutes{}).unlinked(ctx, issuer, f.member); e == nil || errors.Is(e, connect.ErrNoPerson) { |
| + t.Fatal("no team runtime was not unavailable", e) |
| + } |
| +} |
| + |
| +// A subject linked to a local account in the meantime is that account, |
| +// never a second, Home-only one. |
| +func TestTeamUnlinkedRefusesALinkedSubject(t *testing.T) { |
| + f := newTeamHooksFixture(t) |
| + ctx := t.Context() |
| + person, e := f.app.Store().EnsurePerson(ctx, "linked@example.com") |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if _, e = f.app.db.Writer().Exec("INSERT INTO home_identity_links(issuer,subject,person_id) VALUES(?,?,?)", f.rt.bindings.Issuer, f.member, person); e != nil { |
| + t.Fatal(e) |
| } |
| - claims.Subject = "pr_" + strings.Repeat("b", 26) |
| - if e = b.completeTeamPrincipal(r, claims, nil); e == nil || result.status != 503 { |
| - t.Fatal("unavailable roster did not refuse unknown identity", e) |
| + if _, e = f.h.unlinked(ctx, f.rt.bindings.Issuer, f.member); !errors.Is(e, connect.ErrNoPerson) { |
| + t.Fatal("a linked subject was given a Home-only principal", e) |
| } |
| - if _, e = rt.principals.Resolve(ctx, claims.Issuer, claims.Subject); !errors.Is(e, principalstore.ErrRefused) { |
| - t.Fatal("unknown roster allocated principal", e) |
| + var homeOnly int |
| + if e = f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM docs_home_identities").Scan(&homeOnly); e != nil || homeOnly != 0 { |
| + t.Fatal("allocated beside a link", homeOnly, e) |
| + } |
| +} |
| + |
| +// HomeOnly reads the principal Unlinked made, and nothing else: not a |
| +// stranger, and not a local account reached through a link row. connect |
| +// asks it only after refusing that link (its binding no longer matches), |
| +// so answering with the local account would sign the subject in as it. |
| +func TestTeamHomeOnlyIsOnlyTheHomeOnlyPrincipal(t *testing.T) { |
| + f := newTeamHooksFixture(t) |
| + ctx, issuer := t.Context(), f.rt.bindings.Issuer |
| + if _, e := f.h.homeOnly(ctx, issuer, f.member); !errors.Is(e, connect.ErrNoPerson) { |
| + t.Fatal("a subject with no principal resolved", e) |
| + } |
| + made, e := f.h.unlinked(ctx, issuer, f.member) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if p, e := f.h.homeOnly(ctx, issuer, f.member); e != nil || p.ID != made.ID || p.Label != "" { |
| + t.Fatal("the Home-only principal did not resolve", p, e) |
| + } |
| + person, e := f.app.Store().EnsurePerson(ctx, "stale@example.com") |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + stale := "pr_" + "dddddddddddddddddddddddddd" |
| + if _, e = f.app.db.Writer().Exec("INSERT INTO home_identity_links(issuer,subject,person_id,person_binding) VALUES(?,?,?,'stale')", issuer, stale, person); e != nil { |
| + t.Fatal(e) |
| + } |
| + if p, e := f.rt.principals.Resolve(ctx, issuer, stale); e != nil || p.Kind != principalstore.Local { |
| + t.Fatal("fixture: principalstore does not resolve the link row", p, e) |
| + } |
| + if p, e := f.h.homeOnly(ctx, issuer, stale); !errors.Is(e, connect.ErrNoPerson) { |
| + t.Fatal("a link connect refused resolved as a Home-only person", p, e) |
| + } |
| + if e := f.app.db.Writer().Close(); e != nil { |
| + t.Fatal(e) |
| + } |
| + if _, e := f.h.homeOnly(ctx, issuer, f.member); e == nil || errors.Is(e, connect.ErrNoPerson) { |
| + t.Fatal("a storage failure read as no person", e) |
| + } |
| +} |
| + |
| +// homeOnlySubjects is connect's Resolve for a database with no links: the |
| +// HomeOnly hook, its answers mapped as connect maps them. |
| +func homeOnlySubjects(rt *teamRuntime) subjectsFunc { |
| + h := &homeRoutes{team: rt} |
| + return func(ctx context.Context, subject string) (connect.Person, error) { |
| + p, err := h.homeOnly(ctx, rt.bindings.Issuer, subject) |
| + switch { |
| + case errors.Is(err, connect.ErrNoPerson): |
| + return connect.Person{}, connectlinks.ErrRefused |
| + case err != nil: |
| + return connect.Person{}, connectlinks.ErrStorage |
| + } |
| + return p, nil |
| } |
| } |
diff --git a/internal/docs/team_identity_test.go b/internal/docs/team_identity_test.go| index 3408563..89b6321 100644 |
| --- a/internal/docs/team_identity_test.go |
| +++ b/internal/docs/team_identity_test.go |
| @@ -98,7 +98,7 @@ func TestTeamIdentityAddressAbsenceNeverRedeemsEmptyGrant(t *testing.T) { |
| rt, _, _ := testTeamRoster(t, s, app) |
| rt.principals = ps |
| s.team = rt |
| - resolver := identityResolver{store: s, team: rt} |
| + resolver := identityResolver{store: s, team: rt, links: homeOnlySubjects(rt)} |
| id, e := resolver.resolve(identityRequest("GET", subject, homeAssertionMethod)) |
| if e != nil || id.Actor.PersonID != p.ID || id.Actor.VerifiedAddress != nil || id.HomeSubject != subject { |
| t.Fatal("wrong Home principal", e) |
| @@ -137,7 +137,7 @@ func TestTeamIdentityAddressAbsenceNeverRedeemsEmptyGrant(t *testing.T) { |
| // in either of Docs' tables, and writes no marker: the marker pins one issuer, |
| // and a row from another would be read under it. |
| func TestTeamActivationCensusCoversBothIdentityTables(t *testing.T) { |
| - for _, table := range []string{"docs_identity_links", "docs_home_identities"} { |
| + for _, table := range []string{"home_identity_links", "docs_home_identities"} { |
| t.Run(table, func(t *testing.T) { |
| cfg, home := teamConfigFixture(t) |
| settings, e := validatedTeamConfig(cfg, home, "https://docs.example") |
| @@ -146,18 +146,16 @@ func TestTeamActivationCensusCoversBothIdentityTables(t *testing.T) { |
| } |
| app := newSampleDocumentsInternalTestApp(t, "0") |
| ctx := t.Context() |
| - if _, e = migrate.Apply(ctx, app.db, TeamBootSchema); e != nil { |
| - t.Fatal(e) |
| - } |
| + migrateTeam(t, app) |
| const other = "https://other.example" |
| subject := "pr_" + strings.Repeat("a", 26) |
| switch table { |
| - case "docs_identity_links": |
| + case "home_identity_links": |
| person, e := app.Store().EnsurePerson(ctx, "linked@example.com") |
| if e != nil { |
| t.Fatal(e) |
| } |
| - if _, e = app.db.Writer().Exec("INSERT INTO docs_identity_links(issuer,subject,person_id) VALUES(?,?,?)", other, subject, person); e != nil { |
| + if _, e = app.db.Writer().Exec("INSERT INTO home_identity_links(issuer,subject,person_id) VALUES(?,?,?)", other, subject, person); e != nil { |
| t.Fatal(e) |
| } |
| default: |
diff --git a/internal/docs/team_session_reader_test.go b/internal/docs/team_session_reader_test.go| index b22f7a2..31fbb27 100644 |
| --- a/internal/docs/team_session_reader_test.go |
| +++ b/internal/docs/team_session_reader_test.go |
| @@ -14,11 +14,11 @@ import ( |
| func TestTeamSessionReaderMatchesActualLegacySession(t *testing.T) { |
| f := newBridgeFixture(t) |
| - reader, e := newTeamSessionReader(f.app.db.Writer(), f.b.origin, f.b.sessionCookie, f.app.logger) |
| + reader, e := newTeamSessionReader(f.app.db.Writer(), f.h.origin, f.h.sessionCookie, f.app.logger) |
| if e != nil { |
| t.Fatal(e) |
| } |
| - if _, e = newTeamSessionReader(f.app.db.Writer(), f.b.origin, "wrong-cookie", f.app.logger); e == nil { |
| + if _, e = newTeamSessionReader(f.app.db.Writer(), f.h.origin, "wrong-cookie", f.app.logger); e == nil { |
| t.Fatal("different cookie configuration accepted") |
| } |
| for _, method := range []string{"magiclink", "keymail", homeAssertionMethod} { |
| @@ -26,12 +26,12 @@ func TestTeamSessionReaderMatchesActualLegacySession(t *testing.T) { |
| r := bridgeRequest("GET", "/", nil) |
| w := httptest.NewRecorder() |
| at := time.Now().Add(-time.Hour).Truncate(time.Second) |
| - if e = f.b.sessions.SignIn(w, r, sessions.Session{Subject: "opaque-credential", Method: method, AuthTime: at}); e != nil { |
| + if e = f.h.sessions.SignIn(w, r, sessions.Session{Subject: "opaque-credential", Method: method, AuthTime: at}); e != nil { |
| t.Fatal(e) |
| } |
| - cookie := bridgeCookie(t, w, f.b.sessionCookie) |
| + cookie := bridgeCookie(t, w, f.h.sessionCookie) |
| r.AddCookie(cookie) |
| - old, ok := f.b.sessions.From(r) |
| + old, ok := f.h.sessions.From(r) |
| if !ok { |
| t.Fatal("actual legacy session missing") |
| } |
| @@ -57,7 +57,7 @@ func TestTeamSessionReaderMatchesActualLegacySession(t *testing.T) { |
| if _, ok = reader(t.Context(), r); ok { |
| t.Fatal("expired session accepted") |
| } |
| - if _, ok = f.b.sessions.From(r); ok { |
| + if _, ok = f.h.sessions.From(r); ok { |
| t.Fatal("legacy reader differed on expiry") |
| } |
| }) |
| @@ -66,7 +66,7 @@ func TestTeamSessionReaderMatchesActualLegacySession(t *testing.T) { |
| if _, ok := reader(t.Context(), r); ok { |
| t.Fatal("missing session accepted") |
| } |
| - r.AddCookie(&http.Cookie{Name: f.b.sessionCookie, Value: "malformed"}) |
| + r.AddCookie(&http.Cookie{Name: f.h.sessionCookie, Value: "malformed"}) |
| if _, ok := reader(t.Context(), r); ok { |
| t.Fatal("malformed session accepted") |
| } |
| @@ -74,24 +74,24 @@ func TestTeamSessionReaderMatchesActualLegacySession(t *testing.T) { |
| func TestTeamSessionReaderRevocationAndDatabaseErrorParity(t *testing.T) { |
| f := newBridgeFixture(t) |
| - reader, e := newTeamSessionReader(f.app.db.Writer(), f.b.origin, f.b.sessionCookie, f.app.logger) |
| + reader, e := newTeamSessionReader(f.app.db.Writer(), f.h.origin, f.h.sessionCookie, f.app.logger) |
| if e != nil { |
| t.Fatal(e) |
| } |
| r := bridgeRequest("GET", "/", nil) |
| w := httptest.NewRecorder() |
| - if e := f.b.sessions.SignIn(w, r, sessions.Session{Subject: "alice@example.com", Method: "magiclink", AuthTime: time.Now()}); e != nil { |
| + if e := f.h.sessions.SignIn(w, r, sessions.Session{Subject: "alice@example.com", Method: "magiclink", AuthTime: time.Now()}); e != nil { |
| t.Fatal(e) |
| } |
| - r.AddCookie(bridgeCookie(t, w, f.b.sessionCookie)) |
| + r.AddCookie(bridgeCookie(t, w, f.h.sessionCookie)) |
| if _, ok := reader(t.Context(), r); !ok { |
| t.Fatal("live session refused") |
| } |
| - f.b.sessions.SignOut(httptest.NewRecorder(), r) |
| + f.h.sessions.SignOut(httptest.NewRecorder(), r) |
| if _, ok := reader(t.Context(), r); ok { |
| t.Fatal("revoked session accepted") |
| } |
| - if _, ok := f.b.sessions.From(r); ok { |
| + if _, ok := f.h.sessions.From(r); ok { |
| t.Fatal("legacy revocation differs") |
| } |
| if e := f.app.db.Writer().Close(); e != nil { |
| @@ -100,7 +100,7 @@ func TestTeamSessionReaderRevocationAndDatabaseErrorParity(t *testing.T) { |
| if _, ok := reader(t.Context(), r); ok { |
| t.Fatal("database failure accepted") |
| } |
| - if _, ok := f.b.sessions.From(r); ok { |
| + if _, ok := f.h.sessions.From(r); ok { |
| t.Fatal("legacy database failure differs") |
| } |
| } |
| @@ -112,16 +112,16 @@ func TestTeamSessionReaderRevocationAndDatabaseErrorParity(t *testing.T) { |
| // all run when the writer comes back. Review #77, Astra: 64 left behind. |
| func TestTeamSessionReaderCancelledLookupsLeaveNoWorkQueued(t *testing.T) { |
| f := newBridgeFixture(t) |
| - reader, e := newTeamSessionReader(f.app.db.Writer(), f.b.origin, f.b.sessionCookie, f.app.logger) |
| + reader, e := newTeamSessionReader(f.app.db.Writer(), f.h.origin, f.h.sessionCookie, f.app.logger) |
| if e != nil { |
| t.Fatal(e) |
| } |
| r := bridgeRequest("GET", "/", nil) |
| w := httptest.NewRecorder() |
| - if e = f.b.sessions.SignIn(w, r, sessions.Session{Subject: "alice@example.com", Method: "magiclink", AuthTime: time.Now()}); e != nil { |
| + if e = f.h.sessions.SignIn(w, r, sessions.Session{Subject: "alice@example.com", Method: "magiclink", AuthTime: time.Now()}); e != nil { |
| t.Fatal(e) |
| } |
| - r.AddCookie(bridgeCookie(t, w, f.b.sessionCookie)) |
| + r.AddCookie(bridgeCookie(t, w, f.h.sessionCookie)) |
| db := f.app.db.Writer() |
| tx, e := db.BeginTx(t.Context(), nil) |
diff --git a/internal/docs/team_state_test.go b/internal/docs/team_state_test.go| index 99e6f08..26f9f77 100644 |
| --- a/internal/docs/team_state_test.go |
| +++ b/internal/docs/team_state_test.go |
| @@ -7,14 +7,17 @@ import ( |
| "encoding/base64" |
| "io/fs" |
| "path/filepath" |
| - "reflect" |
| "strings" |
| "testing" |
| + "amadan.net/oficina/home/dashboard" |
| + "amadan.net/oficina/home/handoff" |
| "amadan.net/oficina/home/roster" |
| "amadan.net/oficina/home/teammode" |
| "amadan.net/rastrillo/rastrillo/db" |
| "amadan.net/rastrillo/rastrillo/migrate" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + "github.com/carlosframework/docs/internal/docs/linkstore" |
| "github.com/carlosframework/docs/internal/docs/principalstore" |
| "github.com/go-json-experiment/json" |
| ) |
| @@ -44,7 +47,7 @@ func legacyTeamDatabase(t *testing.T, path, migration string, b roster.Bindings) |
| t.Fatal(err) |
| } |
| defer d.Close() |
| - if _, err = migrate.Apply(t.Context(), d, migrate.Merge(BootSchema, principalstore.Schema, old)); err != nil { |
| + if _, err = migrate.Apply(t.Context(), d, migrate.Merge(mainBootSchema, principalstore.Schema, old)); err != nil { |
| t.Fatal(err) |
| } |
| raw, err := json.Marshal(b) |
| @@ -60,6 +63,46 @@ func legacyTeamDatabase(t *testing.T, path, migration string, b roster.Bindings) |
| type ledgerRow struct{ ID, AppliedAt, Checksum string } |
| +// mainBootSchema is BootSchema as main applied it at 7c9122f, the last |
| +// commit before Docs moved onto home/connect: no connect link schema. |
| +var mainBootSchema = migrate.Merge(migrate.MustFromFS(dashboard.Migrations, "oficina_dashboard"), sessions.Schema, authSchema, Schema, linkstore.Schema, migrate.MustFromFS(handoff.Migrations, "oficina_handoff")) |
| + |
| +// requireLedgerKept: every row the old code wrote is still there, unchanged |
| +// (id, applied_at, checksum), and the only new rows are the migrations |
| +// that are new in schema since main. |
| +func requireLedgerKept(t *testing.T, before, after []ledgerRow, schema, mainSchema *migrate.Set) { |
| + t.Helper() |
| + old := map[string]bool{} |
| + for _, m := range mainSchema.All() { |
| + old[m.ID] = true |
| + } |
| + added := map[string]bool{} |
| + for _, m := range schema.All() { |
| + if !old[m.ID] { |
| + added[m.ID] = true |
| + } |
| + } |
| + kept := map[string]ledgerRow{} |
| + for _, r := range after { |
| + kept[r.ID] = r |
| + } |
| + for _, r := range before { |
| + if kept[r.ID] != r { |
| + t.Fatalf("ledger row moved: before %v, after %v", r, kept[r.ID]) |
| + } |
| + delete(kept, r.ID) |
| + } |
| + for id := range kept { |
| + if !added[id] { |
| + t.Fatalf("ledger gained %s, which is not new since main", id) |
| + } |
| + delete(added, id) |
| + } |
| + if len(added) != 0 { |
| + t.Fatalf("new migrations not applied: %v", added) |
| + } |
| +} |
| + |
| func readLedger(t *testing.T, q *sql.DB) []ledgerRow { |
| t.Helper() |
| rows, err := q.QueryContext(t.Context(), "SELECT id, applied_at, checksum FROM rastrillo_migrations ORDER BY id") |
| @@ -81,7 +124,9 @@ func readLedger(t *testing.T, q *sql.DB) []ledgerRow { |
| // A database activated by the old code boots under teammode with its |
| // migration ledger untouched: State("docs").Schema() is the applied |
| // docs_team/0001_team byte for byte, so nothing re-runs and no checksum |
| -// moves, and the old marker is the fingerprint teammode computes. |
| +// moves, and the old marker is the fingerprint teammode computes. The only |
| +// rows added are the migrations new since main (connect's link schema and |
| +// linkstore.ForPrincipals). |
| func TestTeamStateKeepsTheAppliedLedger(t *testing.T) { |
| cfg := newTeamRouterFixture(t).cfg |
| b := roster.Bindings{Issuer: bridgeIssuer, Directory: "https://home.example", Consumer: "router-docs", App: "docs", Team: "TeamA", Audience: bridgeOrigin} |
| @@ -97,9 +142,7 @@ func TestTeamStateKeepsTheAppliedLedger(t *testing.T) { |
| if closeErr := app.Close(); closeErr != nil { |
| t.Fatal(closeErr) |
| } |
| - if !reflect.DeepEqual(before, after) { |
| - t.Fatalf("ledger moved:\nbefore %v\nafter %v", before, after) |
| - } |
| + requireLedgerKept(t, before, after, TeamBootSchema, migrate.Merge(mainBootSchema, principalstore.Schema, teamState.Schema())) |
| if err != nil || !activated || marker != teammode.Fingerprint(b) { |
| t.Fatal("the old marker is not teammode's fingerprint", err) |
| } |
diff --git a/internal/docs/team_stream.go b/internal/docs/team_stream.go| index 83dde9a..d794351 100644 |
| --- a/internal/docs/team_stream.go |
| +++ b/internal/docs/team_stream.go |
| @@ -34,13 +34,13 @@ func (g *teamStreamGuard) remaining() time.Duration { |
| func (g *teamStreamGuard) check() (time.Duration, bool) { |
| t := g.store.team |
| remaining := g.remaining() |
| - if t == nil || t.bridge == nil || t.readSession == nil || remaining <= 0 { |
| + if t == nil || t.home == nil || t.readSession == nil || remaining <= 0 { |
| return 0, false |
| } |
| limit := min(remaining, defaultStreamWriteDeadline) |
| ctx, cancel := context.WithTimeout(g.request.Context(), limit) |
| defer cancel() |
| - if _, present, ok := homeCookie(g.request, t.bridge.sessionCookie); !ok || !present { |
| + if _, present, ok := homeCookie(g.request, t.home.sessionCookie); !ok || !present { |
| return 0, false |
| } |
| session, ok := t.readSession(ctx, g.request) |
| @@ -48,7 +48,7 @@ func (g *teamStreamGuard) check() (time.Duration, bool) { |
| return 0, false |
| } |
| request := sessions.WithSession(g.request.WithContext(ctx), session) |
| - id, e := t.bridge.resolver.resolve(request) |
| + id, e := t.home.resolver.resolve(request) |
| if e != nil || !sameActor(id.Actor, g.access.actor) || id.HomeSubject != g.access.Subject() { |
| return 0, false |
| } |
diff --git a/internal/shipped/shipped.go b/internal/shipped/shipped.go| index c0ec21a..58585a2 100644 |
| --- a/internal/shipped/shipped.go |
| +++ b/internal/shipped/shipped.go |
| @@ -57,6 +57,7 @@ import ( |
| // internal/docs links as nativeauth. |
| var FirstParty = map[string]bool{ |
| "amadan.net/oficina/estilo.git": true, |
| + "amadan.net/oficina/home/connect": true, |
| "amadan.net/oficina/home/dashboard": true, |
| "amadan.net/oficina/home/handoff": true, |
| "amadan.net/oficina/home/roster": true, |