Memoria: roster team mode on home/teammode (Home team-members.md Part B; teammode-package.md §7.2)
With MEMORIA_TEAM_ID, _DIRECTORY_ORIGIN, _PROVISIONING_BASE64,
_OPERATOR_KEYS_BASE64 and _ROSTER_TOKEN set (all or none, only beside
MEMORIA_HOME_*), Home's roster decides admission on every request, as in
Sheets main 8e28205/35dd773 and Slides main 951373f. home/teammode,
home/roster and home/connect are pinned at Home main 67c12e3.
- Configuration, marker, runtime and probe are teammode's. AppWith (main's
constructor now; App is AppWith with team mode off) verifies the record
against the Home credentials and MEMORIA_ORIGIN and reads the marker
(memoria_team) before anything migrates. Census over home_identity_links
and memoria_team_home_members. GET /api/team is teammode.Probe.
- Standing: Member is the whole instance (the corpus is team rung).
NotMember reaches nothing — Memoria has no shares — and is signed out
with the existing "removed" notice, existing sessions included, within
the lease. Unknown ends nothing. MEMORIA_OWNERS becomes optional and
admits a local sign-in only; a local account stands on its Oficina link,
and one without a link is sent to /account/home.
- Connector management is the roster owner's (route and inside each
write); members search and read.
- Paul's list ruling: /, /search and /reports are partial with a notice
under Unknown (always empty here, notice included); standing is read
before a list is built and asked again after, withholding what was
built. Item pages, /add, /facts/correct, /answer and the connectors are
a retryable 503; the native JSON search is a 503.
- Every person-made write runs teammode.Guard inside its own transaction
(Ingest, Delete, corrections, feedback, connector writes). Delete asks
before un-indexing and re-indexes on a refusal. Connector runs and
sibling polls are system writes, unguarded.
- An AI answer is delivered only if the standing it was asked on still
holds when the model returns. MEMORIA_AI stays off unless configured.
- Home-only members come through connect's Unlinked/HomeOnly hooks as
addressless memoria_home_local_identities rows (one ID space with local
accounts), held by triggers; labelled "Oficina account …xxxx".
- In team mode the asker is the person's Home subject (person_ref).
- Siblings: in team mode MEMORIA_TEAM must equal MEMORIA_ORIGIN's own team
label, or boot is refused.
- tools/drive -unknown previews the partial lists.
Tests (team_*_test.go, on teammodetest) mirror Slides': config pins every
binding, all-or-none, marker lock-in and census; Home-only sign-in and
allocation; same-person refusal; removal within the lease; 59 s / 61 s;
partial lists including the empty one; the write-lapse table (12 routes,
database read back, success half as a roster member, connectors as owner);
refused delete stays findable; lapse mid-list and mid-AI-answer; ticking
clock sweeps; siblings bound; probe. 96 hand mutations (81 mine, 15 from
an independent pass), all killed or recorded as equivalent.
Team mode off is byte-identical except /api/team ({"team_mode":false}):
a page dump of origin/main and this branch, standalone and with Home
(anonymous, local, linked, Home session), differs only in that route and
wall-clock timestamps. Not deployed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
46 files changed,
+3,529
−280
AGENTS.md+10 −1Makefile+1 −1cmd/memoria/main.go+7 −2docs/superpowers/specs/2026-09-03-memoria-design.md+75 −0go.mod+3 −1go.sum+6 −0internal/memoria/app.go+81 −20internal/memoria/auth.go+3 −1internal/memoria/chrome.go+14 −1internal/memoria/config.go+30 −1internal/memoria/connector.go+62 −50internal/memoria/corrections.go+13 −9internal/memoria/credits_inventory_test.go+1 −1internal/memoria/custody.go+6 −0internal/memoria/feedback.go+14 −10internal/memoria/handlers.go+62 −18internal/memoria/handlers_connector.go+9 −2internal/memoria/handlers_correct.go+50 −11internal/memoria/home.go+16 −6internal/memoria/home_identity.go+4 −1internal/memoria/native.go+13 −4internal/memoria/render.go+5 −0internal/memoria/siblingsync.go+3 −0internal/memoria/store.go+158 −131internal/memoria/sync.go+4 −0internal/memoria/team_access.go+325 −0internal/memoria/team_access_test.go+489 −0internal/memoria/team_answers.go+60 −0internal/memoria/team_config.go+152 −0internal/memoria/team_config_test.go+298 −0internal/memoria/team_fixture_test.go+256 −0internal/memoria/team_guard.go+138 −0internal/memoria/team_guard_test.go+306 −0internal/memoria/team_home_only.go+70 −0internal/memoria/team_review_test.go+200 −0internal/memoria/team_siblings.go+40 −0internal/memoria/team_survivors_test.go+343 −0internal/memoria/teamstate/migrations/0001_home_members.sql+13 −0internal/memoria/teamstate/store.go+151 −0internal/memoria/templates/index.html+2 −2internal/memoria/templates/reports.html+3 −2internal/memoria/templates/results.html+10 −0internal/memoriatest/errors_gate_test.go+1 −1internal/memoriatest/gates_test.go+8 −1internal/memoriatest/routes_test.go+7 −3tools/drive/main.go+7 −0
CI passed — run details
Intent
diff --git a/AGENTS.md b/AGENTS.md| index 4cd8267..066a8bc 100644 |
| --- a/AGENTS.md |
| +++ b/AGENTS.md |
| @@ -216,7 +216,16 @@ so; it never renders as a confident zero. |
| - The app refuses to start without a DEK, an instance key, owners, and |
| either SMTP or an explicit `MEMORIA_ALLOW_LOGGED_MAIL=1` — because |
| without SMTP rastrillo logs the magic link, and that link is a live |
| - credential in storage we cannot delete. |
| + credential in storage we cannot delete. **In team mode** (the five |
| + `MEMORIA_TEAM_*`, spec §4.3 "Roster team mode") the owners list is |
| + optional and admits a local sign-in only; the roster decides everything |
| + else, on every request. |
| +- **Team mode: ask `a.teamMode()`, never `a.team != nil`.** A configured |
| + instance whose runtime is missing must refuse, not fall back to the |
| + owners list. A person-made write goes through `Store.guard`/`guarded` |
| + inside its own transaction; the instance's own work (a connector run, a |
| + sibling poll) is `systemWrite`, and a write with neither is refused. A |
| + list asks `teamReaches` before it is built and `teamPartial` after. |
| **Deploys** |
| - One binary, `CGO_ENABLED=0`, cgo-free SQLite. |
diff --git a/Makefile b/Makefile| index aadcf7b..8a1ec4e 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -129,6 +129,6 @@ credits: |
| go build -o "$$notices_tmp/notices" amadan.net/oficina/estilo.git/cmd/oficina-notices; \ |
| GOOS=linux GOARCH=arm64 CGO_ENABLED=0 "$$notices_tmp/notices" \ |
| -package ./cmd/memoria -lucide -onest \ |
| - -exclude amadan.net/oficina/estilo.git,amadan.net/oficina/home/connect,amadan.net/oficina/home/handoff,amadan.net/oficina/suite,amadan.net/rastrillo/native/server \ |
| + -exclude amadan.net/oficina/estilo.git,amadan.net/oficina/home/connect,amadan.net/oficina/home/handoff,amadan.net/oficina/home/roster,amadan.net/oficina/home/teammode,amadan.net/oficina/suite,amadan.net/rastrillo/native/server \ |
| > "$$notices_tmp/notices.json"; \ |
| mv "$$notices_tmp/notices.json" internal/memoria/credits/notices.json |
diff --git a/cmd/memoria/main.go b/cmd/memoria/main.go| index c5423d0..d07033d 100644 |
| --- a/cmd/memoria/main.go |
| +++ b/cmd/memoria/main.go |
| @@ -46,7 +46,10 @@ func main() { |
| } |
| defer d.Close() |
| - mux, app, err := memoria.App(d, cfg.Origin, cfg.Sealer, logger) |
| + // AppWith, from the whole configuration: team mode (the five |
| + // MEMORIA_TEAM_* variables) is verified, and the database's marker |
| + // read, before anything migrates. |
| + mux, app, err := memoria.AppWith(d, cfg, logger) |
| if err != nil { |
| logger.Error("build app", "err", err) |
| os.Exit(1) |
| @@ -85,8 +88,10 @@ func main() { |
| os.Exit(1) |
| } |
| app.UseAuth(a) |
| + // WireHome also opens team mode's roster runtime, when configured. |
| + // Its errors carry no configured value. |
| if err := app.WireHome(mux, cfg); err != nil { |
| - logger.Error("Home sign-in unavailable") |
| + logger.Error("Home sign-in unavailable", "err", err) |
| os.Exit(1) |
| } |
| app.MountAuth(mux, cfg.Origin) |
diff --git a/docs/superpowers/specs/2026-09-03-memoria-design.md b/docs/superpowers/specs/2026-09-03-memoria-design.md| index a740d4a..cfbd109 100644 |
| --- a/docs/superpowers/specs/2026-09-03-memoria-design.md |
| +++ b/docs/superpowers/specs/2026-09-03-memoria-design.md |
| @@ -1445,6 +1445,81 @@ Oficina session too and returns the browser to `/signed-out`. |
| directory, where the app switcher's "All apps" goes. |
| +#### Roster team mode on home/teammode (2026-10-30) |
| + |
| +Home's Part B (`team-members.md` §7, `teammode-package.md` §7.2), ported |
| +the way Sheets and Slides were, on Home's shared `home/teammode`, |
| +`home/roster` and `home/connect` (pinned at Home main 67c12e3). This is the |
| +roster admission the paragraphs below describe, arriving through Home's |
| +directory rather than suite call 8. **Off unless configured, and off on |
| +Paul's instance**: with team mode off every page is what it was, byte for |
| +byte, and the only addition is `GET /api/team` answering |
| +`{"team_mode":false}`. |
| + |
| +- **Configuration.** `MEMORIA_TEAM_ID`, `_DIRECTORY_ORIGIN`, |
| + `_PROVISIONING_BASE64`, `_OPERATOR_KEYS_BASE64`, `_ROSTER_TOKEN`: all or |
| + none, and only beside `MEMORIA_HOME_*`. The provisioning record is |
| + verified against Home's issuer and consumer ID, the app, the team, the |
| + directory and `MEMORIA_ORIGIN`. Not `MEMORIA_TEAM`, which is the sibling |
| + transport's host label (§6.4). |
| +- **The marker before migrations.** `memoria_team_required` (set |
| + `memoria_team`) is read before anything migrates. A database activated in |
| + team mode refuses to boot without the same binding — a dropped variable |
| + never hands admission back to `MEMORIA_OWNERS` — and activation refuses a |
| + census that finds a Home identity from another issuer. |
| +- **Admission is the roster, on every request.** Member is the whole |
| + instance: memoria's corpus is the team's (§4.2), with no per-person rows |
| + to reach. NotMember reaches nothing — memoria has no shares — and is |
| + signed out and told so, existing sessions included, within the 60 s |
| + lease. Unknown (the roster unreadable past its lease) ends nothing. |
| + `MEMORIA_OWNERS` becomes optional and admits a **local** sign-in only; a |
| + local account's standing is its Oficina link's, and one with no link is |
| + sent to `/account/home` to make one. |
| +- **The connectors are the roster owners'.** Members search and read the |
| + team's memory; only a roster `owner` manages what feeds it (Notion's |
| + credential, runs, disconnect), checked at the route and again inside each |
| + write's transaction. Recommended in review and **flagged for Paul**: the |
| + alternative, any member, would let anyone on the team point the corpus at |
| + a workspace of their choosing. |
| +- **Unknown on lists (Paul, 2026-10-28).** `/`, `/search` and `/reports` |
| + render partial with a notice. With no shares to fall back on, the partial |
| + list is always empty, and the notice is what stops it reading as "nothing |
| + matched". Standing is read before a list is built and again after, from |
| + the same latched `Access`; a lapse in between withholds what was built. |
| + Every item page, `/add`, `/facts/correct`, `/answer` and the connectors |
| + are a retryable 503 (`Retry-After`, `no-store`), never a 404; the native |
| + API's JSON list, which cannot carry the notice, is a 503. |
| +- **Writes.** Every person-made write — content, delete, corrections, |
| + ratings, native notes, connector changes — runs `teammode.Guard` inside |
| + its own transaction, before and after. Delete asks before un-indexing |
| + too, and a delete refused inside its transaction re-indexes the document, |
| + so a refusal never leaves it stored and unfindable. A connector run and a |
| + sibling poll are the instance's own work and are not guarded: **a Notion |
| + run an owner started keeps importing after that owner is removed** (the |
| + content is the team's, §4.2). Flagged for review. |
| +- **The AI.** `MEMORIA_AI` stays off for team instances (Alta's recipe |
| + writes neither it nor a key) unless the team's owner asks and Paul agrees, |
| + and never with Paul's key. When on, its sources are the person's ruled |
| + search like every page, and an answer is delivered only if the standing |
| + it was asked on still holds when the model returns. |
| +- **Home-only members.** A roster member with no account here signs in with |
| + Home alone, through connect's `Unlinked` and `HomeOnly` hooks. They are a |
| + `memoria_home_local_identities` row with no address — an empty sealed |
| + blob and a random `home-only:` lookup, sharing the ID space connect's |
| + same-person rule compares — and `memoria_team_home_members` says whose; |
| + triggers keep both addressless, undeletable and disjoint from links. |
| + The account menu names them "Oficina account …xxxx". |
| +- **The asker.** In team mode a search, a report and a rating ask as the |
| + person's Home subject (`person_ref`, suite shape), however they signed |
| + in, so one person is one asker. |
| +- **Siblings stay on the team's own hosts.** The transport already binds |
| + every call to `<MEMORIA_TEAM>.<app>.oficina.works`; in team mode |
| + `MEMORIA_TEAM` must also be this instance's own label, the first label of |
| + `MEMORIA_ORIGIN` (`https://<team>.memoria.oficina.works`), or boot is |
| + refused. Paul's apps, at `<app>.oficina.works`, cannot be named. |
| +- **The probe.** `GET /api/team` is `teammode.Probe`: unauthenticated, |
| + `no-store`, `{team_mode, consumer, roster}` and no account data. |
| + |
| **Admission is the home's roster — suite §5.3, ruling 4.** memoria holds no |
| members table of its own and asks no sibling. In **suite shape** it pulls |
| the roster (suite call 8, consumer token, roster epoch in every response) |
diff --git a/go.mod b/go.mod| index 1ecbdae..66d7826 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -6,7 +6,7 @@ toolchain go1.26.5 |
| require ( |
| amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d |
| - amadan.net/oficina/home/connect v0.0.0-20261024233715-ff16bf56bc4d |
| + amadan.net/oficina/home/connect v0.0.0-20261028171508-67c12e39a9d2 |
| amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d |
| amadan.net/oficina/suite v0.0.0-20260905215529-60b01a8a0d6d |
| amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3 |
| @@ -27,6 +27,8 @@ require ( |
| ) |
| require ( |
| + amadan.net/oficina/home/roster v0.0.0-20261028171508-67c12e39a9d2 // indirect |
| + amadan.net/oficina/home/teammode v0.0.0-20261028171508-67c12e39a9d2 // 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 3a7eac9..7648529 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -2,8 +2,14 @@ amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d h1:p9+01xRdBD7s |
| amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw= |
| amadan.net/oficina/home/connect v0.0.0-20261024233715-ff16bf56bc4d h1:9sVZBph2xUuejZt73DYaoCfoyvrvZCnuPHcyMsg562E= |
| amadan.net/oficina/home/connect v0.0.0-20261024233715-ff16bf56bc4d/go.mod h1:ix81eFV87yE9f2SXiRuxYCVM4lAgTRC5YoQMiH3+TDk= |
| +amadan.net/oficina/home/connect v0.0.0-20261028171508-67c12e39a9d2 h1:MPO8MRkk+tT2k+95fZPJ0JStnmAKUCKiVoPbfBVTk6E= |
| +amadan.net/oficina/home/connect v0.0.0-20261028171508-67c12e39a9d2/go.mod h1:ix81eFV87yE9f2SXiRuxYCVM4lAgTRC5YoQMiH3+TDk= |
| amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d h1:8RTZkLQnyxvH2g0RMovhN/m2LN9D8qb+kBfqdBeqq+s= |
| amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d/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/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/suite v0.0.0-20260905215529-60b01a8a0d6d h1:x6Bq9+QzpFYAyV+zRzgyHwD/RmZ4Hy4biwtxK7CdaSs= |
| amadan.net/oficina/suite v0.0.0-20260905215529-60b01a8a0d6d/go.mod h1:Xgw0N+DBiDzkhQHm/nIhgumfaiMElDg/KIFD1OxTm5w= |
| amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3 h1:5EFx7BLJj/+G/rt8bTmeyMWVfF5s5Sns7ajTvX4w/I8= |
diff --git a/internal/memoria/app.go b/internal/memoria/app.go| index 9b9c3f7..7510274 100644 |
| --- a/internal/memoria/app.go |
| +++ b/internal/memoria/app.go |
| @@ -31,7 +31,29 @@ import ( |
| // for why), so a boot that skipped the rebuild would serve an empty |
| // corpus and call it "nothing matched". |
| func App(d *db.DB, origin string, sealer *seal.Sealer, logger *slog.Logger) (*http.ServeMux, *app, error) { |
| - migrated, err := migrate.Apply(context.Background(), d, BootSchema) |
| + return AppWith(d, Config{Origin: origin, Sealer: sealer}, logger) |
| +} |
| + |
| +// AppWith is App from the whole configuration, which is what main calls: |
| +// team mode is decided here, before anything migrates. |
| +// |
| +// With the five MEMORIA_TEAM_* variables set, the provisioning record is |
| +// verified against cfg's Home credentials and origin, and the marker is |
| +// read, before migrate.Apply runs: a database already activated in team |
| +// mode refuses to boot without the same binding (team_config.go). With |
| +// them unset, and a database never activated, this is App exactly as it |
| +// was — BootSchema, applied the same way. |
| +func AppWith(d *db.DB, cfg Config, logger *slog.Logger) (*http.ServeMux, *app, error) { |
| + origin, sealer := cfg.Origin, cfg.Sealer |
| + settings, err := teamSettings(cfg.Team, cfg.Home, origin) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + schema, err := teamBootSchema(context.Background(), d.Writer(), settings, BootSchema) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + migrated, err := migrate.Apply(context.Background(), d, schema) |
| if err != nil { |
| return nil, nil, err |
| } |
| @@ -76,6 +98,13 @@ func App(d *db.DB, origin string, sealer *seal.Sealer, logger *slog.Logger) (*ht |
| } |
| a := &app{db: d, logger: logger, store: store, syncer: NewSyncer(store, logger), origin: origin} |
| + if settings != nil { |
| + a.teamWiring = &teamWiring{settings: settings, transport: cfg.teamTransport, clock: cfg.teamClock} |
| + // Every person-made write is guarded from here on, before the |
| + // runtime exists: a write that arrives without a request's |
| + // standing is refused rather than let through (team_guard.go). |
| + store.team = true |
| + } |
| if err := a.wireNative(origin); err != nil { |
| return nil, nil, err |
| @@ -157,25 +186,30 @@ func App(d *db.DB, origin string, sealer *seal.Sealer, logger *slog.Logger) (*ht |
| // door. |
| r.Group(func(r chi.Router) { |
| r.Use(a.requireSession) |
| - r.Get("/api/native/session", a.nativeSession) |
| - r.Post("/api/native/search", a.nativeSearch) |
| - r.Post("/api/native/notes", a.nativeNote) |
| - r.Get("/", a.index) |
| - r.Get("/add", a.addContent) |
| - r.Get("/search", a.searchResults) |
| - r.Post("/documents", a.createDocument) |
| - r.Get("/documents/{id}", a.showDocument) |
| - r.Get("/documents/{id}/delete", a.confirmDelete) |
| - r.Post("/documents/{id}/delete", a.deleteDocument) |
| - r.Get("/facts/correct", a.correctFacts) |
| - r.Post("/facts/correct", a.saveCorrection) |
| - r.Get("/reports", a.reports) |
| - r.Get("/answer", a.answer) |
| - r.Post("/answer/feedback", a.saveFeedback) |
| - r.Get("/answer/feedback/{id}", a.feedbackPage) |
| - r.Post("/answer/feedback/{id}", a.saveFeedbackNote) |
| - r.Post("/answer/feedback/{id}/delete", a.deleteFeedback) |
| - r.Post("/reports/{id}/delete", a.deleteReport) |
| + // In team mode each route says what it needs of the roster: |
| + // the three list pages render partial under Unknown standing, |
| + // and everything else needs Member (team_access.go). Outside |
| + // team mode both are no gate at all. |
| + list, member := a.standing(needListing), a.standing(needMember) |
| + r.With(member).Get("/api/native/session", a.nativeSession) |
| + r.With(member).Post("/api/native/search", a.nativeSearch) |
| + r.With(member).Post("/api/native/notes", a.nativeNote) |
| + r.With(list).Get("/", a.index) |
| + r.With(member).Get("/add", a.addContent) |
| + r.With(list).Get("/search", a.searchResults) |
| + r.With(member).Post("/documents", a.createDocument) |
| + r.With(member).Get("/documents/{id}", a.showDocument) |
| + r.With(member).Get("/documents/{id}/delete", a.confirmDelete) |
| + r.With(member).Post("/documents/{id}/delete", a.deleteDocument) |
| + r.With(member).Get("/facts/correct", a.correctFacts) |
| + r.With(member).Post("/facts/correct", a.saveCorrection) |
| + r.With(list).Get("/reports", a.reports) |
| + r.With(member).Get("/answer", a.answer) |
| + r.With(member).Post("/answer/feedback", a.saveFeedback) |
| + r.With(member).Get("/answer/feedback/{id}", a.feedbackPage) |
| + r.With(member).Post("/answer/feedback/{id}", a.saveFeedbackNote) |
| + r.With(member).Post("/answer/feedback/{id}/delete", a.deleteFeedback) |
| + r.With(member).Post("/reports/{id}/delete", a.deleteReport) |
| // Connector routes sit INSIDE this group, so they inherit |
| // csrf.Protect and requireSession. A route mounted on the outer |
| @@ -191,6 +225,10 @@ func App(d *db.DB, origin string, sealer *seal.Sealer, logger *slog.Logger) (*ht |
| }) |
| mux := http.NewServeMux() |
| + // Team mode's readiness probe, public and no-store: {"team_mode":false} |
| + // with team mode off, the only thing a non-team instance gains |
| + // (team_config.go). |
| + mux.HandleFunc("GET /api/team", a.teamProbe) |
| mux.HandleFunc("GET /static/credits.css", serveCreditsCSS) |
| mux.Handle("GET /static/", assets.Handler()) |
| // estilo's retired v1 Onest files, kept answering so a page cached |
| @@ -275,6 +313,13 @@ func (a *app) requireSession(next http.Handler) http.Handler { |
| http.Error(w, "sign-in is not configured", http.StatusInternalServerError) |
| return |
| } |
| + // Team mode configured and no roster runtime (WireHome never ran, |
| + // or ran without Home): closed, never the owners list. |
| + if a.teamMode() && a.team == nil { |
| + a.logger.Error("team mode is configured but the roster is not; refusing every request") |
| + http.Error(w, "sign-in is not configured", http.StatusInternalServerError) |
| + return |
| + } |
| // A signed-out page request goes to /signin WITH the page it asked |
| // for (spec §9.4): rastrillo's own refusal sends a bare /signin, so |
| // a document link opened signed out landed on the index. Anything |
| @@ -290,6 +335,12 @@ func (a *app) requireSession(next http.Handler) http.Handler { |
| } |
| } |
| guarded := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if a.teamMode() { |
| + // The roster decides who this is for, on every request |
| + // (team_access.go). |
| + a.teamSession(w, r, next) |
| + return |
| + } |
| address, ok := a.identity(r) |
| if !ok || !a.Admit(address) { |
| // Still closed. What changes is what a REMOVED person is |
| @@ -325,8 +376,18 @@ func (a *app) requireSession(next http.Handler) http.Handler { |
| // check. These routes then need an owner predicate from wherever |
| // membership lives, or they lose their guard — recorded in the spec's |
| // open items, not left to be discovered. |
| +// |
| +// In team mode the owner is the roster's owner role, asked on every |
| +// request: members search and read the team's memory, and only owners |
| +// manage what feeds it (team_access.go's needOwner). MEMORIA_OWNERS then |
| +// admits a local sign-in and nothing more. |
| func (a *app) requireOwner(next http.Handler) http.Handler { |
| + owners := a.standing(needOwner)(next) |
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if a.teamMode() { |
| + owners.ServeHTTP(w, r) |
| + return |
| + } |
| addr, ok := a.identity(r) |
| if !ok || !a.isOwner(addr) { |
| // 404, not 403: AGENTS.md's rule, and a 403 would confirm |
diff --git a/internal/memoria/auth.go b/internal/memoria/auth.go| index 3b96656..25e2dae 100644 |
| --- a/internal/memoria/auth.go |
| +++ b/internal/memoria/auth.go |
| @@ -80,7 +80,9 @@ func (a *app) beginGuard(origin string, next http.HandlerFunc) http.HandlerFunc |
| // refuses to boot without one — and the version of this that |
| // defaults to allowing is the version that dials for everyone |
| // while looking configured. |
| - if len(a.owners) == 0 { |
| + // In team mode an empty list is valid (Home sign-in only), and |
| + // every address is refused below exactly as a stranger's is. |
| + if len(a.owners) == 0 && !a.teamMode() { |
| a.logger.Error("sign-in guard has no owners list; refusing") |
| http.Error(w, "sign-in is not configured", http.StatusInternalServerError) |
| return |
diff --git a/internal/memoria/chrome.go b/internal/memoria/chrome.go| index 2be8dce..3d07fd7 100644 |
| --- a/internal/memoria/chrome.go |
| +++ b/internal/memoria/chrome.go |
| @@ -68,6 +68,9 @@ type viewer struct { |
| address string |
| method string |
| ok bool |
| + // owner is the roster's owner role, in team mode only (team_access.go). |
| + // Outside it the owners list decides, as it always has. |
| + owner bool |
| } |
| // admission is what a request's session says about its person. |
| @@ -108,6 +111,10 @@ func (a *app) admissionOf(r *http.Request) (viewer, admission) { |
| if !ok || s.Subject == "" { |
| return viewer{}, signedOut |
| } |
| + if a.teamMode() { |
| + // The roster decides, never the owners list (team_access.go). |
| + return a.teamAdmission(r, s) |
| + } |
| switch s.Method { |
| case connect.HomeMethod: |
| if a.home == nil { |
| @@ -201,7 +208,13 @@ func (a *app) nav(r *http.Request, v viewer) []chrome.Link { |
| links := []chrome.Link{{Href: "/", Label: "Search", Current: r.URL.Path == "/"}} |
| // Every signed-in person's own corrections (§8.10). |
| links = append(links, chrome.Link{Href: "/reports", Label: "Reports", Current: r.URL.Path == "/reports"}) |
| - if a.isOwner(v.address) { |
| + owner := a.isOwner(v.address) |
| + if a.teamMode() { |
| + // The roster's owner role: an address on MEMORIA_OWNERS only |
| + // admits a local sign-in in team mode. |
| + owner = v.owner |
| + } |
| + if owner { |
| links = append(links, chrome.Link{Href: "/connectors", Label: "Sources", Current: r.URL.Path == "/connectors" || strings.HasPrefix(r.URL.Path, "/connectors/")}) |
| } |
| return links |
diff --git a/internal/memoria/config.go b/internal/memoria/config.go| index b027eca..6d5d1b6 100644 |
| --- a/internal/memoria/config.go |
| +++ b/internal/memoria/config.go |
| @@ -4,8 +4,11 @@ import ( |
| "encoding/base64" |
| "errors" |
| "fmt" |
| + "net/http" |
| "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| "amadan.net/oficina/memoria/internal/memoria/seal" |
| ) |
| @@ -38,6 +41,17 @@ type Config struct { |
| // TensorXKey is the provider credential. Required when AI is on, |
| // ignored when it is off. Never logged, never in an error. |
| TensorXKey string |
| + |
| + // Team is roster team mode's configuration: the five MEMORIA_TEAM_* |
| + // variables, nil when all five are unset (team_config.go). It needs |
| + // Home, and it makes MEMORIA_OWNERS optional: the roster decides who |
| + // may use the instance, and the owners list only admits a local |
| + // sign-in. Verified in AppWith, against Home and the origin. |
| + Team *teammode.Config |
| + // teamTransport and teamClock are the roster's test seams: nil in |
| + // production, where teammode uses its own client and the real clock. |
| + teamTransport http.RoundTripper |
| + teamClock roster.Clock |
| } |
| // ErrMissing is returned when required platform config is absent. |
| @@ -72,7 +86,17 @@ func LoadConfig(getenv func(string) string) (Config, error) { |
| return c, fmt.Errorf("%w: MEMORIA_INSTANCE_KEY", ErrMissing) |
| } |
| - if c.Owners = ParseOwners(getenv("MEMORIA_OWNERS")); len(c.Owners) == 0 { |
| + // Team mode first, because it decides whether MEMORIA_OWNERS is |
| + // required. One of the five set is a configuration, and an invalid |
| + // one; AppWith's Verify refuses it, so it never falls back to the |
| + // owners list. |
| + c.Team = teammode.ConfigFromLookup("MEMORIA", getenv) |
| + |
| + // In team mode the roster is the admission gate and the owners list |
| + // only admits a local sign-in, so an empty one is valid there and |
| + // means "Home sign-in only" (Alta's shape). Outside it, the list is |
| + // the gate, and an empty gate admits anyone who can receive mail. |
| + if c.Owners = ParseOwners(getenv("MEMORIA_OWNERS")); len(c.Owners) == 0 && c.Team == nil { |
| return c, fmt.Errorf("%w: MEMORIA_OWNERS (no admission gate)", ErrMissing) |
| } |
| @@ -143,6 +167,11 @@ func LoadConfig(getenv func(string) string) (Config, error) { |
| return c, err |
| } |
| } |
| + // Team mode exists only beside Home: the roster names Home subjects, |
| + // and nobody could sign in to be asked about. |
| + if c.Team != nil && c.Home == nil { |
| + return c, fmt.Errorf("%w: MEMORIA_HOME_* (the MEMORIA_TEAM_* variables are set, and team mode needs Home sign-in)", ErrMissing) |
| + } |
| return c, nil |
| } |
diff --git a/internal/memoria/connector.go b/internal/memoria/connector.go| index ad01aec..a9fdad9 100644 |
| --- a/internal/memoria/connector.go |
| +++ b/internal/memoria/connector.go |
| @@ -57,22 +57,26 @@ func (s *Store) SaveConnector(ctx context.Context, kind, token, workspace string |
| } |
| now := time.Now().UTC() |
| return s.db.G.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| - var existing Connector |
| - res := tx.Where("kind = ?", kind).First(&existing) |
| - if res.Error == nil { |
| - // An explicit allowlist, never a bound request body. |
| - return tx.Model(&Connector{}).Where("id = ?", existing.ID).Updates(map[string]any{ |
| - "sealed_token": sealed, |
| - "workspace_print": print, |
| - "last_verified": now, |
| - }).Error |
| - } |
| - return tx.Create(&Connector{ |
| - Kind: kind, SealedToken: sealed, WorkspacePrint: print, LastVerified: &now, |
| - }).Error |
| + return s.guard(ctx, ownerWrite, func() error { return saveConnectorTx(tx, kind, sealed, print, now) }) |
| }) |
| } |
| +func saveConnectorTx(tx *gorm.DB, kind string, sealed []byte, print string, now time.Time) error { |
| + var existing Connector |
| + res := tx.Where("kind = ?", kind).First(&existing) |
| + if res.Error == nil { |
| + // An explicit allowlist, never a bound request body. |
| + return tx.Model(&Connector{}).Where("id = ?", existing.ID).Updates(map[string]any{ |
| + "sealed_token": sealed, |
| + "workspace_print": print, |
| + "last_verified": now, |
| + }).Error |
| + } |
| + return tx.Create(&Connector{ |
| + Kind: kind, SealedToken: sealed, WorkspacePrint: print, LastVerified: &now, |
| + }).Error |
| +} |
| + |
| // Connector returns a configured connector, without its token. |
| func (s *Store) Connector(ctx context.Context, kind string) (*Connector, error) { |
| var c Connector |
| @@ -107,23 +111,27 @@ func (s *Store) ConnectorToken(ctx context.Context, kind string) (string, error) |
| // in those words rather than leaving it to be discovered. |
| func (s *Store) DeleteConnector(ctx context.Context, kind string) error { |
| return s.db.G.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| - var c Connector |
| - if err := tx.Where("kind = ?", kind).First(&c).Error; err != nil { |
| - if errors.Is(err, gorm.ErrRecordNotFound) { |
| - return nil |
| - } |
| - return err |
| - } |
| - if err := tx.Where("connector_id = ?", c.ID).Delete(&SourcePage{}).Error; err != nil { |
| - return err |
| - } |
| - if err := tx.Where("connector_id = ?", c.ID).Delete(&SyncRun{}).Error; err != nil { |
| - return err |
| - } |
| - return tx.Where("id = ?", c.ID).Delete(&Connector{}).Error |
| + return s.guard(ctx, ownerWrite, func() error { return deleteConnectorTx(tx, kind) }) |
| }) |
| } |
| +func deleteConnectorTx(tx *gorm.DB, kind string) error { |
| + var c Connector |
| + if err := tx.Where("kind = ?", kind).First(&c).Error; err != nil { |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return nil |
| + } |
| + return err |
| + } |
| + if err := tx.Where("connector_id = ?", c.ID).Delete(&SourcePage{}).Error; err != nil { |
| + return err |
| + } |
| + if err := tx.Where("connector_id = ?", c.ID).Delete(&SyncRun{}).Error; err != nil { |
| + return err |
| + } |
| + return tx.Where("id = ?", c.ID).Delete(&Connector{}).Error |
| +} |
| + |
| // StartRun opens a run, or refuses because one is already active. |
| // |
| // Single-flight is a conditional insert rather than a mutex, so it |
| @@ -136,29 +144,7 @@ func (s *Store) DeleteConnector(ctx context.Context, kind string) error { |
| func (s *Store) StartRun(ctx context.Context, connectorID int64) (*SyncRun, error) { |
| var run SyncRun |
| err := s.db.G.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| - var active []SyncRun |
| - if err := tx.Where("connector_id = ? AND state IN ?", connectorID, |
| - []string{RunEnumerating, RunFetching}).Find(&active).Error; err != nil { |
| - return err |
| - } |
| - for _, a := range active { |
| - if a.Heartbeat != nil && time.Since(*a.Heartbeat) > heartbeatStale { |
| - if err := tx.Model(&SyncRun{}).Where("id = ?", a.ID).Updates(map[string]any{ |
| - "state": RunInterrupted, |
| - "error_code": "interrupted", |
| - }).Error; err != nil { |
| - return err |
| - } |
| - continue |
| - } |
| - return ErrSyncInFlight |
| - } |
| - now := time.Now().UTC() |
| - run = SyncRun{ |
| - ConnectorID: connectorID, State: RunEnumerating, |
| - Total: -1, StartedAt: now, Heartbeat: &now, |
| - } |
| - return tx.Create(&run).Error |
| + return s.guard(ctx, ownerWrite, func() error { return startRunTx(tx, connectorID, &run) }) |
| }) |
| if err != nil { |
| return nil, err |
| @@ -166,6 +152,32 @@ func (s *Store) StartRun(ctx context.Context, connectorID int64) (*SyncRun, erro |
| return &run, nil |
| } |
| +func startRunTx(tx *gorm.DB, connectorID int64, run *SyncRun) error { |
| + var active []SyncRun |
| + if err := tx.Where("connector_id = ? AND state IN ?", connectorID, |
| + []string{RunEnumerating, RunFetching}).Find(&active).Error; err != nil { |
| + return err |
| + } |
| + for _, a := range active { |
| + if a.Heartbeat != nil && time.Since(*a.Heartbeat) > heartbeatStale { |
| + if err := tx.Model(&SyncRun{}).Where("id = ?", a.ID).Updates(map[string]any{ |
| + "state": RunInterrupted, |
| + "error_code": "interrupted", |
| + }).Error; err != nil { |
| + return err |
| + } |
| + continue |
| + } |
| + return ErrSyncInFlight |
| + } |
| + now := time.Now().UTC() |
| + *run = SyncRun{ |
| + ConnectorID: connectorID, State: RunEnumerating, |
| + Total: -1, StartedAt: now, Heartbeat: &now, |
| + } |
| + return tx.Create(run).Error |
| +} |
| + |
| // ReclaimRuns marks every run that was in flight as interrupted. |
| // |
| // Called at boot, and sound by construction rather than by timeout: a |
diff --git a/internal/memoria/corrections.go b/internal/memoria/corrections.go| index 3b356d1..c434578 100644 |
| --- a/internal/memoria/corrections.go |
| +++ b/internal/memoria/corrections.go |
| @@ -211,7 +211,9 @@ func (s *Store) SaveCorrection(ctx context.Context, asker suite.Subject, query, |
| if err != nil { |
| return err |
| } |
| - return s.db.G.WithContext(ctx).Create(&FactReport{ReporterPrint: print, SealedReport: sealed}).Error |
| + return s.guarded(ctx, memberWrite, func(db *gormTx) error { |
| + return db.Create(&FactReport{ReporterPrint: print, SealedReport: sealed}).Error |
| + }) |
| } |
| // ReportView is one of the person's own reports as /reports lists it. |
| @@ -292,14 +294,16 @@ func (s *Store) DeleteReport(ctx context.Context, asker suite.Subject, id int64) |
| if err != nil { |
| return err |
| } |
| - res := s.db.G.WithContext(ctx).Where("id = ? AND reporter_print = ?", id, print).Delete(&FactReport{}) |
| - if res.Error != nil { |
| - return res.Error |
| - } |
| - if res.RowsAffected == 0 { |
| - return ErrReportNotFound |
| - } |
| - return nil |
| + return s.guarded(ctx, memberWrite, func(db *gormTx) error { |
| + res := db.Where("id = ? AND reporter_print = ?", id, print).Delete(&FactReport{}) |
| + if res.Error != nil { |
| + return res.Error |
| + } |
| + if res.RowsAffected == 0 { |
| + return ErrReportNotFound |
| + } |
| + return nil |
| + }) |
| } |
| // ErrReportNotFound is a report id that is not the asker's. |
diff --git a/internal/memoria/credits_inventory_test.go b/internal/memoria/credits_inventory_test.go| index d20022d..6f09885 100644 |
| --- a/internal/memoria/credits_inventory_test.go |
| +++ b/internal/memoria/credits_inventory_test.go |
| @@ -35,7 +35,7 @@ func TestCreditsMatchProductionDependencies(t *testing.T) { |
| if err != nil { |
| t.Fatal("production dependency graph unavailable", err) |
| } |
| - inventory, err := catalog.Collect(bytes.NewReader(raw), map[string]bool{"amadan.net/oficina/estilo.git": true, "amadan.net/oficina/home/handoff": true, "amadan.net/oficina/home/connect": true, "amadan.net/oficina/suite": true, "amadan.net/rastrillo/native/server": true}) |
| + inventory, err := catalog.Collect(bytes.NewReader(raw), map[string]bool{"amadan.net/oficina/estilo.git": true, "amadan.net/oficina/home/handoff": true, "amadan.net/oficina/home/connect": true, "amadan.net/oficina/home/roster": true, "amadan.net/oficina/home/teammode": true, "amadan.net/oficina/suite": true, "amadan.net/rastrillo/native/server": true}) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/memoria/custody.go b/internal/memoria/custody.go| index bebba72..54d7547 100644 |
| --- a/internal/memoria/custody.go |
| +++ b/internal/memoria/custody.go |
| @@ -155,6 +155,12 @@ func WireSiblings(a *app, getenv func(string) string, dial suite.DialFunc) error |
| if err != nil { |
| return err |
| } |
| + // A team instance's siblings are its own team's (team_siblings.go). |
| + if a.teamMode() && len(cfg.Apps) > 0 { |
| + if err := teamSiblingsBound(a.origin, cfg.Team); err != nil { |
| + return err |
| + } |
| + } |
| if len(cfg.Apps) == 0 { |
| // Nothing configured. Custody stays nil, which withholds every |
| // sibling passage — and there are none, because nothing was |
diff --git a/internal/memoria/feedback.go b/internal/memoria/feedback.go| index 510337a..ccb66c3 100644 |
| --- a/internal/memoria/feedback.go |
| +++ b/internal/memoria/feedback.go |
| @@ -106,7 +106,7 @@ func (s *Store) SaveFeedback(ctx context.Context, asker suite.Subject, handle, v |
| return 0, "", err |
| } |
| row := AnswerFeedback{ReporterPrint: print, Verdict: verdict, SealedFeedback: sealed} |
| - if err := s.db.G.WithContext(ctx).Create(&row).Error; err != nil { |
| + if err := s.guarded(ctx, memberWrite, func(db *gormTx) error { return db.Create(&row).Error }); err != nil { |
| return 0, "", err |
| } |
| return row.ID, h.Query, nil |
| @@ -153,7 +153,9 @@ func (s *Store) SetFeedbackNote(ctx context.Context, asker suite.Subject, id int |
| if err != nil { |
| return "", err |
| } |
| - if err := s.db.G.WithContext(ctx).Model(&AnswerFeedback{}).Where("id = ?", row.ID).Update("sealed_feedback", sealed).Error; err != nil { |
| + if err := s.guarded(ctx, memberWrite, func(db *gormTx) error { |
| + return db.Model(&AnswerFeedback{}).Where("id = ?", row.ID).Update("sealed_feedback", sealed).Error |
| + }); err != nil { |
| return "", err |
| } |
| return p.Query, nil |
| @@ -237,12 +239,14 @@ func (s *Store) DeleteFeedback(ctx context.Context, asker suite.Subject, id int6 |
| if err != nil { |
| return err |
| } |
| - res := s.db.G.WithContext(ctx).Where("id = ? AND reporter_print = ?", id, print).Delete(&AnswerFeedback{}) |
| - if res.Error != nil { |
| - return res.Error |
| - } |
| - if res.RowsAffected == 0 { |
| - return ErrFeedbackNotFound |
| - } |
| - return nil |
| + return s.guarded(ctx, memberWrite, func(db *gormTx) error { |
| + res := db.Where("id = ? AND reporter_print = ?", id, print).Delete(&AnswerFeedback{}) |
| + if res.Error != nil { |
| + return res.Error |
| + } |
| + if res.RowsAffected == 0 { |
| + return ErrFeedbackNotFound |
| + } |
| + return nil |
| + }) |
| } |
diff --git a/internal/memoria/handlers.go b/internal/memoria/handlers.go| index 1bbf981..e82da4f 100644 |
| --- a/internal/memoria/handlers.go |
| +++ b/internal/memoria/handlers.go |
| @@ -19,7 +19,6 @@ import ( |
| "amadan.net/rastrillo/rastrillo" |
| "amadan.net/rastrillo/rastrillo/auth" |
| - "amadan.net/oficina/suite" |
| "amadan.net/rastrillo/rastrillo/db" |
| "amadan.net/rastrillo/rastrillo/sessions" |
| "github.com/go-chi/chi/v5" |
| @@ -106,6 +105,16 @@ type app struct { |
| directory string |
| syncer *Syncer |
| + |
| + // teamWiring is set when AppWith verified team configuration, and |
| + // team when WireHome then opened the roster runtime (team_config.go). |
| + // Both nil outside team mode, where nothing team_*.go does runs. |
| + teamWiring *teamWiring |
| + team *teamRuntime |
| + // previewUnknown is tools/drive's view of team mode's Unknown |
| + // standing; it acts only with allowUnauthenticated (AppForTest). |
| + previewUnknown bool |
| + |
| // owners is the admission list, and there is exactly one of it. |
| // |
| // Three things key on it: requireOwner (may this person reach an |
| @@ -211,6 +220,11 @@ type page struct { |
| // here rather than in the browser so that one heuristic has one |
| // home; search.js only honours the attribute the template writes. |
| Primed bool |
| + |
| + // Partial is team mode's Unknown standing on a list page (Paul, |
| + // 2026-10-28): the lists are withheld and the page says why |
| + // (team_answers.go). Never set outside team mode. |
| + Partial bool |
| } |
| // dropZone is the upload form's limits and ALL of its copy, in one |
| @@ -593,12 +607,19 @@ func (a *app) index(w http.ResponseWriter, r *http.Request) { |
| } |
| p := a.pageFor(r, f) |
| p.Query, p.Searched = q, q != "" |
| - a.runSearch(r, &p) |
| - docs, err := a.store.Summaries(r.Context()) |
| - if err != nil { |
| - a.logger.Error("list documents", "err", err) |
| + // Team mode: standing is read before anything is listed, and asked |
| + // again after (team_access.go). Outside it both are no-ops. |
| + if a.teamReaches(r) { |
| + a.runSearch(r, &p) |
| + docs, err := a.store.Summaries(r.Context()) |
| + if err != nil { |
| + a.logger.Error("list documents", "err", err) |
| + } |
| + p.Documents = docs |
| + } |
| + if a.teamPartial(r) { |
| + p.withhold() |
| } |
| - p.Documents = docs |
| // Adding content moved to /add. The one message that still lands here |
| // is a failed delete, and it has a cookie of its own; see notice.go. |
| if kind, msg, ok := indexNotice.take(w, r); ok { |
| @@ -640,12 +661,17 @@ func (a *app) addContent(w http.ResponseWriter, r *http.Request) { |
| func (a *app) searchResults(w http.ResponseWriter, r *http.Request) { |
| q := strings.TrimSpace(r.URL.Query().Get("q")) |
| p := page{Query: q, Searched: q != ""} |
| - a.runSearch(r, &p) |
| - // The passage count is only spoken by the no-match copy, and this |
| - // route runs once per keystroke. Counting only when the count will |
| - // be read keeps a per-keystroke query off the database. |
| - if p.Searched && len(p.Results) == 0 { |
| - p.Chunks = a.chunkCount() |
| + if a.teamReaches(r) { |
| + a.runSearch(r, &p) |
| + // The passage count is only spoken by the no-match copy, and this |
| + // route runs once per keystroke. Counting only when the count will |
| + // be read keeps a per-keystroke query off the database. |
| + if p.Searched && len(p.Results) == 0 { |
| + p.Chunks = a.chunkCount() |
| + } |
| + } |
| + if a.teamPartial(r) { |
| + p.withhold() |
| } |
| renderFragment(w, "results", p) |
| } |
| @@ -670,8 +696,8 @@ func (a *app) runSearch(r *http.Request, p *page) { |
| // is not signed in has nobody for a sibling to rule on, and every |
| // passage would have to be withheld anyway — so this is the same |
| // refusal, said before the round trip rather than after it. |
| - addr, ok := a.identity(r) |
| - if !ok || addr == "" { |
| + asker, ok := a.asker(r) |
| + if !ok { |
| a.logger.Error("search refused: no identity on the request") |
| p.Searched, p.SearchFailed = false, true |
| return |
| @@ -683,8 +709,7 @@ func (a *app) runSearch(r *http.Request, p *page) { |
| if r.URL.Query().Get("typing") == "1" { |
| search = a.store.SearchWhileTyping |
| } |
| - found, err := search(r.Context(), |
| - suite.Subject{Kind: suite.SubjectAddress, Value: addr}, p.Query, 25) |
| + found, err := search(r.Context(), asker, p.Query, 25) |
| if err != nil { |
| // No query text in the log line: AGENTS.md, and `carlos logs` is |
| // storage we cannot grep. |
| @@ -702,7 +727,7 @@ func (a *app) runSearch(r *http.Request, p *page) { |
| p.AnswerSlot = a.store.answerer != nil && AnswerWanted(found) |
| if p.AnswerSlot && r.URL.Query().Get("ai") == "1" && r.URL.Query().Get("typing") != "1" { |
| // The scriptless path: the answer, inline, under the same rules. |
| - if ans, err := a.store.Answer(r.Context(), suite.Subject{Kind: suite.SubjectAddress, Value: addr}, p.Query); err == nil { |
| + if ans, err := a.store.Answer(r.Context(), asker, p.Query); err == nil { |
| p.Answer = ans |
| } |
| } |
| @@ -896,6 +921,11 @@ func (a *app) createDocument(w http.ResponseWriter, r *http.Request) { |
| stored := 0 |
| var refused []string |
| + // In team mode, the guard's refusal of the first ingest it refused: |
| + // standing lapsed mid-submission (team_guard.go). Every later ingest |
| + // is refused too, since the request's standing latches, and each is |
| + // named as not stored like any other refusal. |
| + var standingErr error |
| // Stored, and not searchable in this process. Kept apart from |
| // refused because the two need opposite sentences: see ErrIndexLag, |
| // and see the clause itself in dropZone. |
| @@ -925,6 +955,9 @@ func (a *app) createDocument(w http.ResponseWriter, r *http.Request) { |
| Source: "upload", Key: hdr.Filename, Title: title, Body: string(raw), |
| }) |
| switch { |
| + case isStandingErr(err): |
| + standingErr = err |
| + refused = append(refused, fill(c.ReasonStore, "{name}", name)) |
| case errors.Is(err, ErrIndexLag): |
| // The row committed and the index did not take it. Counted as |
| // stored, because it is, and then named — "could not be |
| @@ -957,6 +990,9 @@ func (a *app) createDocument(w http.ResponseWriter, r *http.Request) { |
| Source: "paste", Key: title, Title: title, Body: body, |
| }) |
| switch { |
| + case isStandingErr(err): |
| + standingErr = err |
| + refused = append(refused, fill(c.ReasonStore, "{name}", c.PasteName)) |
| case errors.Is(err, ErrIndexLag): |
| a.logger.Error("index refresh failed after commit", "source", "paste", "err", err) |
| stored++ |
| @@ -980,6 +1016,12 @@ func (a *app) createDocument(w http.ResponseWriter, r *http.Request) { |
| a.refuse(w, r, "empty", 0) |
| return |
| } |
| + // Nothing landed and standing is why: the retryable answer, as for |
| + // every other write. When something did land the outcome below says |
| + // which, and names the rest as not stored. |
| + if standingErr != nil && stored == 0 && a.guardRefused(w, r, standingErr) { |
| + return |
| + } |
| msg, kind := c.outcome(stored, refused, lagging) |
| if wantsJSON(r) { |
| @@ -1171,7 +1213,9 @@ func (a *app) deleteDocument(w http.ResponseWriter, r *http.Request) { |
| a.errorPage(w, r, http.StatusNotFound, kindDocument, "") |
| return |
| } |
| - if err := a.store.Delete(r.Context(), id); err != nil { |
| + if err := a.store.Delete(r.Context(), id); a.guardRefused(w, r, err) { |
| + return |
| + } else if err != nil { |
| // The delete did not happen, and this used to say nothing about |
| // that: the error was logged and the redirect issued exactly as |
| // if it had. Someone who asked for a passage to stop being |
diff --git a/internal/memoria/handlers_connector.go b/internal/memoria/handlers_connector.go| index 862b3df..b984bbd 100644 |
| --- a/internal/memoria/handlers_connector.go |
| +++ b/internal/memoria/handlers_connector.go |
| @@ -238,7 +238,9 @@ func (a *app) saveNotionConnector(w http.ResponseWriter, r *http.Request) { |
| http.Redirect(w, r, "/connectors/notion?err=verify", http.StatusSeeOther) |
| return |
| } |
| - if err := a.store.SaveConnector(r.Context(), "notion", token, workspace); err != nil { |
| + if err := a.store.SaveConnector(r.Context(), "notion", token, workspace); a.guardRefused(w, r, err) { |
| + return |
| + } else if err != nil { |
| a.logger.Error("save connector", "err", err) |
| http.Redirect(w, r, "/connectors/notion?err=save", http.StatusSeeOther) |
| return |
| @@ -262,6 +264,9 @@ func (a *app) startNotionSync(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| run, err := a.store.StartRun(r.Context(), c.ID) |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| if errors.Is(err, ErrSyncInFlight) { |
| http.Redirect(w, r, "/connectors/notion?err=inflight", http.StatusSeeOther) |
| return |
| @@ -303,7 +308,9 @@ func (a *app) runSync(ctx context.Context, connectorID, runID int64) { |
| // performed in memoria. The confirmation copy says that before the |
| // button is pressed rather than after. |
| func (a *app) disconnectNotion(w http.ResponseWriter, r *http.Request) { |
| - if err := a.store.DeleteConnector(r.Context(), "notion"); err != nil { |
| + if err := a.store.DeleteConnector(r.Context(), "notion"); a.guardRefused(w, r, err) { |
| + return |
| + } else if err != nil { |
| a.logger.Error("disconnect connector", "err", err) |
| http.Redirect(w, r, "/connectors/notion?err=save", http.StatusSeeOther) |
| return |
diff --git a/internal/memoria/handlers_correct.go b/internal/memoria/handlers_correct.go| index 752fcf0..66d2ec7 100644 |
| --- a/internal/memoria/handlers_correct.go |
| +++ b/internal/memoria/handlers_correct.go |
| @@ -35,7 +35,21 @@ type feedbackPage struct { |
| Feedback FeedbackView |
| } |
| +// asker is who a search, a report or a rating is for: the signed-in |
| +// address, lowercased (lone shape, suite §3). In team mode it is the Home |
| +// subject the roster knows them by (suite shape, where Home is the |
| +// identity authority), for everyone — a Home-only member has no address, |
| +// and one person must ask as one subject however they signed in, or their |
| +// own reports would split in two. An unlinked local account has no |
| +// subject, and no standing to ask with. |
| func (a *app) asker(r *http.Request) (suite.Subject, bool) { |
| + if a.teamMode() && !a.allowUnauthenticated { |
| + p, ok := teamPersonFrom(r.Context()) |
| + if !ok || p.subject == "" { |
| + return suite.Subject{}, false |
| + } |
| + return suite.Subject{Kind: suite.SubjectPersonRef, Value: p.subject}, true |
| + } |
| addr, ok := a.identity(r) |
| if !ok || addr == "" { |
| return suite.Subject{}, false |
| @@ -91,6 +105,8 @@ func (a *app) saveCorrection(w http.ResponseWriter, r *http.Request) { |
| err := a.store.SaveCorrection(r.Context(), asker, q, |
| r.PostForm.Get("kind"), r.PostForm.Get("choice"), r.PostForm.Get("note")) |
| switch { |
| + case a.guardRefused(w, r, err): |
| + return |
| case errors.Is(err, ErrChoiceGone): |
| w.WriteHeader(http.StatusConflict) |
| a.renderCorrect(w, r, q, true) |
| @@ -111,19 +127,27 @@ func (a *app) reports(w http.ResponseWriter, r *http.Request) { |
| a.errorPage(w, r, http.StatusNotFound, kindDocument, "") |
| return |
| } |
| - list, err := a.store.Reports(r.Context(), asker) |
| - if err != nil { |
| - a.logger.Error("listing reports failed", "err", err) |
| - a.errorPage(w, r, http.StatusInternalServerError, kindDocument, "") |
| - return |
| + pg := reportsPage{page: a.pageFor(r, frame{parts: []string{"Reports"}})} |
| + // Team mode: standing before the lists, and again after (team_access.go). |
| + if a.teamReaches(r) { |
| + list, err := a.store.Reports(r.Context(), asker) |
| + if err != nil { |
| + a.logger.Error("listing reports failed", "err", err) |
| + a.errorPage(w, r, http.StatusInternalServerError, kindDocument, "") |
| + return |
| + } |
| + fb, err := a.store.Feedback(r.Context(), asker) |
| + if err != nil { |
| + a.logger.Error("listing answer feedback failed", "err", err) |
| + a.errorPage(w, r, http.StatusInternalServerError, kindDocument, "") |
| + return |
| + } |
| + pg.Reports, pg.Feedback = list, fb |
| } |
| - fb, err := a.store.Feedback(r.Context(), asker) |
| - if err != nil { |
| - a.logger.Error("listing answer feedback failed", "err", err) |
| - a.errorPage(w, r, http.StatusInternalServerError, kindDocument, "") |
| - return |
| + if a.teamPartial(r) { |
| + pg.withhold() |
| } |
| - render(w, "reports", reportsPage{page: a.pageFor(r, frame{parts: []string{"Reports"}}), Reports: list, Feedback: fb}) |
| + render(w, "reports", pg) |
| } |
| // deleteReport is POST /reports/{id}/delete. Another person's report is a |
| @@ -136,6 +160,8 @@ func (a *app) deleteReport(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| switch err := a.store.DeleteReport(r.Context(), asker, id); { |
| + case a.guardRefused(w, r, err): |
| + return |
| case errors.Is(err, ErrReportNotFound): |
| a.errorPage(w, r, http.StatusNotFound, kindDocument, "") |
| return |
| @@ -162,6 +188,13 @@ func (a *app) answer(w http.ResponseWriter, r *http.Request) { |
| a.logger.Error("ai answer search failed", "err", err) |
| ans = &AIAnswer{State: AnswerFailed} |
| } |
| + // A model answer can take seconds, and in team mode the standing it |
| + // was asked on must still hold when it is delivered: a person removed |
| + // while the model was thinking gets nothing it said (team_access.go). |
| + if !a.teamReaches(r) { |
| + a.teamUnavailable(w, r) |
| + return |
| + } |
| if ans == nil { |
| w.WriteHeader(http.StatusNoContent) |
| return |
| @@ -187,6 +220,8 @@ func (a *app) saveFeedback(w http.ResponseWriter, r *http.Request) { |
| verdict := r.PostForm.Get("verdict") |
| id, q, err := a.store.SaveFeedback(r.Context(), asker, r.PostForm.Get("handle"), verdict) |
| switch { |
| + case a.guardRefused(w, r, err): |
| + return |
| case errors.Is(err, ErrFeedbackNotFound): |
| a.errorPage(w, r, http.StatusNotFound, kindDocument, "") |
| return |
| @@ -251,6 +286,8 @@ func (a *app) saveFeedbackNote(w http.ResponseWriter, r *http.Request) { |
| } |
| q, err := a.store.SetFeedbackNote(r.Context(), asker, id, r.PostForm.Get("note")) |
| switch { |
| + case a.guardRefused(w, r, err): |
| + return |
| case errors.Is(err, ErrFeedbackNotFound): |
| a.errorPage(w, r, http.StatusNotFound, kindDocument, "") |
| return |
| @@ -270,6 +307,8 @@ func (a *app) deleteFeedback(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| switch err := a.store.DeleteFeedback(r.Context(), asker, id); { |
| + case a.guardRefused(w, r, err): |
| + return |
| case errors.Is(err, ErrFeedbackNotFound): |
| a.errorPage(w, r, http.StatusNotFound, kindDocument, "") |
| return |
diff --git a/internal/memoria/home.go b/internal/memoria/home.go| index b5d6c94..23d405d 100644 |
| --- a/internal/memoria/home.go |
| +++ b/internal/memoria/home.go |
| @@ -7,7 +7,6 @@ import ( |
| "amadan.net/oficina/home/connect" |
| "amadan.net/oficina/home/connect/linkstore" |
| - "amadan.net/oficina/home/handoff" |
| "amadan.net/rastrillo/rastrillo/csrf" |
| "amadan.net/rastrillo/rastrillo/migrate" |
| "amadan.net/rastrillo/rastrillo/sessions" |
| @@ -29,8 +28,9 @@ func (a *app) WireHome(mux *http.ServeMux, cfg Config) error { |
| return errHomeIdentity |
| } |
| h := cfg.Home |
| - schema := migrate.Merge(homeIdentitySchema, migrate.MustFromFS(handoff.Migrations, "oficina_handoff"), migrate.MustFromFS(linkstore.Migrations, linkstore.SchemaNamespace)) |
| - if _, err := migrate.Apply(context.Background(), a.db, schema); err != nil { |
| + // In team mode AppWith has applied this already (teamBoot), and this |
| + // finds every migration recorded. |
| + if _, err := migrate.Apply(context.Background(), a.db, homeSchema()); err != nil { |
| return errHomeIdentity |
| } |
| sess, err := sessions.New(sessions.Config{DB: a.db.Writer(), Origin: cfg.Origin, SigninPath: "/signin", Logger: a.logger}) |
| @@ -44,7 +44,15 @@ func (a *app) WireHome(mux *http.ServeMux, cfg Config) error { |
| } |
| return &connect.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime, At: s.At}, nil |
| } |
| - b, err := connect.New(connect.Config{DB: a.db.Writer(), Origin: cfg.Origin, Issuer: h.Issuer, ConsumerID: h.ConsumerID, Namespace: "oficina/memoria", SessionCookie: sess.CookieName(), Keys: h.Keys, DEK: h.DEK, ReadSession: read, |
| + // In team mode, connect's Home-only hooks: a roster member with no |
| + // account here signs in with Home alone (team_home_only.go). Both |
| + // nil otherwise, which is connect exactly as before. |
| + var unlinked, homeOnly func(context.Context, string, string) (connect.Person, error) |
| + if a.teamMode() { |
| + unlinked, homeOnly = a.teamUnlinked(a.db.Writer()), a.teamHomeOnly(a.db.Writer()) |
| + } |
| + b, err := connect.New(connect.Config{DB: a.db.Writer(), Origin: cfg.Origin, Issuer: h.Issuer, ConsumerID: h.ConsumerID, Namespace: homeNamespace, SessionCookie: sess.CookieName(), Keys: h.Keys, DEK: h.DEK, ReadSession: read, |
| + Unlinked: unlinked, HomeOnly: homeOnly, |
| 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}) |
| }, |
| @@ -59,13 +67,15 @@ func (a *app) WireHome(mux *http.ServeMux, cfg Config) error { |
| if err != nil { |
| return errHomeIdentity |
| } |
| - routes, err := connect.NewRoutes(b, connect.RoutesConfig{Namespace: "oficina/memoria", Origin: cfg.Origin, Issuer: h.Issuer, SessionCookie: sess.CookieName(), DEK: h.DEK, ReadSession: read, SignOut: sess.SignOut, LocalSignin: a.localSignin, Protect: csrf.Protect(cfg.Origin), Render: a.renderHome}) |
| + routes, err := connect.NewRoutes(b, connect.RoutesConfig{Namespace: homeNamespace, Origin: cfg.Origin, Issuer: h.Issuer, SessionCookie: sess.CookieName(), DEK: h.DEK, ReadSession: read, SignOut: sess.SignOut, LocalSignin: a.localSignin, Protect: csrf.Protect(cfg.Origin), Render: a.renderHome}) |
| if err != nil { |
| return errHomeIdentity |
| } |
| a.home = &homeIntegration{bridge: b, routes: routes, sessions: sess} |
| a.directory = h.Directory |
| - return nil |
| + // The roster runtime, last: it needs the bridge, and nothing serves |
| + // until it is open or boot has been refused (team_config.go). |
| + return a.configureTeam(h) |
| } |
| func (a *app) homeMiddleware(origin string) func(http.Handler) http.Handler { |
diff --git a/internal/memoria/home_identity.go b/internal/memoria/home_identity.go| index 39160f3..e288207 100644 |
| --- a/internal/memoria/home_identity.go |
| +++ b/internal/memoria/home_identity.go |
| @@ -86,7 +86,10 @@ func (a *app) lookupHomeLocalIdentity(ctx context.Context, q homeIdentityQueryer |
| if err != nil || lookup != fingerprint || address != normaliseAddress(address) { |
| return "", errHomeIdentity |
| } |
| - if !a.Admit(address) { |
| + // In team mode the roster decides standing, and a link is identity: |
| + // an address taken off MEMORIA_OWNERS loses its local sign-in, not |
| + // the Home sign-in its link gives it (team_access.go). |
| + if !a.teamMode() && !a.Admit(address) { |
| return "", sql.ErrNoRows |
| } |
| return address, nil |
diff --git a/internal/memoria/native.go b/internal/memoria/native.go| index bc14b23..51e5677 100644 |
| --- a/internal/memoria/native.go |
| +++ b/internal/memoria/native.go |
| @@ -8,7 +8,6 @@ import ( |
| "net/http" |
| "strings" |
| - "amadan.net/oficina/suite" |
| nativeauth "amadan.net/rastrillo/native/server" |
| "amadan.net/rastrillo/rastrillo/sessions" |
| @@ -47,8 +46,8 @@ func (a *app) nativeSession(w http.ResponseWriter, r *http.Request) { |
| nativeJSON(w, map[string]string{"app": "memoria"}) |
| } |
| func (a *app) nativeSearch(w http.ResponseWriter, r *http.Request) { |
| - address, ok := a.identity(r) |
| - if !ok || address == "" { |
| + asker, ok := a.asker(r) |
| + if !ok { |
| http.Error(w, "Sign in again", 401) |
| return |
| } |
| @@ -70,11 +69,18 @@ func (a *app) nativeSearch(w http.ResponseWriter, r *http.Request) { |
| // WithoutFacts: this response has no field for the fact box, so building |
| // one would call the model (§8.9) and send passages for an answer the |
| // native client never receives. |
| - found, err := a.store.SearchWithoutFacts(r.Context(), suite.Subject{Kind: suite.SubjectAddress, Value: address}, in.Query, 25) |
| + found, err := a.store.SearchWithoutFacts(r.Context(), asker, in.Query, 25) |
| if err != nil { |
| http.Error(w, "Search is unavailable. Try again.", 503) |
| return |
| } |
| + // A JSON list has nowhere to say it is partial, so in team mode a |
| + // standing that lapsed while it was built is the retryable 503 (Paul, |
| + // 2026-10-28), never a short list read as the whole answer. |
| + if a.teamPartial(r) { |
| + a.teamUnavailable(w, r) |
| + return |
| + } |
| // Search resolves every hit and asks the owning app for this person's current |
| // permission. Never use Summaries or Body to bypass that decision for native UI. |
| type result struct { |
| @@ -140,6 +146,9 @@ func (a *app) nativeNote(w http.ResponseWriter, r *http.Request) { |
| key = parsed.String() |
| } |
| id, err := a.store.Ingest(r.Context(), IngestSpec{Source: "paste", Key: "native-" + key, Title: strings.TrimSpace(in.Title), Body: in.Body}) |
| + if a.guardRefused(w, r, err) { |
| + return |
| + } |
| if err != nil && !errors.Is(err, ErrIndexLag) { |
| http.Error(w, "The note could not be confirmed", 500) |
| return |
diff --git a/internal/memoria/render.go b/internal/memoria/render.go| index edc6ef9..1efe49b 100644 |
| --- a/internal/memoria/render.go |
| +++ b/internal/memoria/render.go |
| @@ -88,6 +88,11 @@ func (a *app) pageFor(r *http.Request, f frame) page { |
| p := page{Frame: a.frameFor(r, f), ModelOn: a.modelOn()} |
| if p.Frame.Signed { |
| p.Chunks = a.chunkCount() |
| + // Team mode: the corpus is counted only for a Member. Anyone |
| + // else is told the count is unavailable, which is true. |
| + if !a.teamReaches(r) { |
| + p.Chunks = -1 |
| + } |
| } |
| return p |
| } |
diff --git a/internal/memoria/siblingsync.go b/internal/memoria/siblingsync.go| index f2833d6..388fd00 100644 |
| --- a/internal/memoria/siblingsync.go |
| +++ b/internal/memoria/siblingsync.go |
| @@ -72,6 +72,9 @@ type PollResult struct { |
| // no-op. The expensive failure is skipping a row nobody will mention |
| // again. |
| func (s *Store) Poll(ctx context.Context, c *sibling.Client, sib sibling.Sibling) (PollResult, error) { |
| + // A poll is the instance's own derived work, not anybody's write |
| + // (team_guard.go). |
| + ctx = systemWrite(ctx) |
| var res PollResult |
| cursor, err := s.cursor(ctx, sib.Name) |
| if err != nil { |
diff --git a/internal/memoria/store.go b/internal/memoria/store.go| index d884ddd..9f7907f 100644 |
| --- a/internal/memoria/store.go |
| +++ b/internal/memoria/store.go |
| @@ -54,6 +54,10 @@ type Store struct { |
| // state a misconfigured slice-1 instance is in, so nil withholds |
| // every sibling passage rather than rendering it. See rule(). |
| custody Custody |
| + // team is set in team mode, and makes every person-made write run |
| + // under teammode.Guard inside its own transaction (team_guard.go). |
| + // false is the write path exactly as it was. |
| + team bool |
| } |
| // NewStore wires the store. The index starts empty — call Rebuild. |
| @@ -358,142 +362,147 @@ func (s *Store) Ingest(ctx context.Context, spec IngestSpec) (int64, error) { |
| var docID int64 |
| var unchanged, rechunk bool |
| + // In team mode the person's standing is checked before and after the |
| + // write, inside this transaction (team_guard.go). A connector run's or |
| + // a sibling poll's ingest is a systemWrite and is not. |
| err = s.db.G.WithContext(ctx).Transaction(func(tx *gormTx) error { |
| - var existing Document |
| - res := tx.Where("source = ? AND external_id = ?", spec.Source, external).First(&existing) |
| - switch { |
| - case res.Error == nil: |
| - docID = existing.ID |
| - if existing.BodyPrint == bodyPrint { |
| - // Same key, same body — but the page may have been |
| - // RENAMED or MOVED, and neither touches the body. |
| - // |
| - // An earlier version returned here unconditionally, so a |
| - // renamed page kept its old title forever and a moved one |
| - // kept its old ancestry. Worse for a connector: an |
| - // ancestor rename does not change a descendant's own edit |
| - // time at all, so nothing upstream ever signalled it. |
| - // Found by a design review. |
| - moved, err := s.titleOrPathMoved(existing, title, pathStr) |
| - if err != nil { |
| - return err |
| - } |
| - if !moved { |
| - // Genuinely unchanged. Do NOT bump memoria's own |
| - // revision: a revision that moves without the content |
| - // moving would make every cached authorization stale |
| - // for no reason. |
| + return s.guard(ctx, memberWrite, func() error { |
| + var existing Document |
| + res := tx.Where("source = ? AND external_id = ?", spec.Source, external).First(&existing) |
| + switch { |
| + case res.Error == nil: |
| + docID = existing.ID |
| + if existing.BodyPrint == bodyPrint { |
| + // Same key, same body — but the page may have been |
| + // RENAMED or MOVED, and neither touches the body. |
| // |
| - // **But the SIBLING's revision must still be |
| - // recorded, and this returned without it.** The two |
| - // numbers answer different questions. memoria's |
| - // counts its own edits; the sibling's is the token S2 |
| - // is asked about, and the sibling issues it for |
| - // reasons memoria cannot see — a permissions change, |
| - // a metadata edit, a re-save that touched no bytes. |
| - // |
| - // Left stale, the failure is permanent and invisible: |
| - // the sibling announces revision 8 of a body |
| - // identical to 7, memoria keeps 7, and every |
| - // subsequent query asks S2 about `(item, 7)`. The |
| - // sibling answers STALE — correctly, it has moved on |
| - // — so the passage is withheld loudly on every page, |
| - // forever, and re-polling cannot fix it because the |
| - // body never changes. "Docs has moved on from 1 |
| - // result; refetching" on every single query, for a |
| - // document the reader is entitled to. |
| - // |
| - // Found by a review, 2026-09-07. |
| - if spec.ItemID != "" && existing.SiblingRevision != spec.SiblingRevision { |
| + // An earlier version returned here unconditionally, so a |
| + // renamed page kept its old title forever and a moved one |
| + // kept its old ancestry. Worse for a connector: an |
| + // ancestor rename does not change a descendant's own edit |
| + // time at all, so nothing upstream ever signalled it. |
| + // Found by a design review. |
| + moved, err := s.titleOrPathMoved(existing, title, pathStr) |
| + if err != nil { |
| + return err |
| + } |
| + if !moved { |
| + // Genuinely unchanged. Do NOT bump memoria's own |
| + // revision: a revision that moves without the content |
| + // moving would make every cached authorization stale |
| + // for no reason. |
| + // |
| + // **But the SIBLING's revision must still be |
| + // recorded, and this returned without it.** The two |
| + // numbers answer different questions. memoria's |
| + // counts its own edits; the sibling's is the token S2 |
| + // is asked about, and the sibling issues it for |
| + // reasons memoria cannot see — a permissions change, |
| + // a metadata edit, a re-save that touched no bytes. |
| + // |
| + // Left stale, the failure is permanent and invisible: |
| + // the sibling announces revision 8 of a body |
| + // identical to 7, memoria keeps 7, and every |
| + // subsequent query asks S2 about `(item, 7)`. The |
| + // sibling answers STALE — correctly, it has moved on |
| + // — so the passage is withheld loudly on every page, |
| + // forever, and re-polling cannot fix it because the |
| + // body never changes. "Docs has moved on from 1 |
| + // result; refetching" on every single query, for a |
| + // document the reader is entitled to. |
| + // |
| + // Found by a review, 2026-09-07. |
| + if spec.ItemID != "" && existing.SiblingRevision != spec.SiblingRevision { |
| + unchanged = true |
| + return tx.Model(&Document{}).Where("id = ?", docID).Updates(map[string]any{ |
| + "sibling_revision": spec.SiblingRevision, |
| + "sibling_item_id": sealedItemID, |
| + }).Error |
| + } |
| unchanged = true |
| - return tx.Model(&Document{}).Where("id = ?", docID).Updates(map[string]any{ |
| - "sibling_revision": spec.SiblingRevision, |
| - "sibling_item_id": sealedItemID, |
| - }).Error |
| + return nil |
| } |
| - unchanged = true |
| - return nil |
| + // Title or path only. Still no revision bump — the |
| + // passages a citation points at have not moved — and the |
| + // chunks are left alone, because the path lives on the |
| + // document. The index is refreshed below, since it is |
| + // the index that carries the path. |
| + // Title or path moved. The sibling's revision travels |
| + // with it for the same reason as above: whatever made the |
| + // sibling issue a new one, S2 will be asked about the new |
| + // one or about nothing. |
| + return tx.Model(&Document{}).Where("id = ?", docID).Updates(map[string]any{ |
| + "sealed_title": sealedTitle, |
| + "sealed_path": sealedPath, |
| + "sibling_revision": spec.SiblingRevision, |
| + "sibling_item_id": sealedItemID, |
| + }).Error |
| } |
| - // Title or path only. Still no revision bump — the |
| - // passages a citation points at have not moved — and the |
| - // chunks are left alone, because the path lives on the |
| - // document. The index is refreshed below, since it is |
| - // the index that carries the path. |
| - // Title or path moved. The sibling's revision travels |
| - // with it for the same reason as above: whatever made the |
| - // sibling issue a new one, S2 will be asked about the new |
| - // one or about nothing. |
| - return tx.Model(&Document{}).Where("id = ?", docID).Updates(map[string]any{ |
| - "sealed_title": sealedTitle, |
| - "sealed_path": sealedPath, |
| - "sibling_revision": spec.SiblingRevision, |
| + rechunk = true |
| + if err := tx.Where("document_id = ?", docID).Delete(&Chunk{}).Error; err != nil { |
| + return err |
| + } |
| + if err := tx.Model(&Document{}).Where("id = ?", docID).Updates(map[string]any{ |
| + "revision": existing.Revision + 1, |
| + "sealed_title": sealedTitle, |
| + "sealed_body": sealedBody, |
| + "sealed_path": sealedPath, |
| + "body_print": bodyPrint, |
| + "bytes": len(body), |
| + // The sibling's own revision moves with the body, and it |
| + // is the sibling's number rather than an increment of |
| + // ours: §4.1 forbids memoria inventing or ordering one. |
| "sibling_item_id": sealedItemID, |
| - }).Error |
| - } |
| - rechunk = true |
| - if err := tx.Where("document_id = ?", docID).Delete(&Chunk{}).Error; err != nil { |
| - return err |
| - } |
| - if err := tx.Model(&Document{}).Where("id = ?", docID).Updates(map[string]any{ |
| - "revision": existing.Revision + 1, |
| - "sealed_title": sealedTitle, |
| - "sealed_body": sealedBody, |
| - "sealed_path": sealedPath, |
| - "body_print": bodyPrint, |
| - "bytes": len(body), |
| - // The sibling's own revision moves with the body, and it |
| - // is the sibling's number rather than an increment of |
| - // ours: §4.1 forbids memoria inventing or ordering one. |
| - "sibling_item_id": sealedItemID, |
| - "sibling_revision": spec.SiblingRevision, |
| - }).Error; err != nil { |
| - return err |
| - } |
| - default: |
| - rechunk = true |
| - d := Document{ |
| - Source: spec.Source, |
| - ExternalID: external, |
| - BodyPrint: bodyPrint, |
| - Revision: 1, |
| - SealedTitle: sealedTitle, |
| - SealedBody: sealedBody, |
| - SealedPath: sealedPath, |
| - SiblingItemID: sealedItemID, |
| - SiblingRevision: spec.SiblingRevision, |
| - Bytes: len(body), |
| - } |
| - if err := tx.Create(&d).Error; err != nil { |
| - return err |
| + "sibling_revision": spec.SiblingRevision, |
| + }).Error; err != nil { |
| + return err |
| + } |
| + default: |
| + rechunk = true |
| + d := Document{ |
| + Source: spec.Source, |
| + ExternalID: external, |
| + BodyPrint: bodyPrint, |
| + Revision: 1, |
| + SealedTitle: sealedTitle, |
| + SealedBody: sealedBody, |
| + SealedPath: sealedPath, |
| + SiblingItemID: sealedItemID, |
| + SiblingRevision: spec.SiblingRevision, |
| + Bytes: len(body), |
| + } |
| + if err := tx.Create(&d).Error; err != nil { |
| + return err |
| + } |
| + docID = d.ID |
| } |
| - docID = d.ID |
| - } |
| - if !rechunk { |
| - return nil |
| - } |
| - rows := make([]Chunk, 0, len(chunks)) |
| - for _, c := range chunks { |
| - // Seal the body ALONE, not Indexable(): the heading has its |
| - // own indexed column, and sealing heading+body made the |
| - // heading count twice in BM25 and appear at the front of |
| - // every snippet. Found by reading a rendered page. |
| - st, err := s.sealer.Seal(seal.PurposeChunk, []byte(c.Text)) |
| - if err != nil { |
| - return err |
| + if !rechunk { |
| + return nil |
| } |
| - sh, err := s.sealer.Seal(seal.PurposeTitle, []byte(c.Heading())) |
| - if err != nil { |
| - return err |
| + rows := make([]Chunk, 0, len(chunks)) |
| + for _, c := range chunks { |
| + // Seal the body ALONE, not Indexable(): the heading has its |
| + // own indexed column, and sealing heading+body made the |
| + // heading count twice in BM25 and appear at the front of |
| + // every snippet. Found by reading a rendered page. |
| + st, err := s.sealer.Seal(seal.PurposeChunk, []byte(c.Text)) |
| + if err != nil { |
| + return err |
| + } |
| + sh, err := s.sealer.Seal(seal.PurposeTitle, []byte(c.Heading())) |
| + if err != nil { |
| + return err |
| + } |
| + rows = append(rows, Chunk{ |
| + DocumentID: docID, |
| + Ordinal: c.Ordinal, |
| + SealedHeading: sh, |
| + SealedText: st, |
| + }) |
| } |
| - rows = append(rows, Chunk{ |
| - DocumentID: docID, |
| - Ordinal: c.Ordinal, |
| - SealedHeading: sh, |
| - SealedText: st, |
| - }) |
| - } |
| - return tx.Create(&rows).Error |
| + return tx.Create(&rows).Error |
| + }) |
| }) |
| if err != nil { |
| return 0, err |
| @@ -1101,16 +1110,34 @@ func (s *Store) Meta(ctx context.Context, id int64) (source string, revision, by |
| // to commit: a stored document, unfindable until the next boot, and an |
| // error the person is shown. That is the survivable direction, and it is |
| // self-healing — the index is rebuilt from the sealed rows at every boot. |
| +// |
| +// In team mode the person's standing is asked before the index is |
| +// touched, and again inside the transaction before and after the delete |
| +// (team_guard.go). A standing that lapses between the two leaves the |
| +// survivable residual above, and a refusal there puts the document's |
| +// passages back rather than waiting for the next boot: a delete refused |
| +// for standing is not a delete that half happened. |
| func (s *Store) Delete(ctx context.Context, id int64) error { |
| + if err := s.allowed(ctx, memberWrite); err != nil { |
| + return err |
| + } |
| if err := s.ix.RemoveDocument(id); err != nil { |
| return err |
| } |
| - return s.db.G.WithContext(ctx).Transaction(func(tx *gormTx) error { |
| - if err := tx.Where("document_id = ?", id).Delete(&Chunk{}).Error; err != nil { |
| - return err |
| - } |
| - return tx.Where("id = ?", id).Delete(&Document{}).Error |
| + err := s.db.G.WithContext(ctx).Transaction(func(tx *gormTx) error { |
| + return s.guard(ctx, memberWrite, func() error { |
| + if err := tx.Where("document_id = ?", id).Delete(&Chunk{}).Error; err != nil { |
| + return err |
| + } |
| + return tx.Where("id = ?", id).Delete(&Document{}).Error |
| + }) |
| }) |
| + if s.team && isStandingErr(err) { |
| + if reErr := s.indexDocument(context.WithoutCancel(ctx), id); reErr != nil { |
| + return fmt.Errorf("%w (and re-indexing the kept document failed: %v)", err, reErr) |
| + } |
| + } |
| + return err |
| } |
| // IndexFile reports the file backing the index, empty when in memory. |
diff --git a/internal/memoria/sync.go b/internal/memoria/sync.go| index f3ffd69..a0c053c 100644 |
| --- a/internal/memoria/sync.go |
| +++ b/internal/memoria/sync.go |
| @@ -135,6 +135,10 @@ func (s *Syncer) startBeat(ctx context.Context, runID int64, st *runStats) func( |
| // RunWith is Run against a supplied client. |
| func (s *Syncer) RunWith(ctx context.Context, client SourceClient, connectorID, runID int64) { |
| + // The run is the team's import, started by an owner and running on |
| + // for minutes: its writes are not that owner's, and are not bound to |
| + // the lease of the request that started it (team_guard.go). |
| + ctx = systemWrite(ctx) |
| roots, orphans, err := client.Roots(ctx) |
| if err != nil { |
| s.fail(ctx, runID, string(notion.CodeOf(err))) |
diff --git a/internal/memoria/team_access.go b/internal/memoria/team_access.go| new file mode 100644 |
| index 0000000..dca86f6 |
| --- /dev/null |
| +++ b/internal/memoria/team_access.go |
| @@ -0,0 +1,325 @@ |
| +package memoria |
| + |
| +// Team mode's per-request standing. Outside team mode (a.teamMode() |
| +// false) nothing here runs and every gate is the owners list it has |
| +// always been. |
| +// |
| +// Standing itself is home/teammode's Access. Identity is resolved from |
| +// the actual session — a local address the owners list admits, an |
| +// account link, or a Home-only member — and the roster is asked about the |
| +// Home subject, if there is one. The answer is one of three: |
| +// |
| +// - Member: the whole of Memoria, which is all team rung: memoria's |
| +// corpus is the team's, with no per-person rows to reach. The |
| +// roster's role says owner or member, and only the roster's; an owner |
| +// also manages the connectors (requireOwner). |
| +// - NotMember: nothing. Memoria has no shares, so a guest reaches |
| +// nothing and is signed out and told so, exactly as a person taken |
| +// off MEMORIA_OWNERS always has been. The one exception is a local |
| +// account with no Oficina link, which has no standing until it links |
| +// and is sent to /account/home to do that. |
| +// - Unknown: the roster could not be read within its lease. Lists are |
| +// partial with a notice (Paul, 2026-10-28) — and, with no shares, |
| +// empty — and everything else is a retryable 503 rather than a 404 |
| +// that would claim the thing is gone. |
| +// |
| +// A Member decision carries a lease. Access.State checks it every time it |
| +// is asked; a write checks it again inside its own transaction, before |
| +// and after (team_guard.go); a list asks it again after it is built. |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/connect/linkstore" |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + |
| + "amadan.net/oficina/memoria/internal/memoria/teamstate" |
| +) |
| + |
| +// teamPerson is who one request's session speaks for in team mode, and |
| +// their standing. Never stored beyond the request. |
| +type teamPerson struct { |
| + // address is the local address, "" for a Home-only member. |
| + address string |
| + // subject is the Home subject the roster knows them by, "" for a |
| + // local account with no Oficina link (no standing). |
| + subject string |
| + // method is the session's sign-in method. |
| + method string |
| + access *teammode.Access |
| +} |
| + |
| +// unlinkedLocal reports whether p is a local account with no Oficina |
| +// link: identity, but nothing to ask the roster about. |
| +func (p *teamPerson) unlinkedLocal() bool { |
| + return p.subject == "" && (p.method == "magiclink" || p.method == "keymail") |
| +} |
| + |
| +var errNoIdentity = errors.New("memoria: no team identity") |
| + |
| +type teamPersonKey struct{} |
| + |
| +// withTeamPerson carries p, and its Access for the store's guard, on ctx. |
| +func withTeamPerson(ctx context.Context, p *teamPerson) context.Context { |
| + return context.WithValue(teammode.WithAccess(ctx, p.access), teamPersonKey{}, p) |
| +} |
| + |
| +func teamPersonFrom(ctx context.Context) (*teamPerson, bool) { |
| + p, ok := ctx.Value(teamPersonKey{}).(*teamPerson) |
| + return p, ok && p != nil |
| +} |
| + |
| +// teamIdentify resolves a session to the person it speaks for. It reads |
| +// and never creates: a Home subject resolves through its link or its |
| +// Home-only row (connect's Resolve, with the HomeOnly hook), and a local |
| +// session through the owners list and its link. errTeamUnavailable is |
| +// storage that cannot be read now; errNoIdentity a session that speaks |
| +// for nobody here. |
| +func (a *app) teamIdentify(ctx context.Context, s sessions.Session) (teamPerson, error) { |
| + if a.team == nil { |
| + return teamPerson{}, errTeamUnavailable |
| + } |
| + switch s.Method { |
| + case connect.HomeMethod: |
| + if a.home == nil { |
| + return teamPerson{}, errNoIdentity |
| + } |
| + p, err := a.home.bridge.Resolve(ctx, s.Subject) |
| + if errors.Is(err, linkstore.ErrStorage) { |
| + return teamPerson{}, errTeamUnavailable |
| + } |
| + if err != nil { |
| + return teamPerson{}, errNoIdentity |
| + } |
| + return teamPerson{address: p.Label, subject: s.Subject, method: s.Method}, nil |
| + case "magiclink", "keymail": |
| + // MEMORIA_OWNERS, in team mode, admits a local sign-in and |
| + // nothing more: the session still needs the owners list, and its |
| + // standing comes from the roster through its link. |
| + address := normaliseAddress(s.Subject) |
| + if address == "" || !a.Admit(address) { |
| + return teamPerson{}, errNoIdentity |
| + } |
| + p := teamPerson{address: address, method: s.Method} |
| + id, found, err := a.homeLocalID(ctx, address) |
| + if err != nil { |
| + return teamPerson{}, errTeamUnavailable |
| + } |
| + if !found { |
| + return p, nil |
| + } |
| + subject, err := teamstate.LinkedSubject(ctx, a.team.db, a.team.issuer(), id) |
| + switch { |
| + case err == nil: |
| + p.subject = subject |
| + case errors.Is(err, teamstate.ErrRefused): |
| + default: |
| + return teamPerson{}, errTeamUnavailable |
| + } |
| + return p, nil |
| + } |
| + return teamPerson{}, errNoIdentity |
| +} |
| + |
| +// teamResolve is teamIdentify with the roster's answer attached: one |
| +// Access per request, which every later check reads (State latches). |
| +func (a *app) teamResolve(ctx context.Context, s sessions.Session) (*teamPerson, error) { |
| + p, err := a.teamIdentify(ctx, s) |
| + if err != nil { |
| + return nil, err |
| + } |
| + p.access = a.team.Access(ctx, p.subject) |
| + return &p, nil |
| +} |
| + |
| +// teamSession is requireSession's inside in team mode: who the session |
| +// is, and the roster's answer, asked once and carried on the request. |
| +// |
| +// A definite NotMember is signed out and told so (offboard), as a person |
| +// taken off MEMORIA_OWNERS always has been, existing sessions included: |
| +// that is removal within the lease. An unlinked local account is let |
| +// through to the routes that need only a session — /account/home, where |
| +// it links — and the content routes send it there (standing). Unknown |
| +// ends nothing. |
| +func (a *app) teamSession(w http.ResponseWriter, r *http.Request, next http.Handler) { |
| + s, ok := sessions.Current(r) |
| + if !ok && a.sess != nil { |
| + s, ok = a.sess.From(r) |
| + } |
| + if !ok { |
| + a.errorPage(w, r, http.StatusNotFound, kindRoute, "") |
| + return |
| + } |
| + p, err := a.teamResolve(r.Context(), s) |
| + switch { |
| + case errors.Is(err, errTeamUnavailable): |
| + a.teamUnavailable(w, r) |
| + return |
| + case err != nil: |
| + a.offboard(w, r) |
| + return |
| + } |
| + if p.access.State() == roster.NotMember && !p.unlinkedLocal() { |
| + a.offboard(w, r) |
| + return |
| + } |
| + next.ServeHTTP(w, r.WithContext(withTeamPerson(r.Context(), p))) |
| +} |
| + |
| +// standingNeed is what a route needs of the roster. |
| +type standingNeed int |
| + |
| +const ( |
| + // needMember: Member. Unknown is a retryable 503. Item pages, the |
| + // add page, the correction page, the AI answer, every write. |
| + needMember standingNeed = iota |
| + // needListing: a list page. Unknown renders it partial, with the |
| + // notice; the handler asks again after building it (teamPartial). |
| + needListing |
| + // needOwner: Member with the roster's owner role (the connectors). |
| + // A member is the same 404 as an unknown route, as before. |
| + needOwner |
| +) |
| + |
| +// standing is the content routes' gate, inside requireSession. Outside |
| +// team mode it is no gate at all. |
| +func (a *app) standing(need standingNeed) func(http.Handler) http.Handler { |
| + return func(next http.Handler) http.Handler { |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if !a.teamMode() || a.allowUnauthenticated { |
| + next.ServeHTTP(w, r) |
| + return |
| + } |
| + p, ok := teamPersonFrom(r.Context()) |
| + if !ok { |
| + // requireSession puts the person on every request that |
| + // reaches here; a route outside it is a wiring bug, and |
| + // the closed answer is the one that cannot leak. |
| + a.teamUnavailable(w, r) |
| + return |
| + } |
| + switch p.access.State() { |
| + case roster.Member: |
| + if need == needOwner && p.access.Role() != rosterOwner { |
| + if p.access.State() == roster.Unknown { |
| + a.teamUnavailable(w, r) |
| + return |
| + } |
| + a.errorPage(w, r, http.StatusNotFound, kindRoute, "") |
| + return |
| + } |
| + case roster.NotMember: |
| + // Only an unlinked local account gets this far |
| + // (teamSession): it has no standing until it links. |
| + if r.Method == http.MethodGet || r.Method == http.MethodHead { |
| + w.Header().Set("Cache-Control", "no-store") |
| + http.Redirect(w, r, "/account/home", http.StatusSeeOther) |
| + return |
| + } |
| + a.errorPage(w, r, http.StatusNotFound, kindRoute, "") |
| + return |
| + default: |
| + if need != needListing { |
| + a.teamUnavailable(w, r) |
| + return |
| + } |
| + } |
| + next.ServeHTTP(w, r) |
| + }) |
| + } |
| +} |
| + |
| +// teamReaches reports whether this request may list the team's memory: |
| +// always outside team mode, and inside it only while the roster says |
| +// Member. Asked BEFORE building a list, so a list is never built on |
| +// standing the request does not have (Sheets' stream-order lesson: read |
| +// standing before deciding reach). |
| +func (a *app) teamReaches(r *http.Request) bool { |
| + if a.allowUnauthenticated && a.previewUnknown { |
| + return false |
| + } |
| + if !a.teamMode() || a.allowUnauthenticated { |
| + return true |
| + } |
| + p, ok := teamPersonFrom(r.Context()) |
| + return ok && p.access.State() == roster.Member |
| +} |
| + |
| +// teamPartial reports whether a list built for this request is |
| +// incomplete because standing is Unknown: Paul's ruling (2026-10-28, |
| +// Home implementation/teammode-package.md §4) is a partial list with a |
| +// notice, not a 503. Asked AFTER building the list, of the same Access: |
| +// State latches, so a lease that lapsed while listing marks the page |
| +// partial — and the caller then withholds what it built, since everything |
| +// Memoria lists stood on the team rung. NotMember is never partial (it |
| +// never reaches a list). Always false outside team mode. |
| +func (a *app) teamPartial(r *http.Request) bool { |
| + if a.allowUnauthenticated && a.previewUnknown { |
| + return true |
| + } |
| + if !a.teamMode() || a.allowUnauthenticated { |
| + return false |
| + } |
| + p, ok := teamPersonFrom(r.Context()) |
| + return !ok || p.access.Partial() |
| +} |
| + |
| +// teamOwner reports whether the roster says this request's person is one |
| +// of the team's owners, now. |
| +func (a *app) teamOwner(r *http.Request) bool { |
| + p, ok := teamPersonFrom(r.Context()) |
| + return ok && p.access.Role() == rosterOwner |
| +} |
| + |
| +// teamAdmission is admissionOf in team mode: the request's own person if |
| +// requireSession already resolved one, else the session resolved and |
| +// asked about now. It never ends a session itself. |
| +func (a *app) teamAdmission(r *http.Request, s sessions.Session) (viewer, admission) { |
| + p, ok := teamPersonFrom(r.Context()) |
| + if !ok { |
| + if a.team == nil { |
| + return viewer{}, unresolved |
| + } |
| + var err error |
| + p, err = a.teamResolve(r.Context(), s) |
| + switch { |
| + case errors.Is(err, errTeamUnavailable): |
| + return viewer{}, unresolved |
| + case err != nil: |
| + return viewer{}, removed |
| + } |
| + } |
| + if p.access.State() == roster.NotMember && !p.unlinkedLocal() { |
| + return viewer{}, removed |
| + } |
| + label := p.address |
| + if label == "" { |
| + label = homeOnlyLabel(p.subject) |
| + } |
| + return viewer{address: label, method: p.method, ok: true, owner: p.access.Role() == rosterOwner}, admitted |
| +} |
| + |
| +// teamLabel is how a Home-only member, who has no address, is shown where |
| +// an address would be: the account menu. |
| +const teamLabel = "Oficina account" |
| + |
| +// homeOnlyLabel is teamLabel and the last four characters of the person |
| +// ref ("Oficina account …k7qz"), as Home's Team page shows a ref. |
| +func homeOnlyLabel(subject string) string { |
| + if len(subject) <= 4 { |
| + return teamLabel |
| + } |
| + return teamLabel + " …" + subject[len(subject)-4:] |
| +} |
| + |
| +// PreviewUnknownStanding makes the lists render as they do in team mode |
| +// under Unknown standing — partial, with the notice — so tools/drive can |
| +// show the pages a browser would. AppForTest only: it does nothing unless |
| +// the app was built through that constructor, and production never calls |
| +// it (TestProductionDoesNotUseTheTestConstructor). |
| +func (a *app) PreviewUnknownStanding() { a.previewUnknown = true } |
diff --git a/internal/memoria/team_access_test.go b/internal/memoria/team_access_test.go| new file mode 100644 |
| index 0000000..3eaa419 |
| --- /dev/null |
| +++ b/internal/memoria/team_access_test.go |
| @@ -0,0 +1,489 @@ |
| +package memoria |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/suite" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| +) |
| + |
| +// partialMark is the partial notice's title as a page renders it. |
| +var partialMark = strings.ReplaceAll(partialTitle, "’", "’") |
| + |
| +func isPartial(body string) bool { |
| + return strings.Contains(body, partialTitle) || strings.Contains(body, partialMark) |
| +} |
| + |
| +// A roster member with no account here signs in with Home alone: an |
| +// addressless person, the team's memory, and the chrome of a signed-in |
| +// person named by their person ref. |
| +func TestTeamHomeOnlyMemberSignsInAndReachesTheTeamsMemory(t *testing.T) { |
| + f := newTeamFixture(t) |
| + doc := f.ingest("plan", "Nebula plan", "The nebula plan is ready.") |
| + f.member(teamSubject('a'), "member") |
| + |
| + var lookup string |
| + var sealed []byte |
| + var person int64 |
| + if err := f.d.Writer().QueryRow("SELECT person_id FROM memoria_team_home_members WHERE subject=?", teamSubject('a')).Scan(&person); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.d.Writer().QueryRow("SELECT address_lookup, address_sealed FROM memoria_home_local_identities WHERE id=?", person).Scan(&lookup, &sealed); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(sealed) != 0 || !strings.HasPrefix(lookup, "home-only:") { |
| + t.Fatalf("Home-only person row = %q, %d sealed bytes; want no address at all", lookup, len(sealed)) |
| + } |
| + |
| + w := f.page("/?q=nebula") |
| + body := w.Body.String() |
| + if w.Code != 200 || !strings.Contains(body, "Nebula plan") || isPartial(body) { |
| + t.Fatalf("member search = %d, want the team's document and no partial notice:\n%s", w.Code, body) |
| + } |
| + if want := "Oficina account …" + teamSubject('a')[len(teamSubject('a'))-4:]; homeOnlyLabel(teamSubject('a')) != want { |
| + t.Fatalf("Home-only label = %q, want %q", homeOnlyLabel(teamSubject('a')), want) |
| + } |
| + if !strings.Contains(body, `action="/signout"`) || !strings.Contains(body, homeOnlyLabel(teamSubject('a'))) { |
| + t.Fatalf("Home-only member's chrome is not signed in as %q", homeOnlyLabel(teamSubject('a'))) |
| + } |
| + if got := f.page("/documents/" + itoa64(doc)); got.Code != 200 { |
| + t.Fatalf("document = %d", got.Code) |
| + } |
| + // A member searches and reads; the connectors are an owner's. |
| + if got := f.page("/connectors"); got.Code != 404 { |
| + t.Fatalf("a member's /connectors = %d, want 404", got.Code) |
| + } |
| + if strings.Contains(body, `href="/connectors"`) { |
| + t.Fatal("a member is shown Sources") |
| + } |
| +} |
| + |
| +// Allocation only for a current Member: a stranger is connect's |
| +// "unknown", an undecidable roster is a 503, and a live session for |
| +// somebody else is refused before anything is allocated. |
| +func TestTeamSignInAllocatesOnlyForACurrentMember(t *testing.T) { |
| + f := newTeamFixture(t, "x@example.test") |
| + people := f.count("memoria_home_local_identities") |
| + |
| + if got := f.freshSignIn(teamSubject('s')); got.Code != http.StatusForbidden { |
| + t.Fatalf("stranger = %d, want connect's 403", got.Code) |
| + } |
| + if f.count("memoria_home_local_identities") != people { |
| + t.Fatal("a stranger was allocated a person") |
| + } |
| + |
| + f.dir.Set(teamSubject('u'), "member") |
| + f.expired() |
| + if got := f.freshSignIn(teamSubject('u')); got.Code != http.StatusServiceUnavailable { |
| + t.Fatalf("Unknown roster = %d, want 503", got.Code) |
| + } |
| + if f.count("memoria_home_local_identities") != people { |
| + t.Fatal("an undecidable roster allocated a person") |
| + } |
| + f.renewed() |
| + |
| + f.cookies = map[string]*http.Cookie{} |
| + f.localSession("x@example.test") |
| + if got := f.signIn(teamSubject('u')); got.Code != http.StatusForbidden { |
| + t.Fatalf("member arriving over another session = %d, want 403", got.Code) |
| + } |
| + if f.count("memoria_team_home_members") != 0 { |
| + t.Fatal("an arrival over a live session allocated a person") |
| + } |
| +} |
| + |
| +// A known Home-only member arriving over somebody else's live session is |
| +// connect's same-person refusal, and that session survives. |
| +func TestTeamKnownArrivalOverAnotherSessionIsRefused(t *testing.T) { |
| + f := newTeamFixture(t, "x@example.test") |
| + f.member(teamSubject('a'), "member") |
| + f.cookies = map[string]*http.Cookie{} |
| + f.localSession("x@example.test") |
| + name := f.app.home.sessions.CookieName() |
| + before := f.cookies[name].Value |
| + if got := f.signIn(teamSubject('a')); got.Code != http.StatusForbidden { |
| + t.Fatalf("known arrival over another session = %d, want 403", got.Code) |
| + } |
| + if f.cookies[name] == nil || f.cookies[name].Value != before { |
| + t.Fatal("the local session was replaced") |
| + } |
| + if s, ok := f.sessionNow(); !ok || s.Subject != "x@example.test" { |
| + t.Fatalf("session now = %+v, want the local one", s) |
| + } |
| +} |
| + |
| +// Removal reaches an existing session within the lease: Memoria has no |
| +// shares, so a person off the roster reaches nothing — signed out and |
| +// told so, as a person taken off MEMORIA_OWNERS always has been. |
| +func TestTeamRemovalEndsAnExistingSession(t *testing.T) { |
| + f := newTeamFixture(t) |
| + doc := f.ingest("plan", "Nebula plan", "The nebula plan is ready.") |
| + f.member(teamSubject('a'), "member") |
| + if got := f.page("/documents/" + itoa64(doc)); got.Code != 200 { |
| + t.Fatalf("before removal = %d", got.Code) |
| + } |
| + f.dir.Set(teamSubject('a'), "") |
| + f.refreshed() |
| + w := f.page("/documents/" + itoa64(doc)) |
| + if w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/signin?err=removed" { |
| + t.Fatalf("after removal = %d %q, want the removed sign-out", w.Code, w.Header().Get("Location")) |
| + } |
| + if _, ok := f.sessionNow(); ok { |
| + t.Fatal("a removed member kept their session") |
| + } |
| + // The sign-in page asks too, before connect's shortcut sends a live |
| + // session on to a page that refuses it. |
| + f.member(teamSubject('c'), "member") |
| + f.dir.Set(teamSubject('c'), "") |
| + f.refreshed() |
| + if w := f.page("/signin"); w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/signin?err=removed" { |
| + t.Fatalf("a removed member's /signin = %d %q, want the removed sign-out", w.Code, w.Header().Get("Location")) |
| + } |
| + // NotMember is never partial: there is no list to be short. |
| + f.member(teamSubject('b'), "member") |
| + f.dir.Set(teamSubject('b'), "") |
| + f.refreshed() |
| + if w := f.page("/?q=nebula"); w.Code != http.StatusSeeOther || isPartial(w.Body.String()) { |
| + t.Fatalf("a removed member's list = %d, partial %v", w.Code, isPartial(w.Body.String())) |
| + } |
| + // Signing in again finds the same Home-only person — identity, not |
| + // standing — and the first page asks the roster and signs them out |
| + // again. Nothing is allocated. |
| + people := f.count("memoria_home_local_identities") |
| + if got := f.freshSignIn(teamSubject('a')); got.Code != http.StatusSeeOther { |
| + t.Fatalf("removed member signing in again = %d, want connect's completion", got.Code) |
| + } |
| + if w := f.page("/"); w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/signin?err=removed" { |
| + t.Fatalf("removed member's page after signing in again = %d %q", w.Code, w.Header().Get("Location")) |
| + } |
| + if f.count("memoria_home_local_identities") != people { |
| + t.Fatal("signing in again allocated a person") |
| + } |
| +} |
| + |
| +// The role is the roster's, and MEMORIA_OWNERS admits a local sign-in and |
| +// nothing more: an owners-list address with no Oficina link has no |
| +// standing and is sent to link; a roster owner manages the connectors and |
| +// a roster member does not. |
| +func TestTeamStandingIsTheRostersNeverTheOwnersLists(t *testing.T) { |
| + f := newTeamFixture(t, "local@example.test") |
| + f.ingest("plan", "Nebula plan", "The nebula plan is ready.") |
| + |
| + f.cookies = map[string]*http.Cookie{} |
| + f.localSession("local@example.test") |
| + w := f.page("/?q=nebula") |
| + if w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/account/home" { |
| + t.Fatalf("unlinked owners-list address = %d %q, want /account/home", w.Code, w.Header().Get("Location")) |
| + } |
| + if strings.Contains(w.Body.String(), "Nebula plan") { |
| + t.Fatal("an unlinked local account saw the team's memory") |
| + } |
| + if got := f.page("/connectors"); got.Code != http.StatusSeeOther { |
| + t.Fatalf("unlinked owners-list address on /connectors = %d", got.Code) |
| + } |
| + if got := f.form("/documents", "title=x&body=y"); got.Code != 404 { |
| + t.Fatalf("unlinked owners-list address writing = %d, want 404", got.Code) |
| + } |
| + if _, ok := f.sessionNow(); !ok { |
| + t.Fatal("an unlinked local account was signed out before it could link") |
| + } |
| + if got := f.page("/account/home"); got.Code != 200 { |
| + t.Fatalf("the link page for an unlinked local account = %d", got.Code) |
| + } |
| + |
| + f.member(teamSubject('o'), "owner") |
| + if got := f.page("/connectors"); got.Code != 200 || !strings.Contains(f.page("/").Body.String(), `href="/connectors"`) { |
| + t.Fatalf("a roster owner's /connectors = %d", got.Code) |
| + } |
| + f.member(teamSubject('m'), "member") |
| + if got := f.page("/connectors"); got.Code != 404 { |
| + t.Fatalf("a roster member's /connectors = %d, want 404", got.Code) |
| + } |
| + if got := f.form("/connectors/notion/disconnect", ""); got.Code != 404 { |
| + t.Fatalf("a roster member's connector write = %d, want 404", got.Code) |
| + } |
| + // A role change reaches an existing session within the lease. |
| + f.member(teamSubject('o'), "owner") |
| + f.dir.Set(teamSubject('o'), "member") |
| + f.refreshed() |
| + if got := f.page("/connectors"); got.Code != 404 { |
| + t.Fatalf("a demoted owner's /connectors = %d, want 404", got.Code) |
| + } |
| +} |
| + |
| +// A linked local account stands on the roster: its Home session and its |
| +// local session ask as one person, by its Home subject, and the owners |
| +// list no longer decides its Home sign-in. |
| +func TestTeamLinkedAccountStandsOnTheRoster(t *testing.T) { |
| + f := newTeamFixture(t, "alice@example.test") |
| + custody := &fixedCustody{apps: docsRoster(), give: suite.VISIBLE} |
| + f.app.store.custody = custody |
| + f.ingest("plan", "Nebula plan", "The nebula plan is ready.") |
| + if _, err := f.app.store.Ingest(systemWrite(context.Background()), IngestSpec{Source: "Docs", Key: "s", Title: "Shared nebula", Body: "nebula sibling content", ItemID: "doc-one", SiblingRevision: 3}); err != nil { |
| + t.Fatal(err) |
| + } |
| + subject := teamSubject('l') |
| + f.dir.Set(subject, "member") |
| + f.refreshed() |
| + f.local(t) |
| + if got := f.linkFromMenu(t, subject); got.Code != http.StatusSeeOther { |
| + t.Fatalf("link = %d %s", got.Code, got.Body.String()) |
| + } |
| + if w := f.page("/?q=nebula"); w.Code != 200 || !strings.Contains(w.Body.String(), "Nebula plan") { |
| + t.Fatalf("linked local session = %d", w.Code) |
| + } |
| + if custody.asker != (suite.Subject{Kind: suite.SubjectPersonRef, Value: subject}) { |
| + t.Fatalf("a linked local session asks as %+v, want its person ref", custody.asker) |
| + } |
| + // On MEMORIA_OWNERS and a roster member: the owners list makes no |
| + // owner in team mode, in the bar or at the route. |
| + if w := f.page("/"); strings.Contains(w.Body.String(), `href="/connectors"`) { |
| + t.Fatal("a roster member on the owners list is shown Sources") |
| + } |
| + if got := f.page("/connectors"); got.Code != 404 { |
| + t.Fatalf("a roster member on the owners list: /connectors = %d, want 404", got.Code) |
| + } |
| + // Off the roster, the LOCAL session is signed out too: a linked |
| + // account is not an unlinked one, whatever its sign-in method. |
| + localJar := map[string]*http.Cookie{} |
| + for k, v := range f.cookies { |
| + localJar[k] = v |
| + } |
| + f.dir.Set(subject, "") |
| + f.refreshed() |
| + if w := f.page("/"); w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/signin?err=removed" { |
| + t.Fatalf("linked local session off the roster = %d %q, want the removed sign-out", w.Code, w.Header().Get("Location")) |
| + } |
| + if _, ok := f.sessionNow(); ok { |
| + t.Fatal("a linked local session off the roster kept its session") |
| + } |
| + f.dir.Set(subject, "member") |
| + f.refreshed() |
| + // Off the owners list: the Home session still stands on the roster. |
| + f.app.SetOwners(nil) |
| + if got := f.freshSignIn(subject); got.Code != http.StatusSeeOther { |
| + t.Fatalf("linked Home sign-in off the owners list = %d", got.Code) |
| + } |
| + if w := f.page("/?q=nebula"); w.Code != 200 || !strings.Contains(w.Body.String(), "Nebula plan") { |
| + t.Fatalf("linked Home session off the owners list = %d", w.Code) |
| + } |
| + // Off the roster: nothing, owners list or not. |
| + f.app.SetOwners([]string{"alice@example.test"}) |
| + f.dir.Set(subject, "") |
| + f.refreshed() |
| + if w := f.page("/"); w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/signin?err=removed" { |
| + t.Fatalf("linked account off the roster = %d %q", w.Code, w.Header().Get("Location")) |
| + } |
| +} |
| + |
| +// A held decision ends at the lease under a failing refresh: 59 s still |
| +// a member, 61 s a retryable no-store 503 rather than a 404 — for a |
| +// document that does not exist too, so there is no oracle. |
| +func TestTeamStandingEndsAtTheLeaseUnderAFailingRefresh(t *testing.T) { |
| + f := newTeamFixture(t) |
| + doc := f.ingest("plan", "Nebula plan", "The nebula plan is ready.") |
| + f.member(teamSubject('a'), "member") |
| + f.dir.SetDown(true) |
| + f.clock.Step(59 * time.Second) |
| + if got := f.page("/documents/" + itoa64(doc)); got.Code != 200 { |
| + t.Fatalf("at 59 s = %d, want 200", got.Code) |
| + } |
| + f.clock.Step(2 * time.Second) |
| + got := f.page("/documents/" + itoa64(doc)) |
| + if got.Code != http.StatusServiceUnavailable || got.Header().Get("Retry-After") == "" || got.Header().Get("Cache-Control") != "no-store" { |
| + t.Fatalf("at 61 s = %d %v, want a retryable no-store 503", got.Code, got.Header()) |
| + } |
| + if got := f.page("/documents/999999"); got.Code != http.StatusServiceUnavailable { |
| + t.Fatalf("missing document under Unknown = %d, want 503", got.Code) |
| + } |
| + if _, ok := f.sessionNow(); !ok { |
| + t.Fatal("Unknown signed the person out") |
| + } |
| +} |
| + |
| +// Unknown: every list is partial with the notice and holds nothing (there |
| +// are no shares to fall back on); every item, the add page, the |
| +// correction page and the connectors are a retryable 503; the native |
| +// API's JSON list, which cannot carry the notice, is a 503 too. |
| +func TestTeamUnknownListsArePartialAndItemsAreRetryable(t *testing.T) { |
| + f := newTeamFixture(t) |
| + doc := f.ingest("plan", "Nebula plan", "The nebula plan is ready.") |
| + f.member(teamSubject('a'), "owner") |
| + f.expired() |
| + |
| + for _, path := range []string{"/?q=nebula", "/", "/reports"} { |
| + w := f.page(path) |
| + body := w.Body.String() |
| + if w.Code != 200 || !isPartial(body) || strings.Contains(body, "Nebula plan") { |
| + t.Fatalf("Unknown %s = %d, want the partial notice and nothing listed:\n%s", path, w.Code, body) |
| + } |
| + if strings.Count(body, partialBody) != 1 { |
| + t.Fatalf("Unknown %s carries the notice %d times", path, strings.Count(body, partialBody)) |
| + } |
| + } |
| + frag := f.do("GET", "/search?q=nebula", "") |
| + if frag.Code != 200 || !isPartial(frag.Body.String()) || strings.Contains(frag.Body.String(), "Nebula plan") { |
| + t.Fatalf("Unknown search fragment = %d:\n%s", frag.Code, frag.Body.String()) |
| + } |
| + for _, path := range []string{"/documents/" + itoa64(doc), "/documents/" + itoa64(doc) + "/delete", "/add", "/facts/correct?q=nebula", "/answer?q=nebula", "/connectors", "/connectors/notion", "/answer/feedback/1", "/api/native/session"} { |
| + got := f.page(path) |
| + if got.Code != http.StatusServiceUnavailable || got.Header().Get("Retry-After") == "" || got.Header().Get("Cache-Control") != "no-store" { |
| + t.Fatalf("Unknown %s = %d %v, want a retryable no-store 503", path, got.Code, got.Header()) |
| + } |
| + // The 503 page wears the person's chrome, and its footer does not |
| + // count a corpus they cannot currently reach. |
| + if b := got.Body.String(); strings.Contains(b, "passages indexed") || strings.Contains(b, "passage indexed") { |
| + t.Fatalf("Unknown %s's 503 page states the passage count", path) |
| + } |
| + } |
| + native := f.json("POST", "/api/native/search", `{"query":"nebula"}`) |
| + if native.Code != http.StatusServiceUnavailable || native.Header().Get("Cache-Control") != "no-store" || strings.Contains(native.Body.String(), "Nebula") { |
| + t.Fatalf("Unknown native search = %d %s, want 503", native.Code, native.Body.String()) |
| + } |
| +} |
| + |
| +// Fable's #53 required test 3, for Memoria: under Unknown the list is |
| +// empty — always, here — and says partial, never "nothing stored", "no |
| +// matches" or "no corrections", and never states a passage count. |
| +func TestTeamEmptyPartialListSaysPartialNotEmpty(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.ingest("plan", "Nebula plan", "The nebula plan is ready.") |
| + f.member(teamSubject('a'), "member") |
| + f.expired() |
| + for path, empty := range map[string][]string{ |
| + "/": {"Nothing stored yet", "0 documents"}, |
| + "/?q=nebula": {"No matches", "Nothing stored yet", "0 documents"}, |
| + "/reports": {"No corrections yet", "No ratings yet"}, |
| + } { |
| + w := f.page(path) |
| + body := w.Body.String() |
| + if w.Code != 200 || !isPartial(body) { |
| + t.Fatalf("empty Unknown %s = %d, want the partial notice:\n%s", path, w.Code, body) |
| + } |
| + for _, s := range empty { |
| + if strings.Contains(body, s) { |
| + t.Errorf("empty Unknown %s says %q", path, s) |
| + } |
| + } |
| + if strings.Contains(body, "passage indexed") || strings.Contains(body, "passages indexed") { |
| + t.Errorf("Unknown %s states the corpus's passage count", path) |
| + } |
| + } |
| +} |
| + |
| +// A storage failure resolving the session's identity is a retryable 503, |
| +// never a sign-out. |
| +func TestTeamIdentityStorageFailureIsUnavailableNotSignOut(t *testing.T) { |
| + f := newTeamFixture(t, "x@example.test") |
| + if _, _, err := f.app.ensureHomeLocalIdentity(context.Background(), sessionFor("x@example.test")); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.localSession("x@example.test") |
| + broken, err := sql.Open("sqlite", "file:closed?mode=memory") |
| + if err == nil { |
| + broken.Close() |
| + } |
| + real := f.app.team.db |
| + f.app.team.db = broken |
| + got := f.page("/") |
| + f.app.team.db = real |
| + if got.Code != http.StatusServiceUnavailable { |
| + t.Fatalf("identity storage failure = %d, want 503", got.Code) |
| + } |
| + if _, ok := f.sessionNow(); !ok { |
| + t.Fatal("a storage failure signed the person out") |
| + } |
| +} |
| + |
| +// connect's HomeOnly hook: a storage failure is not "nobody". |
| +func TestTeamHomeOnlyStorageFailureIsNotNobody(t *testing.T) { |
| + f := newTeamFixture(t) |
| + broken, err := sql.Open("sqlite", "file:closed2?mode=memory") |
| + if err == nil { |
| + broken.Close() |
| + } |
| + _, err = f.app.teamHomeOnly(broken)(context.Background(), homeTestIssuer, teamSubject('a')) |
| + if err == nil || errors.Is(err, connect.ErrNoPerson) { |
| + t.Fatalf("HomeOnly over broken storage = %v, want an error that is not ErrNoPerson", err) |
| + } |
| +} |
| + |
| +// A Home-only person keeps no address, ever: the row cannot be given one, |
| +// deleted, linked to, or re-pointed, and the members table cannot be |
| +// rewritten. |
| +func TestTeamHomeOnlyPersonCannotGainAnAddress(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.member(teamSubject('a'), "member") |
| + var person int64 |
| + if err := f.d.Writer().QueryRow("SELECT person_id FROM memoria_team_home_members WHERE subject=?", teamSubject('a')).Scan(&person); err != nil { |
| + t.Fatal(err) |
| + } |
| + for name, stmt := range map[string]string{ |
| + "address": "UPDATE memoria_home_local_identities SET address_sealed=X'01' WHERE id=?", |
| + "lookup": "UPDATE memoria_home_local_identities SET address_lookup='abc' WHERE id=?", |
| + "delete": "DELETE FROM memoria_home_local_identities WHERE id=?", |
| + "link": "INSERT INTO home_identity_links(issuer,subject,person_id) VALUES('" + homeTestIssuer + "','pr_other',?)", |
| + "re-point": "UPDATE memoria_team_home_members SET person_id=person_id WHERE person_id=?", |
| + "forget": "DELETE FROM memoria_team_home_members WHERE person_id=?", |
| + } { |
| + if _, err := f.d.Writer().Exec(stmt, person); err == nil { |
| + t.Errorf("%s: the trigger let it through", name) |
| + } |
| + } |
| + // With foreign keys off, as an operator's sqlite3 shell has them, the |
| + // triggers still hold the row. |
| + w := f.d.Writer() |
| + if _, err := w.Exec("PRAGMA foreign_keys=OFF"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := w.Exec("DELETE FROM memoria_home_local_identities WHERE id=?", person); err == nil { |
| + t.Error("delete with foreign keys off: the trigger let it through") |
| + } |
| + if _, err := w.Exec("PRAGMA foreign_keys=ON"); err != nil { |
| + t.Fatal(err) |
| + } |
| + // And a person with an address cannot be made Home-only. |
| + res, err := w.Exec("INSERT INTO memoria_home_local_identities(address_lookup,address_sealed) VALUES('abc',X'01')") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + addressful, _ := res.LastInsertId() |
| + if _, err := w.Exec("INSERT INTO memoria_team_home_members(issuer,subject,person_id) VALUES(?,?,?)", homeTestIssuer, teamSubject('n'), addressful); err == nil { |
| + t.Error("an addressful person was made Home-only") |
| + } |
| + res, err = w.Exec("INSERT INTO memoria_home_local_identities(address_lookup,address_sealed) VALUES('home-only:sealed',X'01')") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + prefixed, _ := res.LastInsertId() |
| + if _, err := w.Exec("INSERT INTO memoria_team_home_members(issuer,subject,person_id) VALUES(?,?,?)", homeTestIssuer, teamSubject('n'), prefixed); err == nil { |
| + t.Error("a person with a sealed address was made Home-only") |
| + } |
| + if _, err := w.Exec("INSERT INTO memoria_team_home_members(issuer,subject,person_id) VALUES(?,?,?)", homeTestIssuer, teamSubject('n'), person+1000); err == nil { |
| + t.Error("a Home-only member was given a person that does not exist") |
| + } |
| +} |
| + |
| +// json is a same-origin JSON request, as the native client makes one. |
| +func (f *teamFixture) json(method, path, body string) *httptest.ResponseRecorder { |
| + r := httptest.NewRequest(method, homeTestOrigin+path, strings.NewReader(body)) |
| + r.Header.Set("Content-Type", "application/json") |
| + r.Header.Set("Origin", homeTestOrigin) |
| + for _, c := range f.cookies { |
| + r.AddCookie(c) |
| + } |
| + return f.send(r) |
| +} |
| + |
| +// sessionFor is a fresh local session for address. |
| +func sessionFor(address string) sessions.Session { |
| + return sessions.Session{Subject: address, Method: "magiclink", AuthTime: time.Now()} |
| +} |
diff --git a/internal/memoria/team_answers.go b/internal/memoria/team_answers.go| new file mode 100644 |
| index 0000000..30ed17d |
| --- /dev/null |
| +++ b/internal/memoria/team_answers.go |
| @@ -0,0 +1,60 @@ |
| +package memoria |
| + |
| +// Team mode's answers: the retryable 503 for Unknown standing and the |
| +// partial-list notice. Neither is reached outside team mode. |
| + |
| +import ( |
| + "net/http" |
| + "strconv" |
| + "time" |
| + |
| + "amadan.net/oficina/home/roster" |
| +) |
| + |
| +// teamUnavailable is the retryable answer for Unknown standing: the app's |
| +// own 503 page (or the plain status for anything that did not ask for a |
| +// page — the native API, the search fragment's fetch), never cached, with |
| +// Retry-After. A 404 would tell a team member a document is gone because |
| +// Home was slow. |
| +// |
| +// no-store is errorPage's, on the page and the plain answer alike; the |
| +// tests assert it on every one of these. |
| +func (a *app) teamUnavailable(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Retry-After", strconv.Itoa(int(roster.RetryAfter/time.Second))) |
| + a.errorPage(w, r, http.StatusServiceUnavailable, kindStatus, "") |
| +} |
| + |
| +// The partial notice (Paul, 2026-10-28): what a list page says when the |
| +// roster could not be read within its lease. Memoria has no shares, so the |
| +// partial list is always empty — and the notice is what keeps that from |
| +// reading as "nothing matched" or "nothing stored", which this codebase |
| +// treats as the worst failure shape it has. |
| +const ( |
| + partialTitle = "We couldn’t check your team access" |
| + partialBody = "Nothing from the team’s memory can be shown until it’s checked. Try again in a moment." |
| +) |
| + |
| +// partialNotice is the notice's two sentences, for the templates. |
| +type partialNotice struct{ Title, Body string } |
| + |
| +func (page) PartialNotice() partialNotice { return partialNotice{partialTitle, partialBody} } |
| + |
| +// withhold empties every list on p built from the team's memory and marks |
| +// it partial: what a list page shows when teamPartial says the standing |
| +// it was built on did not hold to the end. Everything Memoria lists is the |
| +// team rung, so nothing survives it. |
| +func (p *page) withhold() { |
| + p.Partial = true |
| + p.Results, p.Documents, p.Notices = nil, nil, nil |
| + p.Facts, p.Explained, p.FactsDeferred = nil, nil, false |
| + p.AnswerSlot, p.Answer = false, nil |
| + p.Primed = false |
| + p.Chunks = -1 |
| +} |
| + |
| +// withhold is page.withhold for the reports page, whose two lists are its |
| +// own. |
| +func (p *reportsPage) withhold() { |
| + p.page.withhold() |
| + p.Reports, p.Feedback = nil, nil |
| +} |
diff --git a/internal/memoria/team_config.go b/internal/memoria/team_config.go| new file mode 100644 |
| index 0000000..6bdd831 |
| --- /dev/null |
| +++ b/internal/memoria/team_config.go |
| @@ -0,0 +1,152 @@ |
| +package memoria |
| + |
| +// Team mode: Home's roster decides standing (Home implementation/ |
| +// team-members.md Part B §7; implementation/teammode-package.md §7.2). |
| +// Configuration, the marker, the roster runtime and the probe are |
| +// home/teammode's: MEMORIA_TEAM_ID, _DIRECTORY_ORIGIN, |
| +// _PROVISIONING_BASE64, _OPERATOR_KEYS_BASE64 and _ROSTER_TOKEN, all or |
| +// none, and only beside MEMORIA_HOME_*. Without them nothing in this file |
| +// runs and Memoria is the owners-list app it has always been. |
| +// |
| +// Not MEMORIA_TEAM. That is the sibling transport's host label (§6.4), a |
| +// different thing with an unfortunately close name; team_siblings.go is |
| +// where the two meet. |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "net/http" |
| + |
| + "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/roster" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + |
| + "amadan.net/oficina/memoria/internal/memoria/teamstate" |
| +) |
| + |
| +var ( |
| + errTeamConfig = teammode.ErrConfig |
| + errTeamUnavailable = teammode.ErrUnavailable |
| +) |
| + |
| +// homeNamespace is Memoria's Home storage namespace: connect's link and |
| +// handoff sealing (WireHome), and in team mode the roster evidence's. |
| +const homeNamespace = "oficina/memoria" |
| + |
| +// teamState is the activation marker and the roster evidence, in |
| +// memoria_team_required and memoria_team_roster_evidence (migration set |
| +// memoria_team, teammode's own SQL). The marker is read before anything |
| +// migrates (teamBootSchema). |
| +var teamState = teammode.MustState("memoria") |
| + |
| +// teamIssuerTables are the tables holding Home identities in an issuer |
| +// column: connect's links and Memoria's Home-only members. teammode.Open |
| +// refuses activation while any row names another issuer. |
| +var teamIssuerTables = []string{"home_identity_links", "memoria_team_home_members"} |
| + |
| +// homeSchema is what WireHome applies: Memoria's Home identity rows, |
| +// handoff's pending exchanges and connect's links. |
| +func homeSchema() *migrate.Set { |
| + return migrate.Merge(homeIdentitySchema, migrate.MustFromFS(handoff.Migrations, "oficina_handoff"), migrate.MustFromFS(linkstore.Migrations, linkstore.SchemaNamespace)) |
| +} |
| + |
| +// teamBoot is base plus team state: the Home schema (applied here rather |
| +// than waiting for WireHome, because the Home-only table's triggers name |
| +// its tables), teammode's marker set, then Memoria's Home-only members. |
| +// Applied only in team mode; once applied it stays, because the marker in |
| +// it is what keeps the database in team mode. WireHome's own apply of the |
| +// Home schema afterwards finds every migration already recorded. |
| +func teamBoot(base *migrate.Set) *migrate.Set { |
| + return migrate.Merge(base, homeSchema(), teamState.Schema(), teamstate.Schema) |
| +} |
| + |
| +// teamSettings verifies team configuration for this instance: nil, nil |
| +// with team mode off; otherwise a verified record or errTeamConfig. Team |
| +// mode exists only beside Home, and the record is verified against the |
| +// same Home issuer, consumer ID and origin the bridge is built with. It |
| +// touches no database, which is what lets AppWith decide the schema |
| +// before anything migrates. |
| +func teamSettings(cfg *teammode.Config, home *connect.DecodedCredentials, origin string) (*teammode.Settings, error) { |
| + if cfg == nil { |
| + return nil, nil |
| + } |
| + if home == nil { |
| + return nil, errTeamConfig |
| + } |
| + return teammode.Verify(cfg, &teammode.Home{Issuer: home.Issuer, ConsumerID: home.ConsumerID}, "memoria", origin) |
| +} |
| + |
| +// teamBootSchema is the schema AppWith applies, chosen before anything is |
| +// migrated. A database activated in team mode refuses to boot without |
| +// team configuration, or with a different binding: an environment |
| +// variable dropped in a redeploy must not quietly hand standing back to |
| +// MEMORIA_OWNERS. |
| +func teamBootSchema(ctx context.Context, db *sql.DB, settings *teammode.Settings, base *migrate.Set) (*migrate.Set, error) { |
| + return teamState.BootSchema(ctx, db, settings, base, teamBoot(base)) |
| +} |
| + |
| +// teamRuntime is the process's roster runtime and the database the |
| +// Home-only members table lives in. |
| +type teamRuntime struct { |
| + *teammode.Runtime |
| + db *sql.DB |
| +} |
| + |
| +func (t *teamRuntime) issuer() string { return t.Bindings().Issuer } |
| + |
| +// teamWiring is what AppWith learnt about team mode before anything |
| +// migrated, kept for WireHome: the verified settings, and the test |
| +// directory and clock (nil in production, where teammode uses its own |
| +// client and the real clock). |
| +type teamWiring struct { |
| + settings *teammode.Settings |
| + transport http.RoundTripper |
| + clock roster.Clock |
| +} |
| + |
| +// teamMode reports whether this instance is configured for team mode, |
| +// whether or not the runtime has been opened yet. Every gate asks this, |
| +// never a.team != nil: a team-mode instance whose runtime is missing |
| +// must refuse, not fall back to the owners list (requireSession). |
| +func (a *app) teamMode() bool { return a.teamWiring != nil } |
| + |
| +// configureTeam runs from WireHome, after the bridge exists and before |
| +// serving. Without settings it does nothing. Anything else either |
| +// produces a verified, activated runtime or refuses boot: there is no |
| +// falling back to the owners list. |
| +func (a *app) configureTeam(home *connect.DecodedCredentials) error { |
| + if a.teamWiring == nil { |
| + return nil |
| + } |
| + if a.home == nil || home == nil { |
| + return errTeamConfig |
| + } |
| + sealer, err := seal.New(home.DEK, homeNamespace) |
| + if err != nil { |
| + return errTeamConfig |
| + } |
| + w := a.db.Writer() |
| + rt, err := teammode.Open(context.Background(), teammode.RuntimeConfig{Settings: a.teamWiring.settings, State: teamState, DB: w, Sealer: sealer, |
| + IssuerTables: teamIssuerTables, Transport: a.teamWiring.transport, Clock: a.teamWiring.clock}) |
| + if err != nil { |
| + return err |
| + } |
| + a.team = &teamRuntime{Runtime: rt, db: w} |
| + return nil |
| +} |
| + |
| +// teamProbe is GET /api/team, the readiness probe Alta polls before it |
| +// activates this instance in Home's directory: teammode's Probe, |
| +// unauthenticated, no-store, {team_mode, consumer, roster} and no account |
| +// data, and {"team_mode":false} with team mode off. |
| +func (a *app) teamProbe(w http.ResponseWriter, r *http.Request) { |
| + var rt *teammode.Runtime |
| + if a.team != nil { |
| + rt = a.team.Runtime |
| + } |
| + teammode.Probe(rt).ServeHTTP(w, r) |
| +} |
diff --git a/internal/memoria/team_config_test.go b/internal/memoria/team_config_test.go| new file mode 100644 |
| index 0000000..1acb68c |
| --- /dev/null |
| +++ b/internal/memoria/team_config_test.go |
| @@ -0,0 +1,298 @@ |
| +package memoria |
| + |
| +import ( |
| + "context" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "log/slog" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| +) |
| + |
| +// The record is verified against bindings built only from configuration: |
| +// Home's issuer and consumer ID, the app, the team, the directory and |
| +// this instance's origin. A record signed for any other value of any one |
| +// of them refuses boot, before anything migrates. |
| +func TestTeamConfigPinsTheProvisioningRecord(t *testing.T) { |
| + key := teamKey(t) |
| + cases := map[string]func(*roster.Bindings, *teammode.Config){ |
| + "issuer": func(b *roster.Bindings, _ *teammode.Config) { b.Issuer = "https://id.other.example" }, |
| + "consumer": func(b *roster.Bindings, _ *teammode.Config) { b.Consumer = "another-consumer" }, |
| + "app": func(b *roster.Bindings, _ *teammode.Config) { b.App = "sheets" }, |
| + "origin": func(b *roster.Bindings, _ *teammode.Config) { b.Audience = "https://other.example.com" }, |
| + "team": func(_ *roster.Bindings, c *teammode.Config) { c.TeamID = "TeamB" }, |
| + "directory": func(_ *roster.Bindings, c *teammode.Config) { c.DirectoryOrigin = "https://dir.other.example" }, |
| + } |
| + for name, change := range cases { |
| + t.Run(name, func(t *testing.T) { |
| + b := teamTestBindings(homeTestOrigin) |
| + change(&b, &teammode.Config{}) |
| + cfg, _, _ := teamConfigFor(t, b, key) |
| + // The instance's own configuration, whatever the record says. |
| + cfg.Origin = homeTestOrigin |
| + change(&roster.Bindings{}, cfg.Team) |
| + d := teamDB(t) |
| + if _, _, _, err := bootTeam(t, d, cfg); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("a record for another %s = %v, want ErrConfig", name, err) |
| + } |
| + if _, activated, _ := teamState.Required(context.Background(), d.Writer()); activated { |
| + t.Fatal("a refused record left a marker") |
| + } |
| + var tables int |
| + d.Writer().QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='documents'").Scan(&tables) |
| + if tables != 0 { |
| + t.Fatal("a refused record migrated the database") |
| + } |
| + }) |
| + } |
| + // And the right record boots. |
| + cfg, _, _ := teamConfigFor(t, teamTestBindings(homeTestOrigin), key) |
| + if _, _, _, err := bootTeam(t, teamDB(t), cfg); err != nil { |
| + t.Fatalf("the instance's own record: %v", err) |
| + } |
| +} |
| + |
| +// teamEnv is an environment LoadConfig accepts, with team configuration |
| +// for bindings b when team is true. |
| +func teamEnv(t *testing.T, team bool, owners string) map[string]string { |
| + t.Helper() |
| + key := teamKey(t) |
| + cfg, _, _ := teamConfigFor(t, teamTestBindings(homeTestOrigin), key) |
| + keys, _ := json.Marshal(map[string]string{"key": base64.StdEncoding.EncodeToString(key.SignPub())}) |
| + env := map[string]string{ |
| + "MEMORIA_DEK": base64.StdEncoding.EncodeToString(make([]byte, 32)), |
| + "MEMORIA_INSTANCE_KEY": "k", |
| + "MEMORIA_ALLOW_LOGGED_MAIL": "1", |
| + "MEMORIA_ORIGIN": homeTestOrigin, |
| + "MEMORIA_OWNERS": owners, |
| + "MEMORIA_HOME_ISSUER": homeTestIssuer, |
| + "MEMORIA_HOME_CONSUMER_ID": teamTestConsumer, |
| + "MEMORIA_HOME_KEYS_BASE64": base64.StdEncoding.EncodeToString(keys), |
| + "MEMORIA_HOME_DEK_BASE64": base64.StdEncoding.EncodeToString(make([]byte, 32)), |
| + } |
| + if team { |
| + names := teammode.EnvNames("MEMORIA") |
| + for i, v := range []string{cfg.Team.TeamID, cfg.Team.DirectoryOrigin, cfg.Team.ProvisioningBase64, cfg.Team.OperatorKeysBase64, cfg.Team.RosterToken} { |
| + env[names[i]] = v |
| + } |
| + } |
| + return env |
| +} |
| + |
| +// Five variables, all or none, and only beside Home. One present is a |
| +// configuration, and an invalid one: there is no falling back to the |
| +// owners list. In team mode MEMORIA_OWNERS is optional, and empty admits |
| +// nobody locally; outside it, it is still required. MEMORIA_AI stays off |
| +// unless asked for, team mode or not (Paul's ruling for team instances). |
| +// |
| +// MUTATION-TESTED 2026-10-30, each seen red and reverted: the owners |
| +// check made unconditional ("owners optional"); the Home requirement |
| +// dropped ("team without Home"). |
| +func TestTeamEnvIsAllOrNoneAndTheOwnersListBecomesOptional(t *testing.T) { |
| + names := teammode.EnvNames("MEMORIA") |
| + if names != [5]string{"MEMORIA_TEAM_ID", "MEMORIA_TEAM_DIRECTORY_ORIGIN", "MEMORIA_TEAM_PROVISIONING_BASE64", "MEMORIA_TEAM_OPERATOR_KEYS_BASE64", "MEMORIA_TEAM_ROSTER_TOKEN"} { |
| + t.Fatalf("env names = %v", names) |
| + } |
| + key := teamKey(t) |
| + for _, only := range names { |
| + env := teamEnv(t, false, "owner@example.test") |
| + env[only] = "x" |
| + c, err := LoadConfig(func(n string) string { return env[n] }) |
| + if err != nil { |
| + t.Fatalf("%s alone: LoadConfig = %v", only, err) |
| + } |
| + if c.Team == nil { |
| + t.Fatalf("%s alone read as team mode off", only) |
| + } |
| + cfg, _, _ := teamConfigFor(t, teamTestBindings(homeTestOrigin), key) |
| + cfg.Team = c.Team |
| + if _, _, _, err := bootTeam(t, teamDB(t), cfg); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("%s alone = %v, want ErrConfig", only, err) |
| + } |
| + } |
| + |
| + // Team mode, no owners list: loads, and AI is off. |
| + env := teamEnv(t, true, "") |
| + c, err := LoadConfig(func(n string) string { return env[n] }) |
| + if err != nil || c.Team == nil { |
| + t.Fatalf("team mode with no owners list: %+v, %v", c.Team, err) |
| + } |
| + if c.AI || c.TensorXKey != "" { |
| + t.Fatal("team mode switched AI on") |
| + } |
| + // The same without team mode is still a refusal. |
| + env = teamEnv(t, false, "") |
| + if _, err := LoadConfig(func(n string) string { return env[n] }); !errors.Is(err, ErrMissing) { |
| + t.Fatalf("no owners list outside team mode = %v, want ErrMissing", err) |
| + } |
| + // Team mode requires Home. |
| + env = teamEnv(t, true, "") |
| + for _, n := range []string{"MEMORIA_HOME_ISSUER", "MEMORIA_HOME_CONSUMER_ID", "MEMORIA_HOME_KEYS_BASE64", "MEMORIA_HOME_DEK_BASE64"} { |
| + delete(env, n) |
| + } |
| + if _, err := LoadConfig(func(n string) string { return env[n] }); err == nil { |
| + t.Fatal("team mode without Home loaded") |
| + } |
| + cfg, _, _ := teamConfigFor(t, teamTestBindings(homeTestOrigin), key) |
| + cfg.Home = nil |
| + if _, _, _, err := bootTeam(t, teamDB(t), cfg); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("team mode without Home at boot = %v, want ErrConfig", err) |
| + } |
| + |
| + // Booted with no owners list, the local sign-in admits nobody, and |
| + // the guard answers a stranger's "sent" rather than failing closed |
| + // as a misconfiguration. |
| + f := newTeamFixture(t) |
| + if f.app.Admit("anyone@example.test") { |
| + t.Fatal("an empty team-mode owners list admits an address") |
| + } |
| + w := f.do("POST", "/auth/begin", "address=anyone%40example.test") |
| + if w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/signin?sent=1" { |
| + t.Fatalf("local sign-in with no owners list = %d %q, want the stranger's ?sent=1", w.Code, w.Header().Get("Location")) |
| + } |
| + if f.mail.body != "" { |
| + t.Fatal("a sign-in link was sent") |
| + } |
| +} |
| + |
| +// The marker locks a database into team mode: once activated it refuses |
| +// to boot without team configuration, or with another binding, before |
| +// anything migrates; the same binding boots again. Its namespace is |
| +// memoria_team. |
| +func TestTeamMarkerLocksTheDatabaseIntoTeamMode(t *testing.T) { |
| + key := teamKey(t) |
| + d := teamDB(t) |
| + cfg, _, _ := teamConfigFor(t, teamTestBindings(homeTestOrigin), key) |
| + if _, _, _, err := bootTeam(t, d, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + fp, activated, err := teamState.Required(context.Background(), d.Writer()) |
| + if err != nil || !activated || fp != teammode.Fingerprint(teamTestBindings(homeTestOrigin)) { |
| + t.Fatalf("marker = %q %v %v", fp, activated, err) |
| + } |
| + var set int |
| + d.Writer().QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='memoria_team_required'").Scan(&set) |
| + if set != 1 { |
| + t.Fatal("the marker is not in the memoria_team namespace") |
| + } |
| + |
| + off := cfg |
| + off.Team = nil |
| + if _, _, _, err := bootTeam(t, d, off); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("activated database without team configuration = %v, want ErrConfig", err) |
| + } |
| + // Refused before anything migrated: App's plain path too. |
| + if _, _, err := App(d, homeTestOrigin, teamSealer(t), slogDiscard()); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("activated database through App = %v, want ErrConfig", err) |
| + } |
| + other := teamTestBindings(homeTestOrigin) |
| + other.Team = "TeamB" |
| + rebound, _, _ := teamConfigFor(t, other, key) |
| + if _, _, _, err := bootTeam(t, d, rebound); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("activated database with another binding = %v, want ErrConfig", err) |
| + } |
| + if _, _, _, err := bootTeam(t, d, cfg); err != nil { |
| + t.Fatalf("the same binding again: %v", err) |
| + } |
| + if _, err := d.Writer().Exec("UPDATE memoria_team_required SET bindings='x'"); err == nil { |
| + t.Fatal("the marker was rewritten") |
| + } |
| + if _, err := d.Writer().Exec("DELETE FROM memoria_team_required"); err == nil { |
| + t.Fatal("the marker was deleted") |
| + } |
| +} |
| + |
| +// The census: a Home identity from another issuer, in either table that |
| +// holds one, refuses activation, and no marker is written. |
| +func TestTeamCensusRefusesAForeignIssuer(t *testing.T) { |
| + key := teamKey(t) |
| + for _, table := range []string{"home_identity_links", "memoria_team_home_members"} { |
| + t.Run(table, func(t *testing.T) { |
| + d := teamDB(t) |
| + cfg, _, _ := teamConfigFor(t, teamTestBindings(homeTestOrigin), key) |
| + // The team schema applied and never activated: what a boot |
| + // refused after migrating leaves behind. |
| + if _, err := migrate.Apply(context.Background(), d, teamBoot(BootSchema)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := d.Writer().Exec("INSERT INTO memoria_home_local_identities(address_lookup,address_sealed) VALUES('home-only:x',X'')"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := d.Writer().Exec("INSERT INTO "+table+"(issuer,subject,person_id) VALUES('https://id.other.example',?,1)", teamSubject('f')); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, _, _, err := bootTeam(t, d, cfg); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("a %s row from another issuer = %v, want ErrConfig", table, err) |
| + } |
| + if _, activated, _ := teamState.Required(context.Background(), d.Writer()); activated { |
| + t.Fatal("a refused census left a marker") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Team mode off: GET /api/team says only that, no-store, and nothing |
| +// team mode adds is in the database. Paul's own instance is this. |
| +func TestTeamProbeOffSaysOnlyThat(t *testing.T) { |
| + f := newHomeRouterFixture(t) |
| + w := f.do("GET", "/api/team", "") |
| + if w.Code != 200 || strings.TrimSpace(w.Body.String()) != `{"team_mode":false}` || w.Header().Get("Cache-Control") != "no-store" { |
| + t.Fatalf("probe off = %d %q %v", w.Code, w.Body.String(), w.Header()) |
| + } |
| + var n int |
| + f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE name LIKE 'memoria_team%'").Scan(&n) |
| + if n != 0 { |
| + t.Fatalf("team mode off created %d team tables or triggers", n) |
| + } |
| + if f.app.teamMode() || f.app.store.team { |
| + t.Fatal("team mode off reads as on") |
| + } |
| +} |
| + |
| +// The probe in team mode: unauthenticated, no-store, the same body |
| +// whoever asks, {team_mode, consumer, roster} and nothing else, through |
| +// its three states. |
| +func TestTeamProbeStatesAndNoAccountData(t *testing.T) { |
| + f := newTeamFixture(t) |
| + probe := func() map[string]any { |
| + t.Helper() |
| + r := httptest.NewRequest("GET", homeTestOrigin+"/api/team", nil) |
| + w := httptest.NewRecorder() |
| + f.handler.ServeHTTP(w, r) |
| + if w.Code != 200 || w.Header().Get("Cache-Control") != "no-store" { |
| + t.Fatalf("probe = %d %v", w.Code, w.Header()) |
| + } |
| + raw, _ := io.ReadAll(w.Body) |
| + var out map[string]any |
| + if err := json.Unmarshal(raw, &out); err != nil { |
| + t.Fatal(err) |
| + } |
| + for k := range out { |
| + if k != "team_mode" && k != "consumer" && k != "roster" { |
| + t.Fatalf("probe carries %q", k) |
| + } |
| + } |
| + if strings.Contains(string(raw), teamSubject('a')) || strings.Contains(string(raw), "TeamA") { |
| + t.Fatalf("probe leaks the team or a member: %s", raw) |
| + } |
| + return out |
| + } |
| + f.member(teamSubject('a'), "owner") |
| + if got := probe(); got["team_mode"] != true || got["consumer"] != teamTestConsumer || got["roster"] != "ok" { |
| + t.Fatalf("probe = %v", got) |
| + } |
| + f.expired() |
| + if got := probe()["roster"]; got == "ok" { |
| + t.Fatalf("probe roster after the lease = %v", got) |
| + } |
| +} |
| + |
| +func slogDiscard() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) } |
diff --git a/internal/memoria/team_fixture_test.go b/internal/memoria/team_fixture_test.go| new file mode 100644 |
| index 0000000..9b95f43 |
| --- /dev/null |
| +++ b/internal/memoria/team_fixture_test.go |
| @@ -0,0 +1,256 @@ |
| +package memoria |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "io" |
| + "log/slog" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/oficina/home/teammode/teammodetest" |
| + assertioncrypto "amadan.net/rastrillo/rastrillo/crypto" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + |
| + "amadan.net/oficina/memoria/internal/memoria/seal" |
| +) |
| + |
| +// Team mode's fixture: Home configured exactly as homeRouterFixture does |
| +// (so its exchange, local sign-in and link helpers all apply), plus |
| +// home/teammode's test directory (teammodetest) answering the roster in |
| +// memory from a member list a test can change or take down, with a roster |
| +// clock a test can step past the lease. The app is built the way main |
| +// builds it: AppWith, SetOwners, NewAuth, UseAuth, WireHome, MountAuth. |
| + |
| +const teamTestConsumer = "memoria-test" |
| + |
| +// teamSubject is a well-formed person ref: "pr_" and 26 copies of c. |
| +func teamSubject(c byte) string { return teammodetest.Subject(c) } |
| + |
| +// teamTestBindings are this instance's: Home's issuer and consumer ID as |
| +// homeRouterFixture configures them, the test directory and team, |
| +// Memoria, and origin. |
| +func teamTestBindings(origin string) roster.Bindings { |
| + b := teammodetest.Bindings("memoria", teamTestConsumer, origin) |
| + b.Issuer = homeTestIssuer |
| + return b |
| +} |
| + |
| +func teamKey(t *testing.T) *assertioncrypto.Keypair { |
| + t.Helper() |
| + key, err := assertioncrypto.Generate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return key |
| +} |
| + |
| +func teamSealer(t *testing.T) *seal.Sealer { |
| + t.Helper() |
| + s, err := seal.New(bytes.Repeat([]byte{6}, 32)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return s |
| +} |
| + |
| +// teamConfigFor is a Config for a team-mode instance on bindings b: Home |
| +// as homeRouterFixture has it, the record signed for b, and the test |
| +// directory and clock. owners is MEMORIA_OWNERS, which in team mode only |
| +// admits a local sign-in; none is Alta's shape. |
| +func teamConfigFor(t *testing.T, b roster.Bindings, key *assertioncrypto.Keypair, owners ...string) (Config, *teammodetest.Directory, *teammodetest.Clock) { |
| + t.Helper() |
| + tcfg, dir := teammodetest.Provision(t, b) |
| + clock := teammodetest.NewClock() |
| + cfg := Config{Origin: b.Audience, Sealer: teamSealer(t), Owners: owners, |
| + Home: &connect.DecodedCredentials{Issuer: homeTestIssuer, ConsumerID: teamTestConsumer, Keys: map[string][]byte{"key": key.SignPub()}, DEK: bytes.Repeat([]byte{7}, 32)}, |
| + Team: tcfg, teamTransport: dir, teamClock: clock} |
| + return cfg, dir, clock |
| +} |
| + |
| +func teamDB(t *testing.T) *db.DB { |
| + t.Helper() |
| + d, err := db.Open(filepath.Join(t.TempDir(), "memoria.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + return d |
| +} |
| + |
| +// bootTeam builds the app over d from cfg as main does, and returns it |
| +// (nil with the error when boot is refused). |
| +func bootTeam(t *testing.T, d *db.DB, cfg Config) (*http.ServeMux, *app, *homeTestMail, error) { |
| + t.Helper() |
| + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + mux, a, err := AppWith(d, cfg, logger) |
| + if err != nil { |
| + return nil, nil, nil, err |
| + } |
| + t.Cleanup(func() { a.store.ix.Close() }) |
| + a.SetOwners(cfg.Owners) |
| + mail := &homeTestMail{} |
| + auth, err := NewAuth(d.Writer(), AuthEnv{Origin: cfg.Origin, InstanceKey: "isolated-test-instance-key", Mailer: mail, HomeEnabled: true}, logger, a) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + a.UseAuth(auth) |
| + if err := a.WireHome(mux, cfg); err != nil { |
| + return nil, nil, nil, err |
| + } |
| + a.MountAuth(mux, cfg.Origin) |
| + return mux, a, mail, nil |
| +} |
| + |
| +type teamFixture struct { |
| + *homeRouterFixture |
| + t *testing.T |
| + d *db.DB |
| + dir *teammodetest.Directory |
| + clock *teammodetest.Clock |
| +} |
| + |
| +func newTeamFixture(t *testing.T, owners ...string) *teamFixture { |
| + t.Helper() |
| + key := teamKey(t) |
| + cfg, dir, clock := teamConfigFor(t, teamTestBindings(homeTestOrigin), key, owners...) |
| + d := teamDB(t) |
| + mux, a, mail, err := bootTeam(t, d, cfg) |
| + if err != nil { |
| + t.Fatalf("boot in team mode: %v", err) |
| + } |
| + return &teamFixture{homeRouterFixture: &homeRouterFixture{a, mux, key, mail, map[string]*http.Cookie{}}, t: t, d: d, dir: dir, clock: clock} |
| +} |
| + |
| +// page is GET path as a browser asks for it (Accept: text/html, so an |
| +// error is the page and not plain text). |
| +func (f *teamFixture) page(path string) *httptest.ResponseRecorder { |
| + r := httptest.NewRequest("GET", homeTestOrigin+path, nil) |
| + r.Header.Set("Accept", "text/html") |
| + for _, c := range f.cookies { |
| + r.AddCookie(c) |
| + } |
| + return f.send(r) |
| +} |
| + |
| +// form POSTs values as a browser's same-origin form does. |
| +func (f *teamFixture) form(path, body string) *httptest.ResponseRecorder { |
| + r := httptest.NewRequest("POST", homeTestOrigin+path, strings.NewReader(body)) |
| + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + r.Header.Set("Origin", homeTestOrigin) |
| + r.Header.Set("Accept", "text/html") |
| + for _, c := range f.cookies { |
| + r.AddCookie(c) |
| + } |
| + return f.send(r) |
| +} |
| + |
| +// signIn runs a whole Home sign-in for subject from wherever the jar is, |
| +// and returns the finish answer. |
| +func (f *teamFixture) signIn(subject string) *httptest.ResponseRecorder { |
| + f.t.Helper() |
| + return f.exchange(f.t, "/auth/start", subject) |
| +} |
| + |
| +// freshSignIn is signIn from an empty jar. |
| +func (f *teamFixture) freshSignIn(subject string) *httptest.ResponseRecorder { |
| + f.cookies = map[string]*http.Cookie{} |
| + return f.signIn(subject) |
| +} |
| + |
| +// member puts subject on the roster with role, refreshes, and signs them |
| +// in with Home from an empty jar, failing unless they got a session. |
| +func (f *teamFixture) member(subject, role string) { |
| + f.t.Helper() |
| + f.dir.Set(subject, role) |
| + f.refreshed() |
| + if got := f.freshSignIn(subject); got.Code != http.StatusSeeOther { |
| + f.t.Fatalf("sign-in of %s = %d %s", subject, got.Code, got.Body.String()) |
| + } |
| +} |
| + |
| +// refreshed steps the roster clock past the refresh point and refreshes, |
| +// so the next request sees the directory's current list. |
| +func (f *teamFixture) refreshed() { |
| + f.t.Helper() |
| + f.clock.Step(roster.RefreshAfter + time.Second) |
| + if err := f.app.team.Refresh(context.Background()); err != nil { |
| + f.t.Fatalf("roster refresh: %v", err) |
| + } |
| +} |
| + |
| +// expired takes the directory down and steps past the lease: Unknown. |
| +func (f *teamFixture) expired() { |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge + time.Second) |
| +} |
| + |
| +// renewed brings the directory back and refreshes. |
| +func (f *teamFixture) renewed() { |
| + f.t.Helper() |
| + f.dir.SetDown(false) |
| + f.refreshed() |
| +} |
| + |
| +// localSession puts a local (magic link) session for address in the jar, |
| +// as a sign-in the owners list admitted would. |
| +func (f *teamFixture) localSession(address string) { |
| + f.t.Helper() |
| + w := httptest.NewRecorder() |
| + r := httptest.NewRequest("GET", homeTestOrigin+"/", nil) |
| + if err := f.app.home.sessions.SignIn(w, r, sessions.Session{Subject: address, Method: "magiclink", AuthTime: time.Now()}); err != nil { |
| + f.t.Fatal(err) |
| + } |
| + for _, c := range w.Result().Cookies() { |
| + f.cookies[c.Name] = c |
| + } |
| +} |
| + |
| +// sessionNow is the session the jar's cookie currently resolves to. |
| +func (f *teamFixture) sessionNow() (sessions.Session, bool) { |
| + r := httptest.NewRequest("GET", homeTestOrigin+"/", nil) |
| + for _, c := range f.cookies { |
| + r.AddCookie(c) |
| + } |
| + return f.app.home.sessions.From(r) |
| +} |
| + |
| +// ingest stores a memoria-owned document directly, as the instance's own |
| +// work (a systemWrite): no request's standing is involved. |
| +func (f *teamFixture) ingest(key, title, body string) int64 { |
| + f.t.Helper() |
| + id, err := f.app.store.Ingest(systemWrite(context.Background()), IngestSpec{Source: "upload", Key: key, Title: title, Body: body}) |
| + if err != nil { |
| + f.t.Fatal(err) |
| + } |
| + return id |
| +} |
| + |
| +// count is SELECT COUNT(*) FROM table. |
| +func (f *teamFixture) count(table string) int { |
| + f.t.Helper() |
| + var n int |
| + if err := f.d.Writer().QueryRow("SELECT COUNT(*) FROM " + table).Scan(&n); err != nil { |
| + f.t.Fatal(err) |
| + } |
| + return n |
| +} |
| + |
| +// asMember is a context carrying a Member's Access for subject, as |
| +// requireSession would put on a request: for the store-level tests. |
| +func (f *teamFixture) asMember(subject string) context.Context { |
| + f.t.Helper() |
| + acc := f.app.team.Access(context.Background(), subject) |
| + if acc.State() != roster.Member { |
| + f.t.Fatalf("%s is not a member now", subject) |
| + } |
| + return teammode.WithAccess(context.Background(), acc) |
| +} |
diff --git a/internal/memoria/team_guard.go b/internal/memoria/team_guard.go| new file mode 100644 |
| index 0000000..8866927 |
| --- /dev/null |
| +++ b/internal/memoria/team_guard.go |
| @@ -0,0 +1,138 @@ |
| +package memoria |
| + |
| +// Team mode's write guard: the request's standing checked again inside |
| +// the transaction that commits a person's write, before and after it |
| +// (teammode.Guard; Home implementation/teammode-package.md §3, invariant |
| +// 13, and Fable's deviation 7 on oficina/sheets #52). The route's gate |
| +// (team_access.go) decides whether the write may start; this decides |
| +// whether it may commit, so a lease that lapses between the two fails the |
| +// write instead of landing it. It never asks the roster: it reads the |
| +// Access the request carries, whose lease check never waits, so it is |
| +// safe under the one-connection SQLite writer. |
| +// |
| +// Memoria has no shares, so nothing a person writes rests on anything but |
| +// standing: a member's write needs Member, and a connector's needs the |
| +// roster's owner role. |
| +// |
| +// Outside team mode Store.team is false and every helper here is the |
| +// write path exactly as it was. |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + |
| + "gorm.io/gorm" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| +) |
| + |
| +// writeRule is what a write's standing must be. |
| +type writeRule int |
| + |
| +const ( |
| + // memberWrite: anything a member may do — add or delete content, |
| + // report a fact, rate an answer. |
| + memberWrite writeRule = iota |
| + // ownerWrite: a connector's credential and runs, which are the |
| + // roster's owners' alone (requireOwner). |
| + ownerWrite |
| +) |
| + |
| +// rosterOwner is the roster's owner role. |
| +const rosterOwner = "owner" |
| + |
| +// teamGuard is teammode.Guard. A variable only so a test can let the |
| +// lease run out between a write and its commit on every write route. |
| +var teamGuard = teammode.Guard |
| + |
| +type systemWriteKey struct{} |
| + |
| +// systemWrite marks ctx as carrying writes that nobody's standing makes: |
| +// a connector run already started, a sibling poll. They are the team's |
| +// own derived work, not a person's, so they are not guarded — and any |
| +// Access the context carried is dropped, so a run that outlives the |
| +// request that started it is not bound to that request's lease. |
| +func systemWrite(ctx context.Context) context.Context { |
| + return context.WithValue(teammode.WithAccess(ctx, nil), systemWriteKey{}, true) |
| +} |
| + |
| +func isSystemWrite(ctx context.Context) bool { |
| + v, _ := ctx.Value(systemWriteKey{}).(bool) |
| + return v |
| +} |
| + |
| +// authorizeFor is the Guard authorize for rule over acc: Member, and for |
| +// ownerWrite the roster's owner role, which Role re-checks against the |
| +// same latched lease. |
| +func authorizeFor(rule writeRule, acc *teammode.Access) func(roster.State) error { |
| + return func(st roster.State) error { |
| + if err := teammode.RequireMember(st); err != nil { |
| + return err |
| + } |
| + if rule == ownerWrite && acc.Role() != rosterOwner { |
| + return teammode.ErrNotMember |
| + } |
| + return nil |
| + } |
| +} |
| + |
| +// guard runs write under rule. Call it INSIDE the write's transaction, |
| +// with write using that transaction. Outside team mode, and for a |
| +// systemWrite, it is write alone. In team mode a context with no Access |
| +// is refused: a person-made write that lost its standing on the way here |
| +// is a bug, and the closed answer is the one that cannot leak. |
| +func (s *Store) guard(ctx context.Context, rule writeRule, write func() error) error { |
| + if !s.team || isSystemWrite(ctx) { |
| + return write() |
| + } |
| + acc, ok := teammode.FromContext(ctx) |
| + if !ok { |
| + return teammode.ErrUnavailable |
| + } |
| + return teamGuard(ctx, authorizeFor(rule, acc), write) |
| +} |
| + |
| +// allowed is guard's authorize alone, for a step that must be refused |
| +// before it happens rather than rolled back after (Delete's index |
| +// removal, which precedes its transaction). |
| +func (s *Store) allowed(ctx context.Context, rule writeRule) error { |
| + return s.guard(ctx, rule, func() error { return nil }) |
| +} |
| + |
| +// guarded runs write against the store's database exactly as it always |
| +// has outside team mode, and in team mode in one transaction, inside |
| +// guard, against that transaction (never the outer handle: the writer |
| +// pool has one connection). |
| +func (s *Store) guarded(ctx context.Context, rule writeRule, write func(db *gorm.DB) error) error { |
| + if !s.team { |
| + return write(s.db.G.WithContext(ctx)) |
| + } |
| + return s.db.G.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| + return s.guard(ctx, rule, func() error { return write(tx) }) |
| + }) |
| +} |
| + |
| +// isStandingErr reports whether err is the guard's refusal. |
| +func isStandingErr(err error) bool { |
| + return errors.Is(err, teammode.ErrUnavailable) || errors.Is(err, teammode.ErrNotMember) |
| +} |
| + |
| +// guardRefused answers a write the guard refused, and reports whether it |
| +// did. Standing lapsed between the route's check and the commit: the same |
| +// retryable 503 as Unknown anywhere else, and a 404 for a definite "no" |
| +// (which one request's Access cannot reach once it has said Member, but |
| +// costs nothing to answer correctly). Outside team mode no error is ever |
| +// one of these. |
| +func (a *app) guardRefused(w http.ResponseWriter, r *http.Request, err error) bool { |
| + switch { |
| + case errors.Is(err, teammode.ErrUnavailable): |
| + a.teamUnavailable(w, r) |
| + case errors.Is(err, teammode.ErrNotMember): |
| + a.errorPage(w, r, http.StatusNotFound, kindRoute, "") |
| + default: |
| + return false |
| + } |
| + return true |
| +} |
diff --git a/internal/memoria/team_guard_test.go b/internal/memoria/team_guard_test.go| new file mode 100644 |
| index 0000000..8901f3b |
| --- /dev/null |
| +++ b/internal/memoria/team_guard_test.go |
| @@ -0,0 +1,306 @@ |
| +package memoria |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "mime/multipart" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/oficina/suite" |
| + |
| + "amadan.net/oficina/memoria/internal/memoria/notion" |
| +) |
| + |
| +// lapsingGuard makes team-mode writes' lease run out between the write and |
| +// its commit: the directory goes down and the clock passes the lease |
| +// inside the transaction, so the guard's after-check reads Unknown. With |
| +// at > 0 only the at-th guarded call lapses (counting from 1); with 0, |
| +// every one. |
| +func lapsingGuard(t *testing.T, f *teamFixture, at int32) func(context.Context, func(roster.State) error, func() error) error { |
| + t.Helper() |
| + var n atomic.Int32 |
| + teamGuard = func(ctx context.Context, authorize func(roster.State) error, write func() error) error { |
| + return teammode.Guard(ctx, authorize, func() error { |
| + err := write() |
| + if k := n.Add(1); at == 0 || k == at { |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge + time.Second) |
| + } |
| + return err |
| + }) |
| + } |
| + t.Cleanup(func() { teamGuard = teammode.Guard }) |
| + return teamGuard |
| +} |
| + |
| +// emptySource is a Notion with nothing in it, for the connector routes. |
| +type emptySource struct{} |
| + |
| +func (emptySource) Roots(context.Context) ([]notion.Ref, []notion.Ref, error) { return nil, nil, nil } |
| +func (emptySource) Fetch(context.Context, notion.Ref) (*notion.Content, error) { |
| + return nil, errors.New("no pages") |
| +} |
| + |
| +// multipartBody is a create-content form: fields, and files by name. |
| +func multipartBody(t *testing.T, fields, files map[string]string) (string, string) { |
| + t.Helper() |
| + var b bytes.Buffer |
| + w := multipart.NewWriter(&b) |
| + for k, v := range fields { |
| + w.WriteField(k, v) |
| + } |
| + for name, body := range files { |
| + part, err := w.CreateFormFile("file", name) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + part.Write([]byte(body)) |
| + } |
| + w.Close() |
| + return b.String(), w.FormDataContentType() |
| +} |
| + |
| +func (f *teamFixture) multipart(path string, fields, files map[string]string) *httptest.ResponseRecorder { |
| + body, ct := multipartBody(f.t, fields, files) |
| + r := httptest.NewRequest("POST", homeTestOrigin+path, strings.NewReader(body)) |
| + r.Header.Set("Content-Type", ct) |
| + r.Header.Set("Origin", homeTestOrigin) |
| + r.Header.Set("Accept", "text/html") |
| + for _, c := range f.cookies { |
| + r.AddCookie(c) |
| + } |
| + return f.send(r) |
| +} |
| + |
| +// teamSnapshot is what a refused write must leave exactly as it was: every |
| +// table a person's write reaches, and the one sealed column one of them |
| +// updates in place. |
| +type teamSnapshot struct { |
| + documents, chunks, reports, feedback, connectors, runs, pages int |
| + feedbackSealed, connectorSealed string |
| + searchable bool |
| +} |
| + |
| +func (f *teamFixture) snapshot() teamSnapshot { |
| + f.t.Helper() |
| + s := teamSnapshot{ |
| + documents: f.count("documents"), chunks: f.count("chunks"), reports: f.count("fact_reports"), |
| + feedback: f.count("answer_feedbacks"), connectors: f.count("connectors"), runs: f.count("sync_runs"), pages: f.count("source_pages"), |
| + } |
| + var sealed []byte |
| + f.d.Writer().QueryRow("SELECT sealed_feedback FROM answer_feedbacks ORDER BY id LIMIT 1").Scan(&sealed) |
| + s.feedbackSealed = string(sealed) |
| + var token []byte |
| + f.d.Writer().QueryRow("SELECT sealed_token FROM connectors ORDER BY id LIMIT 1").Scan(&token) |
| + s.connectorSealed = string(token) |
| + page, err := f.app.store.Search(context.Background(), suite.Subject{Kind: suite.SubjectPersonRef, Value: teamSubject('a')}, "nebula", 25) |
| + s.searchable = err == nil && len(page.Results) > 0 |
| + return s |
| +} |
| + |
| +// Every write route, with the lease lapsing between the write and its |
| +// commit: each answers the retryable 503, and nothing any of them wrote |
| +// survived — the database is read back, not just the status (Fable's #53 |
| +// required test 2, for Memoria), and the deleted document is still found. |
| +// |
| +// MUTATION-TESTED 2026-10-30, each seen red and reverted: Store.guard |
| +// returning write() in team mode (every route); guard's after-check |
| +// dropped in teammode.Guard's place (every route); Ingest's transaction |
| +// unguarded ("paste", "upload", "native note"); DeleteReport and |
| +// DeleteFeedback through the outer handle ("report delete", "feedback |
| +// delete"); connector writes guarded as memberWrite (see the owner test). |
| +func TestTeamEveryWriteRouteRefusesALapseBeforeCommit(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.app.UseFakeSource(emptySource{}, func(context.Context, string) (string, error) { return "workspace", nil }) |
| + f.ingest("plan", "Nebula plan", "The nebula plan is ready.") |
| + doc := f.ingest("office", "Office", "## Office Address\n\nThe office phone number is:\n+353 (0)1 547 7854\n") |
| + // Two people: every route a member may use runs as a roster MEMBER, |
| + // and only the connector routes as the roster owner — so a write |
| + // guarded as an owner's by mistake is refused on its success half. |
| + f.member(teamSubject('o'), "owner") |
| + f.member(teamSubject('a'), "member") |
| + member := f.asMember(teamSubject('a')) |
| + asker := suite.Subject{Kind: suite.SubjectPersonRef, Value: teamSubject('a')} |
| + |
| + // The rows the delete and update routes act on, written under the |
| + // real guard as the member. |
| + if err := f.app.store.SaveCorrection(member, asker, "office phone number", "phone", "none", "first"); err != nil { |
| + t.Fatal(err) |
| + } |
| + handle, err := f.app.store.sealFeedbackHandle(feedbackHandle{Asker: teamSubject('a'), Query: "nebula"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fid, _, err := f.app.store.SaveFeedback(member, asker, handle, "down") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.app.store.SaveConnector(f.asMember(teamSubject('o')), "notion", "secret-token", "workspace"); err != nil { |
| + t.Fatal(err) |
| + } |
| + var report int64 |
| + f.d.Writer().QueryRow("SELECT id FROM fact_reports LIMIT 1").Scan(&report) |
| + lapsing := lapsingGuard(t, f, 0) |
| + |
| + routes := []struct { |
| + name string |
| + do func() *httptest.ResponseRecorder |
| + owner bool |
| + }{ |
| + {"paste", func() *httptest.ResponseRecorder { |
| + return f.multipart("/documents", map[string]string{"title": "Pasted", "body": "nebula pasted"}, nil) |
| + }, false}, |
| + {"upload", func() *httptest.ResponseRecorder { |
| + return f.multipart("/documents", nil, map[string]string{"nebula.txt": "nebula uploaded"}) |
| + }, false}, |
| + {"correction", func() *httptest.ResponseRecorder { |
| + return f.form("/facts/correct", url.Values{"q": {"office phone number"}, "kind": {"phone"}, "choice": {"none"}, "note": {"x"}}.Encode()) |
| + }, false}, |
| + {"report delete", func() *httptest.ResponseRecorder { return f.form("/reports/"+itoa64(report)+"/delete", "") }, false}, |
| + {"feedback", func() *httptest.ResponseRecorder { |
| + return f.form("/answer/feedback", url.Values{"handle": {handle}, "verdict": {"up"}}.Encode()) |
| + }, false}, |
| + {"feedback note", func() *httptest.ResponseRecorder { |
| + return f.form("/answer/feedback/"+itoa64(fid), url.Values{"note": {"changed"}}.Encode()) |
| + }, false}, |
| + {"feedback delete", func() *httptest.ResponseRecorder { return f.form("/answer/feedback/"+itoa64(fid)+"/delete", "") }, false}, |
| + {"native note", func() *httptest.ResponseRecorder { |
| + return f.json("POST", "/api/native/notes", `{"title":"Note","body":"nebula noted"}`) |
| + }, false}, |
| + {"connector save", func() *httptest.ResponseRecorder { |
| + return f.form("/connectors/notion", url.Values{"token": {"another-token"}}.Encode()) |
| + }, true}, |
| + {"connector sync", func() *httptest.ResponseRecorder { return f.form("/connectors/notion/sync", "") }, true}, |
| + {"connector disconnect", func() *httptest.ResponseRecorder { return f.form("/connectors/notion/disconnect", "") }, true}, |
| + {"delete", func() *httptest.ResponseRecorder { return f.form("/documents/"+itoa64(doc)+"/delete", "") }, false}, |
| + } |
| + for _, route := range routes { |
| + t.Run(route.name, func(t *testing.T) { |
| + who, role := teamSubject('a'), "member" |
| + if route.owner { |
| + who, role = teamSubject('o'), "owner" |
| + } |
| + f.member(who, role) |
| + f.renewed() |
| + before := f.snapshot() |
| + if !before.searchable { |
| + t.Fatal("the fixture's document is not searchable before the route") |
| + } |
| + got := route.do() |
| + if got.Code != http.StatusServiceUnavailable || got.Header().Get("Retry-After") == "" || got.Header().Get("Cache-Control") != "no-store" { |
| + t.Fatalf("%s with a lapse before commit = %d %v, want a retryable no-store 503:\n%s", route.name, got.Code, got.Header(), got.Body.String()) |
| + } |
| + if after := f.snapshot(); after != before { |
| + t.Fatalf("%s: a refused write changed the database\nbefore %+v\nafter %+v", route.name, before, after) |
| + } |
| + // The presence half: the same request under the real guard |
| + // writes, so the refusal above was the lapse and not a route |
| + // that writes nothing. |
| + teamGuard = teammode.Guard |
| + defer func() { teamGuard = lapsing }() |
| + f.renewed() |
| + f.member(who, role) |
| + if got := route.do(); got.Code >= 400 { |
| + t.Fatalf("%s under the real guard = %d:\n%s", route.name, got.Code, got.Body.String()) |
| + } |
| + if route.name == "connector sync" && !f.app.WaitForSync(1, 5*time.Second) { |
| + t.Fatal("the sync run did not finish") |
| + } |
| + if after := f.snapshot(); after == before { |
| + t.Fatalf("%s under the real guard changed nothing; the refusal proves nothing", route.name) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Delete's index removal precedes its transaction (AGENTS.md), so a |
| +// standing that holds for the pre-check and lapses inside the transaction |
| +// must put the passages back: the refused delete leaves the document |
| +// whole AND findable, not stored-but-unfindable until the next boot. |
| +// |
| +// MUTATION-TESTED 2026-10-30: the re-index after a standing refusal |
| +// removed → "not findable"; the pre-check removed → still green here (the |
| +// in-transaction guard and the re-index cover it), red in the table above. |
| +func TestTeamRefusedDeleteKeepsTheDocumentFindable(t *testing.T) { |
| + f := newTeamFixture(t) |
| + doc := f.ingest("plan", "Nebula plan", "The nebula plan is ready.") |
| + f.member(teamSubject('a'), "member") |
| + lapsingGuard(t, f, 2) // the pre-check holds; the transaction's lapses |
| + if got := f.form("/documents/"+itoa64(doc)+"/delete", ""); got.Code != http.StatusServiceUnavailable { |
| + t.Fatalf("delete lapsing in its transaction = %d, want 503", got.Code) |
| + } |
| + if f.count("documents") != 1 { |
| + t.Fatal("the document was deleted") |
| + } |
| + if s := f.snapshot(); !s.searchable { |
| + t.Fatal("a refused delete left the document stored but not findable") |
| + } |
| +} |
| + |
| +// In team mode a person's write with no standing on its context is |
| +// refused (closed), and the instance's own work — a connector run, a |
| +// sibling poll — is a systemWrite and is not guarded. Outside team mode |
| +// the guard is the write path exactly as it was. |
| +// |
| +// MUTATION-TESTED 2026-10-30: guard letting a context with no Access |
| +// through → "no standing"; systemWrite not honoured → "system". |
| +func TestTeamWritesNeedStandingAndSystemWorkDoesNot(t *testing.T) { |
| + f := newTeamFixture(t) |
| + spec := IngestSpec{Source: "upload", Key: "k", Title: "Nebula", Body: "nebula"} |
| + if _, err := f.app.store.Ingest(context.Background(), spec); !errors.Is(err, teammode.ErrUnavailable) { |
| + t.Fatalf("no standing: ingest = %v, want ErrUnavailable", err) |
| + } |
| + if f.count("documents") != 0 { |
| + t.Fatal("no standing: a document was stored") |
| + } |
| + if _, err := f.app.store.Ingest(systemWrite(context.Background()), spec); err != nil { |
| + t.Fatalf("system: ingest = %v", err) |
| + } |
| + // A systemWrite drops whatever Access the context carried, so a run |
| + // that outlives its request is not bound to that request's lease. |
| + f.member(teamSubject('a'), "owner") |
| + ctx := systemWrite(f.asMember(teamSubject('a'))) |
| + if _, ok := teammode.FromContext(ctx); ok { |
| + t.Fatal("a systemWrite kept the request's Access") |
| + } |
| + |
| + off := storeForTest(t) |
| + if _, err := off.Ingest(context.Background(), spec); err != nil { |
| + t.Fatalf("team mode off: ingest = %v", err) |
| + } |
| +} |
| + |
| +// The connectors are the roster owner's inside the write too: a member's |
| +// standing commits no connector write, whatever reached the store. |
| +// |
| +// MUTATION-TESTED 2026-10-30: authorizeFor ignoring ownerWrite → red. |
| +func TestTeamConnectorWritesNeedTheOwnerRole(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.member(teamSubject('m'), "member") |
| + member := f.asMember(teamSubject('m')) |
| + if err := f.app.store.SaveConnector(member, "notion", "t", "w"); !errors.Is(err, teammode.ErrNotMember) { |
| + t.Fatalf("a member's connector save = %v, want ErrNotMember", err) |
| + } |
| + if _, err := f.app.store.StartRun(member, 1); !errors.Is(err, teammode.ErrNotMember) { |
| + t.Fatalf("a member's sync start = %v, want ErrNotMember", err) |
| + } |
| + if err := f.app.store.DeleteConnector(member, "notion"); !errors.Is(err, teammode.ErrNotMember) { |
| + t.Fatalf("a member's disconnect = %v, want ErrNotMember", err) |
| + } |
| + if f.count("connectors") != 0 || f.count("sync_runs") != 0 { |
| + t.Fatal("a member's connector write landed") |
| + } |
| + f.member(teamSubject('o'), "owner") |
| + if err := f.app.store.SaveConnector(f.asMember(teamSubject('o')), "notion", "t", "w"); err != nil { |
| + t.Fatalf("an owner's connector save = %v", err) |
| + } |
| +} |
diff --git a/internal/memoria/team_home_only.go b/internal/memoria/team_home_only.go| new file mode 100644 |
| index 0000000..167efe6 |
| --- /dev/null |
| +++ b/internal/memoria/team_home_only.go |
| @@ -0,0 +1,70 @@ |
| +package memoria |
| + |
| +// Home sign-in for a roster member with no account here: connect's two |
| +// team-mode hooks over Memoria's Home identity rows. connect completes an |
| +// ordinary Home sign-in only for a subject with an account link, and |
| +// refuses the rest as "unknown" — right for an owners-list instance, |
| +// where nobody may enter on a Home identity alone. In team mode a roster |
| +// member who has never had a local account must be able to, so WireHome |
| +// gives connect these, and connect's own completion does the rest (its |
| +// cookie checks, the same-person rule, the link flow). |
| +// |
| +// The person Unlinked creates is identity, never standing: every request |
| +// after this one asks the roster again (team_access.go). It holds no |
| +// address: an addressless memoria_home_local_identities row and the |
| +// subject it belongs to (teamstate). |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/teammode" |
| + |
| + "amadan.net/oficina/memoria/internal/memoria/teamstate" |
| +) |
| + |
| +// teamHomeOnly is connect's HomeOnly: the addressless person Unlinked |
| +// gave a subject, read and never created. |
| +func (a *app) teamHomeOnly(d *sql.DB) func(context.Context, string, string) (connect.Person, error) { |
| + return func(ctx context.Context, issuer, subject string) (connect.Person, error) { |
| + id, err := teamstate.HomeMember(ctx, d, issuer, subject) |
| + switch { |
| + case err == nil: |
| + return connect.Person{ID: id}, nil |
| + case errors.Is(err, teamstate.ErrRefused): |
| + return connect.Person{}, connect.ErrNoPerson |
| + } |
| + return connect.Person{}, errTeamUnavailable |
| + } |
| +} |
| + |
| +// teamUnlinked is connect's Unlinked, asked only when nobody is signed in |
| +// and the subject has neither a link nor a Home-only person: an |
| +// addressless person for a subject the roster says is a Member now, with |
| +// the lease on that answer still valid (Runtime.AdmitUnlinked). A |
| +// stranger is connect's "unknown"; an undecidable roster is a 503. |
| +func (a *app) teamUnlinked(d *sql.DB) func(context.Context, string, string) (connect.Person, error) { |
| + return func(ctx context.Context, issuer, subject string) (connect.Person, error) { |
| + if a.team == nil { |
| + return connect.Person{}, errTeamUnavailable |
| + } |
| + if err := a.team.AdmitUnlinked(ctx, issuer, subject); err != nil { |
| + if errors.Is(err, teammode.ErrNotMember) { |
| + return connect.Person{}, connect.ErrNoPerson |
| + } |
| + return connect.Person{}, errTeamUnavailable |
| + } |
| + id, err := teamstate.EnsureHomeMember(ctx, d, issuer, subject) |
| + switch { |
| + case err == nil: |
| + return connect.Person{ID: id}, nil |
| + case errors.Is(err, teamstate.ErrRefused): |
| + // Linked to a local account in the meantime: that person signs |
| + // in as that account, not as a new one. |
| + return connect.Person{}, connect.ErrNoPerson |
| + } |
| + return connect.Person{}, errTeamUnavailable |
| + } |
| +} |
diff --git a/internal/memoria/team_review_test.go b/internal/memoria/team_review_test.go| new file mode 100644 |
| index 0000000..b7bdd28 |
| --- /dev/null |
| +++ b/internal/memoria/team_review_test.go |
| @@ -0,0 +1,200 @@ |
| +package memoria |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/home/teammode" |
| + "amadan.net/oficina/home/teammode/teammodetest" |
| + |
| + "amadan.net/oficina/memoria/internal/memoria/provider" |
| +) |
| + |
| +// Sheets' stream-order lesson (oficina/sheets #54), for Memoria's lists: |
| +// standing is read before anything is listed, and asked again, of the |
| +// same Access, after. With the lease made to end after k clock readings, |
| +// for every k the page is either the whole Member page with no notice, or |
| +// the partial notice with nothing from the team's memory — never a list |
| +// built on standing the request did not have, and never a short list |
| +// without the notice. Both outcomes occur in the sweep. |
| +// |
| +// MUTATION-TESTED 2026-10-30, each seen red and reverted: withhold() not |
| +// clearing Results ("results under the notice"); teamPartial always |
| +// false ("a full page after the lease"); index building before asking |
| +// teamReaches with withhold dropped ("results under the notice"). |
| +func TestTeamListReadsStandingBeforeAndAfterReach(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.ingest("plan", "Nebula plan", "The nebula plan is ready.") |
| + f.member(teamSubject('a'), "member") |
| + var full, partial int |
| + for k := 0; k <= 12; k++ { |
| + for _, path := range []string{"/?q=nebula", "/search?q=nebula", "/reports"} { |
| + f.clock.SetTick(0) |
| + f.recovered() |
| + // The lease's remaining time, in readings of a clock that |
| + // moves a second per reading. |
| + // Under a failing refresh, so the lease ends on its deadline |
| + // and nothing renews it mid-request. |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge - time.Duration(k)*time.Second) |
| + f.clock.SetTick(time.Second) |
| + w := f.page(path) |
| + f.clock.SetTick(0) |
| + body := w.Body.String() |
| + if w.Code != 200 { |
| + t.Fatalf("k=%d %s = %d", k, path, w.Code) |
| + } |
| + listed := strings.Contains(body, "Nebula plan") || strings.Contains(body, "No corrections yet") |
| + switch { |
| + case isPartial(body) && listed: |
| + t.Fatalf("k=%d %s: results under the notice:\n%s", k, path, body) |
| + case !isPartial(body) && !listed: |
| + t.Fatalf("k=%d %s: a short page with no notice:\n%s", k, path, body) |
| + case isPartial(body): |
| + partial++ |
| + default: |
| + full++ |
| + } |
| + } |
| + } |
| + if full == 0 || partial == 0 { |
| + t.Fatalf("the sweep saw %d full and %d partial pages; it must see both", full, partial) |
| + } |
| +} |
| + |
| +// recovered brings the directory back and refreshes until a refresh |
| +// succeeds: a refresh that started while it was down may still be in |
| +// flight, and joining it returns its failure. |
| +func (f *teamFixture) recovered() { |
| + f.t.Helper() |
| + f.dir.SetDown(false) |
| + for i := 0; ; i++ { |
| + f.clock.Step(roster.RefreshAfter + time.Second) |
| + err := f.app.team.Refresh(context.Background()) |
| + if err == nil { |
| + return |
| + } |
| + if i == 3 { |
| + f.t.Fatalf("roster refresh: %v", err) |
| + } |
| + } |
| +} |
| + |
| +// hookAnswerer is a model that does something while it is "thinking". |
| +type hookAnswerer struct { |
| + during func() |
| + reply []provider.Sentence |
| +} |
| + |
| +func (h *hookAnswerer) Answer(context.Context, string, []string) ([]provider.Sentence, error) { |
| + if h.during != nil { |
| + h.during() |
| + } |
| + return h.reply, nil |
| +} |
| + |
| +// A long-running AI answer is revoked within the lease: a person removed |
| +// (or whose standing lapses) while the model is answering gets a |
| +// retryable 503 and not one word of what it said. MEMORIA_AI is off for |
| +// team instances unless the owner asks and Paul agrees; this is what |
| +// holds when it is on. |
| +// |
| +// MUTATION-TESTED 2026-10-30: answer's after-check removed → "delivered". |
| +func TestTeamAIAnswerIsRevokedMidAnswer(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.ingest("p", "Paul Campbell", "## Roles\n\nPaul Campbell is Chief Executive Officer and Chief Technical Officer.") |
| + f.ingest("l", "Leadership Team", "## Leadership\n\nPaul Campbell, Co-founder. Doc Parsons, Co-founder.") |
| + model := &hookAnswerer{reply: []provider.Sentence{{Text: "Paul Campbell is a co-founder of the nebula.", Cite: []int{0}}}} |
| + f.app.store.answerer = model |
| + f.member(teamSubject('a'), "member") |
| + |
| + // The presence half: answered and delivered. |
| + w := f.page("/answer?q=who+is+Paul+Campbell") |
| + if w.Code != 200 || !strings.Contains(w.Body.String(), "co-founder of the nebula") { |
| + t.Fatalf("a member's answer = %d:\n%s", w.Code, w.Body.String()) |
| + } |
| + for name, during := range map[string]func(){ |
| + "removed": func() { f.dir.Set(teamSubject('a'), ""); f.app.team.Refresh(context.Background()) }, |
| + "lapsed": f.expired, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + f.member(teamSubject('a'), "member") |
| + model.during = func() { f.clock.Step(roster.RefreshAfter + time.Second); during() } |
| + // A different question each time: the answer cache is keyed |
| + // on it, and a cached answer never reaches the model. |
| + w := f.page("/answer?q=who+is+Paul+Campbell+" + name) |
| + model.during = nil |
| + if w.Code != http.StatusServiceUnavailable || strings.Contains(w.Body.String(), "co-founder of the nebula") { |
| + t.Fatalf("%s mid-answer = %d, want a 503 and nothing the model said:\n%s", name, w.Code, w.Body.String()) |
| + } |
| + f.renewed() |
| + }) |
| + } |
| +} |
| + |
| +// A team instance never reaches anybody else's siblings: in team mode the |
| +// sibling transport's label must be this instance's own team label, the |
| +// first label of its origin, or boot is refused. Paul's own instance |
| +// (team mode off) is unchanged. |
| +// |
| +// MUTATION-TESTED 2026-10-30: the WireSiblings call to teamSiblingsBound |
| +// removed → "another team's label"; the comparison made a prefix match → |
| +// "a longer label". |
| +func TestTeamSiblingsStayOnTheTeamsOwnHosts(t *testing.T) { |
| + const origin = "https://lagged.memoria.oficina.works" |
| + boot := func(t *testing.T) *app { |
| + t.Helper() |
| + cfg, _, _ := teamConfigFor(t, teamTestBindings(origin), teamKey(t)) |
| + _, a, _, err := bootTeam(t, teamDB(t), cfg) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return a |
| + } |
| + env := func(team string) func(string) string { |
| + m := map[string]string{ |
| + "MEMORIA_TEAM": team, |
| + "MEMORIA_SIBLINGS": "Docs=https://" + team + ".docs.oficina.works", |
| + "MEMORIA_SIBLING_TOKEN_DOCS": "token", |
| + } |
| + return func(k string) string { return m[k] } |
| + } |
| + for name, team := range map[string]string{ |
| + "another team's label": "paul", |
| + "a longer label": "laggedx", |
| + "a shorter label": "lagge", |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + if err := WireSiblings(boot(t), env(team), nil); !errors.Is(err, teammode.ErrConfig) { |
| + t.Fatalf("siblings on %q from lagged's instance = %v, want ErrConfig", team, err) |
| + } |
| + }) |
| + } |
| + if err := WireSiblings(boot(t), env("lagged"), nil); err != nil { |
| + t.Fatalf("siblings on the team's own label = %v", err) |
| + } |
| + if err := WireSiblings(boot(t), func(string) string { return "" }, nil); err != nil { |
| + t.Fatalf("no siblings in team mode = %v", err) |
| + } |
| + // Team mode off: an instance whose origin names no team still takes a |
| + // roster on any label, exactly as before. |
| + f := newHomeRouterFixture(t) |
| + if err := WireSiblings(f.app, env("paul"), nil); err != nil { |
| + t.Fatalf("team mode off = %v", err) |
| + } |
| + // A team instance served from anywhere but its team host refuses any |
| + // sibling at all. |
| + if err := teamSiblingsBound("https://memoria.oficina.works", "lagged"); err == nil { |
| + t.Fatal("a team instance at Paul's host was given siblings") |
| + } |
| + if err := teamSiblingsBound("http://lagged.memoria.oficina.works", "lagged"); err == nil { |
| + t.Fatal("a cleartext origin was accepted") |
| + } |
| +} |
| + |
| +var _ = teammodetest.Team |
diff --git a/internal/memoria/team_siblings.go b/internal/memoria/team_siblings.go| new file mode 100644 |
| index 0000000..f980a7d |
| --- /dev/null |
| +++ b/internal/memoria/team_siblings.go |
| @@ -0,0 +1,40 @@ |
| +package memoria |
| + |
| +// A team instance never reaches anybody else's sibling apps — Paul's |
| +// above all (MEMORIA_SIBLINGS / MEMORIA_TEAM in team mode). |
| +// |
| +// The sibling transport already refuses any host that is not |
| +// `<MEMORIA_TEAM>.<app>.oficina.works` (suite.CheckSiblingHost, at boot in |
| +// LoadSiblings and again before every dial). What that leaves open is |
| +// MEMORIA_TEAM itself: it is an operator's string, and a team instance |
| +// given another team's label would be bound, correctly and completely, to |
| +// the wrong team. So in team mode the label must be this instance's own: |
| +// the first label of MEMORIA_ORIGIN, which Alta sets to |
| +// `https://<label>.memoria.oficina.works` beside MEMORIA_TEAM=<label>. |
| +// Anything else refuses boot. Paul's own apps sit at `<app>.oficina.works`, |
| +// which no label can name. |
| + |
| +import ( |
| + "fmt" |
| + "net/url" |
| + "strings" |
| + |
| + "amadan.net/oficina/suite" |
| +) |
| + |
| +// teamSiblingsBound refuses a sibling roster whose team label is not this |
| +// team instance's own. Called by WireSiblings only in team mode, and only |
| +// when a sibling is configured. |
| +func teamSiblingsBound(origin, team string) error { |
| + u, err := url.Parse(origin) |
| + if err != nil || u.Scheme != "https" { |
| + return fmt.Errorf("%w: in team mode MEMORIA_SIBLINGS needs MEMORIA_ORIGIN to be this team's https://<team>.memoria.%s", errTeamConfig, suite.SuiteDomain) |
| + } |
| + want := team + ".memoria." + suite.SuiteDomain |
| + if team == "" || !strings.EqualFold(strings.TrimSuffix(u.Hostname(), "."), want) || u.Port() != "" { |
| + // Neither value in the message: both are configuration, and the |
| + // operator has them; the rule is what they need. |
| + return fmt.Errorf("%w: in team mode MEMORIA_TEAM must be this instance's own team label, the first label of MEMORIA_ORIGIN (https://<team>.memoria.%s), so siblings stay on this team's hosts", errTeamConfig, suite.SuiteDomain) |
| + } |
| + return nil |
| +} |
diff --git a/internal/memoria/team_survivors_test.go b/internal/memoria/team_survivors_test.go| new file mode 100644 |
| index 0000000..dcd07f5 |
| --- /dev/null |
| +++ b/internal/memoria/team_survivors_test.go |
| @@ -0,0 +1,343 @@ |
| +package memoria |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "io" |
| + "log/slog" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/roster" |
| + "amadan.net/oficina/memoria/internal/memoria/notion" |
| + "amadan.net/oficina/memoria/internal/memoria/sibling" |
| + "amadan.net/oficina/memoria/internal/memoria/teamstate" |
| + "amadan.net/oficina/suite" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| +) |
| + |
| +// Team mode configured and no roster runtime — WireHome never ran — is |
| +// closed: every request is refused, and the owners list decides nothing. |
| +// |
| +// MUTATION-TESTED 2026-10-30: requireSession's teamMode-without-runtime |
| +// refusal removed → red (the owners list admitted the session). |
| +func TestTeamWithoutARuntimeRefusesEverything(t *testing.T) { |
| + cfg, _, _ := teamConfigFor(t, teamTestBindings(homeTestOrigin), teamKey(t), "owner@example.test") |
| + d := teamDB(t) |
| + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + mux, a, err := AppWith(d, cfg, logger) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { a.store.ix.Close() }) |
| + a.SetOwners(cfg.Owners) |
| + auth, err := NewAuth(d.Writer(), AuthEnv{Origin: cfg.Origin, InstanceKey: "k", Mailer: &homeTestMail{}, HomeEnabled: true}, logger, a) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + a.UseAuth(auth) |
| + a.MountAuth(mux, cfg.Origin) |
| + w := httptest.NewRecorder() |
| + if err := a.sess.SignIn(w, httptest.NewRequest("GET", homeTestOrigin+"/", nil), sessions.Session{Subject: "owner@example.test", Method: "magiclink", AuthTime: time.Now()}); err != nil { |
| + t.Fatal(err) |
| + } |
| + r := httptest.NewRequest("GET", homeTestOrigin+"/", nil) |
| + for _, c := range w.Result().Cookies() { |
| + r.AddCookie(c) |
| + } |
| + got := httptest.NewRecorder() |
| + mux.ServeHTTP(got, r) |
| + if got.Code != http.StatusInternalServerError { |
| + t.Fatalf("team mode with no runtime = %d, want every request refused", got.Code) |
| + } |
| +} |
| + |
| +// lapsingCustody lapses the standing of the request it is asked in, while |
| +// the list is being built: a sibling passage is ruled mid-search. |
| +type lapsingCustody struct { |
| + fixedCustody |
| + lapse func() |
| +} |
| + |
| +func (l *lapsingCustody) Rule(ctx context.Context, asker suite.Subject, cands []sibling.Candidate) []sibling.Disposition { |
| + if l.lapse != nil { |
| + l.lapse() |
| + } |
| + return l.fixedCustody.Rule(ctx, asker, cands) |
| +} |
| + |
| +// A lapse while a list is being built: the page withholds what it built |
| +// and says partial; the native API's JSON list, which has nowhere to say |
| +// so, is the retryable 503. Deterministic, where the sweep in |
| +// team_review_test.go is statistical. |
| +// |
| +// MUTATION-TESTED 2026-10-30: nativeSearch's after-check removed → |
| +// "native"; index's teamPartial check removed → "page". |
| +func TestTeamALapseWhileListingWithholdsTheList(t *testing.T) { |
| + f := newTeamFixture(t) |
| + custody := &lapsingCustody{fixedCustody: fixedCustody{apps: docsRoster(), give: suite.VISIBLE}} |
| + f.app.store.custody = custody |
| + f.ingest("plan", "Nebula plan", "The nebula plan is ready.") |
| + if _, err := f.app.store.Ingest(systemWrite(context.Background()), IngestSpec{Source: "Docs", Key: "s", Title: "Shared nebula", Body: "nebula sibling content", ItemID: "doc-one", SiblingRevision: 3}); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.member(teamSubject('a'), "member") |
| + |
| + // The presence half. |
| + if w := f.page("/?q=nebula"); w.Code != 200 || !strings.Contains(w.Body.String(), "Nebula plan") || isPartial(w.Body.String()) { |
| + t.Fatalf("member page = %d", w.Code) |
| + } |
| + if w := f.json("POST", "/api/native/search", `{"query":"nebula"}`); w.Code != 200 || !strings.Contains(w.Body.String(), "Nebula plan") { |
| + t.Fatalf("member native search = %d %s", w.Code, w.Body.String()) |
| + } |
| + |
| + custody.lapse = f.expired |
| + w := f.page("/?q=nebula") |
| + if w.Code != 200 || !isPartial(w.Body.String()) || strings.Contains(w.Body.String(), "Nebula plan") || strings.Contains(w.Body.String(), "Shared nebula") { |
| + t.Fatalf("page: a lapse while listing = %d:\n%s", w.Code, w.Body.String()) |
| + } |
| + f.recovered() |
| + n := f.json("POST", "/api/native/search", `{"query":"nebula"}`) |
| + if n.Code != http.StatusServiceUnavailable || strings.Contains(n.Body.String(), "Nebula") { |
| + t.Fatalf("native: a lapse while listing = %d %s, want 503", n.Code, n.Body.String()) |
| + } |
| +} |
| + |
| +// onePage is a Notion with one page. |
| +type onePage struct{} |
| + |
| +func (onePage) Roots(context.Context) ([]notion.Ref, []notion.Ref, error) { |
| + return []notion.Ref{{ID: "p1", Title: "Nebula page", EditedTime: "2026-10-30T00:00:00.000Z"}}, nil, nil |
| +} |
| +func (onePage) Fetch(context.Context, notion.Ref) (*notion.Content, error) { |
| + return ¬ion.Content{Markdown: "the nebula page body"}, nil |
| +} |
| + |
| +// The instance's own work is not a person's write: a connector run and a |
| +// sibling poll import in team mode with no request's standing behind |
| +// them — after the owner who started the run has gone, too. |
| +// |
| +// MUTATION-TESTED 2026-10-30: systemWrite removed from Syncer.RunWith → |
| +// "connector run"; from Store.Poll → "sibling poll". |
| +func TestTeamTheInstancesOwnWorkIsNotAPersonsWrite(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.member(teamSubject('o'), "owner") |
| + if err := f.app.store.SaveConnector(f.asMember(teamSubject('o')), "notion", "t", "w"); err != nil { |
| + t.Fatal(err) |
| + } |
| + run, err := f.app.store.StartRun(f.asMember(teamSubject('o')), 1) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // The owner leaves before the run imports anything. |
| + f.dir.Set(teamSubject('o'), "") |
| + f.refreshed() |
| + f.app.syncer.RunWith(f.asMemberOrNone(teamSubject('o')), onePage{}, 1, run.ID) |
| + if f.count("documents") != 1 { |
| + t.Fatalf("connector run: %d documents imported, want 1", f.count("documents")) |
| + } |
| + |
| + fs := &feedServer{t: t, pages: map[string]suite.Feed{"": {Cursor: "c1", Rows: []suite.FeedRow{row("d1", 1, false)}}, "c1": {Cursor: "c1", Rows: []suite.FeedRow{}}}, bodies: map[string]string{"d1": "a nebula sibling body"}} |
| + sib, client := fs.start(t) |
| + if _, err := f.app.store.Poll(context.Background(), client, sib); err != nil { |
| + t.Fatalf("sibling poll: %v", err) |
| + } |
| + if f.count("documents") != 2 { |
| + t.Fatalf("sibling poll: %d documents, want 2", f.count("documents")) |
| + } |
| +} |
| + |
| +// asMemberOrNone is the context a request for subject would carry now, |
| +// whatever their standing: what a run started by them inherits. |
| +func (f *teamFixture) asMemberOrNone(subject string) context.Context { |
| + return withTeamPerson(context.Background(), &teamPerson{subject: subject, access: f.app.team.Access(context.Background(), subject)}) |
| +} |
| + |
| +// withhold is what keeps a list built on standing that did not last from |
| +// being shown. The templates also render nothing but the notice when |
| +// Partial is set, so through HTTP this is defence in depth that no page |
| +// can show missing (two mutations survived the page tests): it is called |
| +// directly here, and every list field it must clear is set first. |
| +// |
| +// MUTATION-TESTED 2026-10-30: each of withhold's clears dropped in turn |
| +// (Results, Documents, Facts, Answer, the reports' two lists) → red. |
| +func TestTeamWithholdClearsEveryList(t *testing.T) { |
| + p := page{Results: []Result{{}}, Documents: []Summary{{}}, Notices: []string{"n"}, Facts: []Fact{{}}, Explained: []FactExplanation{{}}, |
| + FactsDeferred: true, AnswerSlot: true, Answer: &AIAnswer{}, Primed: true, Chunks: 7} |
| + p.withhold() |
| + if !p.Partial || p.Results != nil || p.Documents != nil || p.Notices != nil || p.Facts != nil || p.Explained != nil || |
| + p.FactsDeferred || p.AnswerSlot || p.Answer != nil || p.Primed || p.Chunks != -1 { |
| + t.Fatalf("withhold left %+v", p) |
| + } |
| + r := reportsPage{Reports: []ReportView{{}}, Feedback: []FeedbackView{{}}} |
| + r.withhold() |
| + if !r.Partial || r.Reports != nil || r.Feedback != nil { |
| + t.Fatalf("reports withhold left %+v", r) |
| + } |
| +} |
| + |
| +// MEMORIA_OWNERS still decides a LOCAL session in team mode: an address |
| +// taken off it is signed out and told so, as always, whatever its link |
| +// says. (It decides nothing about a Home session: see |
| +// TestTeamLinkedAccountStandsOnTheRoster.) |
| +// |
| +// MUTATION-TESTED 2026-10-30: teamIdentify ignoring the owners list for a |
| +// local session → red. |
| +func TestTeamOwnersListStillGatesALocalSession(t *testing.T) { |
| + f := newTeamFixture(t, "alice@example.test") |
| + subject := teamSubject('l') |
| + f.dir.Set(subject, "member") |
| + f.refreshed() |
| + f.local(t) |
| + if got := f.linkFromMenu(t, subject); got.Code != http.StatusSeeOther { |
| + t.Fatalf("link = %d", got.Code) |
| + } |
| + if w := f.page("/"); w.Code != 200 { |
| + t.Fatalf("linked local session = %d", w.Code) |
| + } |
| + f.app.SetOwners(nil) |
| + if w := f.page("/"); w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/signin?err=removed" { |
| + t.Fatalf("local session off the owners list = %d %q", w.Code, w.Header().Get("Location")) |
| + } |
| +} |
| + |
| +// teamstate refuses, itself, what its callers should never ask: a person |
| +// for a subject that is linked to a local account, and a subject shaped |
| +// like an address. Both are also refused elsewhere (a trigger; roster's |
| +// subject check before any lookup), which is why each is tested here, |
| +// directly, where only this layer can answer. |
| +// |
| +// MUTATION-TESTED 2026-10-30: EnsureHomeMember's link check dropped → |
| +// "linked" (the trigger then answers, as unavailable rather than |
| +// refused); Opaque accepting "@" → "address". |
| +func TestTeamStateRefusesLinkedSubjectsAndAddresses(t *testing.T) { |
| + f := newTeamFixture(t) |
| + w := f.d.Writer() |
| + if _, err := w.Exec("INSERT INTO memoria_home_local_identities(address_lookup,address_sealed) VALUES('abc',X'01')"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := w.Exec("INSERT INTO home_identity_links(issuer,subject,person_id) VALUES(?,?,1)", homeTestIssuer, teamSubject('k')); err != nil { |
| + t.Fatal(err) |
| + } |
| + people := f.count("memoria_home_local_identities") |
| + if _, err := teamstate.EnsureHomeMember(context.Background(), w, homeTestIssuer, teamSubject('k')); !errors.Is(err, teamstate.ErrRefused) { |
| + t.Fatalf("linked: EnsureHomeMember = %v, want ErrRefused", err) |
| + } |
| + if _, err := teamstate.EnsureHomeMember(context.Background(), w, homeTestIssuer, "someone@example.test"); !errors.Is(err, teamstate.ErrRefused) { |
| + t.Fatalf("address: EnsureHomeMember = %v, want ErrRefused", err) |
| + } |
| + if f.count("memoria_home_local_identities") != people { |
| + t.Fatal("a refused subject was allocated a person") |
| + } |
| + // The trigger under it, for a writer that skips the check. |
| + res, err := w.Exec("INSERT INTO memoria_home_local_identities(address_lookup,address_sealed) VALUES('home-only:z',X'')") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + id, _ := res.LastInsertId() |
| + if _, err := w.Exec("INSERT INTO memoria_team_home_members(issuer,subject,person_id) VALUES(?,?,?)", homeTestIssuer, teamSubject('k'), id); err == nil { |
| + t.Fatal("a linked subject was made Home-only beneath the check") |
| + } |
| +} |
| + |
| +// tools/drive's preview of Unknown acts only under AppForTest: on an app |
| +// built for production it changes nothing. |
| +func TestTeamPreviewUnknownIsDriveOnly(t *testing.T) { |
| + f := newHomeRouterFixture(t) |
| + f.app.store.Ingest(context.Background(), IngestSpec{Source: "upload", Key: "n", Title: "Nebula plan", Body: "The nebula plan is ready."}) |
| + f.app.PreviewUnknownStanding() |
| + f.local(t) |
| + if w := f.do("GET", "/?q=nebula", ""); w.Code != 200 || isPartial(w.Body.String()) || !strings.Contains(w.Body.String(), "Nebula plan") { |
| + t.Fatalf("a production app previewing Unknown = %d, partial %v", w.Code, isPartial(w.Body.String())) |
| + } |
| +} |
| + |
| +// A Home session whose subject no longer resolves to anybody here — no |
| +// link, no Home-only person — speaks for nobody: it is signed out and told |
| +// so, on a page and at /signin alike, never an endless 503. |
| +// |
| +// MUTATION-TESTED 2026-10-30 (independent pass, 05 and 15): an |
| +// unresolvable Home subject read as unavailable → red; teamAdmission |
| +// reading it as unresolved → red ("signin"). |
| +func TestTeamAHomeSessionForNobodyIsSignedOut(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.dir.Set(teamSubject('z'), "member") |
| + f.refreshed() |
| + mint := func() { |
| + f.cookies = map[string]*http.Cookie{} |
| + w := httptest.NewRecorder() |
| + if err := f.app.home.sessions.SignIn(w, httptest.NewRequest("GET", homeTestOrigin+"/", nil), sessions.Session{Subject: teamSubject('z'), Method: connect.HomeMethod, AuthTime: time.Now()}); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, c := range w.Result().Cookies() { |
| + f.cookies[c.Name] = c |
| + } |
| + } |
| + mint() |
| + if w := f.page("/"); w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/signin?err=removed" { |
| + t.Fatalf("page: a Home session for nobody = %d %q", w.Code, w.Header().Get("Location")) |
| + } |
| + if _, ok := f.sessionNow(); ok { |
| + t.Fatal("page: a Home session for nobody survived") |
| + } |
| + mint() |
| + if w := f.page("/signin"); w.Code != http.StatusSeeOther || w.Header().Get("Location") != "/signin?err=removed" { |
| + t.Fatalf("signin: a Home session for nobody = %d %q", w.Code, w.Header().Get("Location")) |
| + } |
| +} |
| + |
| +// The roster owner's /connectors under a lease ending mid-request: the |
| +// owner's own page, or a retryable 503 — never the 404 a member gets, |
| +// which would tell an owner the page does not exist because Home was slow. |
| +// |
| +// MUTATION-TESTED 2026-10-30 (independent pass, 03): the owner branch's |
| +// lapse read as NotMember → red. |
| +func TestTeamOwnerScreensUnderALapseAreNever404(t *testing.T) { |
| + f := newTeamFixture(t) |
| + f.member(teamSubject('o'), "owner") |
| + var ok, unavailable int |
| + for k := 0; k <= 10; k++ { |
| + f.clock.SetTick(0) |
| + f.recovered() |
| + f.dir.SetDown(true) |
| + f.clock.Step(roster.MaximumAge - time.Duration(k)*time.Second) |
| + f.clock.SetTick(time.Second) |
| + w := f.page("/connectors") |
| + f.clock.SetTick(0) |
| + switch w.Code { |
| + case 200: |
| + ok++ |
| + case http.StatusServiceUnavailable: |
| + unavailable++ |
| + default: |
| + t.Fatalf("k=%d owner's /connectors = %d", k, w.Code) |
| + } |
| + } |
| + if ok == 0 || unavailable == 0 { |
| + t.Fatalf("the sweep saw %d pages and %d 503s; it must see both", ok, unavailable) |
| + } |
| +} |
| + |
| +// Team mode off, the Home hooks are not wired: an unknown Home subject is |
| +// connect's 403 and nothing is allocated, exactly as before. |
| +// |
| +// MUTATION-TESTED 2026-10-30 (independent pass, 14): the hooks wired |
| +// whenever Home is → red. |
| +func TestTeamOffAnUnknownHomeSubjectIsStillRefused(t *testing.T) { |
| + f := newHomeRouterFixture(t) |
| + var before int |
| + f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM memoria_home_local_identities").Scan(&before) |
| + w := f.exchange(t, homeRedirect(t, f.do("GET", "/signin", "")), teamSubject('u')) |
| + if w.Code != http.StatusForbidden { |
| + t.Fatalf("team mode off, unknown Home subject = %d, want 403", w.Code) |
| + } |
| + var after int |
| + f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM memoria_home_local_identities").Scan(&after) |
| + if after != before { |
| + t.Fatal("team mode off allocated a person for an unknown Home subject") |
| + } |
| +} |
diff --git a/internal/memoria/teamstate/migrations/0001_home_members.sql b/internal/memoria/teamstate/migrations/0001_home_members.sql| new file mode 100644 |
| index 0000000..2fae9fc |
| --- /dev/null |
| +++ b/internal/memoria/teamstate/migrations/0001_home_members.sql |
| @@ -0,0 +1,13 @@ |
| +CREATE TABLE memoria_team_home_members ( |
| + issuer TEXT NOT NULL, |
| + subject TEXT NOT NULL, |
| + person_id INTEGER NOT NULL UNIQUE REFERENCES memoria_home_local_identities(id), |
| + PRIMARY KEY(issuer,subject) |
| +); |
| +CREATE TRIGGER memoria_team_home_member_addressless BEFORE INSERT ON memoria_team_home_members WHEN NOT EXISTS(SELECT 1 FROM memoria_home_local_identities WHERE id=NEW.person_id AND length(address_sealed)=0 AND substr(address_lookup,1,10)='home-only:') BEGIN SELECT RAISE(ABORT,'memoria team: refused'); END; |
| +CREATE TRIGGER memoria_team_home_member_unlinked BEFORE INSERT ON memoria_team_home_members WHEN EXISTS(SELECT 1 FROM home_identity_links WHERE issuer=NEW.issuer AND subject=NEW.subject) BEGIN SELECT RAISE(ABORT,'memoria team: refused'); END; |
| +CREATE TRIGGER memoria_team_home_members_keep_update BEFORE UPDATE ON memoria_team_home_members BEGIN SELECT RAISE(ABORT,'memoria team: refused'); END; |
| +CREATE TRIGGER memoria_team_home_members_keep_delete BEFORE DELETE ON memoria_team_home_members BEGIN SELECT RAISE(ABORT,'memoria team: refused'); END; |
| +CREATE TRIGGER memoria_team_link_not_home_only BEFORE INSERT ON home_identity_links WHEN EXISTS(SELECT 1 FROM memoria_team_home_members WHERE (issuer=NEW.issuer AND subject=NEW.subject) OR person_id=NEW.person_id) BEGIN SELECT RAISE(ABORT,'memoria team: refused'); END; |
| +CREATE TRIGGER memoria_team_home_member_keeps_no_address BEFORE UPDATE ON memoria_home_local_identities WHEN EXISTS(SELECT 1 FROM memoria_team_home_members WHERE person_id=OLD.id) BEGIN SELECT RAISE(ABORT,'memoria team: refused'); END; |
| +CREATE TRIGGER memoria_team_home_member_keep_row BEFORE DELETE ON memoria_home_local_identities WHEN EXISTS(SELECT 1 FROM memoria_team_home_members WHERE person_id=OLD.id) BEGIN SELECT RAISE(ABORT,'memoria team: refused'); END; |
diff --git a/internal/memoria/teamstate/store.go b/internal/memoria/teamstate/store.go| new file mode 100644 |
| index 0000000..4d6906e |
| --- /dev/null |
| +++ b/internal/memoria/teamstate/store.go |
| @@ -0,0 +1,151 @@ |
| +// Package teamstate keeps the Home-only people a roster admitted in team |
| +// mode, and the reverse lookup from a person to the Home subject the |
| +// roster knows them by. |
| +// |
| +// The marker and the roster evidence are not here: they are |
| +// home/teammode's State ("memoria", set memoria_team), merged beside this |
| +// package's own set (memoria_team_home). Memoria's local people are its |
| +// memoria_home_local_identities rows, the IDs connect's links name, so a |
| +// Home-only person is one of those rows holding no address — an empty |
| +// sealed blob and a lookup no address fingerprint can equal — and this |
| +// package's table says which Home subject it belongs to. Sharing the row |
| +// is what keeps the two kinds of person in one ID space: connect's |
| +// same-person rule compares IDs, and a Home-only ID that could equal a |
| +// local account's would let one arrive over the other's session. |
| +// |
| +// None of it is standing. A Home-only row says who a Home subject is on |
| +// this instance, never whether they are on the team: that is the |
| +// roster's answer, asked again on every request. |
| +package teamstate |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "embed" |
| + "errors" |
| + "strings" |
| + "unicode/utf8" |
| + |
| + "github.com/google/uuid" |
| + |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| +) |
| + |
| +//go:embed migrations/*.sql |
| +var migrations embed.FS |
| + |
| +// Schema is the Home-only members table and its triggers. They name |
| +// memoria_home_local_identities and home_identity_links, so it is merged |
| +// after the Home identity and link store sets (team_config.go's teamBoot). |
| +var Schema = migrate.MustFromFS(migrations, "memoria_team_home") |
| + |
| +// homeOnlyLookup prefixes a Home-only person's address_lookup. A real |
| +// lookup is a hex HMAC (seal.Fingerprint), which never contains ':', so no |
| +// address can be looked up to one of these rows; the table's trigger |
| +// insists on the prefix and an empty sealed address. |
| +const homeOnlyLookup = "home-only:" |
| + |
| +var ( |
| + // ErrRefused is a definite "no": no such person, or a subject that |
| + // cannot be one. |
| + ErrRefused = errors.New("memoria team: refused") |
| + // ErrUnavailable is "cannot read it now". |
| + ErrUnavailable = errors.New("memoria team: unavailable") |
| +) |
| + |
| +// HomeMember reads the person a Home-only identity was given. It never |
| +// creates one: ErrRefused means there is none. |
| +func HomeMember(ctx context.Context, db *sql.DB, issuer, subject string) (int64, error) { |
| + if !Opaque(subject) { |
| + return 0, ErrRefused |
| + } |
| + var id int64 |
| + e := db.QueryRowContext(ctx, "SELECT person_id FROM memoria_team_home_members WHERE issuer=? AND subject=?", issuer, subject).Scan(&id) |
| + if errors.Is(e, sql.ErrNoRows) { |
| + return 0, ErrRefused |
| + } |
| + if e != nil { |
| + return 0, ErrUnavailable |
| + } |
| + return id, nil |
| +} |
| + |
| +// LinkedSubject is the Home subject a local account is linked to, through |
| +// connect's link table. ErrRefused means no link, which is no team |
| +// standing, never an error. |
| +func LinkedSubject(ctx context.Context, db *sql.DB, issuer string, person int64) (string, error) { |
| + var subject string |
| + e := db.QueryRowContext(ctx, "SELECT subject FROM home_identity_links WHERE issuer=? AND person_id=?", issuer, person).Scan(&subject) |
| + if errors.Is(e, sql.ErrNoRows) { |
| + return "", ErrRefused |
| + } |
| + if e != nil { |
| + return "", ErrUnavailable |
| + } |
| + return subject, nil |
| +} |
| + |
| +// EnsureHomeMember gives a Home subject an addressless person, or returns |
| +// the one it already has. The caller must have just had a current roster |
| +// answer of Member for this subject: this records identity, not standing, |
| +// and a later request asks the roster again. A subject already linked to |
| +// a local account is refused — that person signs in as that account. |
| +func EnsureHomeMember(ctx context.Context, db *sql.DB, issuer, subject string) (int64, error) { |
| + if !Opaque(subject) || issuer == "" { |
| + return 0, ErrRefused |
| + } |
| + tx, e := db.BeginTx(ctx, nil) |
| + if e != nil { |
| + return 0, ErrUnavailable |
| + } |
| + defer tx.Rollback() |
| + var linked int |
| + if e = tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM home_identity_links WHERE issuer=? AND subject=?", issuer, subject).Scan(&linked); e != nil { |
| + return 0, ErrUnavailable |
| + } |
| + if linked != 0 { |
| + return 0, ErrRefused |
| + } |
| + var id int64 |
| + e = tx.QueryRowContext(ctx, "SELECT person_id FROM memoria_team_home_members WHERE issuer=? AND subject=?", issuer, subject).Scan(&id) |
| + if e == nil { |
| + if tx.Commit() != nil { |
| + return 0, ErrUnavailable |
| + } |
| + return id, nil |
| + } |
| + if !errors.Is(e, sql.ErrNoRows) { |
| + return 0, ErrUnavailable |
| + } |
| + // The person row: no address, sealed or otherwise, and a lookup that |
| + // is random rather than derived from the subject, so nothing about |
| + // the person is written twice. |
| + res, e := tx.ExecContext(ctx, "INSERT INTO memoria_home_local_identities(address_lookup,address_sealed) VALUES(?,?)", homeOnlyLookup+uuid.NewString(), []byte{}) |
| + if e != nil { |
| + return 0, ErrUnavailable |
| + } |
| + if id, e = res.LastInsertId(); e != nil || id <= 0 { |
| + return 0, ErrUnavailable |
| + } |
| + if _, e = tx.ExecContext(ctx, "INSERT INTO memoria_team_home_members(issuer,subject,person_id) VALUES(?,?,?)", issuer, subject, id); e != nil { |
| + return 0, ErrUnavailable |
| + } |
| + if tx.Commit() != nil { |
| + return 0, ErrUnavailable |
| + } |
| + return id, nil |
| +} |
| + |
| +// Opaque is a Home subject's shape: bounded, printable, and never an |
| +// address, so a subject can never be mistaken for one. |
| +func Opaque(s string) bool { |
| + if s == "" || len(s) > 512 || !utf8.ValidString(s) || strings.Contains(s, "@") { |
| + return false |
| + } |
| + for _, r := range s { |
| + if r <= 32 || r == 127 { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
diff --git a/internal/memoria/templates/index.html b/internal/memoria/templates/index.html| index 63a041e..8c5eefe 100644 |
| --- a/internal/memoria/templates/index.html |
| +++ b/internal/memoria/templates/index.html |
| @@ -32,7 +32,7 @@ |
| {{if .Flash}}<div rst-callout rst-tone="{{.FlashKind | tone}}"{{if eq .FlashKind "danger"}} role="alert"{{end}}><div rst-callout-body><p>{{.Flash}}</p></div></div>{{end}} |
| <section rst-section> |
| - <div rst-section-head> |
| + {{if .Partial}}{{if not .Searched}}{{template "partial" .}}{{end}}{{else}}<div rst-section-head> |
| <h2>{{len .Documents}} document{{if ne (len .Documents) 1}}s{{end}}</h2> |
| <a rst-btn="primary" href="/add">Add content</a> |
| </div> |
| @@ -58,6 +58,6 @@ |
| {{end}} |
| </tbody> |
| </table> |
| - {{end}} |
| + {{end}}{{end}} |
| </section> |
| {{end}} |
diff --git a/internal/memoria/templates/reports.html b/internal/memoria/templates/reports.html| index c125b8f..5ad1403 100644 |
| --- a/internal/memoria/templates/reports.html |
| +++ b/internal/memoria/templates/reports.html |
| @@ -3,7 +3,8 @@ |
| holds no passage text. */}} |
| {{define "content"}} |
| <section rst-reports> |
| - <h1>Reports</h1> |
| + <h1>Reports</h1>{{if .Partial}} |
| + {{template "partial" .}}{{else}} |
| {{if not .Reports}} |
| <p rst-muted>No corrections yet. When the answer at the top of a search is wrong, “Is this wrong?” brings you here.</p> |
| {{else}} |
| @@ -43,6 +44,6 @@ |
| </li> |
| {{end}} |
| </ol> |
| - {{end}} |
| + {{end}}{{end}} |
| </section> |
| {{end}} |
diff --git a/internal/memoria/templates/results.html b/internal/memoria/templates/results.html| index bf0ce6f..d4dbf45 100644 |
| --- a/internal/memoria/templates/results.html |
| +++ b/internal/memoria/templates/results.html |
| @@ -11,11 +11,21 @@ |
| and a page with two wordings for that would be two pages. */}} |
| {{define "searchFailed"}}The search did not run. Nothing was found because nothing was searched.{{end}} |
| +{{/* Team mode, standing Unknown (Paul, 2026-10-28): a list page is partial |
| + with this notice, never a 503 — and in Memoria, which has no shares, |
| + the partial list is empty, so this is what stops it reading as |
| + "nothing matched". Rendered only then, and nothing at all otherwise. */}} |
| +{{define "partial"}}<div rst-callout rst-tone="warning"> |
| + <div rst-callout-body><strong>{{.PartialNotice.Title}}</strong><p>{{.PartialNotice.Body}}</p></div> |
| + </div>{{end}} |
| + |
| {{define "results"}} |
| {{if .SearchFailed}} |
| <div rst-callout rst-tone="negative"> |
| <div rst-callout-body><p>{{template "searchFailed"}}</p></div> |
| </div> |
| +{{else if .Partial}}{{if .Searched}} |
| + {{template "partial" .}}{{end}} |
| {{else if .Searched}} |
| {{/* A typing request skipped §8.9's model step (nothing was sent); |
| search.js sees this and asks again, in full, once typing pauses. */}} |
diff --git a/internal/memoriatest/errors_gate_test.go b/internal/memoriatest/errors_gate_test.go| index 90a8357..21cdbb1 100644 |
| --- a/internal/memoriatest/errors_gate_test.go |
| +++ b/internal/memoriatest/errors_gate_test.go |
| @@ -23,7 +23,7 @@ var plainTextErrors = map[string]struct { |
| n int |
| why string |
| }{ |
| - "app.go:requireSession": {1, "a boot misconfiguration (no sign-in wired): every request is refused, and there is no viewer to draw chrome for"}, |
| + "app.go:requireSession": {2, "a boot misconfiguration (no sign-in wired, or team mode configured with no roster runtime): every request is refused, and there is no viewer to draw chrome for"}, |
| "auth.go:beginGuard": {1, "the same misconfiguration on the sign-in POST (no owners list)"}, |
| "errors.go:plainError": {1, "the plain answer itself, for a request that did not ask for a page"}, |
| "errors.go:methodNotAllowed": {1, "405 to a method no route takes, with Allow set: never a navigation (a GET of a POST-only path gets the 404 page)"}, |
diff --git a/internal/memoriatest/gates_test.go b/internal/memoriatest/gates_test.go| index 2d3c5c5..0efa0f8 100644 |
| --- a/internal/memoriatest/gates_test.go |
| +++ b/internal/memoriatest/gates_test.go |
| @@ -486,12 +486,19 @@ func TestProductionDoesNotUseTheTestConstructor(t *testing.T) { |
| // in main it bypasses the owner's opt-in, and handed a real |
| // client it sends content the owner never agreed to send. |
| "UseFakeModel", |
| + // PreviewUnknownStanding is tools/drive's look at team mode's |
| + // partial lists. It acts only under AppForTest, and in main it |
| + // would be a page that withholds everything for no reason. |
| + "PreviewUnknownStanding", |
| } { |
| if strings.Contains(string(raw), seam) { |
| t.Errorf("%s calls the test seam %s; production must not reach it", p, seam) |
| } |
| } |
| - if !strings.Contains(string(raw), "memoria.App(") { |
| + // AppWith is App from the whole Config (team mode, 2026-10-30): |
| + // main builds the app through it, and the checks below must not |
| + // quietly stop applying because the constructor's name grew. |
| + if !strings.Contains(string(raw), "memoria.App(") && !strings.Contains(string(raw), "memoria.AppWith(") { |
| return nil |
| } |
| // Every setter the app needs and cannot supply itself. |
diff --git a/internal/memoriatest/routes_test.go b/internal/memoriatest/routes_test.go| index 50bda00..eba3b69 100644 |
| --- a/internal/memoriatest/routes_test.go |
| +++ b/internal/memoriatest/routes_test.go |
| @@ -71,9 +71,13 @@ func TestNoUndeclaredRoutes(t *testing.T) { |
| // TestBrandRouteIsEstilosPrefix keeps the literal equal to |
| // brand.Prefix. |
| "GET /static/estilo/brand/": true, |
| - "/": true, |
| - "/auth/": true, |
| - "POST /signout": true, |
| + // Team mode's readiness probe (team_config.go): public and |
| + // no-store, {"team_mode":false} with team mode off, and in team |
| + // mode {team_mode, consumer, roster} with no account data. |
| + "GET /api/team": true, |
| + "/": true, |
| + "/auth/": true, |
| + "POST /signout": true, |
| } |
| // Router method -> index of the pattern argument. Handle, HandleFunc, |
| // Mount and Route bind every method, so they read as ANY. |
diff --git a/tools/drive/main.go b/tools/drive/main.go| index e6ed516..0d0ab24 100644 |
| --- a/tools/drive/main.go |
| +++ b/tools/drive/main.go |
| @@ -51,6 +51,10 @@ func main() { |
| // recipe in drop_test.go would have handed the next reader exactly |
| // that panic. |
| parent := flag.String("dir", "", "parent directory for the throwaway database (default: the system temp directory)") |
| + // Team mode's Unknown standing (spec §4.3, "Roster team mode"): the |
| + // lists render partial with the notice. Drive has no roster, so this |
| + // is the only way that section is ever seen before a team uses it. |
| + unknown := flag.Bool("unknown", false, "render the lists as team mode does when the roster cannot be read") |
| flag.Parse() |
| logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn})) |
| @@ -94,6 +98,9 @@ func main() { |
| // numbers in it. |
| seedConnector(app) |
| seedSiblings(app) |
| + if *unknown { |
| + app.PreviewUnknownStanding() |
| + } |
| fmt.Printf("drive serving on http://%s (no sign-in)\n", *addr) |
| if err := http.ListenAndServe(*addr, mux); err != nil { |