oficina / home Public

Add current-authority directory discovery for Oficina agent connections

Prompts:

  Maybe crack on with own-rolled and coalesce on a later Rastrillo update?

Squashed from feat/agent-access into main.
codex agent, operated by paul@keymail.dev d82341cd9a0c3ab332a7257a113510a2e7637af5 parent 548ec74
14 files changed, +543 −20
  • Makefile +2 −1
  • connect/README.md +10 −2
  • connect/api.go +13 −1
  • connect/linkstore/resolve_on_test.go +76 −0
  • connect/linkstore/store.go +10 −3
  • connect/resolve_on_test.go +87 −0
  • docs/superpowers/specs/2026-08-30-home-design.md +31 −0
  • docs/superpowers/specs/2026-10-25-transactional-link-resolution.md +11 −0
  • implementation/teammode-package.md +7 −2
  • internal/home/agent_directory.go +96 −0
  • internal/home/agent_directory_test.go +158 −0
  • internal/home/directory.go +4 −0
  • internal/home/directorydata/store.go +18 −1
  • internal/home/runtime.go +20 −10

CI cancelled — superseded by a newer push — run details

landed from feat/agent-access

diff --git a/Makefile b/Makefile
index a035680..8fbf2c5 100644
--- a/Makefile
+++ b/Makefile
@@ -127,7 +127,8 @@ test-go:
# CGO_ENABLED. Nothing it builds is shipped, so it does not violate the
# cgo-free binary rule, which is about what gets deployed.
test-race:
- go test -race -count=1 ./internal/home/ ./internal/operator/ ./internal/operatorlaunch/ ./internal/provisioner/ ./internal/home/directorydata/
+ go test -race -count=1 ./internal/home/ ./internal/operator/ ./internal/operatorlaunch/ ./internal/home/directorydata/
+ @if [ "$$(go env GOOS)" = linux ]; then go test -race -count=1 ./internal/provisioner/; fi
cd handoff && CGO_ENABLED=1 go test -race -count=1 ./...
cd roster && CGO_ENABLED=1 go test -race -count=1 ./...
cd dashboard && CGO_ENABLED=1 go test -race -count=1 ./...
diff --git a/connect/README.md b/connect/README.md
index 6c185a8..da8f01e 100644
--- a/connect/README.md
+++ b/connect/README.md
@@ -97,8 +97,7 @@ who has never had a local account (`home/teammode`,
`implementation/teammode-package.md`).
- `HomeOnly(ctx, issuer, subject)` reads, never creates, the person a subject
- was given. Connect asks it after the account link wherever it resolves a
- Home subject: `Resolve`, `ResolveSession` and completion, so the
+ was given. Connect asks it after the account link in ordinary resolution: `Resolve`, `ResolveSession` and completion, so the
same-person rules hold for Home-only people too. It returns `ErrNoPerson`
for none. The person has a positive ID and an empty `Label`; connect
refuses one with a label, because there is no address to give.
@@ -187,3 +186,12 @@ local-account hooks. The app-owned content-preservation test now checks an
unchanged content row; framework CSRF coverage belongs to the shared Routes
and each app's router integration tests. Existing Docs tables and bytes are
untouched. This is not a migration path for an already deployed Docs instance.
+
+`Bridge.ResolveOn(ctx, q, subject)` is explicitly limited to existing account
+links. It verifies the complete keyed binding and current local lookup through
+`q`, including while the caller holds SQLite's writer. It never invokes
+`HomeOnly` or `Unlinked`: those hooks cannot use the caller's transaction.
+An addressless identity is refused by this method. Ordinary `Resolve`, session
+resolution and browser completion retain their Home-only behavior. Agent
+consumers that require linked local accounts must apply that restriction to
+reads and response checks as well as writes.
diff --git a/connect/api.go b/connect/api.go
index 3adc220..ad33166 100644
--- a/connect/api.go
+++ b/connect/api.go
@@ -64,8 +64,9 @@ type Config struct {
Unlinked func(ctx context.Context, issuer, subject string) (Person, error)
// HomeOnly reads, never creates, the person Unlinked gave a subject;
// ErrNoPerson when there is none. Connect asks it after the account
- // link, wherever it resolves a Home subject (Resolve, ResolveSession,
+ // link in ordinary resolution (Resolve, ResolveSession,
// completion), so the same-person rules hold for Home-only people too.
+ // ResolveOn is explicitly linked-only: this hook has no transaction input.
// A HomeOnly person has a positive ID and an empty Label: there is no
// address to give, and connect refuses a Home-only person with one.
HomeOnly func(ctx context.Context, issuer, subject string) (Person, error)
@@ -116,6 +117,17 @@ func (b *Bridge) Linked(ctx context.Context, person int64) (bool, error) {
func (b *Bridge) Adopt(ctx context.Context, tx *sql.Tx, issuer, subject string, person int64) error {
return b.links.Adopt(ctx, tx, issuer, subject, person)
}
+
+// ResolveOn resolves an existing account link at the fixed Home issuer on the
+// caller's transaction, including the keyed person binding and current local
+// admission. Unlike Resolve, it does not fall back to Config.HomeOnly: that
+// hook cannot read through the caller's transaction. A Home-only identity is
+// refused rather than resolved outside the transaction's authority checks.
+func (b *Bridge) ResolveOn(ctx context.Context, q linkstore.Queryer, subject string) (Person, error) {
+ id, label, err := b.links.ResolveOn(ctx, q, b.issuer, subject)
+ return Person{ID: id, Label: label}, err
+}
+
func (b *Bridge) ResolveSession(r *http.Request) (Person, error) {
session, err := b.actualSession(r)
if err != nil || session == nil {
diff --git a/connect/linkstore/resolve_on_test.go b/connect/linkstore/resolve_on_test.go
new file mode 100644
index 0000000..05dc9a7
--- /dev/null
+++ b/connect/linkstore/resolve_on_test.go
@@ -0,0 +1,76 @@
+package linkstore
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "testing"
+ "time"
+)
+
+func TestResolveOnUsesHeldTransactionAndCompleteBinding(t *testing.T) {
+ s, _ := fixture(t)
+ s.db.SetMaxOpenConns(1)
+ l := local(1)
+ proof := complete(t, s, l, "subject-one", 42)
+ if _, e := s.Confirm(ctx, proof, l, testNow); e != nil {
+ t.Fatal(e)
+ }
+ id, label, e := s.Resolve(ctx, issuer, "subject-one")
+ if e != nil || id != 1 || label != "one@example.com" {
+ t.Fatal(id, label, e)
+ }
+ for _, mode := range []string{"valid", "binding", "unlink", "address", "admission", "storage", "issuer", "subject", "nil"} {
+ t.Run(mode, func(t *testing.T) {
+ c, cancel := context.WithTimeout(ctx, time.Second)
+ defer cancel()
+ tx, e := s.db.BeginTx(c, nil)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer tx.Rollback()
+ if _, e = tx.ExecContext(c, "UPDATE home_link_clock SET high_water=high_water WHERE id=1"); e != nil {
+ t.Fatal(e)
+ }
+ old := s.lookup
+ defer func() { s.lookup = old }()
+ q := Queryer(tx)
+ iss, sub := issuer, "subject-one"
+ switch mode {
+ case "binding":
+ _, e = tx.ExecContext(c, "UPDATE home_identity_links SET person_binding='broken'")
+ case "unlink":
+ _, e = tx.ExecContext(c, "DELETE FROM home_identity_links")
+ case "address":
+ _, e = tx.ExecContext(c, "UPDATE people SET email='changed@example.com' WHERE id=1")
+ case "admission":
+ s.lookup = func(context.Context, Queryer, int64) (string, error) { return "", sql.ErrNoRows }
+ case "storage":
+ s.lookup = func(context.Context, Queryer, int64) (string, error) { return "", errors.New("secret-diagnostic") }
+ case "issuer":
+ iss = "https://wrong.example.com"
+ case "subject":
+ sub = ""
+ case "nil":
+ q = nil
+ }
+ if e != nil {
+ t.Fatal(e)
+ }
+ id, label, e = s.ResolveOn(c, q, iss, sub)
+ if mode == "valid" {
+ if e != nil || id != 1 || label != "one@example.com" {
+ t.Fatal("escaped transaction", id, label, e)
+ }
+ return
+ }
+ want := ErrRefused
+ if mode == "storage" {
+ want = ErrStorage
+ }
+ if e != want || id != 0 || label != "" {
+ t.Fatal("incomplete or leaked identity", mode, id, label, e)
+ }
+ })
+ }
+}
diff --git a/connect/linkstore/store.go b/connect/linkstore/store.go
index b3179f2..5036cc0 100644
--- a/connect/linkstore/store.go
+++ b/connect/linkstore/store.go
@@ -178,19 +178,26 @@ func (s *Store) Sweep(ctx context.Context, now time.Time) error {
// Resolve reads the current existing person, never EnsurePerson or a cached
// address. A deleted or unlinked person is refused without creating anything.
func (s *Store) Resolve(ctx context.Context, issuer, subject string) (int64, string, error) {
- if issuer != s.issuer || !validSubject(subject) {
+ return s.ResolveOn(ctx, s.db, issuer, subject)
+}
+
+// ResolveOn repeats the complete identity check on the caller's connection.
+// A transaction remains caller-owned. LookupPerson must also use q, so this
+// never opens another SQL connection while a caller holds SQLite's writer.
+func (s *Store) ResolveOn(ctx context.Context, q Queryer, issuer, subject string) (int64, string, error) {
+ if q == nil || issuer != s.issuer || !validSubject(subject) {
return 0, "", ErrRefused
}
var id int64
var address, binding string
- err := s.db.QueryRowContext(ctx, `SELECT person_id, person_binding FROM home_identity_links WHERE issuer = ? AND subject = ?`, issuer, subject).Scan(&id, &binding)
+ err := q.QueryRowContext(ctx, `SELECT person_id, person_binding FROM home_identity_links WHERE issuer = ? AND subject = ?`, issuer, subject).Scan(&id, &binding)
if errors.Is(err, sql.ErrNoRows) {
return 0, "", ErrRefused
}
if err != nil {
return 0, "", ErrStorage
}
- address, err = s.lookup(ctx, s.db, id)
+ address, err = s.lookup(ctx, q, id)
if errors.Is(err, sql.ErrNoRows) {
return 0, "", ErrRefused
}
diff --git a/connect/resolve_on_test.go b/connect/resolve_on_test.go
new file mode 100644
index 0000000..7195b51
--- /dev/null
+++ b/connect/resolve_on_test.go
@@ -0,0 +1,87 @@
+package connect
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/home/connect/linkstore"
+)
+
+func TestResolveOnAdoptedLinkUsesHeldWriter(t *testing.T) {
+ f := newBridgeFixture(t)
+ f.local(t, "one@example.com", "magiclink", time.Time{})
+ person := f.personID(t, "one@example.com")
+ f.db.SetMaxOpenConns(1)
+ ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
+ defer cancel()
+ tx, err := f.db.BeginTx(ctx, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback()
+ if err := f.b.Adopt(ctx, tx, bridgeIssuer, "adopted-subject", person); err != nil {
+ t.Fatal(err)
+ }
+ p, err := f.b.ResolveOn(ctx, tx, "adopted-subject")
+ if err != nil || p.ID != person || p.Label != "one@example.com" {
+ t.Fatal("uncommitted adopted link must resolve on held writer", p, err)
+ }
+ if _, err := tx.ExecContext(ctx, "UPDATE home_identity_links SET person_binding='corrupt' WHERE subject='adopted-subject'"); err != nil {
+ t.Fatal(err)
+ }
+ if p, err := f.b.ResolveOn(ctx, tx, "adopted-subject"); !errors.Is(err, linkstore.ErrRefused) || p != (Person{}) {
+ t.Fatal("corrupt adopted binding accepted", p, err)
+ }
+ if err := tx.Rollback(); err != nil {
+ t.Fatal(err)
+ }
+ if p, err := f.b.Resolve(ctx, "adopted-subject"); !errors.Is(err, linkstore.ErrRefused) || p != (Person{}) {
+ t.Fatal("rolled-back adoption survived", p, err)
+ }
+}
+
+func TestResolveOnNeverEscapesToHomeOnlyHook(t *testing.T) {
+ f, h := newHomeOnlyFixture(t)
+ if w := f.finishAs(t, "pr_member", nil); w.Code != 303 {
+ t.Fatalf("ordinary Home-only sign-in failed: %d", w.Code)
+ }
+ if p, err := f.b.Resolve(t.Context(), "pr_member"); err != nil || p.ID <= 1000 || p.Label != "" {
+ t.Fatal("ordinary Resolve lost Home-only support", p, err)
+ }
+ f.local(t, "one@example.com", "magiclink", time.Time{})
+ person := f.personID(t, "one@example.com")
+ calls := h.homeOnly
+ f.db.SetMaxOpenConns(1)
+ ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
+ defer cancel()
+ tx, err := f.db.BeginTx(ctx, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback()
+ if _, err := tx.ExecContext(ctx, "UPDATE home_link_clock SET high_water=high_water"); err != nil {
+ t.Fatal(err)
+ }
+ for _, subject := range []string{"pr_member", "unknown"} {
+ if p, err := f.b.ResolveOn(ctx, tx, subject); !errors.Is(err, linkstore.ErrRefused) || p != (Person{}) {
+ t.Fatal("unlinked identity accepted in transaction", p, err)
+ }
+ }
+ if _, err := tx.ExecContext(ctx, "INSERT INTO home_identity_links(issuer,subject,person_id,person_binding) VALUES(?,?,?,?)", bridgeIssuer, "pr_member", person, "corrupt"); err != nil {
+ t.Fatal(err)
+ }
+ if p, err := f.b.ResolveOn(ctx, tx, "pr_member"); !errors.Is(err, linkstore.ErrRefused) || p != (Person{}) {
+ t.Fatal("corrupt link fell back to Home-only person", p, err)
+ }
+ if _, err := tx.ExecContext(ctx, "DELETE FROM home_identity_links WHERE subject=?", "pr_member"); err != nil {
+ t.Fatal(err)
+ }
+ if p, err := f.b.ResolveOn(ctx, tx, "pr_member"); !errors.Is(err, linkstore.ErrRefused) || p != (Person{}) {
+ t.Fatal("unlinked person fell back to Home-only", p, err)
+ }
+ if h.homeOnly != calls {
+ t.Fatal("ResolveOn invoked a hook outside the caller transaction")
+ }
+}
diff --git a/docs/superpowers/specs/2026-08-30-home-design.md b/docs/superpowers/specs/2026-08-30-home-design.md
index 8b407a4..167032e 100644
--- a/docs/superpowers/specs/2026-08-30-home-design.md
+++ b/docs/superpowers/specs/2026-08-30-home-design.md
@@ -1606,3 +1606,34 @@ identity authority. That filing belongs at `carlos/pegamento`.
- ~~A real suite domain — triggers §5.7~~ — closed by ruling 16. §5.7 is
titled for the case it does not apply to: the `oficina.works` move needs
no RP rename drill.
+
+
+## Delegated-agent directory read (implementation draft, 2026-10-24)
+
+Paul requested a single browser-approved Oficina connection across apps, with
+an Oficina implementation now and later convergence on Rastrillo. This branch
+adds a directory-only service read. GPT-6 Astra independently passed the scoped
+source/spec review on 2026-10-24, recorded in Home discussion 85. Full required
+checks and deployed canary review remain separate gates before merge. It does
+not change identity assertions or grant app item access.
+
+`POST /api/agent/directory` accepts a single opaque `subject` from the configured
+connection service and returns current team memberships with live, validated app
+origins. It reads the same memberships and instance records as the team chooser,
+in one database snapshot. It never accepts an address, role or destination from
+the caller, never provisions membership and never holds document content.
+
+The endpoint is disabled by default. The directory deployment may set
+`HOME_AGENT_DIRECTORY_TOKEN_SHA256` to the SHA-256 hex digest of an independently
+provisioned random service token (at least 32 random bytes). The connection
+service holds the token; Home holds only its hash. This is service authority to
+read opaque-subject directory facts, not an end-user access token. Rotation
+replaces the hash; the previous credential is refused once the directory process
+restarts with the new configuration. The setting
+is rejected for credential and legacy roles. Cookies cannot authorize this
+endpoint; exact host, bearer, method, bounded JSON and destination validation
+apply. All responses are no-store; addresses, tokens, names and destinations
+remain absent from logs. Home's existing item/content and credential-origin
+boundaries remain binding. The separate connection service owns client grants,
+consent, audience restrictions, refresh rotation and revocation; each app still
+resolves a linked local identity and enforces current item access.
diff --git a/docs/superpowers/specs/2026-10-25-transactional-link-resolution.md b/docs/superpowers/specs/2026-10-25-transactional-link-resolution.md
new file mode 100644
index 0000000..a24457c
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-25-transactional-link-resolution.md
@@ -0,0 +1,11 @@
+# Resolve Home identity on the caller's transaction
+
+Status: implemented and independently approved by GPT-6 Astra; October 30 compatibility integration with Home main also approved. Deployed canary review remains.
+
+The app adapters recheck current Home person ID/address and admission under their SQLite writer, but bypass linkstore's keyed person_binding validation. A corrupt or changed binding between initial bridge resolution and commit must refuse the write, not commit and fail only on response emission.
+
+Add linkstore.Store.ResolveOn(ctx, Queryer, issuer, subject) and connect.Bridge.ResolveOn(ctx, Queryer, subject). Existing linkstore.Store.Resolve delegates to Store.ResolveOn with its stored DB. Bridge.Resolve retains ordinary Home-only resolution; Bridge.ResolveOn is explicitly existing-linked-account-only and never invokes HomeOnly or Unlinked hooks outside the supplied transaction. The new method performs exactly the existing issuer/subject validation, link lookup, LookupPerson using the supplied Queryer, positive-ID/address and constant-time person_binding check, and existing safe refusal/storage errors. No new cryptography, schema, permissions, caches or subject-to-address fallback. The supplied Queryer must be the caller's transaction connection; it remains caller-owned. Bridge uses its fixed configured issuer.
+
+Each app calls bridge.ResolveOn using tx.Statement.ConnPool (the existing QueryRowContext interface), compares stable ID/address to the request's captured identity, and retains operation-specific local permissions in that transaction. This avoids both the incomplete hand-rolled link check and opening a second SQL connection while holding the writer.
+
+Tests: ordinary Resolve parity; a real held SQLite transaction sees its own uncommitted valid/invalid binding, deleted link, changed address and admission refusal; max one SQL connection with a context deadline proves no escape to stored DB; storage errors remain redacted; nil queryer refused. A deliberate mutant using the stored DB or skipping binding validation must fail. Apps add trigger-driven binding corruption after content insertion and assert all content/attribution/receipt effects roll back. Review and full Home CI precede publishing the module revision; consuming branches pin it exactly.
diff --git a/implementation/teammode-package.md b/implementation/teammode-package.md
index 121aa72..ee0e491 100644
--- a/implementation/teammode-package.md
+++ b/implementation/teammode-package.md
@@ -148,10 +148,15 @@ var ErrNoPerson
person, and only when `AdmitUnlinked` returns nil: the roster says Member
now and the decision's lease is still valid when checked again.
15. Connect's same-person rules hold for Home-only people: `HomeOnly` is
- consulted wherever connect resolves a Home subject, so a known Home-only
+ consulted by ordinary resolution (`Resolve`, `ResolveSession`, and browser
+ completion), so a known Home-only
member arriving over somebody else's live session is 403, and that
session survives. An unknown arrival over any live session allocates
- nothing ("unknown", 403).
+ nothing ("unknown", 403). The transaction-aware `ResolveOn` API is a
+ deliberate exception: it resolves existing account links only and never
+ invokes `HomeOnly` or `Unlinked`, whose signatures cannot carry the caller's
+ query/transaction. It refuses addressless people rather than consulting a
+ second connection during an authorization transaction.
16. A Home-only person has no address. Connect refuses one whose `Label` is
not empty. Every cookie shape check stays connect's (Sheets' copy goes).
17. With both hooks nil, connect behaves exactly as before for every existing
diff --git a/internal/home/agent_directory.go b/internal/home/agent_directory.go
new file mode 100644
index 0000000..0ff4441
--- /dev/null
+++ b/internal/home/agent_directory.go
@@ -0,0 +1,96 @@
+package home
+
+import (
+ "crypto/sha256"
+ "crypto/subtle"
+ "errors"
+ "io"
+ "mime"
+ "net/http"
+ "strings"
+
+ "amadan.net/oficina/home/internal/home/directorydata"
+ "github.com/go-json-experiment/json"
+)
+
+const agentDirectoryPath = "/api/agent/directory"
+
+type agentDirectoryApp struct {
+ App string `json:"app"`
+ Origin string `json:"origin"`
+}
+type agentDirectoryTeam struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Apps []agentDirectoryApp `json:"apps"`
+}
+
+// This bearer-only service read is deliberately outside browser sessions. The
+// hash is provisioned only on the directory origin; identity assertions remain
+// identity-only and the credential origin never serves this endpoint.
+func (a *App) agentDirectory(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ if a.runtime == nil || a.runtime.role != "directory" || len(a.runtime.agentDirectoryHash) != 32 || r.Host != strings.TrimPrefix(a.origins.Directory, "https://") {
+ http.NotFound(w, r)
+ return
+ }
+ if r.Method != "POST" {
+ w.Header().Set("Allow", "POST")
+ http.Error(w, "Method not allowed", 405)
+ return
+ }
+ parts := strings.Fields(r.Header.Get("Authorization"))
+ if len(r.Header.Values("Authorization")) != 1 || len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") || len(parts[1]) > 256 {
+ w.Header().Set("WWW-Authenticate", "Bearer")
+ http.Error(w, "Unauthorized", 401)
+ return
+ }
+ sum := sha256.Sum256([]byte(parts[1]))
+ if subtle.ConstantTimeCompare(sum[:], a.runtime.agentDirectoryHash) != 1 {
+ w.Header().Set("WWW-Authenticate", "Bearer")
+ http.Error(w, "Unauthorized", 401)
+ return
+ }
+ media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
+ if err != nil || media != "application/json" {
+ http.Error(w, "Use application/json", 415)
+ return
+ }
+ // One opaque subject is the entire request. 1 KiB leaves ample JSON
+ // framing room while bounding unactionable input before parsing.
+ body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1024))
+ var input struct {
+ Subject string `json:"subject"`
+ }
+ if err != nil || json.Unmarshal(body, &input, json.RejectUnknownMembers(true)) != nil {
+ http.Error(w, "Invalid directory request", 400)
+ return
+ }
+ choices, err := a.directory.store.AgentChoices(r.Context(), input.Subject)
+ if errors.Is(err, directorydata.ErrInvalid) {
+ http.Error(w, "Invalid directory request", 400)
+ return
+ }
+ if err != nil {
+ http.Error(w, "Directory unavailable", 503)
+ return
+ }
+ teams := []agentDirectoryTeam{}
+ for _, choice := range choices {
+ if len(teams) == 0 || teams[len(teams)-1].ID != choice.SQID {
+ teams = append(teams, agentDirectoryTeam{ID: choice.SQID, Name: choice.Name, Apps: []agentDirectoryApp{}})
+ }
+ last := &teams[len(teams)-1]
+ last.Apps = append(last.Apps, agentDirectoryApp{App: choice.App, Origin: choice.Origin})
+ }
+ encoded, err := json.Marshal(struct {
+ Teams []agentDirectoryTeam `json:"teams"`
+ }{teams})
+ if err != nil || len(encoded) > 1<<20 {
+ http.Error(w, "Directory unavailable", 503)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write(encoded)
+}
diff --git a/internal/home/agent_directory_test.go b/internal/home/agent_directory_test.go
new file mode 100644
index 0000000..b91f3ce
--- /dev/null
+++ b/internal/home/agent_directory_test.go
@@ -0,0 +1,158 @@
+package home
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestAgentDirectoryUsesCurrentStandingAndPinnedDestinations(t *testing.T) {
+ f := newMountedChooser(t)
+ team := f.team(t, "AAA111", "blue", "Blue team", chooserPerson)
+ f.team(t, "BBB222", "green", "Other team", chooserOther)
+ f.team(t, "CCC333", "red", "Red team", chooserPerson)
+ if _, err := f.p.directory.db.Writer().Exec("INSERT INTO team_instances VALUES(?,?,?,?,?)", team, "sheets", "https://blue.sheets.oficina.works", "blue-sheets", "live"); err != nil {
+ t.Fatal(err)
+ }
+ const token = "test-service-token-8a919e49f0294d6fa3cebf231948f93e"
+ sum := sha256.Sum256([]byte(token))
+ request := func(host, auth, body string, cookie *http.Cookie) *httptest.ResponseRecorder {
+ r := httptest.NewRequest("POST", host+agentDirectoryPath, strings.NewReader(body))
+ r.Header.Set("Content-Type", "application/json")
+ if auth != "" {
+ r.Header.Set("Authorization", auth)
+ }
+ if cookie != nil {
+ r.AddCookie(cookie)
+ }
+ w := httptest.NewRecorder()
+ f.p.directory.Router().ServeHTTP(w, r)
+ noStore(t, w)
+ return w
+ }
+ body := `{"subject":"` + chooserPerson + `"}`
+ if w := request(directoryOrigin, "Bearer "+token, body, nil); w.Code != 404 {
+ t.Fatal("enabled by default", w.Code)
+ }
+ f.p.directory.runtime.agentDirectoryHash = sum[:]
+ w := request(directoryOrigin, "Bearer "+token, body, nil)
+ var out struct {
+ Teams []agentDirectoryTeam `json:"teams"`
+ }
+ if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &out) != nil || len(out.Teams) != 2 {
+ t.Fatal("directory read", w.Code, w.Body.String())
+ }
+ if out.Teams[0].ID != "AAA111" || len(out.Teams[0].Apps) != 2 || out.Teams[0].Apps[0].Origin != "https://blue.docs.oficina.works" || out.Teams[0].Apps[1].Origin != "https://blue.sheets.oficina.works" || out.Teams[1].ID != "CCC333" {
+ t.Fatal("wrong route")
+ }
+ for _, auth := range []string{"", "Bearer wrong", "Basic " + token} {
+ if w := request(directoryOrigin, auth, body, f.session(t, chooserPerson)); w.Code != 401 {
+ t.Fatal("cookie or invalid bearer authorized", w.Code)
+ }
+ }
+ if w := request(Origin, "Bearer "+token, body, nil); w.Code != 404 {
+ t.Fatal("served credential host", w.Code)
+ }
+ for _, bad := range []string{`{"subject":"` + chooserPerson + `","subject":"` + chooserOther + `"}`, `{"subject":"` + chooserPerson + `","origin":"https://evil.example"}`, `{"subject":"a@example.test"}`} {
+ if w := request(directoryOrigin, "Bearer "+token, bad, nil); w.Code != 400 {
+ t.Fatal("accepted invalid request", w.Code)
+ }
+ }
+ if _, err := f.p.directory.db.Writer().Exec("UPDATE team_instances SET origin='https://evil.example' WHERE team_id=? AND app='docs'", team); err != nil {
+ t.Fatal(err)
+ }
+ if w := request(directoryOrigin, "Bearer "+token, body, nil); w.Code != 503 || strings.Contains(w.Body.String(), "evil.example") {
+ t.Fatal("untrusted destination returned", w.Code)
+ }
+ if _, err := f.p.directory.db.Writer().Exec("UPDATE team_instances SET origin='https://blue.docs.oficina.works' WHERE team_id=? AND app='docs'", team); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.p.directory.db.Writer().Exec("UPDATE team_instances SET state='disabled' WHERE team_id=?", team); err != nil {
+ t.Fatal(err)
+ }
+ if w := request(directoryOrigin, "Bearer "+token, body, nil); w.Code != 200 || strings.Contains(w.Body.String(), "AAA111") {
+ t.Fatal("disabled destination returned")
+ }
+ if _, err := f.p.directory.db.Writer().Exec("UPDATE team_instances SET state='live' WHERE team_id=?", team); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.p.directory.db.Writer().Exec("DELETE FROM memberships WHERE team_id=? AND person_ref=?", team, chooserPerson); err != nil {
+ t.Fatal(err)
+ }
+ if w := request(directoryOrigin, "Bearer "+token, body, nil); w.Code != 200 || strings.Contains(w.Body.String(), "AAA111") {
+ t.Fatal("removed membership returned")
+ }
+ for _, secret := range []string{token, "a@example.test", "Blue team", "https://evil.example"} {
+ if strings.Contains(f.p.logs.String(), secret) {
+ t.Fatal("directory request or data logged")
+ }
+ }
+ for _, tc := range []struct {
+ name, method, media, body string
+ duplicate bool
+ want int
+ }{
+ {"method", "GET", "application/json", body, false, 405},
+ {"media", "POST", "text/plain", body, false, 415},
+ {"oversized", "POST", "application/json", strings.Repeat(" ", 1025), false, 400},
+ {"duplicate bearer", "POST", "application/json", body, true, 401},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ r := httptest.NewRequest(tc.method, directoryOrigin+agentDirectoryPath, strings.NewReader(tc.body))
+ r.Header.Set("Content-Type", tc.media)
+ r.Header.Set("Authorization", "Bearer "+token)
+ if tc.duplicate {
+ r.Header.Add("Authorization", "Bearer "+token)
+ }
+ w := httptest.NewRecorder()
+ f.p.directory.Router().ServeHTTP(w, r)
+ if w.Code != tc.want {
+ t.Fatal(w.Code)
+ }
+ noStore(t, w)
+ })
+ }
+ const replacement = "replacement-service-token-769283cc3ff94cc4ba52"
+ rotated := sha256.Sum256([]byte(replacement))
+ cfg := *f.p.directory.runtime
+ cfg.agentDirectoryHash = rotated[:]
+ reloaded, err := NewRuntime(cfg, f.p.directory.db, quietLogger())
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.p.directory = reloaded
+ if w := request(directoryOrigin, "Bearer "+token, body, nil); w.Code != 401 {
+ t.Fatal("old service token survived configuration reload")
+ }
+ if w := request(directoryOrigin, "Bearer "+replacement, body, nil); w.Code != 200 {
+ t.Fatal("replacement service token refused", w.Code)
+ }
+}
+
+func TestAgentDirectoryConfigurationIsDirectoryOnly(t *testing.T) {
+ _, keys := runtimeEnv(t)
+ t.Setenv("HOME_ROLE", "directory")
+ t.Setenv("HOME_ASSERTION_KEYS", keys)
+ sum := sha256.Sum256([]byte("test-service-token"))
+ t.Setenv("HOME_AGENT_DIRECTORY_TOKEN_SHA256", hex.EncodeToString(sum[:]))
+ if _, err := LoadRuntime("directory.db", quietLogger()); err != nil {
+ t.Fatal(err)
+ }
+ for _, bad := range []string{"not-hex", strings.Repeat("1", 62)} {
+ t.Setenv("HOME_AGENT_DIRECTORY_TOKEN_SHA256", bad)
+ if _, err := LoadRuntime("directory.db", quietLogger()); err == nil {
+ t.Fatal("accepted invalid token hash")
+ }
+ }
+ t.Setenv("HOME_AGENT_DIRECTORY_TOKEN_SHA256", hex.EncodeToString(sum[:]))
+ for _, role := range []string{"", "credential"} {
+ t.Setenv("HOME_ROLE", role)
+ if _, err := LoadRuntime("home.db", quietLogger()); err == nil {
+ t.Fatal("accepted service authority on credential origin")
+ }
+ }
+}
diff --git a/internal/home/directory.go b/internal/home/directory.go
index 21cc254..fc6863e 100644
--- a/internal/home/directory.go
+++ b/internal/home/directory.go
@@ -180,6 +180,10 @@ func (a *App) directoryRouter() http.Handler {
mountSite(r)
})
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ if req.URL.Path == agentDirectoryPath {
+ a.agentDirectory(w, req)
+ return
+ }
if req.URL.Path == rosterPath {
a.directory.roster.ServeHTTP(w, req)
return
diff --git a/internal/home/directorydata/store.go b/internal/home/directorydata/store.go
index f36b86c..e4d5699 100644
--- a/internal/home/directorydata/store.go
+++ b/internal/home/directorydata/store.go
@@ -120,7 +120,21 @@ func (s *Store) Choices(ctx context.Context, subject, app string) ([]Choice, err
if !validSubject(subject) || !s.apps[app] {
return nil, ErrInvalid
}
- rows, err := s.db.QueryContext(ctx, `SELECT t.id,t.sqid,t.label,t.sealed_name,m.role,i.app,i.origin,i.consumer_id,i.state FROM memberships m JOIN teams t ON t.id=m.team_id JOIN team_instances i ON i.team_id=t.id WHERE m.person_ref=? AND i.app=? ORDER BY t.id LIMIT 10001`, subject, app)
+ return s.choices(ctx, subject, app)
+}
+
+// AgentChoices reads current standing and live destinations for one opaque
+// subject, in a single database snapshot. The service caller authenticates
+// separately; these facts never authorize access to an app's items.
+func (s *Store) AgentChoices(ctx context.Context, subject string) ([]Choice, error) {
+ if !validSubject(subject) {
+ return nil, ErrInvalid
+ }
+ return s.choices(ctx, subject, "")
+}
+
+func (s *Store) choices(ctx context.Context, subject, app string) ([]Choice, error) {
+ rows, err := s.db.QueryContext(ctx, `SELECT t.id,t.sqid,t.label,t.sealed_name,m.role,i.app,i.origin,i.consumer_id,i.state FROM memberships m JOIN teams t ON t.id=m.team_id JOIN team_instances i ON i.team_id=t.id WHERE m.person_ref=? AND (?='' OR i.app=?) ORDER BY t.id,i.app LIMIT 10001`, subject, app, app)
if err != nil {
return nil, ErrUnavailable
}
@@ -144,6 +158,9 @@ func (s *Store) Choices(ctx context.Context, subject, app string) ([]Choice, err
if state != "live" {
continue
}
+ if !s.apps[c.App] {
+ continue
+ }
route := Route{TeamID: c.ID, TeamSQID: c.SQID, Label: c.Label, App: c.App, Origin: c.Origin, ConsumerID: c.ConsumerID}
if !ValidOrigin(c.Origin) || !validConsumer(c.ConsumerID) || !s.validateRoute(route) {
return nil, ErrUnavailable
diff --git a/internal/home/runtime.go b/internal/home/runtime.go
index 70e0140..cc8c359 100644
--- a/internal/home/runtime.go
+++ b/internal/home/runtime.go
@@ -25,16 +25,17 @@ var errExchangeConfig = errors.New("home: invalid assertion configuration")
var directorySchema = migrate.Merge(sessions.Schema, migrate.MustFromFS(handoff.Migrations, "oficina_handoff"), directorydata.Schema, directorydata.RosterSchema)
type Runtime struct {
- dashboard []dashboardTeam
- docsPreviewOrigin string
- appPreviewOrigins map[string]string
- roster rosterRuntime
- role string
- origins Origins
- secrets Secrets
- signer *assertioncrypto.Keypair
- keyID string
- keys map[string][]byte
+ agentDirectoryHash []byte
+ dashboard []dashboardTeam
+ docsPreviewOrigin string
+ appPreviewOrigins map[string]string
+ roster rosterRuntime
+ role string
+ origins Origins
+ secrets Secrets
+ signer *assertioncrypto.Keypair
+ keyID string
+ keys map[string][]byte
// consumers is HOME_CONSUMERS as configured; registry, once NewRuntime
// has loaded the credential consumers table, is the union every reader
// uses (consumer_registry.go).
@@ -60,6 +61,12 @@ func LoadRuntime(dbPath string, logger *slog.Logger) (Runtime, error) {
return Runtime{}, err
}
cfg.role = os.Getenv("HOME_ROLE")
+ if raw := os.Getenv("HOME_AGENT_DIRECTORY_TOKEN_SHA256"); raw != "" {
+ cfg.agentDirectoryHash, err = hex.DecodeString(raw)
+ if err != nil || len(cfg.agentDirectoryHash) != 32 || cfg.role != "directory" {
+ return Runtime{}, errExchangeConfig
+ }
+ }
cfg.docsPreviewOrigin = os.Getenv("HOME_DOCS_PREVIEW_ORIGIN")
rawPreviews, err := exchangeJSON("HOME_APP_PREVIEW_ORIGINS", 8192)
if err != nil {
@@ -212,6 +219,9 @@ func (cfg Runtime) ServingSchema() *migrate.Set {
return cfg.Schema()
}
func NewRuntime(cfg Runtime, d *db.DB, logger *slog.Logger) (*App, error) {
+ if len(cfg.agentDirectoryHash) != 0 && (len(cfg.agentDirectoryHash) != 32 || cfg.role != "directory") {
+ return nil, errExchangeConfig
+ }
if !cfg.roster.valid(cfg.role, cfg.keys) || !cfg.validAppPreviews() || !cfg.validResolveKeys() {
return nil, errExchangeConfig
}