oficina / home Public

Expose current directory facts to the Oficina connection service

codex agent, operated by paul@keymail.dev pushed by paul@keymail.dev 24ec569746c73efb3af8c712d968a59d19df6a5a parent ba81936
7 files changed, +329 −12
  • Makefile +2 −1
  • docs/superpowers/specs/2026-08-30-home-design.md +31 −0
  • 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

Intent

Human

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

diff --git a/Makefile b/Makefile
index 47c04de..1c0c2e5 100644
--- a/Makefile
+++ b/Makefile
@@ -121,7 +121,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 connect && CGO_ENABLED=1 go test -race -count=1 ./...
diff --git a/docs/superpowers/specs/2026-08-30-home-design.md b/docs/superpowers/specs/2026-08-30-home-design.md
index 429edb4..36d132b 100644
--- a/docs/superpowers/specs/2026-08-30-home-design.md
+++ b/docs/superpowers/specs/2026-08-30-home-design.md
@@ -1584,3 +1584,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-25, 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/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 3c06ed7..698f358 100644
--- a/internal/home/directory.go
+++ b/internal/home/directory.go
@@ -134,6 +134,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 7c0d792..619c8e7 100644
--- a/internal/home/runtime.go
+++ b/internal/home/runtime.go
@@ -24,16 +24,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 {
- docsPreviewOrigin string
- appPreviewOrigins map[string]string
- roster rosterRuntime
- role string
- origins Origins
- secrets Secrets
- signer *assertioncrypto.Keypair
- keyID string
- keys map[string][]byte
- consumers map[string]string
+ agentDirectoryHash []byte
+ docsPreviewOrigin string
+ appPreviewOrigins map[string]string
+ roster rosterRuntime
+ role string
+ origins Origins
+ secrets Secrets
+ signer *assertioncrypto.Keypair
+ keyID string
+ keys map[string][]byte
+ consumers map[string]string
}
// LoadRuntime keeps existing deployments on the legacy path until a role is
@@ -46,6 +47,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 {
@@ -171,6 +178,9 @@ func (cfg Runtime) Schema() *migrate.Set {
return BootSchema
}
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() {
return nil, errExchangeConfig
}