Expose delegated sheet creation and coherent range reads
26 files changed,
+1,964
−23
Makefile+1 −1cmd/sheets-contract/main.go+22 −0cmd/sheets/main.go+18 −12docs/agent-access.md+45 −0go.mod+16 −2go.sum+34 −0internal/sheets/agent_access.go+225 −0internal/sheets/agent_authority.go+203 −0internal/sheets/agent_authority_test.go+131 −0internal/sheets/agent_create.go+147 −0internal/sheets/agent_create_test.go+140 −0internal/sheets/agent_fixture_test.go+115 −0internal/sheets/agent_integration_test.go+152 −0internal/sheets/agent_limits_test.go+128 −0internal/sheets/agent_operations.go+139 −0internal/sheets/agent_read.go+172 −0internal/sheets/agent_response_test.go+95 −0internal/sheets/agent_storage_test.go+118 −0internal/sheets/app.go+2 −1internal/sheets/auth.go+8 −1internal/sheets/auth_test.go+1 −0internal/sheets/migrations.go+1 −0internal/sheets/migrations/0011_agent_access.sql+14 −0internal/sheets/sheetsvc.go+8 −2internal/sheets/store/handle_write_batch.go+13 −4internal/sheets/store/metadata_read.go+16 −0
CI passed — run details
diff --git a/Makefile b/Makefile| index 3a1b696..60f5dcc 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -1,5 +1,5 @@ |
| comma := , |
| -export GOPRIVATE := $(if $(GOPRIVATE),$(GOPRIVATE)$(comma))amadan.net/oficina/estilo.git |
| +export GOPRIVATE := $(if $(GOPRIVATE),$(GOPRIVATE)$(comma))amadan.net/oficina/estilo.git,amadan.net/oficina/agent-access.git |
| .PHONY: build release test test-vet test-fmt test-build test-migrations test-go test-race test-browser |
diff --git a/cmd/sheets-contract/main.go b/cmd/sheets-contract/main.go| new file mode 100644 |
| index 0000000..52a75f4 |
| --- /dev/null |
| +++ b/cmd/sheets-contract/main.go |
| @@ -0,0 +1,22 @@ |
| +// Command sheets-contract exports the live delegated operation schemas. |
| +package main |
| + |
| +import ( |
| + "amadan.net/oficina/sheets/internal/sheets" |
| + "encoding/json" |
| + "fmt" |
| + "os" |
| +) |
| + |
| +func main() { |
| + operations, err := sheets.AgentContracts() |
| + if err != nil { |
| + fmt.Fprintln(os.Stderr, "Could not export Sheets operation contracts.") |
| + os.Exit(1) |
| + } |
| + encoder := json.NewEncoder(os.Stdout) |
| + encoder.SetIndent("", " ") |
| + if encoder.Encode(operations) != nil { |
| + os.Exit(1) |
| + } |
| +} |
diff --git a/cmd/sheets/main.go b/cmd/sheets/main.go| index 7f5488d..64fac56 100644 |
| --- a/cmd/sheets/main.go |
| +++ b/cmd/sheets/main.go |
| @@ -43,6 +43,19 @@ func main() { |
| os.Exit(1) |
| } |
| + // Sign-in configuration is validated before anything serves. Every |
| + // failure here is one where continuing would produce an instance |
| + // that looks like it works: no mailer means magic links get written |
| + // to platform-held logs instead of emailed, and an empty allowlist |
| + // means anyone who can receive mail can hold a session. Both answer |
| + // /healthz perfectly well, which is why this is a hard exit and not |
| + // a warning. |
| + authEnv, err := sheets.LoadAuthEnv(logger) |
| + if err != nil { |
| + logger.Error("sign-in", "err", err) |
| + os.Exit(1) |
| + } |
| + |
| d, err := rdb.Open(opts.DBPath, logger) |
| if err != nil { |
| logger.Error("open db", "err", err) |
| @@ -61,18 +74,6 @@ func main() { |
| os.Exit(1) |
| } |
| - // Sign-in configuration is validated before anything serves. Every |
| - // failure here is one where continuing would produce an instance |
| - // that looks like it works: no mailer means magic links get written |
| - // to platform-held logs instead of emailed, and an empty allowlist |
| - // means anyone who can receive mail can hold a session. Both answer |
| - // /healthz perfectly well, which is why this is a hard exit and not |
| - // a warning. |
| - authEnv, err := sheets.LoadAuthEnv(logger) |
| - if err != nil { |
| - logger.Error("sign-in", "err", err) |
| - os.Exit(1) |
| - } |
| // Same shape as the sign-in refusals above, and for the same |
| // reason: an instance with no DEK answers /healthz perfectly well |
| // and then fails on the first cell anybody types. The key arrives |
| @@ -106,6 +107,11 @@ func main() { |
| os.Exit(1) |
| } |
| + if err := app.ConfigureAgentAccess(authEnv.AgentIssuer, authEnv.AgentTeam, authEnv.Home); err != nil { |
| + logger.Error("agent configuration unavailable") |
| + os.Exit(1) |
| + } |
| + |
| if err := app.ConfigureNative(); err != nil { |
| logger.Error("native configuration unavailable") |
| os.Exit(1) |
diff --git a/docs/agent-access.md b/docs/agent-access.md| new file mode 100644 |
| index 0000000..543ae94 |
| --- /dev/null |
| +++ b/docs/agent-access.md |
| @@ -0,0 +1,45 @@ |
| +# Delegated Sheets access |
| + |
| +The Oficina connection exposes `sheets_list`, `sheets_list_tabs`, |
| +`sheets_get_range` and `sheets_create`. CLI, Paseo, ChatGPT and Claude use the |
| +same contracts. Existing Home links and current app permissions are required. |
| + |
| +Set `SHEETS_AGENT_ISSUER` to the HTTPS connection-service origin and |
| +`SHEETS_AGENT_TEAM` to this instance's team, alongside existing Home settings. |
| +Both settings are required together. Credentials must target this app's exact |
| +origin plus `/api/v1` and name the configured Home identity issuer. |
| + |
| +Export contracts with `go run ./cmd/sheets-contract`. The bearer endpoints are |
| +`GET /api/v1/operations` and `POST /api/v1/operations/{name}`. The connection |
| +service obtains app credentials; browser cookies do not authenticate them. |
| +Read operations require `sheets:read`; create requires `sheets:write` and current |
| +team membership. Explicitly granted guests can read their permitted sheets. |
| + |
| +IDs, revisions and pagination cursors are decimal JSON strings. IDs must be |
| +positive, canonical and at most 9223372036854775807. Omit the cursor on the first |
| +page. Sheet listing descends by ID; tab listing ascends. Both default to 20 |
| +items and permit at most 100. |
| + |
| +Create accepts a nonzero canonical UUID `client_id`, a title and `tab_name` |
| +(up to 200 Unicode characters each), and `cells` containing up to 500 distinct |
| +`row`, `column`, `raw` entries. Coordinates are zero-based: rows 0–4999 and |
| +columns 0–599. Raw cell input is at most 8 KiB and uses the browser's formula |
| +parser and calculator. The entire sheet, first tab, owner grant, initial cells, |
| +sealed attribution and receipt commit together. Create returns sheet/tab IDs, |
| +a browser URL and current revision; reuse the UUID only for an identical retry. |
| +A retry preserves intervening browser edits and never recreates a deleted sheet. |
| + |
| +Range reads return raw input, calculated value/type, default display text and a |
| +coherent revision for at most 500 cells. Incomplete calculation is an explicit |
| +failure. Inputs and encoded responses are capped at 1 MiB; oversized results |
| +fail without truncation. Formula error values are returned as cell errors. |
| +The revision is the store's next-stamp watermark, shared with range reads. |
| + |
| +The receipt marker binds the Home key, Home issuer, connection issuer and team. |
| +Changes require an explicit operator migration. Never delete the marker or |
| +receipts to make old requests appear new. Creation does not send invitations. |
| +Editing existing cells, formatting, additional tabs, comments, sharing and |
| +import/export remain separate capability slices. |
| + |
| +See [the reviewed specification](superpowers/specs/2026-10-25-agent-access.md). |
| +This branch does not claim deployment or live client certification. |
diff --git a/go.mod b/go.mod| index 26dc9bd..50492d2 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -3,6 +3,7 @@ module amadan.net/oficina/sheets |
| go 1.25.0 |
| 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/connect v0.0.0-20261001093757-2bec942ddd0c |
| amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 |
| @@ -11,8 +12,10 @@ require ( |
| github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327 |
| github.com/chromedp/chromedp v0.14.2 |
| github.com/go-chi/chi/v5 v5.3.2 |
| + github.com/modelcontextprotocol/go-sdk v1.7.0 |
| github.com/xuri/excelize/v2 v2.11.0 |
| golang.org/x/crypto v0.55.0 |
| + golang.org/x/oauth2 v0.35.0 |
| gorm.io/gorm v1.31.2 |
| ) |
| @@ -20,17 +23,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/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/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.38.0 // indirect |
| + golang.org/x/sync v0.22.0 // indirect |
| + golang.org/x/time v0.15.0 // indirect |
| ) |
| require ( |
| amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3 |
| github.com/dustin/go-humanize v1.0.1 // indirect |
| - github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 // indirect |
| - github.com/google/uuid v1.6.0 // indirect |
| + github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 |
| + github.com/google/uuid v1.6.0 |
| github.com/jinzhu/inflection v1.0.0 // indirect |
| github.com/jinzhu/now v1.1.5 // indirect |
| github.com/keymaildev/signin v0.1.1 // indirect |
diff --git a/go.sum b/go.sum| index ddcf78e..99d37f7 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/connect v0.0.0-20261001093757-2bec942ddd0c h1:3yxO2D8BxDLMGfFV2o6Sp9Z91yLnjDCIuRKHVWORa8A= |
| @@ -20,8 +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= |
| @@ -36,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= |
| @@ -54,6 +70,8 @@ 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= |
| @@ -66,8 +84,16 @@ github.com/richardlehane/mscfb v1.0.7 h1:oeoiM0WE79vHwE8RpIYYvIAc8ajTH2mb6UZm55/ |
| github.com/richardlehane/mscfb v1.0.7/go.mod h1:pe0+IUIc0AHh0+teNzBlJCtSyZdFOGgV4ZK9bsoV+Jo= |
| github.com/richardlehane/msoleps v1.0.6 h1:9BvkpjvD+iUBalUY4esMwv6uBkfOip/Lzvd93jvR9gg= |
| github.com/richardlehane/msoleps v1.0.6/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg= |
| +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/tiendc/go-deepcopy v1.7.2 h1:Ut2yYR7W9tWjTQitganoIue4UGxZwCcJy3orjrrIj44= |
| @@ -78,6 +104,10 @@ github.com/xuri/excelize/v2 v2.11.0 h1:HxaEFl6sRN2+8J5a8HaKq+0M4FsjBGMnWWtjOCPSG |
| github.com/xuri/excelize/v2 v2.11.0/go.mod h1:jxFLbzaIwGQ5ufFNvYfUOHqXhfPaNmP14KWfmNz2Uak= |
| github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 h1:+C0TIdyyYmzadGaL/HBLbf3WdLgC29pgyhTjAT/0nuE= |
| github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ= |
| +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/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M= |
| golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis= |
| golang.org/x/image v0.38.0 h1:5l+q+Y9JDC7mBOMjo4/aPhMDcxEptsX+Tt3GgRQRPuE= |
| @@ -86,6 +116,8 @@ golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk= |
| golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40= |
| golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= |
| golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= |
| +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.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= |
| golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= |
| golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= |
| @@ -93,6 +125,8 @@ golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= |
| golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= |
| golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= |
| golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= |
| +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.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE= |
| golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk= |
| gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= |
diff --git a/internal/sheets/agent_access.go b/internal/sheets/agent_access.go| new file mode 100644 |
| index 0000000..48cdedf |
| --- /dev/null |
| +++ b/internal/sheets/agent_access.go |
| @@ -0,0 +1,225 @@ |
| +package sheets |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "mime" |
| + "net/http" |
| + "strconv" |
| + "strings" |
| + "time" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/oficina/home/connect" |
| + "gorm.io/gorm" |
| +) |
| + |
| +var errAgentConfig = errors.New("sheets: invalid agent access configuration") |
| + |
| +func validateAgentConfig(issuer, team, origin string, home *connect.Credentials) error { |
| + if issuer == "" && team == "" { |
| + return nil |
| + } |
| + if issuer == "" || team == "" || strings.TrimSpace(team) != team || len(team) > 128 || home == nil { |
| + return errAgentConfig |
| + } |
| + settings, e := connect.DecodeCredentials(home, origin) |
| + if e != nil || settings == nil { |
| + return errAgentConfig |
| + } |
| + if _, e = access.NewRemoteVerifier(issuer, origin+"/api/v1", settings.Issuer); e != nil { |
| + return errAgentConfig |
| + } |
| + return nil |
| +} |
| + |
| +// ConfigureAgentAccess is called after Home and before Router. The same config |
| +// is validated before opening storage by LoadAuthEnv in the executable. |
| +func (a *App) ConfigureAgentAccess(issuer, team string, home *connect.Credentials) error { |
| + if e := validateAgentConfig(issuer, team, a.origin, home); e != nil { |
| + return e |
| + } |
| + if issuer == "" { |
| + return nil |
| + } |
| + if a.home == nil || a.db == nil || a.sealer == nil { |
| + return errAgentConfig |
| + } |
| + settings, e := connect.DecodeCredentials(home, a.origin) |
| + if e != nil || settings == nil { |
| + return errAgentConfig |
| + } |
| + verifier, e := access.NewRemoteVerifier(issuer, a.origin+"/api/v1", settings.Issuer) |
| + if e != nil { |
| + return errAgentConfig |
| + } |
| + agent := &sheetAgent{app: a, issuer: issuer, identityIssuer: settings.Issuer, team: team, key: append([]byte(nil), settings.DEK...)} |
| + if e = a.db.Transaction(func(tx *gorm.DB) error { return agent.bind(tx) }); e != nil { |
| + return e |
| + } |
| + a.agent, e = agent.httpHandler(verifier) |
| + return e |
| +} |
| +func sheetAgentWriteFailure(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}) |
| +} |
| +func (a *sheetAgent) httpHandler(verifier access.Verifier) (http.Handler, error) { |
| + registry, e := a.registry() |
| + if e != nil { |
| + return nil, e |
| + } |
| + 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") { |
| + sheetAgentWriteFailure(w, access.Fail("unauthenticated", "Connect to Oficina first.")) |
| + return |
| + } |
| + p, e := verifier.Verify(r.Context(), parts[1]) |
| + if e != nil { |
| + sheetAgentWriteFailure(w, e) |
| + return |
| + } |
| + name := strings.TrimPrefix(r.URL.Path, "/api/v1/operations/") |
| + write := name == "sheets_create" |
| + discovery := r.Method == "GET" && r.URL.Path == "/api/v1/operations" |
| + if discovery && !p.Allows(a.team, "sheets:read") { |
| + write = true |
| + } |
| + member, e := a.member(r.Context(), p, write) |
| + if e != nil { |
| + sheetAgentWriteFailure(w, e) |
| + return |
| + } |
| + state := &sheetAgentContext{member: member, sheets: map[uint64]bool{}} |
| + state.verify = func(ctx context.Context) error { |
| + current, e := verifier.Verify(ctx, parts[1]) |
| + if e != nil { |
| + return e |
| + } |
| + scope := "sheets:read" |
| + if write { |
| + scope = "sheets:write" |
| + } |
| + if current.Subject != p.Subject || current.Client != p.Client || current.Grant != p.Grant || !current.Allows(a.team, scope) { |
| + return access.Fail("forbidden", "This connection is no longer authorized.") |
| + } |
| + return nil |
| + } |
| + ctx := context.WithValue(r.Context(), sheetAgentKey{}, state) |
| + 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, "/") { |
| + sheetAgentWriteFailure(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" { |
| + sheetAgentWriteFailure(w, access.Fail("unsupported_media_type", "Send application/json.")) |
| + return |
| + } |
| + raw, e := io.ReadAll(io.LimitReader(r.Body, sheetAgentLimit+1)) |
| + if e != nil { |
| + sheetAgentWriteFailure(w, access.Fail("invalid", "Could not read the request.")) |
| + return |
| + } |
| + if len(raw) > sheetAgentLimit { |
| + sheetAgentWriteFailure(w, access.Fail("too_large", "The operation input exceeds 1 MiB.")) |
| + return |
| + } |
| + result, e = registry.Call(ctx, p, name, raw) |
| + if e != nil { |
| + sheetAgentWriteFailure(w, e) |
| + return |
| + } |
| + } |
| + body, e := json.Marshal(result) |
| + if e != nil { |
| + sheetAgentWriteFailure(w, sheetAgentFailure(e)) |
| + return |
| + } |
| + if len(body) > sheetAgentLimit { |
| + sheetAgentWriteFailure(w, access.Fail("too_large", "The sheet result exceeds 1 MiB.")) |
| + return |
| + } |
| + controller := http.NewResponseController(w) |
| + check := func() error { |
| + deadline := time.Now().Add(5 * time.Second) |
| + if d, ok := ctx.Deadline(); ok && d.Before(deadline) { |
| + deadline = d |
| + } |
| + checkCtx, cancel := context.WithDeadline(ctx, deadline) |
| + defer cancel() |
| + if e := state.verify(checkCtx); e != nil { |
| + return e |
| + } |
| + fresh, e := a.member(checkCtx, p, write) |
| + if e != nil { |
| + return e |
| + } |
| + if fresh.ID != member.ID || fresh.Address != member.Address { |
| + return access.Fail("forbidden", "The current identity changed.") |
| + } |
| + for id := range state.sheets { |
| + role, e := a.role(checkCtx, a.app.db, id, fresh) |
| + if e != nil { |
| + return sheetAgentFailure(e) |
| + } |
| + if !role.Allows(SheetViewer) { |
| + return sheetAgentFailure(errNoAccess) |
| + } |
| + } |
| + if e := checkCtx.Err(); e != nil { |
| + return sheetAgentFailure(e) |
| + } |
| + if e := controller.SetWriteDeadline(deadline); e != nil { |
| + return sheetAgentFailure(e) |
| + } |
| + return nil |
| + } |
| + if e = check(); e != nil { |
| + sheetAgentWriteFailure(w, e) |
| + return |
| + } |
| + defer controller.SetWriteDeadline(time.Time{}) |
| + w.Header().Set("Content-Type", "application/json") |
| + w.Header().Set("Content-Length", strconv.Itoa(len(body))) |
| + w.WriteHeader(http.StatusOK) |
| + for len(body) > 0 { |
| + if e = check(); e != nil { |
| + panic(http.ErrAbortHandler) |
| + } |
| + n := min(len(body), 64<<10) |
| + wrote, e := w.Write(body[:n]) |
| + if e != nil || wrote != n { |
| + panic(http.ErrAbortHandler) |
| + } |
| + body = body[n:] |
| + } |
| + }), nil |
| +} |
| + |
| +func (a *App) agentRoutes(browser http.Handler) http.Handler { |
| + if a.agent == nil { |
| + return browser |
| + } |
| + mux := http.NewServeMux() |
| + mux.Handle("/api/v1/operations", a.agent) |
| + mux.Handle("/api/v1/operations/", a.agent) |
| + mux.Handle("/", browser) |
| + return mux |
| +} |
diff --git a/internal/sheets/agent_authority.go b/internal/sheets/agent_authority.go| new file mode 100644 |
| index 0000000..a4933ae |
| --- /dev/null |
| +++ b/internal/sheets/agent_authority.go |
| @@ -0,0 +1,203 @@ |
| +package sheets |
| + |
| +import ( |
| + "context" |
| + "crypto/hmac" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "strconv" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/oficina/home/connect/linkstore" |
| + "amadan.net/oficina/sheets/internal/sheets/store" |
| + "gorm.io/gorm" |
| +) |
| + |
| +const sheetAgentLimit = 1 << 20 |
| + |
| +type sheetAgent struct { |
| + app *App |
| + issuer, identityIssuer, team string |
| + key []byte |
| +} |
| +type sheetAgentState struct { |
| + ID int `gorm:"primaryKey"` |
| + Keycheck string `gorm:"not null"` |
| +} |
| + |
| +func (sheetAgentState) TableName() string { return "sheets_agent_state" } |
| + |
| +type sheetAgentReceipt struct { |
| + Coordinate string `gorm:"primaryKey"` |
| + Content string `gorm:"not null"` |
| + SheetID uint64 `gorm:"not null"` |
| +} |
| + |
| +func (sheetAgentReceipt) TableName() string { return "sheets_agent_receipts" } |
| + |
| +type sheetAgentAttribution struct { |
| + SheetID uint64 `gorm:"primaryKey"` |
| + MemberID uint64 `gorm:"not null"` |
| + ClientSealed []byte `gorm:"not null"` |
| +} |
| + |
| +func (sheetAgentAttribution) TableName() string { return "sheets_agent_attribution" } |
| + |
| +type sheetAgentContext struct { |
| + member Member |
| + verify func(context.Context) error |
| + sheets map[uint64]bool |
| +} |
| +type sheetAgentKey struct{} |
| + |
| +func sheetAgentFailure(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, errNoAccess) { |
| + return access.Fail("not_found", "This sheet or tab is unavailable.") |
| + } |
| + if errors.Is(err, linkstore.ErrRefused) { |
| + return access.Fail("forbidden", "This Home identity is not admitted.") |
| + } |
| + return access.Fail("unavailable", "Sheet authority, calculation or storage is unavailable.") |
| +} |
| +func sheetAgentID(raw string) (uint64, error) { |
| + id, err := strconv.ParseUint(raw, 10, 63) |
| + if err != nil || id == 0 || strconv.FormatUint(id, 10) != raw { |
| + return 0, access.Fail("invalid", "Use a canonical positive decimal identifier.") |
| + } |
| + return id, nil |
| +} |
| +func (a *sheetAgent) digest(domain string, value any) string { |
| + raw, _ := json.Marshal(value) |
| + mac := hmac.New(sha256.New, a.key) |
| + mac.Write([]byte("oficina/sheets/agent/v1/" + domain + "\x00")) |
| + mac.Write(raw) |
| + return hex.EncodeToString(mac.Sum(nil)) |
| +} |
| +func (a *sheetAgent) bind(tx *gorm.DB) error { |
| + want := a.digest("keycheck", []string{"immutable-authority", a.identityIssuer, a.issuer, a.team}) |
| + if e := tx.Exec("INSERT INTO sheets_agent_state(id,keycheck) SELECT 1,? WHERE NOT EXISTS(SELECT 1 FROM sheets_agent_receipts) ON CONFLICT(id) DO NOTHING", want).Error; e != nil { |
| + return e |
| + } |
| + var got string |
| + if e := tx.Raw("SELECT keycheck FROM sheets_agent_state WHERE id=1").Scan(&got).Error; e != nil { |
| + return e |
| + } |
| + if !hmac.Equal([]byte(got), []byte(want)) { |
| + return access.Fail("unavailable", "Agent receipt authority requires an explicit migration.") |
| + } |
| + return nil |
| +} |
| +func (a *sheetAgent) member(ctx context.Context, p access.Principal, write bool) (Member, error) { |
| + scope := "sheets:read" |
| + if write { |
| + scope = "sheets:write" |
| + } |
| + if p.Client == "" || !p.Allows(a.team, scope) { |
| + return Member{}, access.Fail("forbidden", "This connection does not allow that team and operation.") |
| + } |
| + if a.app.home == nil { |
| + return Member{}, access.Fail("unavailable", "Home identity resolution is unavailable.") |
| + } |
| + person, err := a.app.home.Resolve(ctx, p.Subject) |
| + if err != nil { |
| + return Member{}, sheetAgentFailure(err) |
| + } |
| + var member Member |
| + if err = a.app.db.WithContext(ctx).First(&member, person.ID).Error; err != nil { |
| + return Member{}, sheetAgentFailure(err) |
| + } |
| + if member.ID == 0 || member.Address != person.Label { |
| + return Member{}, sheetAgentFailure(linkstore.ErrRefused) |
| + } |
| + if write && !a.creator(member) { |
| + return Member{}, access.Fail("forbidden", "Creating a sheet requires current team membership.") |
| + } |
| + return member, nil |
| +} |
| +func (a *sheetAgent) creator(member Member) bool { |
| + return a.app.admit != nil && a.app.admit(member.Address) && (TeamRole(member.TeamRole) == TeamOwner || TeamRole(member.TeamRole) == TeamMember) |
| +} |
| + |
| +// role preserves explicit-grant precedence, including unknown-role refusal, |
| +// while distinguishing missing permission from an unavailable authority store. |
| +func (a *sheetAgent) role(ctx context.Context, db *gorm.DB, id uint64, member Member) (SheetRole, error) { |
| + var sheet store.Sheet |
| + if e := db.WithContext(ctx).Where("id=? AND deleted_at IS NULL AND filling_since IS NULL", id).First(&sheet).Error; e != nil { |
| + return "", e |
| + } |
| + var grant Grant |
| + err := db.WithContext(ctx).Where("sheet_id=? AND member_id=?", id, member.ID).First(&grant).Error |
| + if err == nil { |
| + role := SheetRole(grant.Role) |
| + if !role.Valid() { |
| + return "", errNoAccess |
| + } |
| + return role, nil |
| + } |
| + if !errors.Is(err, gorm.ErrRecordNotFound) { |
| + return "", err |
| + } |
| + if TeamRole(member.TeamRole) == TeamOwner || TeamRole(member.TeamRole) == TeamMember { |
| + return SheetEditor, nil |
| + } |
| + return "", errNoAccess |
| +} |
| +func (a *sheetAgent) tab(ctx context.Context, db *gorm.DB, sheetID, tabID uint64, member Member) error { |
| + role, err := a.role(ctx, db, sheetID, member) |
| + if err != nil { |
| + return err |
| + } |
| + if !role.Allows(SheetViewer) { |
| + return errNoAccess |
| + } |
| + var tab store.Tab |
| + return db.WithContext(ctx).Where("id=? AND sheet_id=?", tabID, sheetID).First(&tab).Error |
| +} |
| +func (a *sheetAgent) remember(ctx context.Context, id uint64) { |
| + if state, ok := ctx.Value(sheetAgentKey{}).(*sheetAgentContext); ok && state != nil { |
| + state.sheets[id] = true |
| + } |
| +} |
| +func (a *sheetAgent) creatorInTx(ctx context.Context, tx *gorm.DB, p access.Principal, expected Member) error { |
| + state, ok := ctx.Value(sheetAgentKey{}).(*sheetAgentContext) |
| + if !ok || state == nil || state.verify == nil { |
| + return linkstore.ErrRefused |
| + } |
| + if e := state.verify(ctx); e != nil { |
| + return e |
| + } |
| + var id uint64 |
| + if e := tx.Raw("SELECT person_id FROM home_identity_links WHERE issuer=? AND subject=?", a.identityIssuer, p.Subject).Scan(&id).Error; e != nil { |
| + return e |
| + } |
| + if id == 0 || id != expected.ID { |
| + return linkstore.ErrRefused |
| + } |
| + var member Member |
| + if e := tx.First(&member, id).Error; e != nil { |
| + return e |
| + } |
| + if member.Address != expected.Address || !a.creator(member) { |
| + return linkstore.ErrRefused |
| + } |
| + return nil |
| +} |
| +func sheetAgentBounded(value any) (any, error) { |
| + body, err := json.Marshal(value) |
| + if err != nil { |
| + return nil, sheetAgentFailure(err) |
| + } |
| + if len(body) > sheetAgentLimit { |
| + return nil, access.Fail("too_large", "The sheet result exceeds 1 MiB.") |
| + } |
| + return value, nil |
| +} |
diff --git a/internal/sheets/agent_authority_test.go b/internal/sheets/agent_authority_test.go| new file mode 100644 |
| index 0000000..b87131b |
| --- /dev/null |
| +++ b/internal/sheets/agent_authority_test.go |
| @@ -0,0 +1,131 @@ |
| +package sheets |
| + |
| +import ( |
| + "encoding/json" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/store" |
| +) |
| + |
| +func assertAgentSheetEmpty(t *testing.T, f *sheetAgentFixture) { |
| + t.Helper() |
| + for _, model := range []any{&store.Sheet{}, &store.Tab{}, &Grant{}, &store.Cell{}, &store.Row{}, &store.Col{}, &sheetAgentReceipt{}, &sheetAgentAttribution{}} { |
| + var n int64 |
| + if e := f.a.app.db.Model(model).Count(&n).Error; e != nil || n != 0 { |
| + t.Fatalf("partial creation %T: %d %v", model, n, e) |
| + } |
| + } |
| +} |
| +func TestAgentSheetPrecommitAuthorityRollback(t *testing.T) { |
| + for _, change := range []string{"revoke", "unlink", "downgrade"} { |
| + t.Run(change, func(t *testing.T) { |
| + f := newSheetAgentFixture(t) |
| + if change == "revoke" { |
| + f.revokeAt.Store(3) |
| + } else { |
| + sql := "DELETE FROM home_identity_links" |
| + if change == "downgrade" { |
| + sql = "UPDATE members SET team_role='guest'" |
| + } |
| + if e := f.a.app.db.Exec("CREATE TRIGGER agent_revoke AFTER INSERT ON sheets_agent_receipts BEGIN " + sql + "; END").Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + rec := f.call(t, "sheets_create", initialSheetAgentInput()) |
| + if rec.Code != 401 && rec.Code != 403 { |
| + t.Fatal(rec.Code, rec.Body.String()) |
| + } |
| + assertAgentSheetEmpty(t, f) |
| + }) |
| + } |
| +} |
| +func TestAgentSheetCurrentPermissionsAndForeignTab(t *testing.T) { |
| + f := newSheetAgentFixture(t) |
| + first := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput())) |
| + second := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput())) |
| + mixed := f.rangeInput(first) |
| + mixed["tab_id"] = second.TabID |
| + if rec := f.call(t, "sheets_get_range", mixed); rec.Code != 404 { |
| + t.Fatal("foreign tab", rec.Code) |
| + } |
| + member, e := f.a.member(t.Context(), f.p, false) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = f.a.app.db.Model(&Grant{}).Where("sheet_id=? AND member_id=?", first.SheetID, member.ID).Update("role", "invalid").Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if rec := f.call(t, "sheets_get_range", f.rangeInput(first)); rec.Code != 404 { |
| + t.Fatal("invalid explicit grant fell back to team", rec.Code) |
| + } |
| + rec := f.call(t, "sheets_list", map[string]any{"team": "blue", "limit": 1}) |
| + var page struct { |
| + Sheets []agentSheetSummary `json:"sheets"` |
| + Next string `json:"next_cursor"` |
| + } |
| + if e = json.Unmarshal(rec.Body.Bytes(), &page); e != nil || rec.Code != 200 || len(page.Sheets) != 1 || page.Sheets[0].ID != second.SheetID || page.Next != "" { |
| + t.Fatal("permission before pagination", rec.Code, rec.Body.String()) |
| + } |
| + // An explicitly granted guest can read, but cannot create. |
| + if e = f.a.app.db.Model(&Member{}).Where("id=?", member.ID).Update("team_role", "guest").Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if rec = f.call(t, "sheets_get_range", f.rangeInput(second)); rec.Code != 200 { |
| + t.Fatal("guest grant", rec.Code, rec.Body.String()) |
| + } |
| + if rec = f.call(t, "sheets_create", initialSheetAgentInput()); rec.Code != 403 { |
| + t.Fatal("guest create", rec.Code) |
| + } |
| + if e = f.a.app.db.Where("sheet_id=? AND member_id=?", second.SheetID, member.ID).Delete(&Grant{}).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if rec = f.call(t, "sheets_get_range", f.rangeInput(second)); rec.Code != 404 { |
| + t.Fatal("revoked guest grant", rec.Code) |
| + } |
| +} |
| +func TestAgentSheetInputAuthorityAndSealedMetadataFailures(t *testing.T) { |
| + f := newSheetAgentFixture(t) |
| + input := initialSheetAgentInput() |
| + raw, _ := json.Marshal(input) |
| + for _, bad := range [][]byte{[]byte(strings.Replace(string(raw), "21", `\ud800`, 1)), []byte(strings.Replace(string(raw), "21", string([]byte{255}), 1))} { |
| + if rec := f.raw(t, "sheets_create", bad); rec.Code != 422 { |
| + t.Fatal("malformed Unicode", rec.Code, rec.Body.String()) |
| + } |
| + } |
| + for _, change := range []func(){func() { f.p.Scopes = []string{"sheets:read"} }, func() { f.p.Teams = []string{"green"} }, func() { f.p.Subject = "unlinked" }} { |
| + original := f.p |
| + change() |
| + if rec := f.call(t, "sheets_create", input); rec.Code != 403 { |
| + t.Fatal("invalid authority", rec.Code) |
| + } |
| + f.p = original |
| + } |
| + input.Team = "green" |
| + f.p.Teams = []string{"blue", "green"} |
| + if rec := f.call(t, "sheets_create", input); rec.Code != 403 { |
| + t.Fatal("wrong instance", rec.Code) |
| + } |
| + assertAgentSheetEmpty(t, f) |
| + input.Team = "blue" |
| + made := decodeSheetCreated(t, f.call(t, "sheets_create", input)) |
| + for _, id := range []any{"01", "0", "-1", "9223372036854775808", 9007199254740993} { |
| + in := f.rangeInput(made) |
| + in["sheet_id"] = id |
| + if rec := f.call(t, "sheets_get_range", in); rec.Code != 422 { |
| + t.Fatal("noncanonical id", id, rec.Code) |
| + } |
| + } |
| + if e := f.a.app.db.Model(&store.Sheet{}).Where("id=?", made.SheetID).Update("title_sealed", []byte("damaged")).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if rec := f.call(t, "sheets_list", map[string]any{"team": "blue"}); rec.Code != 503 { |
| + t.Fatal("corrupt title hidden", rec.Code) |
| + } |
| + if e := f.a.app.db.Model(&store.Tab{}).Where("id=?", made.TabID).Update("name_sealed", []byte("damaged")).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if rec := f.call(t, "sheets_list_tabs", map[string]any{"team": "blue", "sheet_id": made.SheetID}); rec.Code != 503 { |
| + t.Fatal("corrupt tab name hidden", rec.Code) |
| + } |
| +} |
diff --git a/internal/sheets/agent_create.go b/internal/sheets/agent_create.go| new file mode 100644 |
| index 0000000..6bce109 |
| --- /dev/null |
| +++ b/internal/sheets/agent_create.go |
| @@ -0,0 +1,147 @@ |
| +package sheets |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "unicode/utf8" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/oficina/sheets/internal/sheets/store" |
| + "github.com/google/uuid" |
| + "gorm.io/gorm" |
| +) |
| + |
| +type sheetAgentCell struct { |
| + Row int `json:"row"` |
| + Column int `json:"column"` |
| + Raw string `json:"raw"` |
| +} |
| +type sheetAgentCreate struct { |
| + Team string `json:"team"` |
| + ClientID string `json:"client_id"` |
| + Title string `json:"title"` |
| + TabName string `json:"tab_name"` |
| + Cells []sheetAgentCell `json:"cells"` |
| +} |
| +type sheetAgentCreated struct { |
| + SheetID string `json:"sheet_id"` |
| + TabID string `json:"tab_id"` |
| + URL string `json:"url"` |
| + Revision string `json:"revision"` |
| +} |
| + |
| +func (a *sheetAgent) create(ctx context.Context, p access.Principal, member Member, input sheetAgentCreate) (any, error) { |
| + id, err := uuid.Parse(input.ClientID) |
| + input.Title = strings.TrimSpace(input.Title) |
| + input.TabName = strings.TrimSpace(input.TabName) |
| + if err != nil || id == uuid.Nil || id.String() != input.ClientID || input.Title == "" || input.TabName == "" || !utf8.ValidString(input.Title) || !utf8.ValidString(input.TabName) || utf8.RuneCountInString(input.Title) > maxTitleRunes || utf8.RuneCountInString(input.TabName) > maxTitleRunes || len(input.Cells) > store.MaxCellBatch { |
| + return nil, access.Fail("invalid", "Invalid initial sheet, tab name or client UUID.") |
| + } |
| + sort.Slice(input.Cells, func(i, j int) bool { |
| + if input.Cells[i].Row != input.Cells[j].Row { |
| + return input.Cells[i].Row < input.Cells[j].Row |
| + } |
| + return input.Cells[i].Column < input.Cells[j].Column |
| + }) |
| + writes := make([]store.CellWrite, len(input.Cells)) |
| + for i, cell := range input.Cells { |
| + if !inCellRange(cell.Row, cell.Column) || len(cell.Raw) > maxRawBytes || !utf8.ValidString(cell.Raw) || i > 0 && cell.Row == input.Cells[i-1].Row && cell.Column == input.Cells[i-1].Column { |
| + return nil, access.Fail("invalid", "Invalid initial cell coordinate or input.") |
| + } |
| + writes[i] = store.CellWrite{Row: cell.Row, Col: cell.Column, Raw: cell.Raw} |
| + } |
| + if len(writes) > 0 { |
| + if err := store.ValidateCellWrites(writes); err != nil { |
| + return nil, access.Fail("invalid", "Invalid initial cell input.") |
| + } |
| + } |
| + coordinate := a.digest("coordinate", []string{a.identityIssuer, a.issuer, p.Subject, p.Client, a.team, input.ClientID}) |
| + payload := a.digest("content", struct { |
| + Title, TabName string |
| + Cells []sheetAgentCell |
| + }{input.Title, input.TabName, input.Cells}) |
| + var sheetID, tabID uint64 |
| + err = a.app.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| + if e := a.bind(tx); e != nil { |
| + return e |
| + } |
| + if e := a.creatorInTx(ctx, tx, p, member); e != nil { |
| + return e |
| + } |
| + var receipt sheetAgentReceipt |
| + 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.") |
| + } |
| + role, e := a.role(ctx, tx, receipt.SheetID, member) |
| + if e != nil { |
| + return e |
| + } |
| + if !role.Allows(SheetViewer) { |
| + return errNoAccess |
| + } |
| + sheetID = receipt.SheetID |
| + var tab store.Tab |
| + if e = tx.Where("sheet_id=?", sheetID).Order("position ASC,id ASC").First(&tab).Error; e != nil { |
| + return e |
| + } |
| + tabID = tab.ID |
| + return a.creatorInTx(ctx, tx, p, member) |
| + } |
| + if !errors.Is(e, gorm.ErrRecordNotFound) { |
| + return e |
| + } |
| + app := *a.app |
| + app.db = tx |
| + summary, e := app.newSheetWithTab(input.Title, input.TabName, member, false) |
| + if e != nil { |
| + return e |
| + } |
| + sheetID, tabID = summary.ID, summary.TabID |
| + if e = store.InitializeTab(tx, a.app.sealer, tabID, writes, member.ID); e != nil { |
| + return e |
| + } |
| + client, e := a.app.sealer.Seal("agent.client/"+strconv.FormatUint(sheetID, 10), []byte(p.Client)) |
| + if e != nil { |
| + return e |
| + } |
| + if e = tx.Create(&sheetAgentAttribution{sheetID, member.ID, client}).Error; e != nil { |
| + return e |
| + } |
| + if e = tx.Create(&sheetAgentReceipt{coordinate, payload, sheetID}).Error; e != nil { |
| + return e |
| + } |
| + var tab store.Tab |
| + if e = tx.First(&tab, tabID).Error; e != nil { |
| + return e |
| + } |
| + // A fresh tab's persisted watermark is the last assigned stamp; a fresh |
| + // canonical handle will expose the next one. Check output size before commit. |
| + if _, e = sheetAgentBounded(a.created(sheetID, tabID, tab.ContentVersion+1)); e != nil { |
| + return e |
| + } |
| + return a.creatorInTx(ctx, tx, p, member) |
| + }) |
| + if err != nil { |
| + return nil, sheetAgentFailure(err) |
| + } |
| + // Only a committed tab can enter the canonical cache. Retries observe edits. |
| + if err = a.tab(ctx, a.app.db, sheetID, tabID, member); err != nil { |
| + return nil, sheetAgentFailure(err) |
| + } |
| + handle, err := store.Open(a.app.db, a.app.sealer, tabID) |
| + if err != nil { |
| + return nil, sheetAgentFailure(err) |
| + } |
| + defer handle.Release() |
| + a.remember(ctx, sheetID) |
| + return sheetAgentBounded(a.created(sheetID, tabID, handle.Version())) |
| +} |
| +func (a *sheetAgent) created(sheetID, tabID, revision uint64) sheetAgentCreated { |
| + id := strconv.FormatUint(sheetID, 10) |
| + return sheetAgentCreated{id, strconv.FormatUint(tabID, 10), a.app.origin + "/sheets/" + id, strconv.FormatUint(revision, 10)} |
| +} |
diff --git a/internal/sheets/agent_create_test.go b/internal/sheets/agent_create_test.go| new file mode 100644 |
| index 0000000..b0b7f5b |
| --- /dev/null |
| +++ b/internal/sheets/agent_create_test.go |
| @@ -0,0 +1,140 @@ |
| +package sheets |
| + |
| +import ( |
| + "bytes" |
| + "encoding/json" |
| + "os" |
| + "strconv" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/sheets/internal/sheets/store" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func TestAgentSheetCreateRangeRetryAndBrowserEdit(t *testing.T) { |
| + f := newSheetAgentFixture(t) |
| + input := initialSheetAgentInput() |
| + created := decodeSheetCreated(t, f.call(t, "sheets_create", input)) |
| + rec := f.call(t, "sheets_get_range", f.rangeInput(created)) |
| + if rec.Code != 200 { |
| + t.Fatal(rec.Code, rec.Body.String()) |
| + } |
| + var snapshot agentRange |
| + if e := json.Unmarshal(rec.Body.Bytes(), &snapshot); e != nil { |
| + t.Fatal(e) |
| + } |
| + if snapshot.Revision != created.Revision || len(snapshot.Cells) != 4 || snapshot.Cells[0].Value != float64(21) || snapshot.Cells[2].Value != float64(42) { |
| + t.Fatal("incoherent formula result", snapshot) |
| + } |
| + var wg sync.WaitGroup |
| + results := make(chan sheetAgentCreated, 4) |
| + for i := 0; i < 4; i++ { |
| + wg.Add(1) |
| + go func() { defer wg.Done(); results <- decodeSheetCreated(t, f.call(t, "sheets_create", input)) }() |
| + } |
| + wg.Wait() |
| + close(results) |
| + for got := range results { |
| + if got != created { |
| + t.Fatal("retry changed receipt", got) |
| + } |
| + } |
| + reversed := input |
| + reversed.Cells = append([]sheetAgentCell(nil), input.Cells...) |
| + reversed.Cells[0], reversed.Cells[2] = reversed.Cells[2], reversed.Cells[0] |
| + if got := decodeSheetCreated(t, f.call(t, "sheets_create", reversed)); got != created { |
| + t.Fatal("cell order changed meaning") |
| + } |
| + changed := input |
| + changed.Title = "Changed title" |
| + if rec = f.call(t, "sheets_create", changed); rec.Code != 409 { |
| + t.Fatal("changed retry", rec.Code) |
| + } |
| + tab, _ := strconv.ParseUint(created.TabID, 10, 64) |
| + h, e := store.Open(f.a.app.db, f.a.app.sealer, tab) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer h.Release() |
| + member, e := f.a.member(t.Context(), f.p, true) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if _, e = h.SetBatch([]store.CellWrite{{Row: 0, Col: 0, Raw: "8"}}, member.ID); e != nil { |
| + t.Fatal(e) |
| + } |
| + retried := decodeSheetCreated(t, f.call(t, "sheets_create", input)) |
| + if retried.SheetID != created.SheetID || retried.Revision == created.Revision || retried.Revision != strconv.FormatUint(h.Version(), 10) { |
| + t.Fatal("retry reset or mislabelled revision", retried) |
| + } |
| + var count int64 |
| + f.a.app.db.Model(&store.Sheet{}).Count(&count) |
| + if count != 1 { |
| + t.Fatal("duplicate sheet", count) |
| + } |
| + // Query actual database paths; plaintext authored data must not reach DB/WAL. |
| + var dbs []struct { |
| + Seq int |
| + Name, File string |
| + } |
| + if e = f.a.app.db.Raw("PRAGMA database_list").Scan(&dbs).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + for _, db := range dbs { |
| + if db.Name != "main" { |
| + continue |
| + } |
| + for _, suffix := range []string{"", "-wal"} { |
| + raw, e := os.ReadFile(db.File + suffix) |
| + if e != nil && !os.IsNotExist(e) { |
| + t.Fatal(e) |
| + } |
| + for _, canary := range []string{input.Title, input.TabName, "PRIVATE_CELL_CANARY_42"} { |
| + if bytes.Contains(raw, []byte(canary)) { |
| + t.Fatal("plaintext persisted", canary, suffix) |
| + } |
| + } |
| + } |
| + } |
| + if e = f.a.app.db.Model(&store.Sheet{}).Where("id=?", created.SheetID).Update("deleted_at", time.Now()).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if rec = f.call(t, "sheets_create", input); rec.Code != 404 { |
| + t.Fatal("deleted replay recreated", rec.Code) |
| + } |
| +} |
| + |
| +func TestAgentSheetAtomicRollbackAndKeyAuthority(t *testing.T) { |
| + f := newSheetAgentFixture(t) |
| + input := initialSheetAgentInput() |
| + for _, table := range []string{"grants", "cells", "sheets_agent_attribution", "sheets_agent_receipts"} { |
| + if e := f.a.app.db.Exec("CREATE TRIGGER agent_failure BEFORE INSERT ON " + table + " BEGIN SELECT RAISE(ABORT,'injected failure'); END").Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if rec := f.call(t, "sheets_create", input); rec.Code != 503 { |
| + t.Error("write failure not surfaced", rec.Code) |
| + } |
| + for _, model := range []any{&store.Sheet{}, &store.Tab{}, &Grant{}, &store.Cell{}, &store.Row{}, &store.Col{}, &sheetAgentReceipt{}, &sheetAgentAttribution{}} { |
| + var count int64 |
| + if e := f.a.app.db.Model(model).Count(&count).Error; e != nil || count != 0 { |
| + t.Fatal("partial sheet persisted", count, e) |
| + } |
| + } |
| + if e := f.a.app.db.Exec("DROP TRIGGER agent_failure").Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + decodeSheetCreated(t, f.call(t, "sheets_create", input)) |
| + for _, change := range []func(*sheetAgent){func(a *sheetAgent) { a.key = bytes.Repeat([]byte{19}, 32) }, func(a *sheetAgent) { a.identityIssuer = "https://other-home.example" }, func(a *sheetAgent) { a.issuer = "https://other-connect.example" }, func(a *sheetAgent) { a.team = "green" }} { |
| + copy := *f.a |
| + change(©) |
| + if e := copy.app.db.Transaction(func(tx *gorm.DB) error { return copy.bind(tx) }); e == nil { |
| + t.Fatal("authority/key change accepted") |
| + } |
| + } |
| + if e := f.a.app.db.Transaction(func(tx *gorm.DB) error { return f.a.bind(tx) }); e != nil { |
| + t.Fatal("same authority refused", e) |
| + } |
| +} |
diff --git a/internal/sheets/agent_fixture_test.go b/internal/sheets/agent_fixture_test.go| new file mode 100644 |
| index 0000000..09d0119 |
| --- /dev/null |
| +++ b/internal/sheets/agent_fixture_test.go |
| @@ -0,0 +1,115 @@ |
| +package sheets |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "net/http/httptest" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "github.com/google/uuid" |
| + "gorm.io/gorm" |
| +) |
| + |
| +type sheetAgentFixture struct { |
| + home *homeFixture |
| + a *sheetAgent |
| + p access.Principal |
| + revoked atomic.Bool |
| + checks atomic.Int64 |
| + revokeAt atomic.Int64 |
| + verified chan struct{} |
| +} |
| +type agentDeadlineRecorder struct { |
| + *httptest.ResponseRecorder |
| + afterWrite func() |
| +} |
| + |
| +func (*agentDeadlineRecorder) SetWriteDeadline(time.Time) error { return nil } |
| +func (w *agentDeadlineRecorder) Write(body []byte) (int, error) { |
| + n, e := w.ResponseRecorder.Write(body) |
| + if w.afterWrite != nil { |
| + f := w.afterWrite |
| + w.afterWrite = nil |
| + f() |
| + } |
| + return n, e |
| +} |
| +func newSheetAgentFixture(t *testing.T, issuers ...string) *sheetAgentFixture { |
| + t.Helper() |
| + home := newHomeFixture(t) |
| + home.local(t, signedInAddress) |
| + home.link(t, "opaque-owner") |
| + issuer := "https://connect.oficina.works" |
| + if len(issuers) > 0 { |
| + issuer = issuers[0] |
| + } |
| + a := &sheetAgent{app: home.app, issuer: issuer, identityIssuer: homeTestIssuer, team: "blue", key: bytes.Repeat([]byte{81}, 32)} |
| + if e := a.app.db.Transaction(func(tx *gorm.DB) error { return a.bind(tx) }); e != nil { |
| + t.Fatal(e) |
| + } |
| + f := &sheetAgentFixture{home: home, a: a, p: access.Principal{Subject: "opaque-owner", Client: "test-client", Grant: "grant-one", Teams: []string{"blue"}, Scopes: []string{"sheets:read", "sheets:write"}}} |
| + f.install(t) |
| + return f |
| +} |
| +func (f *sheetAgentFixture) install(t *testing.T) { |
| + t.Helper() |
| + a := f.a |
| + handler, e := a.httpHandler(access.VerifyFunc(func(ctx context.Context, token string) (access.Principal, error) { |
| + n := f.checks.Add(1) |
| + if n == 1 && f.verified != nil { |
| + close(f.verified) |
| + } |
| + if at := f.revokeAt.Load(); at > 0 && n >= at { |
| + f.revoked.Store(true) |
| + } |
| + if token != "test-token" || f.revoked.Load() { |
| + return access.Principal{}, access.Fail("unauthenticated", "Connection expired.") |
| + } |
| + return f.p, nil |
| + })) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + a.app.agent = handler |
| +} |
| +func (f *sheetAgentFixture) call(t *testing.T, name string, input any) *httptest.ResponseRecorder { |
| + t.Helper() |
| + raw, e := json.Marshal(input) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + return f.raw(t, name, raw) |
| +} |
| +func (f *sheetAgentFixture) raw(t *testing.T, name string, raw []byte) *httptest.ResponseRecorder { |
| + t.Helper() |
| + req := httptest.NewRequest("POST", testOrigin+"/api/v1/operations/"+name, bytes.NewReader(raw)) |
| + req.Header.Set("Authorization", "Bearer test-token") |
| + req.Header.Set("Content-Type", "application/json") |
| + w := &agentDeadlineRecorder{ResponseRecorder: httptest.NewRecorder()} |
| + f.a.app.Router().ServeHTTP(w, req) |
| + return w.ResponseRecorder |
| +} |
| +func initialSheetAgentInput() sheetAgentCreate { |
| + return sheetAgentCreate{Team: "blue", ClientID: uuid.NewString(), Title: "PRIVATE_BUDGET_TITLE_42", TabName: "PRIVATE_TAB_NAME_42", Cells: []sheetAgentCell{{Row: 0, Column: 0, Raw: "21"}, {Row: 1, Column: 0, Raw: "=A1*2"}, {Row: 0, Column: 1, Raw: "PRIVATE_CELL_CANARY_42 ✓"}}} |
| +} |
| +func decodeSheetCreated(t *testing.T, rec *httptest.ResponseRecorder) sheetAgentCreated { |
| + t.Helper() |
| + if rec.Code != 200 { |
| + t.Fatalf("create: %d %s", rec.Code, rec.Body.String()) |
| + } |
| + var out sheetAgentCreated |
| + if e := json.Unmarshal(rec.Body.Bytes(), &out); e != nil { |
| + t.Fatal(e) |
| + } |
| + if out.SheetID == "" || out.TabID == "" || out.Revision == "" { |
| + t.Fatal("incomplete creation receipt") |
| + } |
| + return out |
| +} |
| +func (f *sheetAgentFixture) rangeInput(created sheetAgentCreated) map[string]any { |
| + return map[string]any{"team": "blue", "sheet_id": created.SheetID, "tab_id": created.TabID, "row": 0, "column": 0, "height": 2, "width": 2} |
| +} |
diff --git a/internal/sheets/agent_integration_test.go b/internal/sheets/agent_integration_test.go| new file mode 100644 |
| index 0000000..5cdc1e5 |
| --- /dev/null |
| +++ b/internal/sheets/agent_integration_test.go |
| @@ -0,0 +1,152 @@ |
| +package sheets |
| + |
| +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 Sheets' real handlers, linked identity, sealed spreadsheet content. |
| +// The signed Home/browser/PKCE flow is exercised in the connection module. |
| +func TestAgentGatewayToRealSheets(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 := newSheetAgentFixture(t, issuer.URL) |
| + p := f.p |
| + input, _ := json.Marshal(initialSheetAgentInput()) |
| + 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: homeTestIssuer, 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{"sheets:read": "Read spreadsheets", "sheets:write": "Create spreadsheets"}, 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", homeTestIssuer) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + remote.Client.Transport = issuer.Client().Transport |
| + f.a.app.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, "sheets_create", json.RawMessage(input)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + encoded, _ := json.Marshal(result) |
| + var spreadsheet sheetAgentCreated |
| + if json.Unmarshal(encoded, &spreadsheet) != nil || spreadsheet.SheetID == "" { |
| + t.Fatal("invalid spreadsheet receipt") |
| + } |
| + mcpClient := mcp.NewClient(&mcp.Implementation{Name: "Sheets 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: "sheets_create", Arguments: json.RawMessage(input)}) |
| + if err != nil || retry.IsError { |
| + t.Fatal("MCP retry", retry, err) |
| + } |
| + search, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "sheets_get_range", Arguments: f.rangeInput(spreadsheet)}) |
| + if err != nil || search.IsError { |
| + t.Fatal("MCP search", search, err) |
| + } |
| + text, _ := json.Marshal(search.Content) |
| + if !strings.Contains(string(text), "PRIVATE_CELL_CANARY_42") { |
| + t.Fatal("MCP could not read created spreadsheet") |
| + } |
| + var count int |
| + if err = f.a.app.db.Raw("SELECT COUNT(*) FROM sheets").Scan(&count).Error; err != nil || count != 1 { |
| + t.Fatal("transport retry duplicated spreadsheet", count, err) |
| + } |
| + if err = cli.Logout(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = session.CallTool(ctx, &mcp.CallToolParams{Name: "sheets_create", Arguments: initialSheetAgentInput()}); err == nil { |
| + t.Fatal("MCP survived CLI revocation") |
| + } |
| + if err = f.a.app.db.Raw("SELECT COUNT(*) FROM sheets").Scan(&count).Error; err != nil || count != 1 { |
| + t.Fatal("revoked call wrote spreadsheet", count, err) |
| + } |
| +} |
diff --git a/internal/sheets/agent_limits_test.go b/internal/sheets/agent_limits_test.go| new file mode 100644 |
| index 0000000..20fb749 |
| --- /dev/null |
| +++ b/internal/sheets/agent_limits_test.go |
| @@ -0,0 +1,128 @@ |
| +package sheets |
| + |
| +import ( |
| + "bytes" |
| + "encoding/base64" |
| + "encoding/json" |
| + "strings" |
| + "sync" |
| + "testing" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/sheets/internal/sheets/store" |
| +) |
| + |
| +func (f *sheetAgentFixture) credentials() *connect.Credentials { |
| + keys, _ := json.Marshal(map[string]string{"key": base64.StdEncoding.EncodeToString(f.home.key.SignPub())}) |
| + return &connect.Credentials{Issuer: homeTestIssuer, ConsumerID: "sheets-preview", KeysBase64: base64.StdEncoding.EncodeToString(keys), DEKBase64: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{81}, 32))} |
| +} |
| +func TestAgentSheetProductionConfiguration(t *testing.T) { |
| + f := newSheetAgentFixture(t) |
| + cfg := f.credentials() |
| + if e := f.a.app.ConfigureAgentAccess(f.a.issuer, "blue", cfg); e != nil { |
| + t.Fatal(e) |
| + } |
| + for _, pair := range [][2]string{{f.a.issuer, ""}, {"", "blue"}, {"http://insecure.example", "blue"}, {homeTestIssuer, "blue"}, {f.a.issuer, " blue"}} { |
| + if e := f.a.app.ConfigureAgentAccess(pair[0], pair[1], cfg); e == nil { |
| + t.Fatal("invalid enabled configuration", pair) |
| + } |
| + } |
| + if e := f.a.app.ConfigureAgentAccess(f.a.issuer, "blue", nil); e == nil { |
| + t.Fatal("enabled without Home") |
| + } |
| + for _, missing := range []string{"", "SHEETS_AGENT_ISSUER", "SHEETS_AGENT_TEAM", "SHEETS_HOME_ISSUER"} { |
| + t.Run(missing, func(t *testing.T) { |
| + env := goodEnv() |
| + env["SHEETS_AGENT_ISSUER"] = f.a.issuer |
| + env["SHEETS_AGENT_TEAM"] = "blue" |
| + env["SHEETS_HOME_ISSUER"] = cfg.Issuer |
| + env["SHEETS_HOME_CONSUMER_ID"] = cfg.ConsumerID |
| + env["SHEETS_HOME_KEYS_BASE64"] = cfg.KeysBase64 |
| + env["SHEETS_HOME_DEK_BASE64"] = cfg.DEKBase64 |
| + if missing != "" { |
| + delete(env, missing) |
| + } |
| + setEnv(t, env) |
| + _, e := LoadAuthEnv(quietLogger()) |
| + if (e == nil) != (missing == "") { |
| + t.Fatal("environment acceptance", missing, e) |
| + } |
| + }) |
| + } |
| +} |
| +func TestAgentSheetConcurrentFirstCreation(t *testing.T) { |
| + f := newSheetAgentFixture(t) |
| + input := initialSheetAgentInput() |
| + start := make(chan struct{}) |
| + responses := make(chan []byte, 6) |
| + codes := make(chan int, 6) |
| + var wg sync.WaitGroup |
| + for i := 0; i < 6; i++ { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + <-start |
| + rec := f.call(t, "sheets_create", input) |
| + codes <- rec.Code |
| + responses <- rec.Body.Bytes() |
| + }() |
| + } |
| + close(start) |
| + wg.Wait() |
| + close(codes) |
| + close(responses) |
| + for code := range codes { |
| + if code != 200 { |
| + t.Fatal("concurrent initial request", code) |
| + } |
| + } |
| + var first sheetAgentCreated |
| + for raw := range responses { |
| + var got sheetAgentCreated |
| + if e := json.Unmarshal(raw, &got); e != nil { |
| + t.Fatal(e) |
| + } |
| + if first.SheetID == "" { |
| + first = got |
| + } |
| + if got != first || got.SheetID == "" { |
| + t.Fatal("divergent first receipts", got, first) |
| + } |
| + } |
| + for _, model := range []any{&store.Sheet{}, &store.Tab{}, &sheetAgentReceipt{}, &sheetAgentAttribution{}} { |
| + var n int64 |
| + if e := f.a.app.db.Model(model).Count(&n).Error; e != nil || n != 1 { |
| + t.Fatal("duplicate first creation", n, e) |
| + } |
| + } |
| +} |
| +func TestAgentSheetInputAndResultLimits(t *testing.T) { |
| + f := newSheetAgentFixture(t) |
| + if rec := f.raw(t, "sheets_create", bytes.Repeat([]byte(" "), sheetAgentLimit+1)); rec.Code != 413 { |
| + t.Fatal("oversize request", rec.Code) |
| + } |
| + input := initialSheetAgentInput() |
| + input.Cells = nil |
| + for i := 0; i < 20; i++ { |
| + input.Cells = append(input.Cells, sheetAgentCell{Row: i, Column: 0, Raw: strings.Repeat("<", 4000)}) |
| + } |
| + made := decodeSheetCreated(t, f.call(t, "sheets_create", input)) |
| + if got := decodeSheetCreated(t, f.call(t, "sheets_create", input)); got != made { |
| + t.Fatal("large create not retryable") |
| + } |
| + args := f.rangeInput(made) |
| + args["height"] = 20 |
| + args["width"] = 1 |
| + if rec := f.call(t, "sheets_get_range", args); rec.Code != 413 || strings.Contains(rec.Body.String(), "<<<<") { |
| + t.Fatal("oversize result", rec.Code) |
| + } |
| + for _, change := range []map[string]any{{"height": 0}, {"width": 0}, {"height": 501}, {"height": 25, "width": 25}, {"row": 4999, "height": 2}, {"column": 599, "width": 2}} { |
| + in := f.rangeInput(made) |
| + for key, value := range change { |
| + in[key] = value |
| + } |
| + if rec := f.call(t, "sheets_get_range", in); rec.Code != 422 { |
| + t.Fatal("invalid range", change, rec.Code) |
| + } |
| + } |
| +} |
diff --git a/internal/sheets/agent_operations.go b/internal/sheets/agent_operations.go| new file mode 100644 |
| index 0000000..a9990c1 |
| --- /dev/null |
| +++ b/internal/sheets/agent_operations.go |
| @@ -0,0 +1,139 @@ |
| +package sheets |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + strictjson "github.com/go-json-experiment/json" |
| +) |
| + |
| +func sheetAgentObject(properties map[string]any, required ...string) json.RawMessage { |
| + raw, _ := json.Marshal(map[string]any{"type": "object", "properties": properties, "required": required, "additionalProperties": false}) |
| + return raw |
| +} |
| +func sheetAgentString(max int) map[string]any { |
| + return map[string]any{"type": "string", "maxLength": max} |
| +} |
| +func sheetAgentInteger(max int) map[string]any { |
| + return map[string]any{"type": "integer", "minimum": 0, "maximum": max} |
| +} |
| +func sheetAgentIDSchema() map[string]any { |
| + return map[string]any{"type": "string", "pattern": "^[1-9][0-9]{0,18}$"} |
| +} |
| +func (a *sheetAgent) registry() (*access.Registry, error) { |
| + input := func(properties map[string]any, required ...string) json.RawMessage { |
| + properties["team"] = map[string]any{"type": "string", "minLength": 1, "maxLength": 128} |
| + return sheetAgentObject(properties, append([]string{"team"}, required...)...) |
| + } |
| + page := func(field string, item json.RawMessage) json.RawMessage { |
| + return sheetAgentObject(map[string]any{field: map[string]any{"type": "array", "maxItems": 100, "items": item}, "next_cursor": sheetAgentString(19)}, field, "next_cursor") |
| + } |
| + summary := sheetAgentObject(map[string]any{"id": sheetAgentIDSchema(), "title": sheetAgentString(1024), "url": sheetAgentString(4096)}, "id", "title", "url") |
| + tab := sheetAgentObject(map[string]any{"id": sheetAgentIDSchema(), "name": sheetAgentString(1024)}, "id", "name") |
| + cell := sheetAgentObject(map[string]any{"row": sheetAgentInteger(4999), "column": sheetAgentInteger(599), "raw": sheetAgentString(8192)}, "row", "column", "raw") |
| + value := sheetAgentObject(map[string]any{"row": sheetAgentInteger(4999), "column": sheetAgentInteger(599), "raw": sheetAgentString(8192), "kind": map[string]any{"enum": []string{"empty", "number", "string", "boolean", "error"}}, "value": map[string]any{"type": []string{"null", "number", "string", "boolean"}}, "display": sheetAgentString(sheetAgentLimit)}, "row", "column", "raw", "kind", "value", "display") |
| + ops := []access.Operation{ |
| + {Name: "sheets_list", Description: "List spreadsheets currently readable in this team.", Scope: "sheets:read", ReadOnly: true, Idempotent: true, Input: input(map[string]any{"limit": map[string]any{"type": "integer", "minimum": 1, "maximum": 100}, "cursor": sheetAgentIDSchema()}), Output: page("sheets", summary), Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) { |
| + var in struct { |
| + Limit int `json:"limit"` |
| + Cursor string `json:"cursor"` |
| + } |
| + if json.Unmarshal(raw, &in) != nil { |
| + return nil, access.Fail("invalid", "Invalid pagination arguments.") |
| + } |
| + return a.list(ctx, sheetAgentMember(ctx), in.Limit, in.Cursor) |
| + }}, |
| + {Name: "sheets_list_tabs", Description: "List tabs in one currently readable spreadsheet.", Scope: "sheets:read", ReadOnly: true, Idempotent: true, Input: input(map[string]any{"sheet_id": sheetAgentIDSchema(), "limit": map[string]any{"type": "integer", "minimum": 1, "maximum": 100}, "cursor": sheetAgentIDSchema()}, "sheet_id"), Output: page("tabs", tab), Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) { |
| + var in struct { |
| + SheetID string `json:"sheet_id"` |
| + Limit int `json:"limit"` |
| + Cursor string `json:"cursor"` |
| + } |
| + if json.Unmarshal(raw, &in) != nil { |
| + return nil, access.Fail("invalid", "Invalid tab pagination arguments.") |
| + } |
| + id, err := sheetAgentID(in.SheetID) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return a.tabs(ctx, sheetAgentMember(ctx), id, in.Limit, in.Cursor) |
| + }}, |
| + {Name: "sheets_get_range", Description: "Read at most 500 cells with raw input, calculated values and one coherent tab revision.", Scope: "sheets:read", ReadOnly: true, Idempotent: true, Input: input(map[string]any{"sheet_id": sheetAgentIDSchema(), "tab_id": sheetAgentIDSchema(), "row": sheetAgentInteger(4999), "column": sheetAgentInteger(599), "height": map[string]any{"type": "integer", "minimum": 1, "maximum": 500}, "width": map[string]any{"type": "integer", "minimum": 1, "maximum": 500}}, "sheet_id", "tab_id", "row", "column", "height", "width"), Output: sheetAgentObject(map[string]any{"sheet_id": sheetAgentIDSchema(), "tab_id": sheetAgentIDSchema(), "revision": sheetAgentIDSchema(), "cells": map[string]any{"type": "array", "maxItems": 500, "items": value}}, "sheet_id", "tab_id", "revision", "cells"), Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) { |
| + var in struct { |
| + SheetID string `json:"sheet_id"` |
| + TabID string `json:"tab_id"` |
| + Row int `json:"row"` |
| + Column int `json:"column"` |
| + Height int `json:"height"` |
| + Width int `json:"width"` |
| + } |
| + if json.Unmarshal(raw, &in) != nil { |
| + return nil, access.Fail("invalid", "Invalid range arguments.") |
| + } |
| + sheet, e := sheetAgentID(in.SheetID) |
| + if e != nil { |
| + return nil, e |
| + } |
| + tab, e := sheetAgentID(in.TabID) |
| + if e != nil { |
| + return nil, e |
| + } |
| + return a.readRange(ctx, sheetAgentMember(ctx), sheet, tab, in.Row, in.Column, in.Height, in.Width) |
| + }}, |
| + {Name: "sheets_create", Description: "Create a spreadsheet and first tab with up to 500 initial cells; reuse the same client UUID only for retries.", Scope: "sheets:write", Idempotent: true, Input: input(map[string]any{"client_id": sheetAgentString(36), "title": map[string]any{"type": "string", "minLength": 1, "maxLength": 200}, "tab_name": map[string]any{"type": "string", "minLength": 1, "maxLength": 200}, "cells": map[string]any{"type": "array", "maxItems": 500, "items": cell}}, "client_id", "title", "tab_name", "cells"), Output: sheetAgentObject(map[string]any{"sheet_id": sheetAgentIDSchema(), "tab_id": sheetAgentIDSchema(), "revision": sheetAgentIDSchema(), "url": sheetAgentString(4096)}, "sheet_id", "tab_id", "revision", "url"), Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) { |
| + var in sheetAgentCreate |
| + if json.Unmarshal(raw, &in) != nil { |
| + return nil, access.Fail("invalid", "Invalid initial sheet arguments.") |
| + } |
| + return a.create(ctx, p, sheetAgentMember(ctx), in) |
| + }}, |
| + } |
| + for i := range ops { |
| + scope := ops[i].Scope |
| + invoke := ops[i].Invoke |
| + ops[i].Available = func(p access.Principal) bool { return p.Allows(a.team, scope) } |
| + ops[i].Invoke = func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) { |
| + if len(raw) > sheetAgentLimit { |
| + return nil, access.Fail("too_large", "The operation input exceeds 1 MiB.") |
| + } |
| + var in struct { |
| + Team string `json:"team"` |
| + } |
| + if strictjson.Unmarshal(raw, &in) != nil { |
| + return nil, access.Fail("invalid", "Send valid Unicode JSON.") |
| + } |
| + if in.Team != a.team { |
| + return nil, access.Fail("forbidden", "This instance does not serve that team.") |
| + } |
| + member, err := a.member(ctx, p, scope == "sheets:write") |
| + if err != nil { |
| + return nil, err |
| + } |
| + state, ok := ctx.Value(sheetAgentKey{}).(*sheetAgentContext) |
| + if !ok || state == nil { |
| + return nil, access.Fail("unavailable", "Request authority is unavailable.") |
| + } |
| + if state.member.ID != member.ID || state.member.Address != member.Address { |
| + return nil, access.Fail("forbidden", "The current identity changed.") |
| + } |
| + state.member = member |
| + return invoke(ctx, p, raw) |
| + } |
| + } |
| + return access.NewRegistry(ops...) |
| +} |
| +func sheetAgentMember(ctx context.Context) Member { |
| + if state, ok := ctx.Value(sheetAgentKey{}).(*sheetAgentContext); ok && state != nil { |
| + return state.member |
| + } |
| + return Member{} |
| +} |
| +func AgentContracts() ([]access.Operation, error) { |
| + a := &sheetAgent{team: "contract"} |
| + registry, err := a.registry() |
| + if err != nil { |
| + return nil, err |
| + } |
| + return registry.List(access.Principal{Subject: "contract", Teams: []string{"contract"}, Scopes: []string{"sheets:read", "sheets:write"}}), nil |
| +} |
diff --git a/internal/sheets/agent_read.go b/internal/sheets/agent_read.go| new file mode 100644 |
| index 0000000..fb65c5e |
| --- /dev/null |
| +++ b/internal/sheets/agent_read.go |
| @@ -0,0 +1,172 @@ |
| +package sheets |
| + |
| +import ( |
| + "context" |
| + "math" |
| + "strconv" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/oficina/sheets/internal/sheets/calc" |
| + "amadan.net/oficina/sheets/internal/sheets/store" |
| +) |
| + |
| +type agentSheetSummary struct { |
| + ID string `json:"id"` |
| + Title string `json:"title"` |
| + URL string `json:"url"` |
| +} |
| +type agentTabSummary struct { |
| + ID string `json:"id"` |
| + Name string `json:"name"` |
| +} |
| + |
| +func agentPageSize(limit int) (int, error) { |
| + if limit == 0 { |
| + return 20, nil |
| + } |
| + if limit < 1 || limit > 100 { |
| + return 0, access.Fail("invalid", "Choose a page size from 1 to 100.") |
| + } |
| + return limit, nil |
| +} |
| +func (a *sheetAgent) list(ctx context.Context, member Member, limit int, cursor string) (any, error) { |
| + limit, err := agentPageSize(limit) |
| + if err != nil { |
| + return nil, err |
| + } |
| + team := TeamRole(member.TeamRole) == TeamOwner || TeamRole(member.TeamRole) == TeamMember |
| + q := a.app.db.WithContext(ctx).Model(&store.Sheet{}).Where("sheets.deleted_at IS NULL AND sheets.filling_since IS NULL").Where(`EXISTS(SELECT 1 FROM grants g WHERE g.sheet_id=sheets.id AND g.member_id=? AND g.role IN ('owner','editor','commenter','viewer')) OR (? AND NOT EXISTS(SELECT 1 FROM grants g WHERE g.sheet_id=sheets.id AND g.member_id=?))`, member.ID, team, member.ID) |
| + if cursor != "" { |
| + id, e := sheetAgentID(cursor) |
| + if e != nil { |
| + return nil, e |
| + } |
| + q = q.Where("sheets.id < ?", id) |
| + } |
| + var rows []store.Sheet |
| + if err = q.Order("sheets.id DESC").Limit(limit + 1).Find(&rows).Error; err != nil { |
| + return nil, sheetAgentFailure(err) |
| + } |
| + next := "" |
| + if len(rows) > limit { |
| + rows = rows[:limit] |
| + next = strconv.FormatUint(rows[len(rows)-1].ID, 10) |
| + } |
| + out := make([]agentSheetSummary, 0, len(rows)) |
| + for _, row := range rows { |
| + title, e := store.ReadTitle(a.app.sealer, row) |
| + if e != nil { |
| + return nil, sheetAgentFailure(e) |
| + } |
| + a.remember(ctx, row.ID) |
| + id := strconv.FormatUint(row.ID, 10) |
| + out = append(out, agentSheetSummary{id, string(title), a.app.origin + "/sheets/" + id}) |
| + } |
| + return sheetAgentBounded(struct { |
| + Sheets []agentSheetSummary `json:"sheets"` |
| + Next string `json:"next_cursor"` |
| + }{out, next}) |
| +} |
| +func (a *sheetAgent) tabs(ctx context.Context, member Member, sheetID uint64, limit int, cursor string) (any, error) { |
| + role, err := a.role(ctx, a.app.db, sheetID, member) |
| + if err != nil { |
| + return nil, sheetAgentFailure(err) |
| + } |
| + if !role.Allows(SheetViewer) { |
| + return nil, sheetAgentFailure(errNoAccess) |
| + } |
| + limit, err = agentPageSize(limit) |
| + if err != nil { |
| + return nil, err |
| + } |
| + q := a.app.db.WithContext(ctx).Where("sheet_id=?", sheetID) |
| + if cursor != "" { |
| + id, e := sheetAgentID(cursor) |
| + if e != nil { |
| + return nil, e |
| + } |
| + q = q.Where("id > ?", id) |
| + } |
| + var rows []store.Tab |
| + if err = q.Order("id ASC").Limit(limit + 1).Find(&rows).Error; err != nil { |
| + return nil, sheetAgentFailure(err) |
| + } |
| + next := "" |
| + if len(rows) > limit { |
| + rows = rows[:limit] |
| + next = strconv.FormatUint(rows[len(rows)-1].ID, 10) |
| + } |
| + out := make([]agentTabSummary, 0, len(rows)) |
| + for _, row := range rows { |
| + name, e := store.ReadTabName(a.app.sealer, row) |
| + if e != nil { |
| + return nil, sheetAgentFailure(e) |
| + } |
| + out = append(out, agentTabSummary{strconv.FormatUint(row.ID, 10), string(name)}) |
| + } |
| + a.remember(ctx, sheetID) |
| + return sheetAgentBounded(struct { |
| + Tabs []agentTabSummary `json:"tabs"` |
| + Next string `json:"next_cursor"` |
| + }{out, next}) |
| +} |
| + |
| +type agentRangeCell struct { |
| + Row int `json:"row"` |
| + Column int `json:"column"` |
| + Raw string `json:"raw"` |
| + Kind string `json:"kind"` |
| + Value any `json:"value"` |
| + Display string `json:"display"` |
| +} |
| +type agentRange struct { |
| + SheetID string `json:"sheet_id"` |
| + TabID string `json:"tab_id"` |
| + Revision string `json:"revision"` |
| + Cells []agentRangeCell `json:"cells"` |
| +} |
| + |
| +func (a *sheetAgent) readRange(ctx context.Context, member Member, sheetID, tabID uint64, row, col, height, width int) (any, error) { |
| + if height < 1 || width < 1 || height > 500 || width > 500 || height > 500/width || !inCellRange(row, col) || !inCellRange(row+height-1, col+width-1) { |
| + return nil, access.Fail("invalid", "Choose a supported range of at most 500 cells.") |
| + } |
| + if err := a.tab(ctx, a.app.db, sheetID, tabID, member); err != nil { |
| + return nil, sheetAgentFailure(err) |
| + } |
| + handle, err := store.Open(a.app.db, a.app.sealer, tabID) |
| + if err != nil { |
| + return nil, sheetAgentFailure(err) |
| + } |
| + defer handle.Release() |
| + snapshot, err := handle.ReadRange(row, col, height, width) |
| + if err != nil { |
| + return nil, sheetAgentFailure(err) |
| + } |
| + cells := make([]agentRangeCell, 0, len(snapshot.Cells)) |
| + for _, cell := range snapshot.Cells { |
| + out := agentRangeCell{Row: cell.Row, Column: cell.Col, Raw: cell.Raw, Kind: "empty", Display: display(cell.Value, nil)} |
| + switch cell.Value.Kind { |
| + case calc.KindNum: |
| + if math.IsNaN(cell.Value.Num) || math.IsInf(cell.Value.Num, 0) { |
| + return nil, access.Fail("unavailable", "A calculated value is not finite.") |
| + } |
| + out.Kind = "number" |
| + out.Value = cell.Value.Num |
| + case calc.KindStr: |
| + out.Kind = "string" |
| + out.Value = cell.Value.Str |
| + case calc.KindBool: |
| + out.Kind = "boolean" |
| + out.Value = cell.Value.Bool |
| + case calc.KindErr: |
| + out.Kind = "error" |
| + out.Value = out.Display |
| + case calc.KindEmpty: |
| + default: |
| + return nil, access.Fail("unavailable", "A calculated value is unavailable.") |
| + } |
| + cells = append(cells, out) |
| + } |
| + a.remember(ctx, sheetID) |
| + return sheetAgentBounded(agentRange{strconv.FormatUint(sheetID, 10), strconv.FormatUint(tabID, 10), strconv.FormatUint(snapshot.Version, 10), cells}) |
| +} |
diff --git a/internal/sheets/agent_response_test.go b/internal/sheets/agent_response_test.go| new file mode 100644 |
| index 0000000..5efffc6 |
| --- /dev/null |
| +++ b/internal/sheets/agent_response_test.go |
| @@ -0,0 +1,95 @@ |
| +package sheets |
| + |
| +import ( |
| + "bytes" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "strconv" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +type agentRevokingWriter struct { |
| + http.ResponseWriter |
| + revoke func() |
| +} |
| + |
| +func (w *agentRevokingWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } |
| +func (w *agentRevokingWriter) Write(body []byte) (int, error) { |
| + n, e := w.ResponseWriter.Write(body) |
| + if w.revoke != nil { |
| + f := w.revoke |
| + w.revoke = nil |
| + f() |
| + } |
| + return n, e |
| +} |
| +func TestAgentSheetResponseRevocation(t *testing.T) { |
| + f := newSheetAgentFixture(t) |
| + input := initialSheetAgentInput() |
| + input.Cells = nil |
| + for i := 0; i < 20; i++ { |
| + input.Cells = append(input.Cells, sheetAgentCell{Row: i, Column: 0, Raw: strings.Repeat("z", 4000)}) |
| + } |
| + made := decodeSheetCreated(t, f.call(t, "sheets_create", input)) |
| + f.checks.Store(0) |
| + f.revokeAt.Store(2) |
| + if rec := f.call(t, "sheets_get_range", f.rangeInput(made)); rec.Code != 401 || strings.Contains(rec.Body.String(), "zzzz") { |
| + t.Fatal("response escaped final check", rec.Code) |
| + } |
| + f.revoked.Store(false) |
| + f.revokeAt.Store(0) |
| + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + f.a.app.Router().ServeHTTP(&agentRevokingWriter{w, func() { f.revoked.Store(true) }}, r) |
| + })) |
| + defer server.Close() |
| + args := f.rangeInput(made) |
| + args["height"] = 20 |
| + args["width"] = 1 |
| + raw, _ := json.Marshal(args) |
| + req, _ := http.NewRequest("POST", server.URL+"/api/v1/operations/sheets_get_range", bytes.NewReader(raw)) |
| + req.Header.Set("Authorization", "Bearer test-token") |
| + req.Header.Set("Content-Type", "application/json") |
| + res, e := server.Client().Do(req) |
| + if e != nil { |
| + t.Fatal("first response chunk missing", e) |
| + } |
| + defer res.Body.Close() |
| + body, e := io.ReadAll(res.Body) |
| + if !errors.Is(e, io.ErrUnexpectedEOF) || res.StatusCode != 200 || len(body) == 0 || len(body) > 64<<10 || json.Valid(body) { |
| + t.Fatal("revoked stream completed", res.StatusCode, len(body), e) |
| + } |
| +} |
| +func TestAgentSheetExactLargeIDsAndPagination(t *testing.T) { |
| + f := newSheetAgentFixture(t) |
| + const base = int64(9007199254740992) |
| + for _, table := range []string{"sheets", "tabs"} { |
| + if e := f.a.app.db.Exec("INSERT INTO sqlite_sequence(name,seq) VALUES(?,?)", table, base).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + first := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput())) |
| + if first.SheetID != strconv.FormatInt(base+1, 10) || first.TabID != strconv.FormatInt(base+1, 10) { |
| + t.Fatal("large ID lost", first) |
| + } |
| + second := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput())) |
| + type result struct { |
| + Sheets []agentSheetSummary `json:"sheets"` |
| + Next string `json:"next_cursor"` |
| + } |
| + var page result |
| + rec := f.call(t, "sheets_list", map[string]any{"team": "blue", "limit": 1}) |
| + if e := json.Unmarshal(rec.Body.Bytes(), &page); e != nil || rec.Code != 200 || len(page.Sheets) != 1 || page.Sheets[0].ID != second.SheetID || page.Next != second.SheetID { |
| + t.Fatal("first page", rec.Body.String(), e) |
| + } |
| + rec = f.call(t, "sheets_list", map[string]any{"team": "blue", "limit": 1, "cursor": page.Next}) |
| + if e := json.Unmarshal(rec.Body.Bytes(), &page); e != nil || rec.Code != 200 || len(page.Sheets) != 1 || page.Sheets[0].ID != first.SheetID || page.Next != "" { |
| + t.Fatal("second page", rec.Body.String(), e) |
| + } |
| + if rec = f.call(t, "sheets_get_range", f.rangeInput(first)); rec.Code != 200 { |
| + t.Fatal("large-ID range", rec.Code, rec.Body.String()) |
| + } |
| +} |
diff --git a/internal/sheets/agent_storage_test.go b/internal/sheets/agent_storage_test.go| new file mode 100644 |
| index 0000000..eb04a63 |
| --- /dev/null |
| +++ b/internal/sheets/agent_storage_test.go |
| @@ -0,0 +1,118 @@ |
| +package sheets |
| + |
| +import ( |
| + "amadan.net/oficina/sheets/internal/sheets/seal" |
| + "bytes" |
| + "net/http/httptest" |
| + "testing" |
| + |
| + rdb "amadan.net/rastrillo/rastrillo/db" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func TestAgentSheetReceiptRestartAndAttribution(t *testing.T) { |
| + f := newSheetAgentFixture(t) |
| + input := initialSheetAgentInput() |
| + created := decodeSheetCreated(t, f.call(t, "sheets_create", input)) |
| + var attribution sheetAgentAttribution |
| + if e := f.a.app.db.First(&attribution, "sheet_id=?", created.SheetID).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + plain, e := f.a.app.sealer.Open("agent.client/"+created.SheetID, attribution.ClientSealed) |
| + if e != nil || string(plain) != f.p.Client || bytes.Contains(attribution.ClientSealed, []byte(f.p.Client)) { |
| + t.Fatal("client attribution is not sealed and recoverable", e) |
| + } |
| + member, e := f.a.member(t.Context(), f.p, false) |
| + if e != nil || member.ID != attribution.MemberID { |
| + t.Fatal("operator attribution", e) |
| + } |
| + var files []struct{ Name, File string } |
| + if e = f.a.app.db.Raw("PRAGMA database_list").Scan(&files).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + path := "" |
| + for _, file := range files { |
| + if file.Name == "main" { |
| + path = file.File |
| + } |
| + } |
| + d, e := f.a.app.db.DB() |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = d.Close(); e != nil { |
| + t.Fatal(e) |
| + } |
| + reopened, e := rdb.Open(path, quietLogger()) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer reopened.Close() |
| + sealer, e := seal.New(make([]byte, dekBytes)) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + app := New(Config{DB: reopened.G, Sealer: sealer, Origin: testOrigin, Admit: Admits([]string{signedInAddress})}) |
| + cfg := f.credentials() |
| + auth, e := NewAuth(reopened.Writer(), AuthEnv{Origin: testOrigin, InstanceKey: "test-instance-key", Owners: []string{signedInAddress}, Home: cfg, Mailer: f.home.app.testMailer(t)}, quietLogger(), app) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer CloseSigninMail(auth) |
| + app.UseAuth(auth) |
| + if e = app.ConfigureHome(cfg); e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = app.ConfigureAgentAccess(f.a.issuer, f.a.team, cfg); e != nil { |
| + t.Fatal(e) |
| + } |
| + a := *f.a |
| + a.app = app |
| + restarted := &sheetAgentFixture{home: f.home, a: &a, p: f.p} |
| + restarted.install(t) |
| + if got := decodeSheetCreated(t, restarted.call(t, "sheets_create", input)); got != created { |
| + t.Fatal("restart replay changed receipt", got, created) |
| + } |
| + |
| + if e = reopened.G.Transaction(func(tx *gorm.DB) error { return a.bind(tx) }); e != nil { |
| + t.Fatal("unchanged restart refused", e) |
| + } |
| + coordinate := a.digest("coordinate", []string{a.identityIssuer, a.issuer, f.p.Subject, f.p.Client, a.team, input.ClientID}) |
| + var receipt sheetAgentReceipt |
| + if e = reopened.G.First(&receipt, "coordinate=?", coordinate).Error; e != nil || receipt.SheetID != attribution.SheetID { |
| + t.Fatal("receipt did not survive restart", e) |
| + } |
| + a.issuer = "https://other-connect.example" |
| + if e = reopened.G.Transaction(func(tx *gorm.DB) error { return a.bind(tx) }); e == nil { |
| + t.Fatal("restart changed authority") |
| + } |
| +} |
| +func TestAgentSheetReservedWriterRevocationAndCookieRefusal(t *testing.T) { |
| + f := newSheetAgentFixture(t) |
| + f.revokeAt.Store(2) |
| + if rec := f.call(t, "sheets_create", initialSheetAgentInput()); rec.Code != 401 { |
| + t.Fatal("reserved writer used revoked delegation", rec.Code) |
| + } |
| + assertAgentSheetEmpty(t, f) |
| + req := httptest.NewRequest("GET", testOrigin+"/api/v1/operations", nil) |
| + for _, cookie := range f.home.jar { |
| + req.AddCookie(cookie) |
| + } |
| + rec := httptest.NewRecorder() |
| + f.a.app.Router().ServeHTTP(rec, req) |
| + if rec.Code != 401 { |
| + t.Fatal("browser cookie authenticated agent API", rec.Code) |
| + } |
| +} |
| +func TestAgentSheetAuthorityStorageFailure(t *testing.T) { |
| + f := newSheetAgentFixture(t) |
| + created := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput())) |
| + if e := f.a.app.db.Exec("ALTER TABLE grants RENAME TO unavailable_grants").Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + for name, args := range map[string]any{"sheets_list": map[string]any{"team": "blue"}, "sheets_get_range": f.rangeInput(created)} { |
| + if rec := f.call(t, name, args); rec.Code != 503 { |
| + t.Fatal("authority failure hidden", name, rec.Code) |
| + } |
| + } |
| +} |
diff --git a/internal/sheets/app.go b/internal/sheets/app.go| index 86eb225..3afc002 100644 |
| --- a/internal/sheets/app.go |
| +++ b/internal/sheets/app.go |
| @@ -54,6 +54,7 @@ type Config struct { |
| // App holds the wiring. One per process. |
| type App struct { |
| + agent http.Handler |
| native *nativeauth.Auth |
| home *connect.Bridge |
| homeRoutes *connect.Routes |
| @@ -276,7 +277,7 @@ func (a *App) Router() http.Handler { |
| r.Get("/jobs/{id}/fragment", a.jobPages.Fragment) |
| r.Get("/jobs/{id}/events", a.jobPages.Events) |
| }) |
| - return r |
| + return a.agentRoutes(r) |
| } |
| // requireSession is auth.RequireSession in production and a |
diff --git a/internal/sheets/auth.go b/internal/sheets/auth.go| index 263893e..5f2dff9 100644 |
| --- a/internal/sheets/auth.go |
| +++ b/internal/sheets/auth.go |
| @@ -18,7 +18,9 @@ import ( |
| // AuthEnv is everything sign-in needs from the environment, already |
| // validated. Building it is the only place these variable names appear. |
| type AuthEnv struct { |
| - Home *connect.Credentials |
| + AgentIssuer string |
| + AgentTeam string |
| + Home *connect.Credentials |
| // Origin is the instance's external origin, scheme included. It is |
| // the base of every emailed link and the CSRF origin check, which |
| // makes a WRONG value the dangerous case rather than a missing one: |
| @@ -76,6 +78,8 @@ func loopback(origin string) bool { |
| // any address. Both serve pages and answer /healthz. |
| func LoadAuthEnv(logger *slog.Logger) (AuthEnv, error) { |
| env := AuthEnv{ |
| + AgentIssuer: os.Getenv("SHEETS_AGENT_ISSUER"), |
| + AgentTeam: os.Getenv("SHEETS_AGENT_TEAM"), |
| Home: connect.CredentialsFromEnv("SHEETS"), |
| Origin: strings.TrimSpace(os.Getenv("SHEETS_ORIGIN")), |
| InstanceKey: strings.TrimSpace(os.Getenv("SHEETS_INSTANCE_KEY")), |
| @@ -114,6 +118,9 @@ func LoadAuthEnv(logger *slog.Logger) (AuthEnv, error) { |
| if _, err := connect.DecodeCredentials(env.Home, env.Origin); err != nil { |
| return AuthEnv{}, errHome |
| } |
| + if err := validateAgentConfig(env.AgentIssuer, env.AgentTeam, env.Origin, env.Home); err != nil { |
| + return AuthEnv{}, err |
| + } |
| env.Mailer = mail.FromEnv("CARLOS", logger) |
| return env, nil |
diff --git a/internal/sheets/auth_test.go b/internal/sheets/auth_test.go| index 775a114..b71d189 100644 |
| --- a/internal/sheets/auth_test.go |
| +++ b/internal/sheets/auth_test.go |
| @@ -19,6 +19,7 @@ func setEnv(t *testing.T, kv map[string]string) { |
| t.Helper() |
| for _, k := range []string{ |
| "SHEETS_ORIGIN", "SHEETS_INSTANCE_KEY", "SHEETS_OWNERS", |
| + "SHEETS_AGENT_ISSUER", "SHEETS_AGENT_TEAM", |
| "SHEETS_HOME_ISSUER", "SHEETS_HOME_CONSUMER_ID", "SHEETS_HOME_KEYS_BASE64", "SHEETS_HOME_DEK_BASE64", |
| "CARLOS_SMTP_HOST", "CARLOS_SMTP_FROM", |
| } { |
diff --git a/internal/sheets/migrations.go b/internal/sheets/migrations.go| index d66f731..d5b275b 100644 |
| --- a/internal/sheets/migrations.go |
| +++ b/internal/sheets/migrations.go |
| @@ -51,6 +51,7 @@ var BootSchema = migrate.Merge(sessions.Schema, auth.Schema, Schema, migrate.Mus |
| // structs live where they belong. See store/models.go for why they |
| // moved. |
| var Models = []any{ |
| + sheetAgentState{}, sheetAgentReceipt{}, sheetAgentAttribution{}, |
| store.Sheet{}, store.Tab{}, store.Row{}, store.Col{}, |
| store.Cell{}, store.Format{}, store.Event{}, Member{}, Grant{}, ShareLink{}, Comment{}, TabView{}, |
| } |
diff --git a/internal/sheets/migrations/0011_agent_access.sql b/internal/sheets/migrations/0011_agent_access.sql| new file mode 100644 |
| index 0000000..3c8845a |
| --- /dev/null |
| +++ b/internal/sheets/migrations/0011_agent_access.sql |
| @@ -0,0 +1,14 @@ |
| +CREATE TABLE sheets_agent_state ( |
| + id INTEGER PRIMARY KEY CHECK(id=1), |
| + keycheck TEXT NOT NULL |
| +); |
| +CREATE TABLE sheets_agent_receipts ( |
| + coordinate TEXT PRIMARY KEY NOT NULL, |
| + content TEXT NOT NULL, |
| + sheet_id INTEGER NOT NULL |
| +); |
| +CREATE TABLE sheets_agent_attribution ( |
| + sheet_id INTEGER PRIMARY KEY NOT NULL, |
| + member_id INTEGER NOT NULL, |
| + client_sealed BLOB NOT NULL |
| +); |
diff --git a/internal/sheets/sheetsvc.go b/internal/sheets/sheetsvc.go| index 1a66551..19ccd2c 100644 |
| --- a/internal/sheets/sheetsvc.go |
| +++ b/internal/sheets/sheetsvc.go |
| @@ -91,6 +91,12 @@ func (a *App) createFillingSheet(title string, by Member) (SheetSummary, error) |
| } |
| func (a *App) newSheet(title string, by Member, filling bool) (SheetSummary, error) { |
| + return a.newSheetWithTab(title, firstTabName, by, filling) |
| +} |
| + |
| +// newSheetWithTab shares the ordinary creation transaction and owner grant. |
| +// Agent callers validate their explicit first-tab name before entering it. |
| +func (a *App) newSheetWithTab(title, tabName string, by Member, filling bool) (SheetSummary, error) { |
| if a.db == nil { |
| return SheetSummary{}, errNoDB |
| } |
| @@ -108,7 +114,7 @@ func (a *App) newSheet(title string, by Member, filling bool) (SheetSummary, err |
| if err != nil { |
| return SheetSummary{}, err |
| } |
| - sealedName, err := a.sealer.Seal("tab.name", []byte(firstTabName)) |
| + sealedName, err := a.sealer.Seal("tab.name", []byte(tabName)) |
| if err != nil { |
| return SheetSummary{}, err |
| } |
| @@ -140,7 +146,7 @@ func (a *App) newSheet(title string, by Member, filling bool) (SheetSummary, err |
| } |
| return SheetSummary{ |
| ID: sheet.ID, Title: clean, TabID: tab.ID, |
| - TabName: firstTabName, UpdatedAt: sheet.UpdatedAt, |
| + TabName: tabName, UpdatedAt: sheet.UpdatedAt, |
| }, nil |
| } |
diff --git a/internal/sheets/store/handle_write_batch.go b/internal/sheets/store/handle_write_batch.go| index 74f4340..fbf9dad 100644 |
| --- a/internal/sheets/store/handle_write_batch.go |
| +++ b/internal/sheets/store/handle_write_batch.go |
| @@ -16,21 +16,30 @@ type CellWrite struct { |
| var errCellBatch = errors.New("store: invalid cell batch") |
| -func (h *Handle) SetBatch(writes []CellWrite, actor uint64) (Report, error) { |
| +// ValidateCellWrites uses the same shape and parser checks as SetBatch. |
| +func ValidateCellWrites(writes []CellWrite) error { |
| if len(writes) == 0 || len(writes) > MaxCellBatch { |
| - return Report{}, errCellBatch |
| + return errCellBatch |
| } |
| seen := make(map[[2]int]bool, len(writes)) |
| for _, w := range writes { |
| pos := [2]int{w.Row, w.Col} |
| if w.Row < 0 || w.Col < 0 || seen[pos] { |
| - return Report{}, errCellBatch |
| + return errCellBatch |
| } |
| seen[pos] = true |
| if _, _, err := contentNode(w.Raw); err != nil { |
| - return Report{}, errCellBatch |
| + return errCellBatch |
| } |
| } |
| + return nil |
| +} |
| + |
| +func (h *Handle) SetBatch(writes []CellWrite, actor uint64) (Report, error) { |
| + if err := ValidateCellWrites(writes); err != nil { |
| + return Report{}, err |
| + } |
| + |
| h.mu.Lock() |
| defer h.mu.Unlock() |
diff --git a/internal/sheets/store/metadata_read.go b/internal/sheets/store/metadata_read.go| new file mode 100644 |
| index 0000000..06094bd |
| --- /dev/null |
| +++ b/internal/sheets/store/metadata_read.go |
| @@ -0,0 +1,16 @@ |
| +package store |
| + |
| +import "amadan.net/oficina/sheets/internal/sheets/seal" |
| + |
| +// ReadTitle returns a decryption error instead of disguising damaged metadata |
| +// as an empty title. Callers must establish current access before calling it. |
| +func ReadTitle(sealer *seal.Sealer, sheet Sheet) (string, error) { |
| + plain, err := sealer.Open("sheet.title", sheet.TitleSealed) |
| + return string(plain), err |
| +} |
| + |
| +// ReadTabName has the same failure semantics as ReadTitle. |
| +func ReadTabName(sealer *seal.Sealer, tab Tab) (string, error) { |
| + plain, err := sealer.Open("tab.name", tab.NameSealed) |
| + return string(plain), err |
| +} |