oficina / docs Public

Expose delegated document operations through current Home authority

codex agent, operated by paul@keymail.dev pushed by paul@keymail.dev 3acf639a345e0d2d9b7945c0b424cec6770f3d93 parent 1d5e1a0
16 files changed, +1,611 −45
  • .amadan/ci.d/10-gate +1 −1
  • cmd/docs-contract/main.go +22 −0
  • cmd/docs/main.go +2 −0
  • docs/agent-access.md +39 −0
  • docs/superpowers/specs/2026-10-25-agent-access.md +23 −1
  • go.mod +14 −0
  • go.sum +42 −0
  • internal/docs/agent_access.go +248 −0
  • internal/docs/agent_access_test.go +605 −0
  • internal/docs/agent_integration_test.go +152 −0
  • internal/docs/agent_store.go +371 −0
  • internal/docs/app.go +17 −1
  • internal/docs/identity.go +46 −35
  • internal/docs/migrations/0009_agent_access.sql +15 −0
  • internal/docs/team_access.go +9 −7
  • internal/docs/team_emission.go +5 −0

CI passed — run details

diff --git a/.amadan/ci.d/10-gate b/.amadan/ci.d/10-gate
index 26f2d11..eac4608 100755
--- a/.amadan/ci.d/10-gate
+++ b/.amadan/ci.d/10-gate
@@ -18,7 +18,7 @@ rustup target list --installed 2>/dev/null | grep -qx wasm32-unknown-unknown \
|| { echo "gate: wasm32-unknown-unknown target missing — rustup target add wasm32-unknown-unknown" >&2; exit 1; }
export CGO_ENABLED=0
-export GOPRIVATE="${GOPRIVATE:+$GOPRIVATE,}amadan.net/oficina/estilo.git"
+export GOPRIVATE="${GOPRIVATE:+$GOPRIVATE,}amadan.net/oficina/estilo.git,amadan.net/oficina/agent-access.git"
# The runner clones a fresh worktree per branch, so fixtures/node_modules
# (gitignored, like any node_modules) never carries over from a previous
diff --git a/cmd/docs-contract/main.go b/cmd/docs-contract/main.go
new file mode 100644
index 0000000..6dc3f37
--- /dev/null
+++ b/cmd/docs-contract/main.go
@@ -0,0 +1,22 @@
+// Command docs-contract exports the live delegated operation schemas.
+package main
+
+import (
+ "encoding/json"
+ "fmt"
+ "github.com/carlosframework/docs/internal/docs"
+ "os"
+)
+
+func main() {
+ operations, err := docs.AgentContracts()
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "Could not export Docs operation contracts.")
+ os.Exit(1)
+ }
+ encoder := json.NewEncoder(os.Stdout)
+ encoder.SetIndent("", " ")
+ if encoder.Encode(operations) != nil {
+ os.Exit(1)
+ }
+}
diff --git a/cmd/docs/main.go b/cmd/docs/main.go
index 22d2cb1..a669e2b 100644
--- a/cmd/docs/main.go
+++ b/cmd/docs/main.go
@@ -270,6 +270,8 @@ func main() {
// — otherwise Serve would open a second connection to the file New
// already owns.
cfg := docs.Config{
+ AgentIssuer: os.Getenv("DOCS_AGENT_ISSUER"),
+ AgentTeam: os.Getenv("DOCS_AGENT_TEAM"),
DBPath: opts.DBPath,
ContentKey: os.Getenv("DOCS_CONTENT_KEY"),
Env: env,
diff --git a/docs/agent-access.md b/docs/agent-access.md
new file mode 100644
index 0000000..28396fd
--- /dev/null
+++ b/docs/agent-access.md
@@ -0,0 +1,39 @@
+# Delegated Docs access
+
+This branch adds `docs_list`, `docs_get` and `docs_create` to the shared Oficina
+connection. The same operation contracts serve the Oficina CLI, Paseo, ChatGPT
+and Claude through the connection service. They require a configured Home
+identity link and current document permission.
+
+Set `DOCS_AGENT_ISSUER` to the connection service HTTPS origin and
+`DOCS_AGENT_TEAM` to the instance team. Both are required together with the
+existing Home configuration. In team mode the team must match its provisioned
+binding. The verifier expects this app's exact origin plus `/api/v1` as audience
+and the configured Home issuer as identity authority. Browser login and native
+routes retain their existing guards.
+
+Export deployment contracts with `go run ./cmd/docs-contract`. The protected
+endpoints are `GET /api/v1/operations` and
+`POST /api/v1/operations/{name}`. App credentials come from the connection
+service; cookies and personal browser sessions do not authenticate this API.
+
+Create requires activated content sealing and a nonzero canonical UUID
+`client_id`. Supply a title and up to 200 literal paragraph/heading blocks, with
+128 KiB of text total. Paragraphs have `type: paragraph` and `text`; headings
+have `type: heading`, `text` and `level` from 1 to 6. Reuse the UUID only to retry
+the identical initial content. A successful response contains the document ID,
+URL and current body revision; read content separately with `docs_get`.
+
+Get returns text and ProseMirror JSON from the same replay, with a decimal
+`body_revision` string. Responses are capped at 1 MiB. List uses 20 items by
+default, up to 100, and returns an opaque `next_cursor`. Initial creation does
+not provide later edits, sharing, export, comments or deletion.
+
+The receipt marker binds the Home key, Home issuer, connection issuer and team.
+Changing any requires an explicit operator migration; never erase receipt state
+to make retries appear new. Enabling access does not activate or convert legacy
+content storage. All content writes use the existing sealed collaborative core.
+
+See the reviewed design in
+[the agent access spec](superpowers/specs/2026-10-25-agent-access.md). This branch
+is not a claim of deployment or live client certification.
diff --git a/docs/superpowers/specs/2026-10-25-agent-access.md b/docs/superpowers/specs/2026-10-25-agent-access.md
index 942dafa..52c840c 100644
--- a/docs/superpowers/specs/2026-10-25-agent-access.md
+++ b/docs/superpowers/specs/2026-10-25-agent-access.md
@@ -35,7 +35,9 @@ cursor contains the last returned timestamp and exact decimal database ID; both
are validated and bound to that ordering. Apply current ListFor permission SQL
before pagination. It is a current view, not a snapshot across requests.
-Get returns public Sqid, title, URL, body_revision (decimal string), plain text
+Create returns a bounded summary (public Sqid, title, URL, updated_at) and
+body_revision; it does not echo the initial body. This keeps the maximum valid
+input retryable even when JSON escaping expands content. Get returns public Sqid, title, URL, body_revision (decimal string), plain text
and ProseMirror JSON from a single replay handle. body_revision is that replay's
sequence; it versions body updates, not title renames. Never separately query
currentSeq to label an earlier replay. The maximum encoded operation result is
@@ -137,3 +139,23 @@ heading bounds, block count, total bytes, reinitialization, unsafe client ID,
unsafe document allocation and discarded initial update. Full local CI reached
the existing release-launch test and hit macOS's temporary socket path limit;
rerun with TMPDIR=/tmp. Full CI and whole-branch review remain required.
+
+## Adapter review progress (2026-10-25)
+
+GPT-6 Astra's early source review found five issues, now corrected and covered:
+reverify delegation after reserving the writer and before commit; export common
+contracts across teams and enforce the target team at invocation; reject lossy
+raw JSON Unicode; return a bounded create summary; preserve recoverable client
+attribution sealed separately from digest-only receipts. The revised source
+review found no further blocker. This is not final whole-branch approval.
+
+Actual linked identity, sealed SQLite/core, concurrent retries, browser-edit
+retry, deletion, transactional failure/unlink/revocation, authority-key restart,
+foreign-document filtering, exact pagination, team-epoch refusal/partial abort,
+and independent explicit grants pass focused tests. A real HTTPS grant service,
+shared CLI/gateway and official MCP client create/read/retry Docs and revoke an
+already-open MCP connection through CLI logout. Twelve effective mutations fail
+the intended gates. A first legacy-storage mutation survived because the test
+was still using an activated database; a genuine legacy fixture corrected the
+test, and the same mutation now fails. Full CI and deployed verification remain
+separate gates.
diff --git a/go.mod b/go.mod
index 47c91b6..32f9553 100644
--- a/go.mod
+++ b/go.mod
@@ -3,6 +3,7 @@ module github.com/carlosframework/docs
go 1.26.5
require (
+ amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000
amadan.net/oficina/estilo.git v0.0.0-20261001093750-530cb932e768
amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489
amadan.net/oficina/home/roster v0.0.0-20260908123429-74dda570e0cf
@@ -15,7 +16,9 @@ require (
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2
github.com/google/uuid v1.6.0
github.com/keymaildev/signin v0.1.1
+ github.com/modelcontextprotocol/go-sdk v1.7.0
github.com/tetratelabs/wazero v1.12.0
+ golang.org/x/oauth2 v0.35.0
golang.org/x/text v0.39.0
gorm.io/gorm v1.31.2
modernc.org/sqlite v1.55.0
@@ -25,17 +28,28 @@ require (
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
+ github.com/danieljoos/wincred v1.2.3 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/gobwas/httphead v0.1.0 // indirect
github.com/gobwas/pool v0.2.1 // indirect
github.com/gobwas/ws v1.4.0 // indirect
+ github.com/godbus/dbus/v5 v5.2.2 // indirect
+ github.com/gofrs/flock v0.12.1 // indirect
+ github.com/google/jsonschema-go v0.4.3 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
+ github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect
+ github.com/segmentio/asm v1.1.3 // indirect
+ github.com/segmentio/encoding v0.5.4 // indirect
+ github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
+ github.com/zalando/go-keyring v0.2.8 // indirect
golang.org/x/mod v0.37.0 // indirect
+ golang.org/x/sync v0.21.0 // indirect
golang.org/x/sys v0.46.0 // indirect
+ golang.org/x/time v0.15.0 // indirect
gorm.io/plugin/dbresolver v1.6.2 // indirect
modernc.org/libc v1.74.1 // indirect
modernc.org/mathutil v1.7.1 // indirect
diff --git a/go.sum b/go.sum
index a01869c..5d5f3ff 100644
--- a/go.sum
+++ b/go.sum
@@ -1,3 +1,5 @@
+amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000 h1:L07nc+dmLI7c1PBkSkbnrjOK5f8p6OBbA/yTxznxCAw=
+amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000/go.mod h1:Ph9PIa3VE1IEaUzZiQH6D+IQ6HThWWGfVr0ecMMgrFA=
amadan.net/oficina/estilo.git v0.0.0-20261001093750-530cb932e768 h1:bVscoa9fH5LdLDjlyecZhrX7JzWPT0blb57MH0FIm2U=
amadan.net/oficina/estilo.git v0.0.0-20261001093750-530cb932e768/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 h1:RPKtyry/71i06o8L+gjAaUyexbmG56kO1YPs601URAM=
@@ -20,6 +22,12 @@ github.com/chromedp/chromedp v0.14.2 h1:r3b/WtwM50RsBZHMUm9fsNhhzRStTHrKdr2zmwbZ
github.com/chromedp/chromedp v0.14.2/go.mod h1:rHzAv60xDE7VNy/MYtTUrYreSc0ujt2O1/C3bzctYBo=
github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipwM=
github.com/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8=
+github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ=
+github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
+github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY=
@@ -34,6 +42,16 @@ github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs=
github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc=
+github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
+github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
+github.com/gofrs/flock v0.12.1 h1:MTLVXXHf8ekldpJk3AKicLij9MdwOWkZ+a/jHHZby9E=
+github.com/gofrs/flock v0.12.1/go.mod h1:9zxTsyu5xtJ9DK+1tFZyibEV7y3uwDxPPfbxeeHCoD0=
+github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
+github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
+github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
+github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -52,18 +70,38 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
+github.com/modelcontextprotocol/go-sdk v1.7.0 h1:yqjY2dsbKAC0LSuWZVBMrHgiG8ukXv6NRo0JiALay44=
+github.com/modelcontextprotocol/go-sdk v1.7.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde h1:x0TT0RDC7UhAVbbWWBzr41ElhJx5tXPWkIHA2HWPRuw=
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
+github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 h1:1EYB5IzjZawrrnELUi78f9fPu57HuXjmddZPjrls/28=
+github.com/santhosh-tekuri/jsonschema/v6 v6.0.3/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
+github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
+github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
+github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
+github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
+github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
+github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
+github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
+github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/tetratelabs/wazero v1.12.0 h1:DuWcpNu/FzgEXgGBDp8J1Spc+CWOvvtvVyjKlaZopYU=
github.com/tetratelabs/wazero v1.12.0/go.mod h1:LvKtzl2RqO4gyF27BiXU+nKAjcV8f38U+kP/q2vgxh0=
+github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
+github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
+github.com/zalando/go-keyring v0.2.8 h1:6sD/Ucpl7jNq10rM2pgqTs0sZ9V3qMrqfIIy5YPccHs=
+github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cmakZDO5QGii0=
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
+golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
+golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -71,8 +109,12 @@ golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=
golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM=
+golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
+golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
diff --git a/internal/docs/agent_access.go b/internal/docs/agent_access.go
new file mode 100644
index 0000000..249acb8
--- /dev/null
+++ b/internal/docs/agent_access.go
@@ -0,0 +1,248 @@
+package docs
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "mime"
+ "net/http"
+ "strings"
+
+ access "amadan.net/oficina/agent-access.git"
+ strictjson "github.com/go-json-experiment/json"
+ "gorm.io/gorm"
+)
+
+var errAgentConfig = errors.New("docs: invalid agent access configuration")
+
+func validatedAgentConfig(cfg Config, home *homeSettings, team *teamSettings) (*access.RemoteVerifier, error) {
+ if cfg.AgentIssuer == "" && cfg.AgentTeam == "" {
+ return nil, nil
+ }
+ if home == nil || cfg.AgentIssuer == "" || cfg.AgentTeam == "" || len(cfg.AgentTeam) > 128 || strings.TrimSpace(cfg.AgentTeam) != cfg.AgentTeam {
+ return nil, errAgentConfig
+ }
+ if team != nil && cfg.AgentTeam != team.record.Bindings().Team {
+ return nil, errAgentConfig
+ }
+ verifier, err := access.NewRemoteVerifier(cfg.AgentIssuer, cfg.Origin+"/api/v1", home.issuer)
+ if err != nil {
+ return nil, errAgentConfig
+ }
+ return verifier, nil
+}
+
+const agentSummaryProperties = `"id":{"type":"string"},"title":{"type":"string"},"url":{"type":"string"},"updated_at":{"type":"string"}`
+const agentCreatedSchema = `{"type":"object","required":["id","title","url","updated_at","body_revision"],"additionalProperties":false,"properties":{` + agentSummaryProperties + `,"body_revision":{"type":"string","pattern":"^[0-9]+$"}}}`
+const agentBodySchema = `{"type":"object","required":["id","title","url","updated_at","body_revision","text","content"],"additionalProperties":false,"properties":{` + agentSummaryProperties + `,"body_revision":{"type":"string","pattern":"^[0-9]+$"},"text":{"type":"string"},"content":{"type":"object"}}}`
+
+func (a *documentAgent) registry() (*access.Registry, error) {
+ input := func(properties, required string) json.RawMessage {
+ return json.RawMessage(`{"type":"object","additionalProperties":false,"required":["team"` + required + `],"properties":{"team":{"type":"string","minLength":1,"maxLength":128}` + properties + `}}`)
+ }
+ ops := []access.Operation{
+ {Name: "docs_list", Description: "List documents currently readable in this team.", Scope: "docs:read", ReadOnly: true, Idempotent: true,
+ Input: input(`,"limit":{"type":"integer","minimum":1,"maximum":100},"cursor":{"type":"string","maxLength":512}`, ""),
+ Output: json.RawMessage(`{"type":"object","required":["documents","next_cursor"],"additionalProperties":false,"properties":{"documents":{"type":"array","maxItems":100,"items":{"type":"object","additionalProperties":false,"required":["id","title","url","updated_at"],"properties":{` + agentSummaryProperties + `}}},"next_cursor":{"type":"string"}}}`),
+ Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) {
+ ctx, id, err := a.prepare(ctx, p, false)
+ if err != nil {
+ return nil, err
+ }
+ var in struct {
+ Limit int `json:"limit"`
+ Cursor string `json:"cursor"`
+ }
+ if err = json.Unmarshal(raw, &in); err != nil {
+ return nil, access.Fail("invalid", "Invalid operation arguments.")
+ }
+ return a.documents(ctx, id.Actor, in.Limit, in.Cursor)
+ }},
+ {Name: "docs_get", Description: "Read a document as plain text and structured content at one body revision.", Scope: "docs:read", ReadOnly: true, Idempotent: true,
+ Input: input(`,"id":{"type":"string","pattern":"^[23456789abcdefghjkmnpqrstuvwxyz]{10}$"}`, `,"id"`), Output: json.RawMessage(agentBodySchema),
+ Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) {
+ ctx, id, err := a.prepare(ctx, p, false)
+ if err != nil {
+ return nil, err
+ }
+ var in struct {
+ ID string `json:"id"`
+ }
+ if err = json.Unmarshal(raw, &in); err != nil {
+ return nil, access.Fail("invalid", "Invalid operation arguments.")
+ }
+ return a.body(ctx, id.Actor, in.ID)
+ }},
+ {Name: "docs_create", Description: "Create a document with literal paragraph and heading text; reuse the same client UUID only for retries.", Scope: "docs:write", Idempotent: true,
+ Input: input(`,"client_id":{"type":"string","maxLength":36},"title":{"type":"string","minLength":1,"maxLength":512},"blocks":{"type":"array","maxItems":200,"items":{"type":"object","required":["type","text"],"additionalProperties":false,"properties":{"type":{"enum":["paragraph","heading"]},"text":{"type":"string","maxLength":131072},"level":{"type":"integer","minimum":0,"maximum":6}}}}`, `,"client_id","title","blocks"`), Output: json.RawMessage(agentCreatedSchema),
+ Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) {
+ ctx, id, err := a.prepare(ctx, p, true)
+ if err != nil {
+ return nil, err
+ }
+ var in agentCreateInput
+ if err = json.Unmarshal(raw, &in); err != nil {
+ return nil, access.Fail("invalid", "Invalid operation arguments.")
+ }
+ return a.create(ctx, p, id, in)
+ }},
+ }
+ for i := range ops {
+ invoke := ops[i].Invoke
+ ops[i].Invoke = func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) {
+ var parsed struct {
+ Team string `json:"team"`
+ }
+ if strictjson.Unmarshal(raw, &parsed) != nil {
+ return nil, access.Fail("invalid", "Send valid Unicode JSON.")
+ }
+ if parsed.Team != a.team {
+ return nil, access.Fail("forbidden", "This instance does not serve that team.")
+ }
+ return invoke(ctx, p, raw)
+ }
+ scope := ops[i].Scope
+ ops[i].Available = func(p access.Principal) bool { return p.Allows(a.team, scope) }
+ }
+ return access.NewRegistry(ops...)
+}
+
+func agentWriteFailure(w http.ResponseWriter, err error) {
+ f := access.SafeFailure(err)
+ status := map[string]int{"unauthenticated": 401, "forbidden": 403, "not_found": 404, "invalid": 422, "conflict": 409, "too_large": 413, "unsupported_media_type": 415, "unavailable": 503}[f.Code]
+ if status == 0 {
+ status = 500
+ }
+ if status == 401 {
+ w.Header().Set("WWW-Authenticate", "Bearer")
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ _ = json.NewEncoder(w).Encode(map[string]any{"error": f})
+}
+
+// httpHandler keeps final Docs permission/epoch checks on the real writer.
+func (a *documentAgent) httpHandler(verifier access.Verifier) (http.Handler, error) {
+ registry, err := a.registry()
+ if err != nil {
+ return nil, err
+ }
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ parts := strings.Fields(r.Header.Get("Authorization"))
+ if len(r.Header.Values("Authorization")) != 1 || len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
+ agentWriteFailure(w, access.Fail("unauthenticated", "Connect to Oficina first."))
+ return
+ }
+ p, err := verifier.Verify(r.Context(), parts[1])
+ if err != nil {
+ agentWriteFailure(w, err)
+ return
+ }
+ name := strings.TrimPrefix(r.URL.Path, "/api/v1/operations/")
+ write := name == "docs_create"
+ // Discovery can describe a write-only connection without granting reads.
+ discovery := r.Method == "GET" && r.URL.Path == "/api/v1/operations"
+ if discovery && !p.Allows(a.team, "docs:read") {
+ write = true
+ }
+ ctx, id, err := a.prepare(r.Context(), p, write)
+ if err != nil {
+ agentWriteFailure(w, err)
+ return
+ }
+ guard := ctx.Value(accessContextKey{}).(*requestAccess)
+ guard.delegationCheck = func(ctx context.Context) error {
+ current, e := verifier.Verify(ctx, parts[1])
+ if e != nil {
+ return e
+ }
+ scope := "docs:read"
+ if write {
+ scope = "docs:write"
+ }
+ if current.Subject != p.Subject || current.Client != p.Client || current.Grant != p.Grant || !current.Allows(a.team, scope) {
+ return errIdentityRefused
+ }
+ return nil
+ }
+ guard.extraCheck = func(ctx context.Context) error {
+ if err := guard.delegationCheck(ctx); err != nil {
+ return err
+ }
+ fresh, e := a.resolver.resolveHome(ctx, p.Subject)
+ if e != nil {
+ return e
+ }
+ if !sameActor(fresh.Actor, id.Actor) {
+ return errIdentityRefused
+ }
+ if a.store.team == nil {
+ allowed, e := a.list.allows(actorAddress(id.Actor))
+ if e != nil {
+ return e
+ }
+ if !allowed {
+ return errIdentityRefused
+ }
+ }
+ return nil
+ }
+ var result any
+ if discovery {
+ result = map[string]any{"operations": registry.List(p)}
+ } else {
+ if r.Method != "POST" || !strings.HasPrefix(r.URL.Path, "/api/v1/operations/") || strings.Contains(name, "/") {
+ agentWriteFailure(w, access.Fail("not_found", "This operation is unavailable."))
+ return
+ }
+ media, _, e := mime.ParseMediaType(r.Header.Get("Content-Type"))
+ if e != nil || media != "application/json" {
+ agentWriteFailure(w, access.Fail("unsupported_media_type", "Send application/json."))
+ return
+ }
+ raw, e := io.ReadAll(io.LimitReader(r.Body, access.MaxPayload+1))
+ if e != nil {
+ agentWriteFailure(w, access.Fail("invalid", "Could not read the request."))
+ return
+ }
+ result, err = registry.Call(ctx, p, name, raw)
+ if err != nil {
+ agentWriteFailure(w, err)
+ return
+ }
+ }
+ body, err := json.Marshal(result)
+ if err != nil {
+ agentWriteFailure(w, agentFailure(err))
+ return
+ }
+ if len(body) > agentResultLimit {
+ agentWriteFailure(w, access.Fail("too_large", "The document result exceeds 1 MiB."))
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ if err = writeGuardedBody(w, r.WithContext(ctx), http.StatusOK, body); err != nil {
+ panic(http.ErrAbortHandler)
+ }
+ }), nil
+}
+
+func newDocumentAgent(cfg Config, settings *homeSettings, home *homeRoutes, store *Store, list allowlist, verifier access.Verifier) (http.Handler, error) {
+ a := &documentAgent{store: store, resolver: home.bridge.resolver, list: list, origin: cfg.Origin, issuer: cfg.AgentIssuer, identityIssuer: settings.issuer, team: cfg.AgentTeam, key: append([]byte(nil), settings.dek...)}
+ if err := store.db.Transaction(func(tx *gorm.DB) error { return a.bind(tx) }); err != nil {
+ return nil, err
+ }
+ return a.httpHandler(verifier)
+}
+
+// AgentContracts exports identical operation contracts for every Docs team.
+func AgentContracts() ([]access.Operation, error) {
+ a := &documentAgent{team: "contract"}
+ registry, err := a.registry()
+ if err != nil {
+ return nil, err
+ }
+ return registry.List(access.Principal{Subject: "contract", Teams: []string{"contract"}, Scopes: []string{"docs:read", "docs:write"}}), nil
+}
diff --git a/internal/docs/agent_access_test.go b/internal/docs/agent_access_test.go
new file mode 100644
index 0000000..af513bf
--- /dev/null
+++ b/internal/docs/agent_access_test.go
@@ -0,0 +1,605 @@
+package docs
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/handoff/seal"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+type docAgentFixture struct {
+ a *documentAgent
+ app *App
+ p access.Principal
+ handler http.Handler
+ revoked atomic.Bool
+ checks atomic.Int64
+ revokeAt atomic.Int64
+ verified chan struct{}
+}
+
+func TestAgentDocumentRevokedWriterNeverCommits(t *testing.T) {
+ for _, phase := range []string{"waiting", "before-commit"} {
+ t.Run(phase, func(t *testing.T) {
+ f := newDocAgentFixture(t)
+ if phase == "waiting" {
+ held, release := make(chan struct{}), make(chan struct{})
+ txDone := make(chan error, 1)
+ go func() {
+ txDone <- f.a.store.db.Transaction(func(tx *gorm.DB) error { close(held); <-release; return nil })
+ }()
+ <-held
+ f.verified = make(chan struct{})
+ result := make(chan *httptest.ResponseRecorder, 1)
+ go func() { result <- f.call(t, "docs_create", initialAgentInput()) }()
+ select {
+ case <-f.verified:
+ case <-time.After(5 * time.Second):
+ close(release)
+ t.Fatal("request never verified")
+ }
+ f.revoked.Store(true)
+ close(release)
+ if err := <-txDone; err != nil {
+ t.Fatal(err)
+ }
+ if rec := <-result; rec.Code != 401 {
+ t.Error("waiting revoked create", rec.Code, rec.Body.String())
+ }
+ } else {
+ // Initial verification, reserved writer, then final in-transaction check.
+ f.revokeAt.Store(3)
+ if rec := f.call(t, "docs_create", initialAgentInput()); rec.Code != 401 {
+ t.Error("final revoked create", rec.Code, rec.Body.String())
+ }
+ }
+ for _, model := range []any{&Document{}, &DocUpdate{}, &agentReceipt{}, &agentAttribution{}} {
+ var count int64
+ if e := f.a.store.db.Model(model).Count(&count).Error; e != nil || count != 0 {
+ t.Fatal("revoked create persisted", count, e)
+ }
+ }
+ })
+ }
+}
+
+type docAgentCredentials struct{}
+
+func (docAgentCredentials) Downstream(context.Context, access.Principal, string, string, []string) (string, error) {
+ return "test-token", nil
+}
+
+func TestAgentDocumentTeamContractsComposeAndWrongInstanceRefuses(t *testing.T) {
+ f := newDocAgentFixture(t)
+ other := *f.a
+ other.team = "green"
+ f.p.Teams = []string{"blue", "green"}
+ first, e := f.a.registry()
+ if e != nil {
+ t.Fatal(e)
+ }
+ second, e := other.registry()
+ if e != nil {
+ t.Fatal(e)
+ }
+ gateway, e := access.Gateway([]access.Route{{Team: "blue", Resource: bridgeOrigin + "/api/v1", Operations: first.List(f.p)}, {Team: "green", Resource: "https://green.docs.oficina.works/api/v1", Operations: second.List(f.p)}}, docAgentCredentials{}, nil)
+ if e != nil || len(gateway.List(f.p)) != 3 {
+ t.Fatal("contracts cannot compose", e)
+ }
+ in := initialAgentInput()
+ in.Team = "green"
+ if rec := f.call(t, "docs_create", in); rec.Code != 403 {
+ t.Fatal("multi-team credential crossed instance", rec.Code)
+ }
+}
+
+func TestAgentDocumentRejectsLossyJSONAndKeepsLargeCreateRetryable(t *testing.T) {
+ f := newDocAgentFixture(t)
+ for _, text := range []string{string([]byte{0xff}), `\ud800`, `\udfff`} {
+ raw := `{"team":"blue","client_id":"` + uuid.NewString() + `","title":"title","blocks":[{"type":"paragraph","text":"` + text + `"}]}`
+ req := httptest.NewRequest("POST", bridgeOrigin+"/api/v1/operations/docs_create", strings.NewReader(raw))
+ req.Header.Set("Authorization", "Bearer test-token")
+ req.Header.Set("Content-Type", "application/json")
+ w := &teamDeadlineRecorder{ResponseRecorder: httptest.NewRecorder()}
+ f.handler.ServeHTTP(w, req)
+ if w.Code != 422 {
+ t.Fatal("lossy JSON accepted", w.Code, w.Body.String())
+ }
+ }
+ var count int64
+ f.a.store.db.Model(&Document{}).Count(&count)
+ if count != 0 {
+ t.Fatal("malformed input wrote documents")
+ }
+ in := initialAgentInput()
+ in.Blocks = []agentBlock{{Type: "paragraph", Text: strings.Repeat("<", 128<<10)}}
+ body := decodeAgentBody(t, f.call(t, "docs_create", in))
+ retry := decodeAgentBody(t, f.call(t, "docs_create", in))
+ if body.ID != retry.ID || body.Revision != retry.Revision {
+ t.Fatal("large create retry changed result")
+ }
+ if rec := f.call(t, "docs_get", map[string]any{"team": "blue", "id": body.ID}); rec.Code != 413 {
+ t.Fatal("oversized read was not refused", rec.Code)
+ }
+ var doc Document
+ if e := f.a.store.db.Where("sqid=?", body.ID).First(&doc).Error; e != nil {
+ t.Fatal(e)
+ }
+ var attribution agentAttribution
+ if e := f.a.store.db.First(&attribution, doc.ID).Error; e != nil {
+ t.Fatal(e)
+ }
+ sealer, e := seal.New(f.a.key, "oficina/docs")
+ if e != nil {
+ t.Fatal(e)
+ }
+ client, e := sealer.Open("agent-client/"+doc.GUID, attribution.ClientSealed)
+ if e != nil || string(client) != f.p.Client || bytes.Contains(attribution.ClientSealed, []byte(f.p.Client)) {
+ t.Fatal("client attribution not recoverable and sealed", e)
+ }
+}
+
+func TestAgentDocumentPagesUseCurrentPermissionAndExactCursor(t *testing.T) {
+ f := newDocAgentFixture(t)
+ for i := 0; i < 3; i++ {
+ decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput()))
+ }
+ // Tie timestamps so the stable ID tiebreaker is necessary.
+ if e := f.a.store.db.Model(&Document{}).Where("id > 0").Update("updated_at", time.Date(2026, 10, 25, 0, 0, 0, 0, time.UTC)).Error; e != nil {
+ t.Fatal(e)
+ }
+ cursor := ""
+ seen := map[string]bool{}
+ for i := 0; i < 3; i++ {
+ rec := f.call(t, "docs_list", map[string]any{"team": "blue", "limit": 1, "cursor": cursor})
+ if rec.Code != 200 {
+ t.Fatal(rec.Code, rec.Body.String())
+ }
+ var page struct {
+ Documents []agentDocument `json:"documents"`
+ Next string `json:"next_cursor"`
+ }
+ if e := json.Unmarshal(rec.Body.Bytes(), &page); e != nil {
+ t.Fatal(e)
+ }
+ if len(page.Documents) != 1 || seen[page.Documents[0].ID] {
+ t.Fatal("pagination duplicated or skipped", page)
+ }
+ seen[page.Documents[0].ID] = true
+ cursor = page.Next
+ }
+ if cursor != "" {
+ t.Fatal("last page has cursor")
+ }
+ if rec := f.call(t, "docs_list", map[string]any{"team": "blue", "cursor": "not-a-cursor"}); rec.Code != 422 {
+ t.Fatal("malformed cursor accepted", rec.Code)
+ }
+ other, e := f.a.store.EnsurePerson(t.Context(), "foreign@example.com")
+ if e != nil {
+ t.Fatal(e)
+ }
+ doc, e := f.a.store.Create(t.Context(), other, "Private foreign title")
+ if e != nil {
+ t.Fatal(e)
+ }
+ if rec := f.call(t, "docs_get", map[string]any{"team": "blue", "id": doc.Sqid}); rec.Code != 404 {
+ t.Fatal("foreign document disclosed", rec.Code)
+ }
+ rec := f.call(t, "docs_list", map[string]any{"team": "blue"})
+ if rec.Code != 200 || strings.Contains(rec.Body.String(), doc.Title) {
+ t.Fatal("foreign title in list", rec.Code)
+ }
+}
+
+func newDocAgentFixture(t *testing.T, issuers ...string) *docAgentFixture {
+ t.Helper()
+ return newDocAgentFixtureWithStorage(t, true, issuers...)
+}
+func newDocAgentFixtureWithStorage(t *testing.T, activate bool, issuers ...string) *docAgentFixture {
+ t.Helper()
+ f := newBridgeFixture(t)
+ f.link(t, f.local(t, "owner@example.com", "keymail", time.Now()), "opaque-owner")
+ cipher, err := newContentCipher("", "development")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if activate {
+ if err = convertContent(t.Context(), f.app.store.db, cipher); err != nil {
+ t.Fatal(err)
+ }
+ f.app.store.content = cipher
+ }
+ a := &documentAgent{store: f.app.store, resolver: f.b.resolver, list: allowlist{addrs: map[string]struct{}{"owner@example.com": {}}}, origin: bridgeOrigin, issuer: "https://connect.oficina.works", identityIssuer: bridgeIssuer, team: "blue", key: bytes.Repeat([]byte{41}, 32)}
+ if len(issuers) > 0 {
+ a.issuer = issuers[0]
+ }
+ a.list.granted = func(address string) (bool, error) { return a.store.HasGrant(t.Context(), address) }
+ if err = a.store.db.Transaction(func(tx *gorm.DB) error { return a.bind(tx) }); err != nil {
+ t.Fatal(err)
+ }
+ out := &docAgentFixture{a: a, app: f.app, p: access.Principal{Subject: "opaque-owner", Client: "test-client", Grant: "grant-one", Teams: []string{"blue"}, Scopes: []string{"docs:read", "docs:write"}}}
+ out.handler, err = a.httpHandler(access.VerifyFunc(func(ctx context.Context, token string) (access.Principal, error) {
+ n := out.checks.Add(1)
+ if n == 1 && out.verified != nil {
+ close(out.verified)
+ }
+ if at := out.revokeAt.Load(); at > 0 && n >= at {
+ out.revoked.Store(true)
+ }
+ if token != "test-token" || out.revoked.Load() {
+ return access.Principal{}, access.Fail("unauthenticated", "Connection expired.")
+ }
+ return out.p, nil
+ }))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return out
+}
+func (f *docAgentFixture) call(t *testing.T, name string, input any) *httptest.ResponseRecorder {
+ t.Helper()
+ body, err := json.Marshal(input)
+ if err != nil {
+ t.Fatal(err)
+ }
+ r := httptest.NewRequest("POST", bridgeOrigin+"/api/v1/operations/"+name, bytes.NewReader(body))
+ r.Header.Set("Authorization", "Bearer test-token")
+ r.Header.Set("Content-Type", "application/json")
+ w := &teamDeadlineRecorder{ResponseRecorder: httptest.NewRecorder()}
+ f.handler.ServeHTTP(w, r)
+ return w.ResponseRecorder
+}
+func initialAgentInput() agentCreateInput {
+ return agentCreateInput{Team: "blue", ClientID: uuid.NewString(), Title: "API document", Blocks: []agentBlock{{Type: "heading", Text: "Meeting", Level: 2}, {Type: "paragraph", Text: "PRIVATE_INITIAL_BODY_7f39 <script> literal ✓"}}}
+}
+func decodeAgentBody(t *testing.T, w *httptest.ResponseRecorder) agentBody {
+ t.Helper()
+ if w.Code != 200 {
+ t.Fatalf("operation failed: %d %s", w.Code, w.Body.String())
+ }
+ var body agentBody
+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
+ t.Fatal(err)
+ }
+ return body
+}
+func TestAgentDocumentCreatesRealSealedContentAndRetries(t *testing.T) {
+ f := newDocAgentFixture(t)
+ in := initialAgentInput()
+ body := decodeAgentBody(t, f.call(t, "docs_create", in))
+ body = decodeAgentBody(t, f.call(t, "docs_get", map[string]any{"team": "blue", "id": body.ID}))
+ if body.ID == "" || body.Revision != "1" || !strings.Contains(body.Text, "PRIVATE_INITIAL_BODY_7f39") || !strings.Contains(string(body.Content), `"level":2`) {
+ t.Fatalf("invalid core body: %+v", body)
+ }
+ got := decodeAgentBody(t, f.call(t, "docs_get", map[string]any{"team": "blue", "id": body.ID}))
+ if got.Text != body.Text || got.Revision != body.Revision {
+ t.Fatal("get mismatch")
+ }
+ var wg sync.WaitGroup
+ results := make(chan *httptest.ResponseRecorder, 4)
+ for i := 0; i < 4; i++ {
+ wg.Add(1)
+ go func() { defer wg.Done(); results <- f.call(t, "docs_create", in) }()
+ }
+ wg.Wait()
+ close(results)
+ for rec := range results {
+ if retry := decodeAgentBody(t, rec); retry.ID != body.ID {
+ t.Fatal("retry duplicated document")
+ }
+ }
+ changed := in
+ changed.Title = "Different"
+ if rec := f.call(t, "docs_create", changed); rec.Code != 409 {
+ t.Fatal("changed retry", rec.Code)
+ }
+ var n int64
+ if err := f.a.store.db.Model(&Document{}).Count(&n).Error; err != nil || n != 1 {
+ t.Fatal(n, err)
+ }
+ var doc Document
+ if err := f.a.store.db.Where("sqid=?", body.ID).First(&doc).Error; err != nil {
+ t.Fatal(err)
+ }
+ // Real browser-compatible update advances the body; retry must not reapply initial content.
+ ctx, id, err := f.a.prepare(t.Context(), f.p, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = f.a.store.ApplyUpdate(ctx, &doc, id.Actor, validUpdate(t)); err != nil {
+ t.Fatal(err)
+ }
+ retried := decodeAgentBody(t, f.call(t, "docs_create", in))
+ if retried.ID != body.ID || retried.Revision != "2" {
+ t.Fatal("retry reset body revision", retried.Revision)
+ }
+ for _, suffix := range []string{"", "-wal"} {
+ raw, e := os.ReadFile(f.app.cfg.DBPath + suffix)
+ if e != nil && !os.IsNotExist(e) {
+ t.Fatal(e)
+ }
+ if bytes.Contains(raw, []byte("PRIVATE_INITIAL_BODY_7f39")) {
+ t.Fatal("plaintext body in storage", suffix)
+ }
+ }
+ if err = f.a.store.db.Model(&doc).Update("deleted_at", time.Now()).Error; err != nil {
+ t.Fatal(err)
+ }
+ if rec := f.call(t, "docs_create", in); rec.Code != 404 {
+ t.Fatal("deleted retry recreated", rec.Code)
+ }
+}
+func TestAgentDocumentAtomicRollbackAndAuthorityBinding(t *testing.T) {
+ f := newDocAgentFixture(t)
+ in := initialAgentInput()
+ for _, table := range []string{"doc_updates", "docs_agent_receipts", "docs_agent_attribution"} {
+ if err := f.a.store.db.Exec("CREATE TRIGGER agent_failure BEFORE INSERT ON " + table + " BEGIN SELECT RAISE(ABORT,'injected failure'); END").Error; err != nil {
+ t.Fatal(err)
+ }
+ if rec := f.call(t, "docs_create", in); rec.Code != 503 {
+ t.Fatal("write failure not surfaced", rec.Code)
+ }
+ for _, model := range []any{&Document{}, &DocUpdate{}, &agentReceipt{}, &agentAttribution{}} {
+ var count int64
+ if e := f.a.store.db.Model(model).Count(&count).Error; e != nil || count != 0 {
+ t.Fatal("partial creation", count, e)
+ }
+ }
+ if err := f.a.store.db.Exec("DROP TRIGGER agent_failure").Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ body := decodeAgentBody(t, f.call(t, "docs_create", in))
+ for _, change := range []func(*documentAgent){func(a *documentAgent) { a.key = bytes.Repeat([]byte{42}, 32) }, func(a *documentAgent) { a.identityIssuer = "https://another-home.example" }, func(a *documentAgent) { a.issuer = "https://another-connect.example" }, func(a *documentAgent) { a.team = "other" }} {
+ copy := *f.a
+ change(&copy)
+ if err := copy.store.db.Transaction(func(tx *gorm.DB) error { return copy.bind(tx) }); err == nil {
+ t.Fatal("authority/key change accepted")
+ }
+ }
+ copy := *f.a
+
+ reopened, err := New(f.app.cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reopened.Close()
+ copy.store = reopened.store
+ if err := copy.store.db.Transaction(func(tx *gorm.DB) error { return copy.bind(tx) }); err != nil {
+ t.Fatal("same authority restart refused", err)
+ }
+ if retry := decodeAgentBody(t, f.call(t, "docs_create", in)); retry.ID != body.ID {
+ t.Fatal("same authority retry changed ID")
+ }
+ f.a.store.content = nil
+ if rec := f.call(t, "docs_create", initialAgentInput()); rec.Code != 503 {
+ t.Fatal("legacy storage write", rec.Code)
+ }
+}
+
+func TestAgentDocumentIdentityLostBeforeCommitRollsBack(t *testing.T) {
+ f := newDocAgentFixture(t)
+ if e := f.a.store.db.Exec("CREATE TRIGGER agent_unlink AFTER INSERT ON docs_agent_receipts BEGIN DELETE FROM docs_identity_links; END").Error; e != nil {
+ t.Fatal(e)
+ }
+ rec := f.call(t, "docs_create", initialAgentInput())
+ for _, model := range []any{&Document{}, &DocUpdate{}, &agentReceipt{}, &agentAttribution{}} {
+ var count int64
+ if e := f.a.store.db.Model(model).Count(&count).Error; e != nil || count != 0 {
+ t.Fatal("lost identity committed creation", count, e)
+ }
+ }
+ if rec.Code != 403 {
+ t.Fatal("lost identity refusal", rec.Code)
+ }
+ var links int
+ f.a.store.db.Raw("SELECT COUNT(*) FROM docs_identity_links").Scan(&links)
+ if links != 1 {
+ t.Fatal("identity deletion was not rolled back")
+ }
+}
+func TestAgentDocumentScopeIdentityAndFinalRevocation(t *testing.T) {
+ f := newDocAgentFixture(t)
+ body := decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput()))
+ in := map[string]any{"team": "blue", "id": body.ID}
+ saved := f.p
+ f.p.Subject = "never-linked"
+ if rec := f.call(t, "docs_get", in); rec.Code != 403 {
+ t.Fatal("unlinked", rec.Code)
+ }
+ f.p = saved
+ f.p.Scopes = []string{"docs:write"}
+ if rec := f.call(t, "docs_get", in); rec.Code != 403 {
+ t.Fatal("wrong scope", rec.Code)
+ }
+ f.p = saved
+ in["team"] = "foreign"
+ if rec := f.call(t, "docs_get", in); rec.Code != 403 {
+ t.Fatal("wrong team", rec.Code)
+ }
+ in["team"] = "blue"
+ f.revoked.Store(true)
+ if rec := f.call(t, "docs_get", in); rec.Code != 401 {
+ t.Fatal("revoked", rec.Code)
+ }
+ f.revoked.Store(false)
+ if err := f.a.store.db.Exec("DELETE FROM docs_identity_links WHERE subject=?", f.p.Subject).Error; err != nil {
+ t.Fatal(err)
+ }
+ if rec := f.call(t, "docs_get", in); rec.Code != 403 {
+ t.Fatal("unlinked existing credential", rec.Code)
+ }
+ var count int64
+ f.a.store.db.Model(&Person{}).Count(&count)
+ if count != 1 {
+ t.Fatal("agent provisioned identity")
+ }
+}
+func TestAgentDocumentHTTPAbortsRevocationDuringEmission(t *testing.T) {
+ f := newDocAgentFixture(t)
+ in := initialAgentInput()
+ in.Blocks = []agentBlock{{Type: "paragraph", Text: strings.Repeat("x", 100<<10)}}
+ body := decodeAgentBody(t, f.call(t, "docs_create", in))
+ raw, _ := json.Marshal(map[string]any{"team": "blue", "id": body.ID})
+ r := httptest.NewRequest("POST", bridgeOrigin+"/api/v1/operations/docs_get", bytes.NewReader(raw))
+ r.Header.Set("Content-Type", "application/json")
+ r.Header.Set("Authorization", "Bearer test-token")
+ w := &teamDeadlineRecorder{ResponseRecorder: httptest.NewRecorder(), afterWrite: func() { f.revoked.Store(true) }}
+ aborted := false
+ func() {
+ defer func() {
+ if e := recover(); e != nil {
+ if e != http.ErrAbortHandler {
+ panic(e)
+ }
+ aborted = true
+ }
+ }()
+ f.handler.ServeHTTP(w, r)
+ }()
+ if !aborted || w.Body.Len() != 64<<10 {
+ t.Fatal("revocation emitted a successful partial body", aborted, w.Body.Len())
+ }
+}
+func TestAgentDocumentHTTPWorksWithoutBrowserSession(t *testing.T) {
+ f := newDocAgentFixture(t)
+ server := httptest.NewServer(f.handler)
+ defer server.Close()
+ raw, _ := json.Marshal(initialAgentInput())
+ req, _ := http.NewRequest("POST", server.URL+"/api/v1/operations/docs_create", bytes.NewReader(raw))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer test-token")
+ response, err := server.Client().Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer response.Body.Close()
+ body, err := io.ReadAll(response.Body)
+ if err != nil || response.StatusCode != 200 {
+ t.Fatal(response.StatusCode, string(body), err)
+ }
+}
+func TestAgentDocumentConfigRefusesPartialAndWrongIdentityNamespace(t *testing.T) {
+ home := &homeSettings{issuer: bridgeIssuer}
+ for _, cfg := range []Config{{AgentTeam: "blue"}, {AgentIssuer: "https://connect.oficina.works"}, {AgentIssuer: bridgeIssuer, AgentTeam: "blue"}, {AgentIssuer: "http://connect.oficina.works", AgentTeam: "blue"}} {
+ cfg.Origin = bridgeOrigin
+ if _, err := validatedAgentConfig(cfg, home, nil); !errors.Is(err, errAgentConfig) {
+ t.Fatal("invalid configuration accepted")
+ }
+ }
+ if _, err := validatedAgentConfig(Config{AgentIssuer: "https://connect.oficina.works", AgentTeam: "blue", Origin: bridgeOrigin}, nil, nil); err == nil {
+ t.Fatal("Home required")
+ }
+}
+
+func TestAgentDocumentTeamEpochIsCheckedDuringActualEmission(t *testing.T) {
+ for _, mode := range []string{"late", "partial", "explicit-grant"} {
+ t.Run(mode, func(t *testing.T) {
+ f := newDocAgentFixture(t)
+ in := initialAgentInput()
+ in.Blocks = []agentBlock{{Type: "paragraph", Text: strings.Repeat("z", 100<<10)}}
+ body := decodeAgentBody(t, f.call(t, "docs_create", in))
+ var doc Document
+ if e := f.a.store.db.Where("sqid=?", body.ID).First(&doc).Error; e != nil {
+ t.Fatal(e)
+ }
+ if mode == "explicit-grant" {
+ other, e := f.a.store.EnsurePerson(t.Context(), "other@example.com")
+ if e != nil {
+ t.Fatal(e)
+ }
+ if e = f.a.store.db.Model(&doc).Update("owner_id", other).Error; e != nil {
+ t.Fatal(e)
+ }
+ doc.OwnerID = other
+ if e := f.a.store.Grant(t.Context(), doc.OwnerID, doc.Sqid, "owner@example.com", RoleReader); e != nil {
+ t.Fatal(e)
+ }
+ }
+ // Fixture provisioning uses its own fixed Home issuer/subject. Move the test
+ // link before activating the immutable team identity schema.
+ subject := "pr_" + strings.Repeat("a", 26)
+ if e := f.a.store.db.Exec("UPDATE docs_identity_links SET issuer=?,subject=?", "https://id.example", subject).Error; e != nil {
+ t.Fatal(e)
+ }
+ rt, clock, _ := testTeamRoster(t, f.a.store, f.app)
+ f.a.resolver.team = rt
+ f.a.identityIssuer = rt.bindings.Issuer
+ f.a.team = rt.bindings.Team
+ f.p.Subject = subject
+ f.p.Teams = []string{rt.bindings.Team}
+ calls := 0
+ handler, e := f.a.httpHandler(access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ calls++
+ if mode == "late" && calls == 2 {
+ clock.step(60 * time.Second)
+ }
+ return f.p, nil
+ }))
+ if e != nil {
+ t.Fatal(e)
+ }
+ if mode == "explicit-grant" {
+ clock.step(60 * time.Second)
+ }
+ raw, _ := json.Marshal(map[string]any{"team": rt.bindings.Team, "id": doc.Sqid})
+ req := httptest.NewRequest("POST", bridgeOrigin+"/api/v1/operations/docs_get", bytes.NewReader(raw))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer token")
+ w := &teamDeadlineRecorder{ResponseRecorder: httptest.NewRecorder()}
+ if mode == "partial" {
+ w.afterWrite = func() { clock.step(60 * time.Second) }
+ }
+ aborted := false
+ func() {
+ defer func() {
+ if e := recover(); e != nil {
+ if e != http.ErrAbortHandler {
+ panic(e)
+ }
+ aborted = true
+ }
+ }()
+ handler.ServeHTTP(w, req)
+ }()
+ switch mode {
+ case "late":
+ if aborted || w.Code != 503 || strings.Contains(w.Body.String(), strings.Repeat("z", 64)) {
+ t.Fatal("late epoch leaked body", w.Code, aborted)
+ }
+ case "partial":
+ if !aborted || w.Body.Len() != 64<<10 {
+ t.Fatal("expired epoch did not abort", aborted, w.Body.Len())
+ }
+ case "explicit-grant":
+ if aborted || w.Code != 200 || !strings.Contains(w.Body.String(), strings.Repeat("z", 64)) {
+ t.Fatal("explicit grant lost independent authority", w.Code, aborted)
+ }
+ }
+ })
+ }
+}
+
+func TestAgentDocumentLegacyStorageRefusesBeforeWrite(t *testing.T) {
+ f := newDocAgentFixtureWithStorage(t, false)
+ rec := f.call(t, "docs_create", initialAgentInput())
+ var count int64
+ f.a.store.db.Model(&Document{}).Count(&count)
+ if rec.Code != 503 || count != 0 {
+ t.Fatal("legacy storage accepted agent write", rec.Code, count)
+ }
+}
diff --git a/internal/docs/agent_integration_test.go b/internal/docs/agent_integration_test.go
new file mode 100644
index 0000000..fd9502e
--- /dev/null
+++ b/internal/docs/agent_integration_test.go
@@ -0,0 +1,152 @@
+package docs
+
+import (
+ "context"
+ "crypto/sha256"
+ "database/sql"
+ "encoding/base64"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/agent-access.git/client"
+ "amadan.net/oficina/agent-access.git/grant"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+ "golang.org/x/oauth2"
+)
+
+type agentCredentials struct{ value client.Credentials }
+
+func (m *agentCredentials) Load() (client.Credentials, error) { return m.value, nil }
+func (m *agentCredentials) Save(v client.Credentials) error { m.value = v; return nil }
+func (m *agentCredentials) Delete() error { m.value = client.Credentials{}; return nil }
+
+type agentBearer struct {
+ base http.RoundTripper
+ token string
+}
+
+func (b agentBearer) RoundTrip(r *http.Request) (*http.Response, error) {
+ copy := r.Clone(r.Context())
+ copy.Header.Set("Authorization", "Bearer "+b.token)
+ return b.base.RoundTrip(copy)
+}
+
+// This fixture crosses real HTTPS boundaries from the shared CLI/MCP gateway
+// into Docs' real handlers, linked identity, sealed collaborative content.
+// The signed Home/browser/PKCE flow is exercised in the connection module.
+func TestAgentGatewayToRealDocs(t *testing.T) {
+ ctx := t.Context()
+ var appHandler, httpHandler http.Handler
+ appServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { appHandler.ServeHTTP(w, r) }))
+ defer appServer.Close()
+ issuer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { httpHandler.ServeHTTP(w, r) }))
+ defer issuer.Close()
+ f := newDocAgentFixture(t, issuer.URL)
+ p := f.p
+ input, _ := json.Marshal(initialAgentInput())
+ database, err := sql.Open("sqlite", filepath.Join(t.TempDir(), "grants.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer database.Close()
+ database.SetMaxOpenConns(1)
+ store, err := grant.NewStore(ctx, database)
+ if err != nil {
+ t.Fatal(err)
+ }
+ teams := func(context.Context, string) ([]grant.Team, error) {
+ return []grant.Team{{ID: "blue", Name: "Blue"}}, nil
+ }
+ grants, err := grant.NewServer(grant.Config{IdentityIssuer: bridgeIssuer, Origin: issuer.URL, Resource: issuer.URL + "/mcp", Store: store, ConsentKey: []byte(strings.Repeat("k", 32)), Clients: []grant.Client{{ID: client.ClientID, Name: "Oficina CLI", Loopback: true}}, Scopes: map[string]string{"docs:read": "Read documents", "docs:write": "Create documents"}, Subject: func(*http.Request) string { return "" }, Teams: teams, ResourceTeams: func(ctx context.Context, subject, resource string) ([]grant.Team, error) {
+ if resource != appServer.URL+"/api/v1" {
+ return nil, nil
+ }
+ return teams(ctx, subject)
+ }, SignInPath: "/signin"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ remote, err := access.NewRemoteVerifier(issuer.URL, appServer.URL+"/api/v1", bridgeIssuer)
+ if err != nil {
+ t.Fatal(err)
+ }
+ remote.Client.Transport = issuer.Client().Transport
+ f.a.origin = appServer.URL
+ appHandler, err = f.a.httpHandler(remote)
+ if err != nil {
+ t.Fatal(err)
+ }
+ contracts, err := AgentContracts()
+ if err != nil {
+ t.Fatal(err)
+ }
+ gateway, err := access.Gateway([]access.Route{{Team: "blue", Resource: appServer.URL + "/api/v1", Operations: contracts}}, store, appServer.Client().Transport)
+ if err != nil {
+ t.Fatal(err)
+ }
+ serviceMux := http.NewServeMux()
+ serviceMux.Handle("/mcp", gateway.MCP(grants))
+ serviceMux.Handle("/api/v1/operations", gateway.HTTP(grants))
+ serviceMux.Handle("/api/v1/operations/", gateway.HTTP(grants))
+ serviceMux.Handle("/", grants.Handler())
+ httpHandler = serviceMux
+ verifier := oauth2.GenerateVerifier()
+ challenge := sha256.Sum256([]byte(verifier))
+ redirect := "http://127.0.0.1:43210/callback"
+ code, err := store.CreateCode(ctx, grant.Grant{Subject: p.Subject, ClientID: client.ClientID, Teams: p.Teams, Scopes: p.Scopes}, grant.Code{Redirect: redirect, Challenge: base64.RawURLEncoding.EncodeToString(challenge[:]), Resource: issuer.URL + "/mcp"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ token, err := store.Exchange(ctx, code, client.ClientID, redirect, issuer.URL+"/mcp", verifier)
+ if err != nil {
+ t.Fatal(err)
+ }
+ credentials := &agentCredentials{client.Credentials{Server: issuer.URL, Resource: issuer.URL + "/mcp", TokenEndpoint: issuer.URL + "/oauth/token", Token: &oauth2.Token{AccessToken: token.AccessToken, TokenType: "Bearer"}}}
+ cli := client.New(credentials)
+ cli.HTTP = issuer.Client()
+ result, err := cli.Call(ctx, "docs_create", json.RawMessage(input))
+ if err != nil {
+ t.Fatal(err)
+ }
+ encoded, _ := json.Marshal(result)
+ var document agentCreated
+ if json.Unmarshal(encoded, &document) != nil || document.ID == "" {
+ t.Fatal("invalid document receipt")
+ }
+ mcpClient := mcp.NewClient(&mcp.Implementation{Name: "Docs integration", Version: "1"}, nil)
+ session, err := mcpClient.Connect(ctx, &mcp.StreamableClientTransport{Endpoint: issuer.URL + "/mcp", HTTPClient: &http.Client{Transport: agentBearer{issuer.Client().Transport, token.AccessToken}}}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer session.Close()
+ retry, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "docs_create", Arguments: json.RawMessage(input)})
+ if err != nil || retry.IsError {
+ t.Fatal("MCP retry", retry, err)
+ }
+ search, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "docs_get", Arguments: map[string]any{"team": "blue", "id": document.ID}})
+ if err != nil || search.IsError {
+ t.Fatal("MCP search", search, err)
+ }
+ text, _ := json.Marshal(search.Content)
+ if !strings.Contains(string(text), "PRIVATE_INITIAL_BODY_7f39") {
+ t.Fatal("MCP could not read created document")
+ }
+ var count int
+ if err = f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&count); err != nil || count != 1 {
+ t.Fatal("transport retry duplicated document", count, err)
+ }
+ if err = cli.Logout(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = session.CallTool(ctx, &mcp.CallToolParams{Name: "docs_create", Arguments: initialAgentInput()}); err == nil {
+ t.Fatal("MCP survived CLI revocation")
+ }
+ if err = f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&count); err != nil || count != 1 {
+ t.Fatal("revoked call wrote document", count, err)
+ }
+}
diff --git a/internal/docs/agent_store.go b/internal/docs/agent_store.go
new file mode 100644
index 0000000..8fad820
--- /dev/null
+++ b/internal/docs/agent_store.go
@@ -0,0 +1,371 @@
+package docs
+
+import (
+ "context"
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "strconv"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/handoff/seal"
+ "amadan.net/oficina/home/roster"
+ "github.com/carlosframework/docs/internal/core"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+const agentResultLimit = 1 << 20
+
+type documentAgent struct {
+ store *Store
+ resolver identityResolver
+ list allowlist
+ origin, issuer, identityIssuer, team string
+ key []byte
+}
+type agentBlock struct {
+ Type string `json:"type"`
+ Text string `json:"text"`
+ Level uint8 `json:"level,omitempty"`
+}
+type agentCreateInput struct {
+ Team string `json:"team"`
+ ClientID string `json:"client_id"`
+ Title string `json:"title"`
+ Blocks []agentBlock `json:"blocks"`
+}
+type agentDocument struct {
+ ID string `json:"id"`
+ Title string `json:"title"`
+ URL string `json:"url"`
+ UpdatedAt string `json:"updated_at"`
+}
+type agentBody struct {
+ agentDocument
+ Revision string `json:"body_revision"`
+ Text string `json:"text"`
+ Content json.RawMessage `json:"content"`
+}
+type agentReceipt struct {
+ Coordinate string `gorm:"primaryKey"`
+ Content string
+ DocumentID int64
+}
+type agentAttribution struct {
+ DocumentID int64 `gorm:"primaryKey"`
+ OperatorID int64
+ ClientSealed []byte
+}
+
+func (agentAttribution) TableName() string { return "docs_agent_attribution" }
+
+type agentCreated struct {
+ agentDocument
+ Revision string `json:"body_revision"`
+}
+
+func (agentReceipt) TableName() string { return "docs_agent_receipts" }
+
+func (a *documentAgent) digest(domain string, value any) string {
+ raw, _ := json.Marshal(value) // only fixed structs and string slices enter here
+ mac := hmac.New(sha256.New, a.key)
+ mac.Write([]byte("oficina/docs/agent/v1/" + domain + "\x00"))
+ mac.Write(raw)
+ return hex.EncodeToString(mac.Sum(nil))
+}
+func (a *documentAgent) bind(tx *gorm.DB) error {
+ want := a.digest("keycheck", []string{"immutable-authority", a.identityIssuer, a.issuer, a.team})
+ // This write reserves SQLite's writer before checking state or receipts.
+ if err := tx.Exec("INSERT INTO docs_agent_state(id,keycheck) SELECT 1,? WHERE NOT EXISTS(SELECT 1 FROM docs_agent_receipts) ON CONFLICT(id) DO NOTHING", want).Error; err != nil {
+ return err
+ }
+ var got string
+ if err := tx.Raw("SELECT keycheck FROM docs_agent_state WHERE id=1").Scan(&got).Error; err != nil {
+ return err
+ }
+ if !hmac.Equal([]byte(got), []byte(want)) {
+ return access.Fail("unavailable", "Agent receipt authority requires an explicit migration.")
+ }
+ return nil
+}
+func agentFailure(err error) error {
+ if err == nil {
+ return nil
+ }
+ var failure access.Failure
+ if errors.As(err, &failure) {
+ return failure
+ }
+ if errors.Is(err, gorm.ErrRecordNotFound) || errors.Is(err, ErrNotWritable) {
+ return access.Fail("not_found", "This document is unavailable.")
+ }
+ if errors.Is(err, errIdentityRefused) || errors.Is(err, errTeamNotMember) {
+ return access.Fail("forbidden", "This identity is not admitted for that operation.")
+ }
+ return access.Fail("unavailable", "Document authority or storage is unavailable.")
+}
+func (a *documentAgent) prepare(ctx context.Context, p access.Principal, write bool) (context.Context, requestIdentity, error) {
+ scope := "docs:read"
+ if write {
+ scope = "docs:write"
+ }
+ if p.Client == "" || !p.Allows(a.team, scope) {
+ return ctx, requestIdentity{}, access.Fail("forbidden", "This connection does not allow that team and operation.")
+ }
+ id, err := a.resolver.resolveHome(ctx, p.Subject)
+ if err != nil {
+ return ctx, id, agentFailure(err)
+ }
+ if a.store.team == nil {
+ admitted, e := a.list.allows(actorAddress(id.Actor))
+ if e != nil {
+ return ctx, id, agentFailure(e)
+ }
+ if !admitted || write && !a.list.configured(actorAddress(id.Actor)) {
+ return ctx, id, agentFailure(errIdentityRefused)
+ }
+ }
+ if existing, ok := ctx.Value(accessContextKey{}).(*requestAccess); ok && existing != nil {
+ if existing.runtime != a.store.team || !sameActor(existing.actor, id.Actor) {
+ return ctx, id, agentFailure(errIdentityRefused)
+ }
+ } else {
+ guard := &requestAccess{actor: id.Actor, responseStore: a.store, responseDocs: map[int64]permission{}, decision: roster.Decision{State: roster.NotMember}}
+ if a.store.team != nil {
+ guard = a.store.team.resolveAccess(ctx, id)
+ guard.responseStore = a.store
+ guard.responseDocs = map[int64]permission{}
+ }
+ ctx = context.WithValue(ctx, accessContextKey{}, guard)
+ }
+ if write {
+ if e := a.store.requireMember(ctx, id.Actor); e != nil {
+ return ctx, id, agentFailure(e)
+ }
+ }
+ return ctx, id, nil
+}
+func (a *documentAgent) remember(ctx context.Context, doc *Document) {
+ if guard, ok := ctx.Value(accessContextKey{}).(*requestAccess); ok && guard != nil {
+ guard.responseDocs[doc.ID] = permissionRead
+ }
+}
+func (a *documentAgent) summary(doc *Document) agentDocument {
+ return agentDocument{doc.Sqid, doc.Title, a.origin + "/d/" + doc.Sqid, doc.UpdatedAt.UTC().Format(time.RFC3339Nano)}
+}
+func agentBounded(value any) (any, error) {
+ body, err := json.Marshal(value)
+ if err != nil {
+ return nil, agentFailure(err)
+ }
+ if len(body) > agentResultLimit {
+ return nil, access.Fail("too_large", "The document result exceeds 1 MiB.")
+ }
+ return value, nil
+}
+func (a *documentAgent) body(ctx context.Context, actor Actor, sqid string) (any, error) {
+ doc, err := a.store.GetFor(ctx, actor, sqid)
+ if err != nil {
+ return nil, agentFailure(err)
+ }
+ h, seq, _, err := a.store.replay(ctx, doc)
+ if err != nil {
+ return nil, agentFailure(err)
+ }
+ defer h.Close(ctx)
+ text, err := h.Text(ctx)
+ if err != nil {
+ return nil, agentFailure(err)
+ }
+ content, err := h.JSON(ctx)
+ if err != nil {
+ return nil, agentFailure(err)
+ }
+ a.remember(ctx, doc)
+ return agentBounded(agentBody{a.summary(doc), strconv.FormatInt(seq, 10), text, json.RawMessage(content)})
+}
+
+type agentCursor struct {
+ At string `json:"at"`
+ ID string `json:"id"`
+}
+
+func (a *documentAgent) documents(ctx context.Context, actor Actor, limit int, cursor string) (any, error) {
+ if limit == 0 {
+ limit = 20
+ }
+ if limit < 1 || limit > 100 {
+ return nil, access.Fail("invalid", "Choose a page size from 1 to 100.")
+ }
+ q := a.store.permissionScope(ctx, a.store.db.WithContext(ctx), actor, permissionRead).Where("documents.deleted_at IS NULL")
+ if cursor != "" {
+ var c agentCursor
+ raw, err := base64.RawURLEncoding.Strict().DecodeString(cursor)
+ if err != nil || len(raw) > 256 || base64.RawURLEncoding.EncodeToString(raw) != cursor || access.UniqueJSON(raw) != nil || json.Unmarshal(raw, &c) != nil {
+ return nil, access.Fail("invalid", "Invalid document cursor.")
+ }
+ at, e1 := time.Parse(time.RFC3339Nano, c.At)
+ id, e2 := strconv.ParseInt(c.ID, 10, 64)
+ if e1 != nil || e2 != nil || id <= 0 || strconv.FormatInt(id, 10) != c.ID || at.UTC().Format(time.RFC3339Nano) != c.At {
+ return nil, access.Fail("invalid", "Invalid document cursor.")
+ }
+ q = q.Where("(documents.updated_at < ? OR (documents.updated_at = ? AND documents.id < ?))", at, at, id)
+ }
+ var rows []*Document
+ if err := q.Order("documents.updated_at DESC, documents.id DESC").Limit(limit + 1).Find(&rows).Error; err != nil {
+ return nil, agentFailure(err)
+ }
+ next := ""
+ if len(rows) > limit {
+ rows = rows[:limit]
+ last := rows[len(rows)-1]
+ raw, _ := json.Marshal(agentCursor{last.UpdatedAt.UTC().Format(time.RFC3339Nano), strconv.FormatInt(last.ID, 10)})
+ next = base64.RawURLEncoding.EncodeToString(raw)
+ }
+ items := make([]agentDocument, 0, len(rows))
+ for _, doc := range rows {
+ a.remember(ctx, doc)
+ items = append(items, a.summary(doc))
+ }
+ return agentBounded(struct {
+ Documents []agentDocument `json:"documents"`
+ Next string `json:"next_cursor"`
+ }{items, next})
+}
+
+// checkCreator runs on the reserved writer. It reads the same identity tables as
+// the resolver without opening a second SQL connection inside the transaction.
+func (a *documentAgent) checkCreator(ctx context.Context, tx *gorm.DB, p access.Principal, id requestIdentity) error {
+ guard, ok := ctx.Value(accessContextKey{}).(*requestAccess)
+ if !ok || guard == nil || guard.delegationCheck == nil {
+ return errIdentityRefused
+ }
+ if err := guard.delegationCheck(ctx); err != nil {
+ return err
+ }
+
+ query := "SELECT person_id AS id FROM docs_identity_links WHERE issuer=? AND subject=?"
+ args := []any{a.identityIssuer, p.Subject}
+ if a.store.team != nil {
+ query += " UNION ALL SELECT principal_id AS id FROM docs_home_identities WHERE issuer=? AND subject=?"
+ args = append(args, a.identityIssuer, p.Subject)
+ }
+ var ids []int64
+ if err := tx.Raw(query, args...).Scan(&ids).Error; err != nil {
+ return err
+ }
+ if len(ids) != 1 || ids[0] != id.Actor.PersonID {
+ return errIdentityRefused
+ }
+ if id.Actor.VerifiedAddress != nil {
+ var person Person
+ if err := tx.First(&person, id.Actor.PersonID).Error; err != nil {
+ return err
+ }
+ if subjectOf(person.Email) != *id.Actor.VerifiedAddress {
+ return errIdentityRefused
+ }
+ }
+ if a.store.team == nil && !a.list.configured(actorAddress(id.Actor)) {
+ return errIdentityRefused
+ }
+ return a.store.requireMember(ctx, id.Actor)
+}
+func (a *documentAgent) create(ctx context.Context, p access.Principal, id requestIdentity, input agentCreateInput) (any, error) {
+ u, err := uuid.Parse(input.ClientID)
+ if err != nil || u == uuid.Nil || u.String() != input.ClientID || !utf8.ValidString(input.Title) || strings.TrimSpace(input.Title) == "" || len(input.Title) > 512 || len(input.Blocks) > 200 {
+ return nil, access.Fail("invalid", "Invalid title, client UUID or initial content.")
+ }
+ blocks := make([]core.InitialBlock, len(input.Blocks))
+ total := 0
+ for i, b := range input.Blocks {
+ total += len(b.Text)
+ if !utf8.ValidString(b.Text) || total > 128<<10 || b.Type != "paragraph" && b.Type != "heading" || b.Type == "paragraph" && b.Level != 0 || b.Type == "heading" && (b.Level < 1 || b.Level > 6) {
+ return nil, access.Fail("invalid", "Invalid initial content.")
+ }
+ blocks[i] = core.InitialBlock{Text: b.Text, Level: b.Level}
+ }
+ if a.store.content == nil {
+ return nil, access.Fail("unavailable", "Activate sealed document storage before agent writes.")
+ }
+ coordinate := a.digest("coordinate", []string{a.identityIssuer, a.issuer, p.Subject, p.Client, a.team, input.ClientID})
+ payload := a.digest("content", struct {
+ Title string
+ Blocks []agentBlock
+ }{input.Title, input.Blocks})
+ var doc Document
+ err = a.store.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if e := a.bind(tx); e != nil {
+ return e
+ }
+ if e := a.checkCreator(ctx, tx, p, id); e != nil {
+ return e
+ }
+ var receipt agentReceipt
+ e := tx.Where("coordinate=?", coordinate).First(&receipt).Error
+ if e == nil {
+ if receipt.Content != payload {
+ return access.Fail("conflict", "This client UUID already names different initial content.")
+ }
+ if e = tx.Where("id=? AND deleted_at IS NULL", receipt.DocumentID).First(&doc).Error; e != nil {
+ return e
+ }
+ return a.store.checkPermission(ctx, tx, id.Actor, doc.ID, permissionRead)
+ }
+ if !errors.Is(e, gorm.ErrRecordNotFound) {
+ return e
+ }
+ store := *a.store
+ store.db = tx
+ created, e := store.CreateDraft(ctx, id.Actor.PersonID, input.Title, "")
+ if e != nil {
+ return e
+ }
+ update, e := store.core.InitialUpdate(ctx, created.GUID, created.ClientID, blocks)
+ if e != nil {
+ return e
+ }
+ if _, e = store.ApplyUpdate(ctx, created, id.Actor, update); e != nil {
+ return e
+ }
+ sealer, e := seal.New(a.key, "oficina/docs")
+ if e != nil {
+ return e
+ }
+ client, e := sealer.Seal("agent-client/"+created.GUID, []byte(p.Client))
+ if e != nil {
+ return e
+ }
+ if e = tx.Create(&agentAttribution{created.ID, id.Actor.PersonID, client}).Error; e != nil {
+ return e
+ }
+ receipt = agentReceipt{coordinate, payload, created.ID}
+ if e = tx.Create(&receipt).Error; e != nil {
+ return e
+ }
+ doc = *created
+ return a.checkCreator(ctx, tx, p, id)
+ })
+ if err != nil {
+ return nil, agentFailure(err)
+ }
+ // A retry reads the current body, including intervening browser edits.
+ current, e := a.store.GetFor(ctx, id.Actor, doc.Sqid)
+ if e != nil {
+ return nil, agentFailure(e)
+ }
+ h, seq, _, e := a.store.replay(ctx, current)
+ if e != nil {
+ return nil, agentFailure(e)
+ }
+ defer h.Close(ctx)
+ a.remember(ctx, current)
+ return agentBounded(agentCreated{a.summary(current), strconv.FormatInt(seq, 10)})
+}
diff --git a/internal/docs/app.go b/internal/docs/app.go
index 27f33b5..7ef71b0 100644
--- a/internal/docs/app.go
+++ b/internal/docs/app.go
@@ -41,7 +41,9 @@ import (
// Config configures New.
type Config struct {
- Home *HomeConfig
+ AgentIssuer string
+ AgentTeam string
+ Home *HomeConfig
// Directory is the hub directory origin ($HOME_DIRECTORY_ORIGIN): the
// app switcher's "All apps". Empty means no switcher.
Directory string
@@ -358,6 +360,10 @@ func New(cfg Config) (*App, error) {
if err != nil {
return nil, err
}
+ agentVerifier, err := validatedAgentConfig(cfg, homeSettings, teamSettings)
+ if err != nil {
+ return nil, err
+ }
instanceKey, err := resolveInstanceKey(cfg)
if err != nil {
return nil, err
@@ -723,6 +729,16 @@ func New(cfg Config) (*App, error) {
mux := http.NewServeMux()
mux.Handle("/", r)
+ if agentVerifier != nil {
+ agentHandler, e := newDocumentAgent(cfg, homeSettings, home, store, list, agentVerifier)
+ if e != nil {
+ rt.Close(context.Background())
+ d.Close()
+ return nil, e
+ }
+ mux.Handle("/api/v1/operations", agentHandler)
+ mux.Handle("/api/v1/operations/", agentHandler)
+ }
built = true
return &App{cfg: cfg, db: d, mux: mux, logger: logger, core: rt, store: store, handlers: h, mailRecorder: mailRecorder, signinMail: signinMail}, nil
diff --git a/internal/docs/identity.go b/internal/docs/identity.go
index 95a5a9c..34b8135 100644
--- a/internal/docs/identity.go
+++ b/internal/docs/identity.go
@@ -42,50 +42,61 @@ type identityResolver struct {
linkedPerson func(context.Context, string, string) (int64, error)
}
-func (v identityResolver) resolve(r *http.Request) (requestIdentity, error) {
- session, ok := sessions.Current(r)
- if !ok || session.Subject == "" || v.store == nil {
- return requestIdentity{}, errIdentityRefused
- }
- if v.store.team != nil && v.team == nil {
+// resolveHome resolves an already verified Home subject without manufacturing a
+// browser session or provisioning a person. Both transports use the same links.
+func (v identityResolver) resolveHome(ctx context.Context, subject string) (requestIdentity, error) {
+ if subject == "" || v.store == nil || v.store.team != nil && v.team == nil {
return requestIdentity{}, errIdentityRefused
}
- if session.Method == homeAssertionMethod {
- if v.team != nil {
- p, err := v.team.principals.Resolve(r.Context(), v.team.bindings.Issuer, session.Subject)
- if errors.Is(err, principalstore.ErrRefused) {
- return requestIdentity{}, errIdentityRefused
- }
- if err != nil {
- return requestIdentity{}, errIdentityStorage
- }
- return requestIdentity{Actor: Actor{PersonID: p.ID, VerifiedAddress: p.VerifiedAddress}, Session: session, HomeSubject: session.Subject}, nil
- }
- if v.issuer == "" || v.linkedPerson == nil {
- return requestIdentity{}, errIdentityRefused
- }
- person, err := v.linkedPerson(r.Context(), v.issuer, session.Subject)
- if errors.Is(err, errIdentityRefused) {
+ if v.team != nil {
+ p, err := v.team.principals.Resolve(ctx, v.team.bindings.Issuer, subject)
+ if errors.Is(err, principalstore.ErrRefused) {
return requestIdentity{}, errIdentityRefused
}
if err != nil {
return requestIdentity{}, errIdentityStorage
}
- if person <= 0 {
- return requestIdentity{}, errIdentityRefused
- }
- var p Person
- if err = v.store.db.WithContext(r.Context()).First(&p, person).Error; err != nil {
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return requestIdentity{}, errIdentityRefused
- }
- return requestIdentity{}, errIdentityStorage
- }
- address := subjectOf(p.Email)
- if address == "" {
+ return requestIdentity{Actor: Actor{PersonID: p.ID, VerifiedAddress: p.VerifiedAddress}, HomeSubject: subject}, nil
+ }
+ if v.issuer == "" || v.linkedPerson == nil {
+ return requestIdentity{}, errIdentityRefused
+ }
+ person, err := v.linkedPerson(ctx, v.issuer, subject)
+ if errors.Is(err, errIdentityRefused) {
+ return requestIdentity{}, errIdentityRefused
+ }
+ if err != nil {
+ return requestIdentity{}, errIdentityStorage
+ }
+ if person <= 0 {
+ return requestIdentity{}, errIdentityRefused
+ }
+ var p Person
+ if err = v.store.db.WithContext(ctx).First(&p, person).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
return requestIdentity{}, errIdentityRefused
}
- return requestIdentity{Actor: localActor(p.ID, address), Session: session}, nil
+ return requestIdentity{}, errIdentityStorage
+ }
+ address := subjectOf(p.Email)
+ if address == "" {
+ return requestIdentity{}, errIdentityRefused
+ }
+ return requestIdentity{Actor: localActor(p.ID, address)}, nil
+}
+
+func (v identityResolver) resolve(r *http.Request) (requestIdentity, error) {
+ session, ok := sessions.Current(r)
+ if !ok || session.Subject == "" || v.store == nil {
+ return requestIdentity{}, errIdentityRefused
+ }
+ if v.store.team != nil && v.team == nil {
+ return requestIdentity{}, errIdentityRefused
+ }
+ if session.Method == homeAssertionMethod {
+ id, err := v.resolveHome(r.Context(), session.Subject)
+ id.Session = session
+ return id, err
}
if v.team != nil && session.Method != "magiclink" && session.Method != "keymail" {
return requestIdentity{}, errIdentityRefused
diff --git a/internal/docs/migrations/0009_agent_access.sql b/internal/docs/migrations/0009_agent_access.sql
new file mode 100644
index 0000000..96b54b3
--- /dev/null
+++ b/internal/docs/migrations/0009_agent_access.sql
@@ -0,0 +1,15 @@
+CREATE TABLE docs_agent_state (
+ id INTEGER PRIMARY KEY CHECK(id=1),
+ keycheck TEXT NOT NULL
+);
+CREATE TABLE docs_agent_receipts (
+ coordinate TEXT PRIMARY KEY NOT NULL,
+ content TEXT NOT NULL,
+ document_id INTEGER NOT NULL
+);
+
+CREATE TABLE docs_agent_attribution (
+ document_id INTEGER PRIMARY KEY NOT NULL,
+ operator_id INTEGER NOT NULL,
+ client_sealed BLOB NOT NULL
+);
diff --git a/internal/docs/team_access.go b/internal/docs/team_access.go
index a3abbfa..524462c 100644
--- a/internal/docs/team_access.go
+++ b/internal/docs/team_access.go
@@ -12,13 +12,15 @@ import (
type accessContextKey struct{}
type requestAccess struct {
- uncertain bool
- responseStore *Store
- responseDocs map[int64]permission
- runtime *teamRuntime
- actor Actor
- subject string
- decision roster.Decision
+ extraCheck func(context.Context) error
+ delegationCheck func(context.Context) error
+ uncertain bool
+ responseStore *Store
+ responseDocs map[int64]permission
+ runtime *teamRuntime
+ actor Actor
+ subject string
+ decision roster.Decision
}
type permission uint8
diff --git a/internal/docs/team_emission.go b/internal/docs/team_emission.go
index 2605287..444a7b9 100644
--- a/internal/docs/team_emission.go
+++ b/internal/docs/team_emission.go
@@ -31,6 +31,11 @@ func (s *Store) rememberResponse(ctx context.Context, p permission, docs ...*Doc
}
}
func (a *requestAccess) checkResponse(ctx context.Context) error {
+ if a.extraCheck != nil {
+ if err := a.extraCheck(ctx); err != nil {
+ return err
+ }
+ }
if a.responseStore == nil {
return errTeamUnavailable
}