Add delegated Slides operations with atomic creation and guarded responses
35 files changed,
+2,169
−89
.amadan/README.md+1 −1cmd/slides-contract/main.go+22 −0cmd/slides/main.go+18 −12docs/agent-access.md+19 −0docs/superpowers/specs/2026-10-25-agent-access.md+6 −0go.mod+17 −3go.sum+44 −0internal/slides/agent_access.go+224 −0internal/slides/agent_attribution.go+64 −0internal/slides/agent_authority.go+147 −0internal/slides/agent_authority_test.go+222 −0internal/slides/agent_config_test.go+95 −0internal/slides/agent_create.go+147 −0internal/slides/agent_create_test.go+84 −0internal/slides/agent_fixture_test.go+94 −0internal/slides/agent_integration_test.go+154 −0internal/slides/agent_migrations/migrations/0001_connections.sql+3 −0internal/slides/agent_operations.go+94 −0internal/slides/agent_read.go+58 −0internal/slides/agent_read_test.go+140 −0internal/slides/agent_response_test.go+93 −0internal/slides/agent_wait_test.go+88 −0internal/slides/agents.go+1 −1internal/slides/app.go+12 −0internal/slides/config.go+3 −1internal/slides/core/testdata/slides_core.wasmbinaryinternal/slides/credits/assets.json+13 −2internal/slides/credits/notices.json+99 −0internal/slides/credits/upstream/fastrand-vendor.json+19 −0internal/slides/decks.go+55 −40internal/slides/handlers.go+3 −0internal/slides/pdfcore/testdata/slides_pdf.wasmbinaryscripts/build-pdf-wasm.sh+54 −19scripts/build-wasm.sh+52 −7scripts/credits.py+24 −3
CI passed — run details
diff --git a/.amadan/README.md b/.amadan/README.md| index 869296e..edffefd 100644 |
| --- a/.amadan/README.md |
| +++ b/.amadan/README.md |
| @@ -10,7 +10,7 @@ It needs a Rust toolchain with the `wasm32-unknown-unknown` target and the |
| `rustfmt` and `clippy` components (`rust-toolchain.toml` pins 1.98.0 and |
| asks for all three), Go, and — since slice 2 — **Node 20 or newer with |
| `npm`**, because the editor's bundle and the fixture vectors are both |
| -built by JS this repo owns. `CGO_ENABLED=0` is exported for every step. |
| +built by JS this repo owns. Canonical Wasm builds additionally require Docker, or bubblewrap on Linux amd64. Both modules build under pinned Rust 1.98.0 at fixed Linux paths with separate target caches; a native fallback would defeat the byte comparison. `CGO_ENABLED=0` is exported for every step. |
| The gate sources `~/.cargo/env` itself and checks every tool up front, so |
| a missing dependency fails on the first line with its own name rather |
| than fifty lines in as `cargo: command not found`. |
diff --git a/cmd/slides-contract/main.go b/cmd/slides-contract/main.go| new file mode 100644 |
| index 0000000..6297560 |
| --- /dev/null |
| +++ b/cmd/slides-contract/main.go |
| @@ -0,0 +1,22 @@ |
| +// Command slides-contract exports the live delegated operation schemas. |
| +package main |
| + |
| +import ( |
| + "amadan.net/oficina/slides/internal/slides" |
| + "encoding/json" |
| + "fmt" |
| + "os" |
| +) |
| + |
| +func main() { |
| + operations, err := slides.AgentContracts() |
| + if err != nil { |
| + fmt.Fprintln(os.Stderr, "Could not export Slides operation contracts.") |
| + os.Exit(1) |
| + } |
| + encoder := json.NewEncoder(os.Stdout) |
| + encoder.SetIndent("", " ") |
| + if encoder.Encode(operations) != nil { |
| + os.Exit(1) |
| + } |
| +} |
diff --git a/cmd/slides/main.go b/cmd/slides/main.go| index ac74ca0..466d0f4 100644 |
| --- a/cmd/slides/main.go |
| +++ b/cmd/slides/main.go |
| @@ -208,6 +208,22 @@ func main() { |
| origin = "http://" + opts.Addr |
| } |
| + var homeConfig *connect.Credentials |
| + hc := connect.Credentials{Issuer: os.Getenv("SLIDES_HOME_ISSUER"), ConsumerID: os.Getenv("SLIDES_HOME_CONSUMER_ID"), KeysBase64: os.Getenv("SLIDES_HOME_KEYS_BASE64"), DEKBase64: os.Getenv("SLIDES_HOME_DEK_BASE64")} |
| + if hc.Issuer != "" || hc.ConsumerID != "" || hc.KeysBase64 != "" || hc.DEKBase64 != "" { |
| + // The hub directory the app switcher's "All apps" links to. |
| + // Optional, and unprefixed: the same name and the same value |
| + // Home itself reads (connect.CredentialsFromEnv reads it the |
| + // same way; this app builds Credentials by hand). Checked by |
| + // connect.DecodeCredentials, so a malformed value refuses boot. |
| + hc.Directory = os.Getenv("HOME_DIRECTORY_ORIGIN") |
| + homeConfig = &hc |
| + } |
| + if err := slides.ValidateAgentConfig(os.Getenv("SLIDES_AGENT_ISSUER"), os.Getenv("SLIDES_AGENT_TEAM"), origin, homeConfig); err != nil { |
| + logger.Error("configure agent access", "err", err) |
| + os.Exit(1) |
| + } |
| + |
| store, err := newBlobs(env, opts.DBPath, logger) |
| if err != nil { |
| logger.Error("bind object store", "err", err) |
| @@ -223,18 +239,8 @@ func main() { |
| // Every empty value below is a startup refusal inside slides.New |
| // unless env is "development" — see config.go's package comment. |
| - var homeConfig *connect.Credentials |
| - hc := connect.Credentials{Issuer: os.Getenv("SLIDES_HOME_ISSUER"), ConsumerID: os.Getenv("SLIDES_HOME_CONSUMER_ID"), KeysBase64: os.Getenv("SLIDES_HOME_KEYS_BASE64"), DEKBase64: os.Getenv("SLIDES_HOME_DEK_BASE64")} |
| - if hc.Issuer != "" || hc.ConsumerID != "" || hc.KeysBase64 != "" || hc.DEKBase64 != "" { |
| - // The hub directory the app switcher's "All apps" links to. |
| - // Optional, and unprefixed: the same name and the same value |
| - // Home itself reads (connect.CredentialsFromEnv reads it the |
| - // same way; this app builds Credentials by hand). Checked by |
| - // connect.DecodeCredentials, so a malformed value refuses boot. |
| - hc.Directory = os.Getenv("HOME_DIRECTORY_ORIGIN") |
| - homeConfig = &hc |
| - } |
| - mux, a, err := slides.New(d, slides.Config{Home: homeConfig, |
| + |
| + mux, a, err := slides.New(d, slides.Config{Home: homeConfig, AgentIssuer: os.Getenv("SLIDES_AGENT_ISSUER"), AgentTeam: os.Getenv("SLIDES_AGENT_TEAM"), |
| Origin: origin, |
| Env: env, |
| InstanceKey: os.Getenv("SLIDES_INSTANCE_KEY"), |
diff --git a/docs/agent-access.md b/docs/agent-access.md| new file mode 100644 |
| index 0000000..a433f35 |
| --- /dev/null |
| +++ b/docs/agent-access.md |
| @@ -0,0 +1,19 @@ |
| +# Oficina delegated connection |
| + |
| +The optional adapter exposes Slides through one Oficina browser grant. Configure `SLIDES_AGENT_ISSUER` (the separate connection service) and `SLIDES_AGENT_TEAM` together, with the existing valid `SLIDES_HOME_*` configuration. Both must be empty to disable it. The app verifies its exact audience `<SLIDES_ORIGIN>/api/v1` and exact Home identity issuer, then resolves an existing linked, currently admitted local account. An agent cannot create or silently link an account. |
| + |
| +The operation descriptors are exported with `go run ./cmd/slides-contract`. Use these in the connection service's trusted team/instance directory. They drive the same API, CLI and MCP contracts: |
| + |
| +| Tool | Scope | Input | |
| +|---|---|---| |
| +| slides_list_decks | slides:read | team, optional limit (1–100), cursor | |
| +| slides_get_deck | slides:read | team, sqid | |
| +| slides_create_deck | slides:write | team, client_id UUID, title, optional theme, slides | |
| + |
| +Each initial slide contains `heading`, `body_markdown`, and `notes_markdown`. Supply 1–50 slides and at most 128 KiB of combined text. Titles are at most 512 UTF-8 bytes. New decks start private and use the existing collaborative block tree, so browser editing and presentation work normally. Reads include speaker notes for the same current permissions as the existing drive API. Results and input are bounded at 1 MiB. Creation returns only sqid, URL and decimal-string revision. |
| + |
| +Reuse the same nonzero canonical UUID and identical normalized payload after an uncertain response. Metadata, core update, actor attribution and receipt commit together. Retrying never overwrites later edits or recreates a deleted deck. Changing Home DEK, Home issuer, connection issuer or team after receipts exist requires an explicit migration; restarting with a new retry namespace is refused. |
| + |
| +The CLI uses `oficina call slides_create_deck --input <JSON-file>` according to the installed CLI's help. Paseo can use the CLI's local MCP bridge and credential store. ChatGPT and Claude use the public remote connection service and their separately registered OAuth callbacks. App-adapter tests are not certification of those live hosts. No production deployment is claimed by this branch. |
| + |
| +The original `/api/v1/decks` drive API remains available for its existing tokens. Delegated semantic editing, asset uploads, exports, presentation control and sharing are follow-on operation contracts; these three tools do not claim to expose them yet. |
diff --git a/docs/superpowers/specs/2026-10-25-agent-access.md b/docs/superpowers/specs/2026-10-25-agent-access.md| index 9cc0c83..2ca283f 100644 |
| --- a/docs/superpowers/specs/2026-10-25-agent-access.md |
| +++ b/docs/superpowers/specs/2026-10-25-agent-access.md |
| @@ -33,3 +33,9 @@ Track every returned deck and recheck original bearer, fresh Home/local identity |
| Meaningful tests use real Home link fixtures, real core replay and actual HTTP transports: disabled/partial configuration; wrong team/scope/identity namespace; private/team/granted visibility before pagination; exact large IDs; strict invalid Unicode and unknown fields; bounded create/input/output; atomic rollback at update/receipt/final authority stages; reserved-writer revocation; changed principal/local link/admission; startup and live marker tampering; independent old receipt/attribution adoption refusal; fresh restart, concurrent create, preserved subsequent browser edits and deleted retry; actual chunked response revocation. A real HTTPS grant-service/CLI/MCP fixture discovers and creates/reads/retries a deck and refuses after logout. Mutation evidence must distinguish each critical boundary from a later check masking its absence. |
| Run the full `.amadan/ci.d/10-gate`, focused race checks, source review and remote CI before merge. No deployed or four-host certification is claimed until real tests run there. Follow-on semantic edits, assets, export/presentation/sharing require separate contract work against existing domain seams. |
| + |
| +## Build reproducibility amendment |
| + |
| +The full gate discovered that unchanged Slides Rust source rebuilt under the pinned 1.98.0 compiler differs from the committed Wasm: Cargo crate identities and symbol/code ordering vary by checkout and host despite remapped diagnostic paths. Adopt the existing Docs canonical builder for both Slides modules: Linux amd64, fixed `/work` source and fixed Cargo/Rustup roots, pinned Rust Docker image (or the same fixed-root bubblewrap environment on Linux amd64). Preserve Rust source, lockfiles, ABI and semantic behavior; regenerate committed CRDT/PDF artifacts with those builders, then require the normal byte comparisons, Rust tests and JS/core parity. Native Rust lint/tests remain native. Canonical target caches are worktree-specific; source is mounted read-only and only dedicated build caches are writable. No weakened or skipped gate. |
| + |
| +Credits regeneration additionally recognizes only the preexisting fastrand 2.5.0 vendor patch at its exact path. A reviewed upstream-archive hash manifest verifies every vendored file (only the parsed normal wasm getrandom feature differs), rejects symlink escapes and all other source replacements, and feeds actual vendored license notices. Vendor files join the credit input inventory. No dependency source or lockfile changes. |
diff --git a/go.mod b/go.mod| index 969daad..3862fc7 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -5,16 +5,21 @@ go 1.25.0 |
| toolchain go1.26.5 |
| require ( |
| + amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000 |
| amadan.net/oficina/estilo.git v0.0.0-20261024225350-d53b8e9533a1 |
| - amadan.net/oficina/home/connect v0.0.0-20261001093757-2bec942ddd0c |
| + amadan.net/oficina/home/connect v0.0.0-20261025004522-7430dd23a847 |
| amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 |
| amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060 |
| 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/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 |
| + github.com/google/uuid v1.6.0 |
| + github.com/modelcontextprotocol/go-sdk v1.7.0 |
| github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e |
| github.com/tetratelabs/wazero v1.12.0 |
| golang.org/x/image v0.44.0 |
| + golang.org/x/oauth2 v0.35.0 |
| gorm.io/gorm v1.31.2 |
| ) |
| @@ -23,21 +28,30 @@ require ( |
| github.com/BurntSushi/toml v1.6.0 // indirect |
| github.com/carlosframework/rastrillo v0.23.0 // indirect |
| github.com/chromedp/sysutil v1.1.0 // indirect |
| + github.com/danieljoos/wincred v1.2.3 // indirect |
| github.com/dustin/go-humanize v1.0.1 // indirect |
| - github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 // 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/google/uuid v1.6.0 // indirect |
| + github.com/godbus/dbus/v5 v5.2.2 // indirect |
| + github.com/gofrs/flock v0.12.1 // indirect |
| + github.com/google/jsonschema-go v0.4.3 // indirect |
| github.com/jinzhu/inflection v1.0.0 // indirect |
| github.com/jinzhu/now v1.1.5 // indirect |
| github.com/keymaildev/signin v0.1.1 // indirect |
| github.com/mattn/go-isatty v0.0.20 // indirect |
| github.com/ncruces/go-strftime v1.0.0 // indirect |
| github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect |
| + github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect |
| + github.com/segmentio/asm v1.1.3 // indirect |
| + github.com/segmentio/encoding v0.5.4 // indirect |
| + github.com/yosida95/uritemplate/v3 v3.0.2 // indirect |
| + github.com/zalando/go-keyring v0.2.8 // indirect |
| golang.org/x/mod v0.37.0 // indirect |
| + golang.org/x/sync v0.22.0 // indirect |
| golang.org/x/sys v0.46.0 // indirect |
| golang.org/x/text v0.40.0 // indirect |
| + golang.org/x/time v0.15.0 // indirect |
| gorm.io/plugin/dbresolver v1.6.2 // indirect |
| modernc.org/libc v1.74.1 // indirect |
| modernc.org/mathutil v1.7.1 // indirect |
diff --git a/go.sum b/go.sum| index e8281d7..5cf8cfb 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -1,7 +1,11 @@ |
| +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-20261024225350-d53b8e9533a1 h1:Xaidrm9rzFyne6PujFYXiY7nGRy+/KzH7kGBM2+D5LQ= |
| amadan.net/oficina/estilo.git v0.0.0-20261024225350-d53b8e9533a1/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw= |
| amadan.net/oficina/home/connect v0.0.0-20261001093757-2bec942ddd0c h1:3yxO2D8BxDLMGfFV2o6Sp9Z91yLnjDCIuRKHVWORa8A= |
| amadan.net/oficina/home/connect v0.0.0-20261001093757-2bec942ddd0c/go.mod h1:YroavXe43Wietec+po8mtSk4a9Bir2h31Q3iAf4MWxI= |
| +amadan.net/oficina/home/connect v0.0.0-20261025004522-7430dd23a847 h1:pJYp3kEWLUXXoi4UtRH8SIX+HyAyQUQOaFNE7XuY20Y= |
| +amadan.net/oficina/home/connect v0.0.0-20261025004522-7430dd23a847/go.mod h1:YroavXe43Wietec+po8mtSk4a9Bir2h31Q3iAf4MWxI= |
| amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 h1:RPKtyry/71i06o8L+gjAaUyexbmG56kO1YPs601URAM= |
| amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k= |
| amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060 h1:K2PXcCKfm+AYrqgH1ea6cNsFs4sN7MKLvq+uBY11NZE= |
| @@ -18,6 +22,12 @@ github.com/chromedp/chromedp v0.14.2 h1:r3b/WtwM50RsBZHMUm9fsNhhzRStTHrKdr2zmwbZ |
| github.com/chromedp/chromedp v0.14.2/go.mod h1:rHzAv60xDE7VNy/MYtTUrYreSc0ujt2O1/C3bzctYBo= |
| github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipwM= |
| github.com/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8= |
| +github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ= |
| +github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs= |
| +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= |
| +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= |
| +github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= |
| +github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= |
| github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= |
| github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= |
| github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY= |
| @@ -32,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= |
| @@ -50,20 +70,40 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE |
| github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= |
| github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= |
| github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= |
| +github.com/modelcontextprotocol/go-sdk v1.7.0 h1:yqjY2dsbKAC0LSuWZVBMrHgiG8ukXv6NRo0JiALay44= |
| +github.com/modelcontextprotocol/go-sdk v1.7.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts= |
| github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= |
| github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= |
| github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde h1:x0TT0RDC7UhAVbbWWBzr41ElhJx5tXPWkIHA2HWPRuw= |
| github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0= |
| +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= |
| +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= |
| github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= |
| github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= |
| +github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 h1:1EYB5IzjZawrrnELUi78f9fPu57HuXjmddZPjrls/28= |
| +github.com/santhosh-tekuri/jsonschema/v6 v6.0.3/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU= |
| +github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc= |
| +github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg= |
| +github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0= |
| +github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0= |
| github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0= |
| github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M= |
| +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= |
| +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= |
| +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= |
| +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= |
| github.com/tetratelabs/wazero v1.12.0 h1:DuWcpNu/FzgEXgGBDp8J1Spc+CWOvvtvVyjKlaZopYU= |
| github.com/tetratelabs/wazero v1.12.0/go.mod h1:LvKtzl2RqO4gyF27BiXU+nKAjcV8f38U+kP/q2vgxh0= |
| +github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4= |
| +github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4= |
| +github.com/zalando/go-keyring v0.2.8 h1:6sD/Ucpl7jNq10rM2pgqTs0sZ9V3qMrqfIIy5YPccHs= |
| +github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cmakZDO5QGii0= |
| golang.org/x/image v0.44.0 h1:+tDekMZED9+LrtB3G5xzRggpVh9CARjZqROla3R3R+I= |
| golang.org/x/image v0.44.0/go.mod h1:V8K3KE9KKKE+pLpQDOeN18w9oacNSvy1tDOirTu4xtY= |
| golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= |
| golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= |
| +golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ= |
| +golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= |
| golang.org/x/sync v0.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= |
| @@ -71,8 +111,12 @@ golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= |
| golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= |
| golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= |
| golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= |
| +golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= |
| +golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= |
| golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= |
| golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= |
| +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= |
| +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= |
| gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo= |
| gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM= |
| gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ= |
diff --git a/internal/slides/agent_access.go b/internal/slides/agent_access.go| new file mode 100644 |
| index 0000000..ba8dad6 |
| --- /dev/null |
| +++ b/internal/slides/agent_access.go |
| @@ -0,0 +1,224 @@ |
| +package slides |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "mime" |
| + "net/http" |
| + "strconv" |
| + "strings" |
| + "time" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + "gorm.io/gorm" |
| +) |
| + |
| +var errAgentConfig = errors.New("slides: invalid agent access configuration") |
| + |
| +// ValidateAgentConfig checks delegated access before the executable opens storage. |
| +func ValidateAgentConfig(issuer, team, origin string, home *connect.Credentials) error { |
| + return validateAgentConfig(issuer, team, origin, home) |
| +} |
| + |
| +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 |
| +} |
| + |
| +func (a *app) configureAgentAccess() error { |
| + if a.cfg.AgentIssuer == "" { |
| + return nil |
| + } |
| + settings, e := connect.DecodeCredentials(a.cfg.Home, a.cfg.Origin) |
| + if e != nil { |
| + return e |
| + } |
| + verifier, e := access.NewRemoteVerifier(a.cfg.AgentIssuer, a.cfg.Origin+"/api/v1", settings.Issuer) |
| + if e != nil { |
| + return e |
| + } |
| + agent := &slideAgent{app: a, issuer: a.cfg.AgentIssuer, identityIssuer: settings.Issuer, team: a.cfg.AgentTeam, key: append([]byte(nil), settings.DEK...)} |
| + return a.mountAgent(agent, verifier) |
| +} |
| +func (a *app) mountAgent(agent *slideAgent, verifier access.Verifier) error { |
| + if a.home == nil { |
| + return errAgentConfig |
| + } |
| + if _, e := migrate.Apply(context.Background(), a.db, agentSchema); e != nil { |
| + return e |
| + } |
| + if e := a.db.G.Transaction(func(tx *gorm.DB) error { return agent.bind(tx) }); e != nil { |
| + return e |
| + } |
| + handler, e := agent.httpHandler(verifier) |
| + if e != nil { |
| + return e |
| + } |
| + a.agent = handler |
| + a.agentAccess = agent |
| + return nil |
| +} |
| +func slideAgentWriteFailure(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 *slideAgent) 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") { |
| + slideAgentWriteFailure(w, access.Fail("unauthenticated", "Connect to Oficina first.")) |
| + return |
| + } |
| + p, e := verifier.Verify(r.Context(), parts[1]) |
| + if e != nil { |
| + slideAgentWriteFailure(w, e) |
| + return |
| + } |
| + name := strings.TrimPrefix(r.URL.Path, "/api/v1/operations/") |
| + write := name == "slides_create_deck" |
| + discovery := r.Method == "GET" && r.URL.Path == "/api/v1/operations" |
| + if discovery && !p.Allows(a.team, "slides:read") { |
| + write = true |
| + } |
| + member, e := a.member(r.Context(), p, write) |
| + if e != nil { |
| + slideAgentWriteFailure(w, e) |
| + return |
| + } |
| + state := &slideAgentContext{member: member, slides: map[int64]bool{}} |
| + state.verify = func(ctx context.Context) error { |
| + current, e := verifier.Verify(ctx, parts[1]) |
| + if e != nil { |
| + return e |
| + } |
| + scope := "slides:read" |
| + if write { |
| + scope = "slides: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(), slideAgentKey{}, 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, "/") { |
| + slideAgentWriteFailure(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" { |
| + slideAgentWriteFailure(w, access.Fail("unsupported_media_type", "Send application/json.")) |
| + return |
| + } |
| + raw, e := io.ReadAll(io.LimitReader(r.Body, slideAgentLimit+1)) |
| + if e != nil { |
| + slideAgentWriteFailure(w, access.Fail("invalid", "Could not read the request.")) |
| + return |
| + } |
| + if len(raw) > slideAgentLimit { |
| + slideAgentWriteFailure(w, access.Fail("too_large", "The operation input exceeds 1 MiB.")) |
| + return |
| + } |
| + result, e = registry.Call(ctx, p, name, raw) |
| + if e != nil { |
| + slideAgentWriteFailure(w, e) |
| + return |
| + } |
| + } |
| + body, e := json.Marshal(result) |
| + if e != nil { |
| + slideAgentWriteFailure(w, slideAgentFailure(e)) |
| + return |
| + } |
| + if len(body) > slideAgentLimit { |
| + slideAgentWriteFailure(w, access.Fail("too_large", "The deck 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.Email != member.Email { |
| + return access.Fail("forbidden", "The current identity changed.") |
| + } |
| + for id := range state.slides { |
| + var d Deck |
| + if e := visibleDecksOn(a.app.db.G.WithContext(checkCtx), fresh).Where("decks.id=?", id).Take(&d).Error; e != nil { |
| + return slideAgentFailure(e) |
| + } |
| + } |
| + |
| + if e := checkCtx.Err(); e != nil { |
| + return slideAgentFailure(e) |
| + } |
| + if e := controller.SetWriteDeadline(deadline); e != nil { |
| + return slideAgentFailure(e) |
| + } |
| + return nil |
| + } |
| + if e = check(); e != nil { |
| + slideAgentWriteFailure(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 |
| +} |
diff --git a/internal/slides/agent_attribution.go b/internal/slides/agent_attribution.go| new file mode 100644 |
| index 0000000..519562f |
| --- /dev/null |
| +++ b/internal/slides/agent_attribution.go |
| @@ -0,0 +1,64 @@ |
| +package slides |
| + |
| +import ( |
| + "context" |
| + "strconv" |
| + "strings" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/oficina/home/handoff/seal" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func (a *slideAgent) actor(tx *gorm.DB, p access.Principal, u User) (string, error) { |
| + coordinate := a.digest("actor", []string{a.identityIssuer, a.issuer, p.Subject, p.Client, a.team, strconv.FormatInt(u.ID, 10)}) |
| + sealer, e := seal.New(a.key, "oficina/slides/agent/v1") |
| + if e != nil { |
| + return "", e |
| + } |
| + ciphertext, e := sealer.Seal("client/"+coordinate, []byte(p.Client)) |
| + if e != nil { |
| + return "", e |
| + } |
| + e = tx.Exec("INSERT INTO slides_connections(coordinate,operator_id,client_sealed) VALUES(?,?,?) ON CONFLICT(coordinate) DO NOTHING", coordinate, u.ID, ciphertext).Error |
| + return "connection:" + coordinate, e |
| +} |
| +func (a *app) connectionLabels(ctx context.Context, actors []string) map[string]string { |
| + out := map[string]string{} |
| + if a.cfg.Home == nil { |
| + return out |
| + } |
| + keys := []string{} |
| + for _, actor := range actors { |
| + if key, ok := strings.CutPrefix(actor, "connection:"); ok { |
| + keys = append(keys, key) |
| + } |
| + } |
| + if len(keys) == 0 { |
| + return out |
| + } |
| + var rows []struct { |
| + Coordinate string |
| + ClientSealed []byte |
| + Email string |
| + } |
| + if e := a.db.G.WithContext(ctx).Raw("SELECT c.coordinate,c.client_sealed,u.email FROM slides_connections c JOIN users u ON u.id=c.operator_id WHERE c.coordinate IN ?", keys).Scan(&rows).Error; e != nil { |
| + return out |
| + } |
| + settings, e := connect.DecodeCredentials(a.cfg.Home, a.cfg.Origin) |
| + if e != nil || settings == nil { |
| + return out |
| + } |
| + sealer, e := seal.New(settings.DEK, "oficina/slides/agent/v1") |
| + if e != nil { |
| + return out |
| + } |
| + for _, r := range rows { |
| + client, e := sealer.Open("client/"+r.Coordinate, r.ClientSealed) |
| + if e == nil { |
| + out["connection:"+r.Coordinate] = agentMark + agentPrincipal(string(client), r.Email) |
| + } |
| + } |
| + return out |
| +} |
diff --git a/internal/slides/agent_authority.go b/internal/slides/agent_authority.go| new file mode 100644 |
| index 0000000..97d9e4f |
| --- /dev/null |
| +++ b/internal/slides/agent_authority.go |
| @@ -0,0 +1,147 @@ |
| +package slides |
| + |
| +import ( |
| + "context" |
| + "crypto/hmac" |
| + "crypto/sha256" |
| + "embed" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "io/fs" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/oficina/home/connect/linkstore" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + "gorm.io/gorm" |
| +) |
| + |
| +//go:embed agent_migrations/migrations/*.sql |
| +var agentMigrationFS embed.FS |
| +var agentSchema = func() *migrate.Set { |
| + sub, _ := fs.Sub(agentMigrationFS, "agent_migrations") |
| + return migrate.MustFromFS(sub, "slides_agent") |
| +}() |
| + |
| +const slideAgentLimit = 1 << 20 |
| + |
| +type slideAgent struct { |
| + app *app |
| + issuer, identityIssuer, team string |
| + key []byte |
| +} |
| +type slideAgentContext struct { |
| + member User |
| + verify func(context.Context) error |
| + slides map[int64]bool |
| +} |
| +type slideAgentKey struct{} |
| + |
| +func slideAgentFailure(err error) error { |
| + if err == nil { |
| + return nil |
| + } |
| + var f access.Failure |
| + if errors.As(err, &f) { |
| + return f |
| + } |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return access.Fail("not_found", "This deck is unavailable.") |
| + } |
| + if errors.Is(err, linkstore.ErrRefused) { |
| + return access.Fail("forbidden", "This Home identity is not admitted.") |
| + } |
| + return access.Fail("unavailable", "Deck authority or storage is unavailable.") |
| +} |
| +func (a *slideAgent) digest(domain string, value any) string { |
| + raw, _ := json.Marshal(value) |
| + mac := hmac.New(sha256.New, a.key) |
| + mac.Write([]byte("oficina/slides/agent/v1/" + domain + "\x00")) |
| + mac.Write(raw) |
| + return hex.EncodeToString(mac.Sum(nil)) |
| +} |
| +func (a *slideAgent) bind(tx *gorm.DB) error { |
| + want := a.digest("keycheck", []string{"immutable-authority", a.identityIssuer, a.issuer, a.team}) |
| + if e := tx.Exec("INSERT INTO slides_agent_state(id,keycheck) SELECT 1,? WHERE NOT EXISTS(SELECT 1 FROM slides_agent_receipts) AND NOT EXISTS(SELECT 1 FROM slides_connections) ON CONFLICT(id) DO NOTHING", want).Error; e != nil { |
| + return e |
| + } |
| + var got string |
| + if e := tx.Raw("SELECT keycheck FROM slides_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 *slideAgent) member(ctx context.Context, p access.Principal, write bool) (User, error) { |
| + scope := "slides:read" |
| + if write { |
| + scope = "slides:write" |
| + } |
| + if p.Subject == "" || p.Client == "" || len(p.Client) > 256 || p.Grant == "" || !p.Allows(a.team, scope) { |
| + return User{}, access.Fail("forbidden", "This connection does not allow that team and operation.") |
| + } |
| + if a.app.home == nil { |
| + return User{}, access.Fail("unavailable", "Home identity resolution is unavailable.") |
| + } |
| + person, e := a.app.home.Resolve(ctx, p.Subject) |
| + if e != nil { |
| + return User{}, slideAgentFailure(e) |
| + } |
| + var u User |
| + if e = a.app.db.G.WithContext(ctx).First(&u, person.ID).Error; e != nil { |
| + return User{}, slideAgentFailure(e) |
| + } |
| + if u.ID <= 0 || u.Email != person.Label || !a.app.allowed.allows(u.Email) { |
| + return User{}, slideAgentFailure(linkstore.ErrRefused) |
| + } |
| + return u, nil |
| +} |
| +func slideAgentMember(ctx context.Context) User { |
| + if state, ok := ctx.Value(slideAgentKey{}).(*slideAgentContext); ok && state != nil { |
| + return state.member |
| + } |
| + return User{} |
| +} |
| +func (a *slideAgent) remember(ctx context.Context, id int64) { |
| + if state, ok := ctx.Value(slideAgentKey{}).(*slideAgentContext); ok && state != nil { |
| + state.slides[id] = true |
| + } |
| +} |
| +func (a *slideAgent) writer(ctx context.Context, tx *gorm.DB, p access.Principal, u User) error { |
| + state, ok := ctx.Value(slideAgentKey{}).(*slideAgentContext) |
| + if !ok || state == nil || state.verify == nil { |
| + return linkstore.ErrRefused |
| + } |
| + if e := state.verify(ctx); e != nil { |
| + return e |
| + } |
| + person, e := a.app.home.ResolveOn(ctx, tx.Statement.ConnPool, p.Subject) |
| + if e != nil { |
| + return e |
| + } |
| + if person.ID != u.ID || person.Label != u.Email { |
| + return linkstore.ErrRefused |
| + } |
| + id := person.ID |
| + |
| + var current User |
| + if e := tx.First(¤t, id).Error; e != nil { |
| + return e |
| + } |
| + if current.Email != u.Email || !a.app.allowed.allows(current.Email) { |
| + return linkstore.ErrRefused |
| + } |
| + return nil |
| +} |
| +func slideAgentBounded(value any) (any, error) { |
| + body, e := json.Marshal(value) |
| + if e != nil { |
| + return nil, slideAgentFailure(e) |
| + } |
| + if len(body) > slideAgentLimit { |
| + return nil, access.Fail("too_large", "The deck result exceeds 1 MiB.") |
| + } |
| + return value, nil |
| +} |
diff --git a/internal/slides/agent_authority_test.go b/internal/slides/agent_authority_test.go| new file mode 100644 |
| index 0000000..c21c560 |
| --- /dev/null |
| +++ b/internal/slides/agent_authority_test.go |
| @@ -0,0 +1,222 @@ |
| +package slides |
| + |
| +import ( |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "gorm.io/gorm" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| +) |
| + |
| +func TestAgentDeckAtomicAuthority(t *testing.T) { |
| + for _, mode := range []string{"reserved", "final", "unlink", "binding", "member", "update", "receipt"} { |
| + t.Run(mode, func(t *testing.T) { |
| + f := newSlideAgentFixture(t) |
| + trigger := "" |
| + switch mode { |
| + case "reserved": |
| + f.revokeAt.Store(2) |
| + trigger = "CREATE TRIGGER body_trap BEFORE INSERT ON decks BEGIN SELECT RAISE(ABORT,'body attempted'); END" |
| + case "final": |
| + f.revokeAt.Store(3) |
| + case "unlink": |
| + trigger = "CREATE TRIGGER lose_link AFTER UPDATE OF deck_id ON slides_agent_receipts BEGIN DELETE FROM home_identity_links; END" |
| + case "binding": |
| + trigger = "CREATE TRIGGER lose_binding AFTER INSERT ON deck_updates BEGIN UPDATE home_identity_links SET person_binding='broken'; END" |
| + case "member": |
| + trigger = "CREATE TRIGGER lose_member AFTER UPDATE OF deck_id ON slides_agent_receipts BEGIN UPDATE users SET email='removed@example.com'; END" |
| + case "update": |
| + trigger = "CREATE TRIGGER fail_update BEFORE INSERT ON deck_updates BEGIN SELECT RAISE(ABORT,'write failed'); END" |
| + case "receipt": |
| + trigger = "CREATE TRIGGER fail_receipt BEFORE UPDATE OF deck_id ON slides_agent_receipts BEGIN SELECT RAISE(ABORT,'receipt failed'); END" |
| + } |
| + if trigger != "" { |
| + if e := f.a.app.db.G.Exec(trigger).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + r := f.call(t, "slides_create_deck", initialSlideAgentInput()) |
| + want := 503 |
| + if mode == "reserved" || mode == "final" { |
| + want = 401 |
| + } |
| + if mode == "unlink" || mode == "member" || mode == "binding" { |
| + want = 403 |
| + } |
| + if r.Code != want { |
| + t.Fatal(mode, r.Code, r.Body.String()) |
| + } |
| + for _, table := range []string{"decks", "deck_updates", "slides_agent_receipts", "slides_connections"} { |
| + var n int |
| + if e := f.a.app.db.G.Raw("SELECT COUNT(*) FROM " + table).Scan(&n).Error; e != nil || n != 0 { |
| + t.Fatal("partial create", table, n, e) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| +func TestAgentDeckRetryAndMarker(t *testing.T) { |
| + for _, mode := range []string{"retry-final", "marker-create", "marker-retry"} { |
| + t.Run(mode, func(t *testing.T) { |
| + f := newSlideAgentFixture(t) |
| + in := initialSlideAgentInput() |
| + slideCreated(t, f.call(t, "slides_create_deck", in)) |
| + want := 503 |
| + if mode == "retry-final" { |
| + f.checks.Store(0) |
| + f.revokeAt.Store(3) |
| + want = 401 |
| + } else { |
| + if e := f.a.app.db.G.Exec("UPDATE slides_agent_state SET keycheck='damaged'").Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if mode == "marker-create" { |
| + in.ClientID = initialSlideAgentInput().ClientID |
| + } |
| + } |
| + if r := f.call(t, "slides_create_deck", in); r.Code != want { |
| + t.Fatal(mode, r.Code) |
| + } |
| + var n int |
| + f.a.app.db.G.Raw("SELECT COUNT(*) FROM decks").Scan(&n) |
| + if n != 1 { |
| + t.Fatal(n) |
| + } |
| + }) |
| + } |
| +} |
| +func TestAgentDeckPrincipalContinuity(t *testing.T) { |
| + for _, field := range []string{"subject", "client", "grant", "team", "scope"} { |
| + t.Run(field, func(t *testing.T) { |
| + f := newSlideAgentFixture(t) |
| + var checks atomic.Int64 |
| + e := f.a.app.mountAgent(f.a, access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| + p := f.p |
| + if checks.Add(1) > 1 { |
| + switch field { |
| + case "subject": |
| + p.Subject = "other" |
| + case "client": |
| + p.Client = "other" |
| + case "grant": |
| + p.Grant = "other" |
| + case "team": |
| + p.Teams = []string{"other"} |
| + case "scope": |
| + p.Scopes = []string{"slides:read"} |
| + } |
| + } |
| + return p, nil |
| + })) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if r := f.call(t, "slides_create_deck", initialSlideAgentInput()); r.Code != 403 { |
| + t.Fatal(r.Code) |
| + } |
| + var n int |
| + f.a.app.db.G.Raw("SELECT COUNT(*) FROM decks").Scan(&n) |
| + if n != 0 { |
| + t.Fatal(n) |
| + } |
| + }) |
| + } |
| +} |
| +func TestAgentDeckDurableBinding(t *testing.T) { |
| + f := newSlideAgentFixture(t) |
| + in := initialSlideAgentInput() |
| + sqid := slideCreated(t, f.call(t, "slides_create_deck", in)) |
| + var path string |
| + if e := f.a.app.db.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path); e != nil { |
| + t.Fatal(e) |
| + } |
| + f.a.app.Close() |
| + f.a.app.db.Close() |
| + d, e := db.Open(path, quietLogger()) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer d.Close() |
| + _, app, e := New(d, f.a.app.cfg) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer app.Close() |
| + f.a.app = app |
| + f.install(t) |
| + if retry := slideCreated(t, f.call(t, "slides_create_deck", in)); retry != sqid { |
| + t.Fatal("restart lost receipt") |
| + } |
| + for _, mode := range []string{"home", "issuer", "team", "key"} { |
| + t.Run(mode, func(t *testing.T) { |
| + copy := *f.a |
| + switch mode { |
| + case "home": |
| + copy.identityIssuer = "https://other-home.test" |
| + case "issuer": |
| + copy.issuer = "https://other-connect.test" |
| + case "team": |
| + copy.team = "other" |
| + case "key": |
| + copy.key = bytes.Repeat([]byte{41}, 32) |
| + } |
| + if e := app.db.G.Transaction(copy.bind); e == nil { |
| + t.Fatal("rebound authority") |
| + } |
| + }) |
| + } |
| + if e := app.db.G.Exec("DELETE FROM slides_agent_state").Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + for _, table := range []string{"slides_connections", "slides_agent_receipts"} { |
| + t.Run(table, func(t *testing.T) { |
| + e := app.db.G.Transaction(func(tx *gorm.DB) error { |
| + if e := tx.Exec("DELETE FROM " + table).Error; e != nil { |
| + return e |
| + } |
| + if e := f.a.bind(tx); e == nil { |
| + t.Fatal("adopted old state") |
| + } |
| + return gorm.ErrInvalidTransaction |
| + }) |
| + if e != gorm.ErrInvalidTransaction { |
| + t.Fatal(e) |
| + } |
| + }) |
| + } |
| +} |
| +func TestAgentDeckMalformedUnicode(t *testing.T) { |
| + f := newSlideAgentFixture(t) |
| + in := initialSlideAgentInput() |
| + in.Title = "REPLACEME" |
| + raw, _ := json.Marshal(in) |
| + for _, bad := range []string{`\ud800`, string([]byte{255})} { |
| + if r := f.raw(t, "slides_create_deck", []byte(strings.Replace(string(raw), "REPLACEME", bad, 1))); r.Code != 422 { |
| + t.Fatal(r.Code) |
| + } |
| + } |
| +} |
| + |
| +// Call the transaction body directly so a later response check cannot mask |
| +// omission of the completed receipt's final in-transaction guard. |
| +func TestAgentDeckCompletedRetryWriterGuard(t *testing.T) { |
| + f := newSlideAgentFixture(t) |
| + in := initialSlideAgentInput() |
| + slideCreated(t, f.call(t, "slides_create_deck", in)) |
| + var checks int |
| + state := &slideAgentContext{member: f.u, slides: map[int64]bool{}, verify: func(context.Context) error { |
| + checks++ |
| + if checks >= 2 { |
| + return access.Fail("unauthenticated", "Revoked.") |
| + } |
| + return nil |
| + }} |
| + ctx := context.WithValue(t.Context(), slideAgentKey{}, state) |
| + if _, e := f.a.create(ctx, f.p, f.u, in); e == nil || access.SafeFailure(e).Code != "unauthenticated" { |
| + t.Fatal("completed retry omitted final writer guard", e) |
| + } |
| +} |
diff --git a/internal/slides/agent_config_test.go b/internal/slides/agent_config_test.go| new file mode 100644 |
| index 0000000..d5368b9 |
| --- /dev/null |
| +++ b/internal/slides/agent_config_test.go |
| @@ -0,0 +1,95 @@ |
| +package slides |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "net/http/httptest" |
| + "testing" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| +) |
| + |
| +func TestAgentDeckConfigurationAndRouter(t *testing.T) { |
| + _, base, _ := homeFixture(t) |
| + for _, mode := range []string{"issuer-only", "team-only", "no-home", "same-issuer"} { |
| + t.Run(mode, func(t *testing.T) { |
| + cfg := base.cfg |
| + cfg.AgentIssuer = "https://connect.example.com" |
| + cfg.AgentTeam = "blue" |
| + switch mode { |
| + case "issuer-only": |
| + cfg.AgentTeam = "" |
| + case "team-only": |
| + cfg.AgentIssuer = "" |
| + case "no-home": |
| + cfg.Home = nil |
| + case "same-issuer": |
| + cfg.AgentIssuer = cfg.Home.Issuer |
| + } |
| + d := testDB(t) |
| + if _, a, e := New(d, cfg); e == nil { |
| + a.Close() |
| + t.Fatal("partial authority accepted") |
| + } |
| + var n int |
| + if e := d.Writer().QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='decks'").Scan(&n); e != nil || n != 0 { |
| + t.Fatal("mutated database on invalid config", n, e) |
| + } |
| + }) |
| + } |
| + cfg := base.cfg |
| + cfg.AgentIssuer = "https://connect.example.com" |
| + cfg.AgentTeam = "blue" |
| + mux, a, e := New(testDB(t), cfg) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer a.Close() |
| + u := User{ID: 72, Email: "owner@example.com"} |
| + if e = a.db.G.Create(&u).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + homeLinked(t, a, u) |
| + if e = a.mountAgent(a.agentAccess, access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| + return access.Principal{Subject: "home-person", Client: "fixture", Grant: "grant", Teams: []string{"blue"}, Scopes: []string{"slides:read", "slides:write"}}, nil |
| + })); e != nil { |
| + t.Fatal(e) |
| + } |
| + // The production mux captured the startup handler; use an introspection server |
| + // test separately for actual remote verification. The specific operation paths |
| + // must nevertheless be outside browser CSRF and reject an absent bearer as JSON. |
| + r := httptest.NewRequest("POST", homeTestOrigin+"/api/v1/operations/slides_create_deck", bytes.NewReader([]byte(`{}`))) |
| + w := httptest.NewRecorder() |
| + mux.ServeHTTP(w, r) |
| + if w.Code != 401 || !json.Valid(w.Body.Bytes()) { |
| + t.Fatal("bearer route hidden by browser CSRF", w.Code, w.Body.String()) |
| + } |
| + disabled, app, e := New(testDB(t), base.cfg) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer app.Close() |
| + w = httptest.NewRecorder() |
| + disabled.ServeHTTP(w, r) |
| + if app.agent != nil || w.Code == 200 { |
| + t.Fatal("disabled connection active", w.Code) |
| + } |
| +} |
| +func TestAgentDeckHistoricalAttributionAndSealBinding(t *testing.T) { |
| + f := newSlideAgentFixture(t) |
| + slideCreated(t, f.call(t, "slides_create_deck", initialSlideAgentInput())) |
| + var update DeckUpdate |
| + f.a.app.db.G.Take(&update) |
| + f.a.app.agentAccess = nil |
| + f.a.app.agent = nil |
| + if label := f.a.app.actorLabels(t.Context(), []string{update.Actor})[update.Actor]; label == "" { |
| + t.Fatal("disabled connection erased history") |
| + } |
| + if e := f.a.app.db.G.Exec("UPDATE slides_connections SET coordinate='other'").Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if label := f.a.app.actorLabels(t.Context(), []string{"connection:other"})["connection:other"]; label != "" { |
| + t.Fatal("ciphertext moved to unrelated actor", label) |
| + } |
| +} |
diff --git a/internal/slides/agent_create.go b/internal/slides/agent_create.go| new file mode 100644 |
| index 0000000..e03df53 |
| --- /dev/null |
| +++ b/internal/slides/agent_create.go |
| @@ -0,0 +1,147 @@ |
| +package slides |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "strconv" |
| + "strings" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/oficina/slides/internal/slides/core" |
| + "amadan.net/oficina/slides/internal/slides/deck" |
| + "github.com/google/uuid" |
| + "gorm.io/gorm" |
| +) |
| + |
| +type slideAgentInitial struct { |
| + Heading string `json:"heading"` |
| + Body string `json:"body_markdown"` |
| + Notes string `json:"notes_markdown"` |
| +} |
| +type slideAgentCreate struct { |
| + Team string `json:"team"` |
| + ClientID string `json:"client_id"` |
| + Title string `json:"title"` |
| + Theme string `json:"theme,omitempty"` |
| + Slides []slideAgentInitial `json:"slides"` |
| +} |
| + |
| +func (a *slideAgent) create(ctx context.Context, p access.Principal, u User, in slideAgentCreate) (any, error) { |
| + id, e := uuid.Parse(in.ClientID) |
| + if e != nil || id == uuid.Nil || id.String() != in.ClientID { |
| + return nil, access.Fail("invalid", "Supply a canonical nonzero UUID client_id.") |
| + } |
| + in.Title = strings.TrimSpace(in.Title) |
| + if in.Theme == "" { |
| + in.Theme = defaultTheme |
| + } |
| + if in.Title == "" || len(in.Title) > 512 || !validTheme(in.Theme) || len(in.Slides) < 1 || len(in.Slides) > 50 { |
| + return nil, access.Fail("invalid", "Supply a title, supported theme and one to fifty slides.") |
| + } |
| + n := 0 |
| + for _, s := range in.Slides { |
| + n += len(s.Heading) + len(s.Body) + len(s.Notes) |
| + } |
| + if n > 128<<10 { |
| + return nil, access.Fail("too_large", "Initial slide text exceeds 128 KiB.") |
| + } |
| + coordinate := a.digest("receipt", []string{a.identityIssuer, a.issuer, p.Subject, p.Client, a.team, in.ClientID}) |
| + content := a.digest("content", in) |
| + var d Deck |
| + var h *core.Handle |
| + created := false |
| + defer func() { |
| + if h != nil { |
| + h.Close(ctx) |
| + } |
| + }() |
| + e = a.app.db.G.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| + if e := a.bind(tx); e != nil { |
| + return e |
| + } |
| + if e := a.writer(ctx, tx, p, u); e != nil { |
| + return e |
| + } |
| + if e := tx.Exec("INSERT INTO slides_agent_receipts(coordinate,content) VALUES(?,?) ON CONFLICT(coordinate) DO NOTHING", coordinate, content).Error; e != nil { |
| + return e |
| + } |
| + var saved string |
| + var deckID sql.NullInt64 |
| + if e := tx.Raw("SELECT content,deck_id FROM slides_agent_receipts WHERE coordinate=?", coordinate).Row().Scan(&saved, &deckID); e != nil { |
| + return e |
| + } |
| + if saved != content { |
| + return access.Fail("conflict", "This client_id was already used with different deck content.") |
| + } |
| + if deckID.Valid { |
| + if e := visibleDecksOn(tx, u).Where("decks.id=?", deckID.Int64).Take(&d).Error; e != nil { |
| + return e |
| + } |
| + return a.writer(ctx, tx, p, u) |
| + } |
| + var e error |
| + d, e = createDeckRowOn(ctx, tx, u, in.Title, in.Theme) |
| + if e != nil { |
| + return e |
| + } |
| + h, e = a.app.core.NewDoc(ctx, d.Sqid, serverClientID) |
| + if e != nil { |
| + return e |
| + } |
| + ops, e := slideAgentOps(in) |
| + if e != nil { |
| + return e |
| + } |
| + actor, e := a.actor(tx, p, u) |
| + if e != nil { |
| + return e |
| + } |
| + if e = applyOpsOn(ctx, tx, h, &d, actor, ops, nil); e != nil { |
| + return e |
| + } |
| + if e = h.Check(ctx); e != nil { |
| + return e |
| + } |
| + raw, e := h.JSON(ctx) |
| + if e != nil { |
| + return e |
| + } |
| + if _, e = deck.Parse(raw); e != nil { |
| + return e |
| + } |
| + done := tx.Exec("UPDATE slides_agent_receipts SET deck_id=? WHERE coordinate=? AND deck_id IS NULL", d.ID, coordinate) |
| + if done.Error != nil { |
| + return done.Error |
| + } |
| + if done.RowsAffected != 1 { |
| + return access.Fail("unavailable", "The creation receipt could not be completed.") |
| + } |
| + if e = a.writer(ctx, tx, p, u); e != nil { |
| + return e |
| + } |
| + d.Seq++ |
| + created = true |
| + return nil |
| + }) |
| + if e != nil { |
| + return nil, slideAgentFailure(e) |
| + } |
| + if created { |
| + a.app.live.PublishSeq(d.Sqid, d.Seq) |
| + a.app.maybeSnapshot(ctx, d, h, d.Seq) |
| + } |
| + a.remember(ctx, d.ID) |
| + return map[string]any{"sqid": d.Sqid, "url": a.app.cfg.Origin + "/d/" + d.Sqid, "revision": strconv.FormatInt(d.Seq, 10)}, nil |
| +} |
| +func slideAgentOps(in slideAgentCreate) ([]byte, error) { |
| + ops := []op{{"op": "set_meta", "title": in.Title, "theme": in.Theme}} |
| + for _, s := range in.Slides { |
| + id, blocks, e := slideIDs(2) |
| + if e != nil { |
| + return nil, e |
| + } |
| + ops = append(ops, addSlide(id, "title-body"), addBlock(id, blocks[0], "heading", "heading", s.Heading, map[string]any{"level": 1}), addBlock(id, blocks[1], "text", "body", s.Body, nil), op{"op": "set_notes", "id": id, "markdown": s.Notes}) |
| + } |
| + return json.Marshal(ops) |
| +} |
diff --git a/internal/slides/agent_create_test.go b/internal/slides/agent_create_test.go| new file mode 100644 |
| index 0000000..8812256 |
| --- /dev/null |
| +++ b/internal/slides/agent_create_test.go |
| @@ -0,0 +1,84 @@ |
| +package slides |
| + |
| +import ( |
| + "encoding/json" |
| + "strings" |
| + "sync" |
| + "testing" |
| +) |
| + |
| +func TestAgentDeckCreateRealCoreAndRetry(t *testing.T) { |
| + f := newSlideAgentFixture(t) |
| + in := initialSlideAgentInput() |
| + sqid := slideCreated(t, f.call(t, "slides_create_deck", in)) |
| + get := func() string { |
| + r := f.call(t, "slides_get_deck", map[string]any{"team": "blue", "sqid": sqid}) |
| + if r.Code != 200 { |
| + t.Fatal(r.Code, r.Body.String()) |
| + } |
| + return r.Body.String() |
| + } |
| + if b := get(); !strings.Contains(b, "REAL_DECK_CANARY") || !strings.Contains(b, "Speaker notes") { |
| + t.Fatal(b) |
| + } |
| + var d Deck |
| + if e := f.a.app.db.G.Where("sqid=?", sqid).Take(&d).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + var update DeckUpdate |
| + f.a.app.db.G.Where("deck_id=?", d.ID).Take(&update) |
| + if !strings.HasPrefix(update.Actor, "connection:") { |
| + t.Fatal(update.Actor) |
| + } |
| + if label := f.a.app.actorLabels(t.Context(), []string{update.Actor})[update.Actor]; !strings.Contains(label, "test-client") || !strings.Contains(label, f.u.Email) { |
| + t.Fatal("attribution missing", label) |
| + } |
| + ops, _ := json.Marshal([]op{{"op": "set_meta", "title": "Later browser edit"}}) |
| + if e := f.a.app.editDeck(t.Context(), &d, actorFor(f.u), ops, map[string]any{"title": "Later browser edit"}); e != nil { |
| + t.Fatal(e) |
| + } |
| + if retry := slideCreated(t, f.call(t, "slides_create_deck", in)); retry != sqid { |
| + t.Fatal("new deck on retry") |
| + } |
| + if !strings.Contains(get(), "Later browser edit") { |
| + t.Fatal("retry overwrote content") |
| + } |
| + in.Title = "different" |
| + if r := f.call(t, "slides_create_deck", in); r.Code != 409 { |
| + t.Fatal(r.Code) |
| + } |
| + in.Title = "Deck ✓" |
| + if e := f.a.app.db.G.Delete(&d).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if r := f.call(t, "slides_create_deck", in); r.Code != 404 { |
| + t.Fatal("deleted deck recreated", r.Code) |
| + } |
| +} |
| +func TestAgentDeckConcurrentFirstCreate(t *testing.T) { |
| + f := newSlideAgentFixture(t) |
| + in := initialSlideAgentInput() |
| + var wg sync.WaitGroup |
| + ids := make(chan string, 6) |
| + for i := 0; i < 6; i++ { |
| + wg.Add(1) |
| + go func() { defer wg.Done(); ids <- slideCreated(t, f.call(t, "slides_create_deck", in)) }() |
| + } |
| + wg.Wait() |
| + close(ids) |
| + first := "" |
| + for id := range ids { |
| + if first == "" { |
| + first = id |
| + } |
| + if id != first { |
| + t.Fatal("duplicate deck") |
| + } |
| + } |
| + for _, table := range []string{"decks", "deck_updates", "slides_agent_receipts", "slides_connections"} { |
| + var n int |
| + if e := f.a.app.db.G.Raw("SELECT COUNT(*) FROM " + table).Scan(&n).Error; e != nil || n != 1 { |
| + t.Fatal(table, n, e) |
| + } |
| + } |
| +} |
diff --git a/internal/slides/agent_fixture_test.go b/internal/slides/agent_fixture_test.go| new file mode 100644 |
| index 0000000..efe047b |
| --- /dev/null |
| +++ b/internal/slides/agent_fixture_test.go |
| @@ -0,0 +1,94 @@ |
| +package slides |
| + |
| +import ( |
| + access "amadan.net/oficina/agent-access.git" |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "github.com/google/uuid" |
| + "net/http/httptest" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| +) |
| + |
| +type slideAgentFixture struct { |
| + a *slideAgent |
| + u User |
| + p access.Principal |
| + checks atomic.Int64 |
| + revokeAt atomic.Int64 |
| +} |
| +type agentDeadlineRecorder struct { |
| + *httptest.ResponseRecorder |
| + afterWrite func() |
| +} |
| + |
| +func (*agentDeadlineRecorder) SetWriteDeadline(time.Time) error { return nil } |
| +func (w *agentDeadlineRecorder) Write(b []byte) (int, error) { |
| + n, e := w.ResponseRecorder.Write(b) |
| + if w.afterWrite != nil { |
| + f := w.afterWrite |
| + w.afterWrite = nil |
| + f() |
| + } |
| + return n, e |
| +} |
| +func newSlideAgentFixture(t *testing.T, issuers ...string) *slideAgentFixture { |
| + _, app, u := homeFixture(t) |
| + homeLinked(t, app, u) |
| + issuer := "https://connect.example.com" |
| + if len(issuers) > 0 { |
| + issuer = issuers[0] |
| + } |
| + a := &slideAgent{app: app, issuer: issuer, identityIssuer: app.cfg.Home.Issuer, team: "blue", key: bytes.Repeat([]byte{8}, 32)} |
| + f := &slideAgentFixture{a: a, u: u, p: access.Principal{Subject: "home-person", Client: "test-client", Grant: "grant-one", Teams: []string{"blue"}, Scopes: []string{"slides:read", "slides:write"}}} |
| + f.install(t) |
| + return f |
| +} |
| +func (f *slideAgentFixture) install(t *testing.T) { |
| + t.Helper() |
| + e := f.a.app.mountAgent(f.a, access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| + n := f.checks.Add(1) |
| + if at := f.revokeAt.Load(); at > 0 && n >= at { |
| + return access.Principal{}, access.Fail("unauthenticated", "Revoked.") |
| + } |
| + return f.p, nil |
| + })) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| +} |
| +func (f *slideAgentFixture) raw(t *testing.T, name string, raw []byte) *httptest.ResponseRecorder { |
| + t.Helper() |
| + r := httptest.NewRequest("POST", homeTestOrigin+"/api/v1/operations/"+name, bytes.NewReader(raw)) |
| + r.Header.Set("Authorization", "Bearer test-token") |
| + r.Header.Set("Content-Type", "application/json") |
| + w := &agentDeadlineRecorder{ResponseRecorder: httptest.NewRecorder()} |
| + f.a.app.agent.ServeHTTP(w, r) |
| + return w.ResponseRecorder |
| +} |
| +func (f *slideAgentFixture) call(t *testing.T, name string, input any) *httptest.ResponseRecorder { |
| + t.Helper() |
| + b, e := json.Marshal(input) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + return f.raw(t, name, b) |
| +} |
| +func initialSlideAgentInput() slideAgentCreate { |
| + return slideAgentCreate{Team: "blue", ClientID: uuid.NewString(), Title: "Deck ✓", Slides: []slideAgentInitial{{Heading: "Welcome", Body: "**REAL_DECK_CANARY**", Notes: "Speaker notes"}}} |
| +} |
| +func slideCreated(t *testing.T, r *httptest.ResponseRecorder) string { |
| + t.Helper() |
| + if r.Code != 200 { |
| + t.Fatal(r.Code, r.Body.String()) |
| + } |
| + var v struct { |
| + Sqid string `json:"sqid"` |
| + } |
| + if e := json.Unmarshal(r.Body.Bytes(), &v); e != nil || v.Sqid == "" { |
| + t.Fatal(e, r.Body.String()) |
| + } |
| + return v.Sqid |
| +} |
diff --git a/internal/slides/agent_integration_test.go b/internal/slides/agent_integration_test.go| new file mode 100644 |
| index 0000000..b577be4 |
| --- /dev/null |
| +++ b/internal/slides/agent_integration_test.go |
| @@ -0,0 +1,154 @@ |
| +package slides |
| + |
| +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 Slides' real handlers, linked identity, canonical deck content. |
| +// The signed Home/browser/PKCE flow is exercised in the connection module. |
| +func TestAgentGatewayToRealSlides(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 := newSlideAgentFixture(t, issuer.URL) |
| + p := f.p |
| + input, _ := json.Marshal(initialSlideAgentInput()) |
| + 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: "https://home.example.com", 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{"slides:read": "Read presentations", "slides:write": "Create presentations"}, 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", "https://home.example.com") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + remote.Client.Transport = issuer.Client().Transport |
| + f.a.app.cfg.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, "slides_create_deck", json.RawMessage(input)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + encoded, _ := json.Marshal(result) |
| + var deck struct { |
| + Sqid string `json:"sqid"` |
| + } |
| + if json.Unmarshal(encoded, &deck) != nil || deck.Sqid == "" { |
| + t.Fatal("invalid deck receipt") |
| + } |
| + mcpClient := mcp.NewClient(&mcp.Implementation{Name: "Slides 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: "slides_create_deck", Arguments: json.RawMessage(input)}) |
| + if err != nil || retry.IsError { |
| + t.Fatal("MCP retry", retry, err) |
| + } |
| + search, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "slides_get_deck", Arguments: map[string]any{"team": "blue", "sqid": deck.Sqid}}) |
| + if err != nil || search.IsError { |
| + t.Fatal("MCP search", search, err) |
| + } |
| + text, _ := json.Marshal(search.Content) |
| + if !strings.Contains(string(text), "REAL_DECK_CANARY") { |
| + t.Fatal("MCP could not read created deck") |
| + } |
| + var count int |
| + if err = f.a.app.db.G.Raw("SELECT COUNT(*) FROM decks").Scan(&count).Error; err != nil || count != 1 { |
| + t.Fatal("transport retry duplicated deck", count, err) |
| + } |
| + if err = cli.Logout(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = session.CallTool(ctx, &mcp.CallToolParams{Name: "slides_create_deck", Arguments: initialSlideAgentInput()}); err == nil { |
| + t.Fatal("MCP survived CLI revocation") |
| + } |
| + if err = f.a.app.db.G.Raw("SELECT COUNT(*) FROM decks").Scan(&count).Error; err != nil || count != 1 { |
| + t.Fatal("revoked call wrote deck", count, err) |
| + } |
| +} |
diff --git a/internal/slides/agent_migrations/migrations/0001_connections.sql b/internal/slides/agent_migrations/migrations/0001_connections.sql| new file mode 100644 |
| index 0000000..66e9e63 |
| --- /dev/null |
| +++ b/internal/slides/agent_migrations/migrations/0001_connections.sql |
| @@ -0,0 +1,3 @@ |
| +CREATE TABLE slides_agent_state(id INTEGER PRIMARY KEY, keycheck TEXT NOT NULL); |
| +CREATE TABLE slides_agent_receipts(coordinate TEXT PRIMARY KEY, content TEXT NOT NULL, deck_id INTEGER); |
| +CREATE TABLE slides_connections(coordinate TEXT PRIMARY KEY, operator_id INTEGER NOT NULL, client_sealed BLOB NOT NULL); |
diff --git a/internal/slides/agent_operations.go b/internal/slides/agent_operations.go| new file mode 100644 |
| index 0000000..c8aeb15 |
| --- /dev/null |
| +++ b/internal/slides/agent_operations.go |
| @@ -0,0 +1,94 @@ |
| +package slides |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + strictjson "github.com/go-json-experiment/json" |
| +) |
| + |
| +func slideAgentObject(props map[string]any, required ...string) json.RawMessage { |
| + b, _ := json.Marshal(map[string]any{"type": "object", "properties": props, "required": required, "additionalProperties": false}) |
| + return b |
| +} |
| +func slideAgentString(max int) map[string]any { |
| + return map[string]any{"type": "string", "maxLength": max} |
| +} |
| +func (a *slideAgent) registry() (*access.Registry, error) { |
| + input := func(props map[string]any, required ...string) json.RawMessage { |
| + props["team"] = map[string]any{"type": "string", "minLength": 1, "maxLength": 128} |
| + return slideAgentObject(props, append([]string{"team"}, required...)...) |
| + } |
| + sqid := map[string]any{"type": "string", "pattern": "^[23456789abcdefghjkmnpqrstuvwxyz]{10}$"} |
| + revision := map[string]any{"type": "string", "pattern": "^(0|[1-9][0-9]{0,18})$"} |
| + summary := slideAgentObject(map[string]any{"sqid": sqid, "title": slideAgentString(slideAgentLimit), "theme": slideAgentString(128), "revision": revision}, "sqid", "title", "theme", "revision") |
| + initial := slideAgentObject(map[string]any{"heading": slideAgentString(128 << 10), "body_markdown": slideAgentString(128 << 10), "notes_markdown": slideAgentString(128 << 10)}, "heading", "body_markdown", "notes_markdown") |
| + ops := []access.Operation{ |
| + {Name: "slides_list_decks", Description: "List currently readable presentations in this team.", Scope: "slides:read", ReadOnly: true, Idempotent: true, Input: input(map[string]any{"limit": map[string]any{"type": "integer", "minimum": 1, "maximum": 100}, "cursor": map[string]any{"type": "string", "pattern": "^[1-9][0-9]{0,18}$"}}), Output: slideAgentObject(map[string]any{"decks": map[string]any{"type": "array", "maxItems": 100, "items": summary}, "next_cursor": slideAgentString(19)}, "decks", "next_cursor"), 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, slideAgentMember(ctx), in.Limit, in.Cursor) |
| + }}, |
| + {Name: "slides_get_deck", Description: "Read a presentation's canonical block tree and speaker notes at one revision.", Scope: "slides:read", ReadOnly: true, Idempotent: true, Input: input(map[string]any{"sqid": sqid}, "sqid"), Output: slideAgentObject(map[string]any{"sqid": sqid, "revision": revision, "deck": map[string]any{"type": "object"}}, "sqid", "revision", "deck"), Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) { |
| + var in struct { |
| + Sqid string `json:"sqid"` |
| + } |
| + if json.Unmarshal(raw, &in) != nil { |
| + return nil, access.Fail("invalid", "Invalid deck identifier.") |
| + } |
| + return a.get(ctx, slideAgentMember(ctx), in.Sqid) |
| + }}, |
| + {Name: "slides_create_deck", Description: "Create a private presentation with up to fifty initial slides. Reuse the same client UUID only for retries.", Scope: "slides:write", Idempotent: true, Input: input(map[string]any{"client_id": slideAgentString(36), "title": map[string]any{"type": "string", "minLength": 1, "maxLength": 512}, "theme": map[string]any{"enum": themeIDs}, "slides": map[string]any{"type": "array", "minItems": 1, "maxItems": 50, "items": initial}}, "client_id", "title", "slides"), Output: slideAgentObject(map[string]any{"sqid": sqid, "url": slideAgentString(4096), "revision": revision}, "sqid", "url", "revision"), Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) { |
| + var in slideAgentCreate |
| + if json.Unmarshal(raw, &in) != nil { |
| + return nil, access.Fail("invalid", "Invalid initial deck arguments.") |
| + } |
| + return a.create(ctx, p, slideAgentMember(ctx), in) |
| + }}, |
| + } |
| + for i := range ops { |
| + scope, invoke := ops[i].Scope, 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) > slideAgentLimit { |
| + 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.") |
| + } |
| + u, e := a.member(ctx, p, scope == "slides:write") |
| + if e != nil { |
| + return nil, e |
| + } |
| + state, ok := ctx.Value(slideAgentKey{}).(*slideAgentContext) |
| + if !ok || state == nil { |
| + return nil, access.Fail("unavailable", "Request authority is unavailable.") |
| + } |
| + if state.member.ID != u.ID || state.member.Email != u.Email { |
| + return nil, access.Fail("forbidden", "The current identity changed.") |
| + } |
| + return invoke(ctx, p, raw) |
| + } |
| + } |
| + return access.NewRegistry(ops...) |
| +} |
| +func AgentContracts() ([]access.Operation, error) { |
| + a := &slideAgent{team: "contract"} |
| + r, e := a.registry() |
| + if e != nil { |
| + return nil, e |
| + } |
| + return r.List(access.Principal{Subject: "contract", Teams: []string{"contract"}, Scopes: []string{"slides:read", "slides:write"}}), nil |
| +} |
diff --git a/internal/slides/agent_read.go b/internal/slides/agent_read.go| new file mode 100644 |
| index 0000000..d10ff30 |
| --- /dev/null |
| +++ b/internal/slides/agent_read.go |
| @@ -0,0 +1,58 @@ |
| +package slides |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "strconv" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| +) |
| + |
| +func (a *slideAgent) list(ctx context.Context, u User, limit int, cursor string) (any, error) { |
| + if limit == 0 { |
| + limit = 20 |
| + } |
| + if limit < 1 || limit > 100 { |
| + return nil, access.Fail("invalid", "Limit must be one to one hundred.") |
| + } |
| + q := a.app.visibleDecks(ctx, u) |
| + if cursor != "" { |
| + id, e := strconv.ParseInt(cursor, 10, 64) |
| + if e != nil || id <= 0 || strconv.FormatInt(id, 10) != cursor { |
| + return nil, access.Fail("invalid", "Use a canonical positive decimal cursor.") |
| + } |
| + q = q.Where("decks.id<?", id) |
| + } |
| + rows := []Deck{} |
| + if e := q.Order("decks.id DESC").Limit(limit + 1).Find(&rows).Error; e != nil { |
| + return nil, slideAgentFailure(e) |
| + } |
| + next := "" |
| + if len(rows) > limit { |
| + rows = rows[:limit] |
| + next = strconv.FormatInt(rows[len(rows)-1].ID, 10) |
| + } |
| + out := []map[string]any{} |
| + for _, d := range rows { |
| + a.remember(ctx, d.ID) |
| + out = append(out, map[string]any{"sqid": d.Sqid, "title": d.Title, "theme": d.Theme, "revision": strconv.FormatInt(d.Seq, 10)}) |
| + } |
| + return slideAgentBounded(map[string]any{"decks": out, "next_cursor": next}) |
| +} |
| +func (a *slideAgent) get(ctx context.Context, u User, sqid string) (any, error) { |
| + var d Deck |
| + if e := a.app.visibleDecks(ctx, u).Where("sqid=?", sqid).Take(&d).Error; e != nil { |
| + return nil, slideAgentFailure(e) |
| + } |
| + h, _, e := a.app.openDeck(ctx, d) |
| + if e != nil { |
| + return nil, slideAgentFailure(e) |
| + } |
| + defer h.Close(ctx) |
| + raw, e := h.JSON(ctx) |
| + if e != nil { |
| + return nil, slideAgentFailure(e) |
| + } |
| + a.remember(ctx, d.ID) |
| + return slideAgentBounded(map[string]any{"sqid": d.Sqid, "revision": strconv.FormatInt(d.Seq, 10), "deck": json.RawMessage(raw)}) |
| +} |
diff --git a/internal/slides/agent_read_test.go b/internal/slides/agent_read_test.go| new file mode 100644 |
| index 0000000..0fc930c |
| --- /dev/null |
| +++ b/internal/slides/agent_read_test.go |
| @@ -0,0 +1,140 @@ |
| +package slides |
| + |
| +import ( |
| + access "amadan.net/oficina/agent-access.git" |
| + "encoding/json" |
| + "strconv" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestAgentDeckVisibilityAndExactCursor(t *testing.T) { |
| + f := newSlideAgentFixture(t) |
| + const base = int64(9007199254740992) |
| + rows := []Deck{{ID: base + 1, Sqid: "23456789ab", Title: "owned", OwnerID: f.u.ID, Rung: rungPrivate, Theme: "paper"}, {ID: base + 2, Sqid: "23456789ac", Title: "team", OwnerID: 99, Rung: rungTeam, Theme: "paper"}, {ID: base + 3, Sqid: "23456789ad", Title: "granted", OwnerID: 99, Rung: rungGranted, Theme: "paper"}, {ID: base + 4, Sqid: "23456789ae", Title: "PRIVATE_DENIED", OwnerID: 99, Rung: rungPrivate, Theme: "paper"}} |
| + if e := f.a.app.db.G.Create(&rows).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if e := f.a.app.db.G.Exec("INSERT INTO deck_grants(deck_id,user_id) VALUES(?,?)", base+3, f.u.ID).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + var page struct { |
| + Decks []struct { |
| + Sqid string `json:"sqid"` |
| + } |
| + Next string `json:"next_cursor"` |
| + } |
| + r := f.call(t, "slides_list_decks", map[string]any{"team": "blue", "limit": 1}) |
| + if e := json.Unmarshal(r.Body.Bytes(), &page); e != nil || r.Code != 200 || len(page.Decks) != 1 || page.Decks[0].Sqid != rows[2].Sqid || page.Next != strconv.FormatInt(base+3, 10) { |
| + t.Fatal(r.Code, r.Body.String(), e) |
| + } |
| + r = f.call(t, "slides_list_decks", map[string]any{"team": "blue", "limit": 1, "cursor": page.Next}) |
| + if e := json.Unmarshal(r.Body.Bytes(), &page); e != nil || r.Code != 200 || len(page.Decks) != 1 || page.Decks[0].Sqid != rows[1].Sqid || page.Next != strconv.FormatInt(base+2, 10) { |
| + t.Fatal(r.Code, r.Body.String(), e) |
| + } |
| + if r := f.call(t, "slides_get_deck", map[string]any{"team": "blue", "sqid": rows[3].Sqid}); r.Code != 404 { |
| + t.Fatal(r.Code) |
| + } |
| + for _, cursor := range []string{"09223372036854775807", "9223372036854775808"} { |
| + if r := f.call(t, "slides_list_decks", map[string]any{"team": "blue", "cursor": cursor}); r.Code != 422 { |
| + t.Fatal(r.Code) |
| + } |
| + } |
| +} |
| +func TestAgentDeckRawCorePrecision(t *testing.T) { |
| + f := newSlideAgentFixture(t) |
| + sqid := slideCreated(t, f.call(t, "slides_create_deck", initialSlideAgentInput())) |
| + var d Deck |
| + f.a.app.db.G.Where("sqid=?", sqid).Take(&d) |
| + h, view, e := f.a.app.openDeck(t.Context(), d) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + h.Close(t.Context()) |
| + ops, _ := json.Marshal([]op{{"op": "set_slide", "id": view.Slides[0].ID, "layout": "canvas"}, {"op": "set_block", "slide": view.Slides[0].ID, "id": view.Slides[0].Blocks[0].ID, "z": 1.75}}) |
| + if e = f.a.app.editDeck(t.Context(), &d, actorFor(f.u), ops, nil); e != nil { |
| + t.Fatal(e) |
| + } |
| + r := f.call(t, "slides_get_deck", map[string]any{"team": "blue", "sqid": sqid}) |
| + if r.Code != 200 || !strings.Contains(r.Body.String(), `"z":1.75`) { |
| + t.Fatal("core precision lost", r.Code, r.Body.String()) |
| + } |
| +} |
| +func TestAgentDeckLimitsAndAuthorization(t *testing.T) { |
| + f := newSlideAgentFixture(t) |
| + for _, mode := range []string{"team", "scope", "uuid", "unknown", "title", "text", "input"} { |
| + t.Run(mode, func(t *testing.T) { |
| + in := initialSlideAgentInput() |
| + want := 422 |
| + switch mode { |
| + case "team": |
| + in.Team = "other" |
| + f.p.Teams = []string{"blue", "other"} |
| + defer func() { f.p.Teams = []string{"blue"} }() |
| + want = 403 |
| + case "scope": |
| + f.p.Scopes = []string{"slides:read"} |
| + defer func() { f.p.Scopes = []string{"slides:read", "slides:write"} }() |
| + want = 403 |
| + case "uuid": |
| + in.ClientID = strings.ReplaceAll(in.ClientID, "-", "") |
| + case "title": |
| + in.Title = strings.Repeat("界", 200) |
| + case "text": |
| + in.Slides[0].Body = strings.Repeat("x", 128<<10) |
| + in.Slides[0].Heading = "x" |
| + want = 413 |
| + case "input": |
| + in.Slides[0].Body = strings.Repeat("x", slideAgentLimit) |
| + want = 413 |
| + } |
| + raw, _ := json.Marshal(in) |
| + if mode == "unknown" { |
| + raw = append(raw[:len(raw)-1], []byte(`,"unrecognized":true}`)...) |
| + } |
| + if r := f.raw(t, "slides_create_deck", raw); r.Code != want { |
| + t.Fatal(mode, r.Code, r.Body.String()) |
| + } |
| + }) |
| + } |
| + // A committed creation always has a small result, even if a later read is too large. |
| + in := initialSlideAgentInput() |
| + in.Slides[0] = slideAgentInitial{Heading: "Large", Body: strings.Repeat("&", 100000)} |
| + sqid := slideCreated(t, f.call(t, "slides_create_deck", in)) |
| + slideCreated(t, f.call(t, "slides_create_deck", in)) |
| + var d Deck |
| + f.a.app.db.G.Where("sqid=?", sqid).Take(&d) |
| + h, view, e := f.a.app.openDeck(t.Context(), d) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + h.Close(t.Context()) |
| + ops, _ := json.Marshal([]op{{"op": "set_text", "slide": view.Slides[0].ID, "id": view.Slides[0].Blocks[1].ID, "markdown": strings.Repeat("z", 1100000)}}) |
| + if e = f.a.app.editDeck(t.Context(), &d, actorFor(f.u), ops, nil); e != nil { |
| + t.Fatal(e) |
| + } |
| + h, _, e = f.a.app.openDeck(t.Context(), d) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + raw, e := h.JSON(t.Context()) |
| + h.Close(t.Context()) |
| + if e != nil || len(raw) <= slideAgentLimit { |
| + t.Fatal("oversize fixture is not large enough", len(raw), e) |
| + } |
| + if _, e := f.a.get(t.Context(), f.u, sqid); e == nil || access.SafeFailure(e).Code != "too_large" { |
| + t.Fatal("operation itself did not bound canonical get", e) |
| + } |
| + r := f.call(t, "slides_get_deck", map[string]any{"team": "blue", "sqid": sqid}) |
| + if r.Code != 413 { |
| + t.Fatal("oversize canonical get", r.Code) |
| + } |
| + |
| + // Legacy content can be larger than the new creation contract. |
| + if e := f.a.app.db.G.Model(&Deck{}).Where("sqid=?", sqid).Update("title", strings.Repeat("x", slideAgentLimit)).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if r := f.call(t, "slides_list_decks", map[string]any{"team": "blue"}); r.Code != 413 { |
| + t.Fatal("oversize result", r.Code) |
| + } |
| +} |
diff --git a/internal/slides/agent_response_test.go b/internal/slides/agent_response_test.go| new file mode 100644 |
| index 0000000..76d605e |
| --- /dev/null |
| +++ b/internal/slides/agent_response_test.go |
| @@ -0,0 +1,93 @@ |
| +package slides |
| + |
| +import ( |
| + access "amadan.net/oficina/agent-access.git" |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +type agentRevokingWriter struct { |
| + http.ResponseWriter |
| + revoke func() |
| +} |
| + |
| +func (w *agentRevokingWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } |
| +func (w *agentRevokingWriter) Write(b []byte) (int, error) { |
| + n, e := w.ResponseWriter.Write(b) |
| + if w.revoke != nil { |
| + f := w.revoke |
| + w.revoke = nil |
| + f() |
| + } |
| + return n, e |
| +} |
| +func TestAgentDeckResponseRevocation(t *testing.T) { |
| + f := newSlideAgentFixture(t) |
| + in := initialSlideAgentInput() |
| + in.Slides[0].Body = strings.Repeat("z", 80000) |
| + sqid := slideCreated(t, f.call(t, "slides_create_deck", in)) |
| + args := map[string]any{"team": "blue", "sqid": sqid} |
| + f.checks.Store(0) |
| + f.revokeAt.Store(2) |
| + if r := f.call(t, "slides_get_deck", args); r.Code != 401 || strings.Contains(r.Body.String(), "zzzz") { |
| + t.Fatal("response leaked", r.Code) |
| + } |
| + f.revokeAt.Store(0) |
| + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + f.a.app.agent.ServeHTTP(&agentRevokingWriter{w, func() { f.revokeAt.Store(1) }}, r) |
| + })) |
| + defer server.Close() |
| + raw, _ := json.Marshal(args) |
| + req, _ := http.NewRequest("POST", server.URL+"/api/v1/operations/slides_get_deck", 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(e) |
| + } |
| + defer res.Body.Close() |
| + b, e := io.ReadAll(res.Body) |
| + if !errors.Is(e, io.ErrUnexpectedEOF) || res.StatusCode != 200 || len(b) == 0 || len(b) > 64<<10 || json.Valid(b) { |
| + t.Fatal("revoked stream completed", res.StatusCode, len(b), e) |
| + } |
| +} |
| +func TestAgentDeckResponseLocalAuthority(t *testing.T) { |
| + for _, mode := range []string{"link", "permission"} { |
| + t.Run(mode, func(t *testing.T) { |
| + f := newSlideAgentFixture(t) |
| + sqid := slideCreated(t, f.call(t, "slides_create_deck", initialSlideAgentInput())) |
| + // The second credential verification is the final read-emission boundary. |
| + var checks int |
| + handler, e := f.a.httpHandler(verifyAgentFunc(func() { |
| + checks++ |
| + if checks == 2 { |
| + sql := "DELETE FROM home_identity_links" |
| + if mode == "permission" { |
| + sql = "UPDATE decks SET owner_id=99,rung='private'" |
| + } |
| + if e := f.a.app.db.G.Exec(sql).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + }, f.p)) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + f.a.app.agent = handler |
| + if r := f.call(t, "slides_get_deck", map[string]any{"team": "blue", "sqid": sqid}); r.Code != 403 && r.Code != 404 { |
| + t.Fatal("local authority lost", r.Code) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func verifyAgentFunc(before func(), p access.Principal) access.Verifier { |
| + return access.VerifyFunc(func(context.Context, string) (access.Principal, error) { before(); return p, nil }) |
| +} |
diff --git a/internal/slides/agent_wait_test.go b/internal/slides/agent_wait_test.go| new file mode 100644 |
| index 0000000..ce47534 |
| --- /dev/null |
| +++ b/internal/slides/agent_wait_test.go |
| @@ -0,0 +1,88 @@ |
| +package slides |
| + |
| +import ( |
| + "context" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func TestAgentDeckRevocationWhileWaitingForWriter(t *testing.T) { |
| + f := newSlideAgentFixture(t) |
| + var revoked atomic.Bool |
| + if e := f.a.app.mountAgent(f.a, access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| + if revoked.Load() { |
| + return access.Principal{}, access.Fail("unauthenticated", "Revoked.") |
| + } |
| + return f.p, nil |
| + })); e != nil { |
| + t.Fatal(e) |
| + } |
| + // If authorization is moved after body work, this fault wins and produces503. |
| + if _, e := f.a.app.db.Writer().Exec("CREATE TRIGGER body_must_not_run BEFORE INSERT ON decks BEGIN SELECT RAISE(ABORT,'body attempted'); END"); e != nil { |
| + t.Fatal(e) |
| + } |
| + var path string |
| + if e := f.a.app.db.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path); e != nil { |
| + t.Fatal(e) |
| + } |
| + other, e := db.Open(path, f.a.app.logger) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer other.Close() |
| + held, e := other.Writer().BeginTx(t.Context(), nil) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer held.Rollback() |
| + if _, e = held.Exec("UPDATE slides_agent_state SET keycheck=keycheck"); e != nil { |
| + t.Fatal(e) |
| + } |
| + // The separate SQLite connection holds the writer; WAL identity reads finish. |
| + // Observe entry into the real reservation statement after BOTH Home lookups. |
| + attempted := make(chan struct{}) |
| + var once atomic.Bool |
| + if e = f.a.app.db.G.Callback().Raw().Before("gorm:raw").Register("test:agent_writer", func(tx *gorm.DB) { |
| + if strings.HasPrefix(tx.Statement.SQL.String(), "INSERT INTO slides_agent_state") && once.CompareAndSwap(false, true) { |
| + close(attempted) |
| + } |
| + }); e != nil { |
| + t.Fatal(e) |
| + } |
| + defer f.a.app.db.G.Callback().Raw().Remove("test:agent_writer") |
| + result := make(chan int, 1) |
| + go func() { result <- f.call(t, "slides_create_deck", initialSlideAgentInput()).Code }() |
| + select { |
| + case <-attempted: |
| + case <-time.After(3 * time.Second): |
| + t.Fatal("request never reached reserved-writer statement") |
| + } |
| + select { |
| + case code := <-result: |
| + t.Fatal("writer did not block", code) |
| + case <-time.After(20 * time.Millisecond): |
| + } |
| + revoked.Store(true) |
| + if e = held.Commit(); e != nil { |
| + t.Fatal(e) |
| + } |
| + select { |
| + case code := <-result: |
| + if code != 401 { |
| + t.Fatal("body attempted before fresh delegation check", code) |
| + } |
| + case <-time.After(3 * time.Second): |
| + t.Fatal("writer did not resume") |
| + } |
| + var n int |
| + f.a.app.db.G.Raw("SELECT COUNT(*) FROM decks").Scan(&n) |
| + if n != 0 { |
| + t.Fatal(n) |
| + } |
| +} |
diff --git a/internal/slides/agents.go b/internal/slides/agents.go| index 337b48b..cc04343 100644 |
| --- a/internal/slides/agents.go |
| +++ b/internal/slides/agents.go |
| @@ -296,7 +296,7 @@ func (a *app) actorLabels(ctx context.Context, actors []string) map[string]strin |
| } |
| } |
| - out := map[string]string{} |
| + out := a.connectionLabels(ctx, actors) |
| if len(personIDs) > 0 { |
| var people []User |
| if err := a.db.G.WithContext(ctx).Where("id IN ?", personIDs).Find(&people).Error; err != nil { |
diff --git a/internal/slides/app.go b/internal/slides/app.go| index 6f08bc2..c044b9a 100644 |
| --- a/internal/slides/app.go |
| +++ b/internal/slides/app.go |
| @@ -261,6 +261,10 @@ func New(d *db.DB, cfg Config) (*http.ServeMux, *app, error) { |
| // surface will authenticate, which is what CSRF is an attack on. |
| // api.go's package comment says the same thing at length, and |
| // docs/api.md says it to the person reading the API. |
| + if a.agent != nil { |
| + mux.Handle("/api/v1/operations", a.agent) |
| + mux.Handle("/api/v1/operations/", a.agent) |
| + } |
| mux.Handle(apiPrefix+"/", a.apiRouter()) |
| mux.Handle("/", r) |
| return mux, a, nil |
| @@ -295,6 +299,9 @@ func newApp(d *db.DB, cfg Config) (*app, *rauth.Auth, error) { |
| if err != nil { |
| return nil, nil, err |
| } |
| + if err := validateAgentConfig(cfg.AgentIssuer, cfg.AgentTeam, cfg.Origin, cfg.Home); err != nil { |
| + return nil, nil, err |
| + } |
| boot := BootSchema |
| if homeConfig != nil { |
| boot = migrate.Merge(BootSchema, homeSchema) |
| @@ -375,6 +382,11 @@ func newApp(d *db.DB, cfg Config) (*app, *rauth.Auth, error) { |
| return nil, nil, err |
| } |
| + if err := a.configureAgentAccess(); err != nil { |
| + a.Close() |
| + return nil, nil, err |
| + } |
| + |
| // The export's status page, its polled fragment and its SSE stream |
| // (exports.go). rastrillo/jobs owns the lifecycle and the |
| // owner-only lookup; the two renderers are this app's, so the page |
diff --git a/internal/slides/config.go b/internal/slides/config.go| index 89bcff4..e2222b6 100644 |
| --- a/internal/slides/config.go |
| +++ b/internal/slides/config.go |
| @@ -41,7 +41,9 @@ const DefaultOrigin = "http://localhost:8091" |
| // Config is what New needs to build the app. cmd/slides/main.go fills |
| // it from the environment; the test harness fills it directly. |
| type Config struct { |
| - Home *connect.Credentials |
| + Home *connect.Credentials |
| + AgentIssuer string |
| + AgentTeam string |
| // Origin is this instance's external origin, scheme included — |
| // "https://slides.oficina.works". It is three things at once: |
| // csrf.Protect's yardstick for the legacy Origin/Referer fallback |
diff --git a/internal/slides/core/testdata/slides_core.wasm b/internal/slides/core/testdata/slides_core.wasm| index 111db4d..8488e81 100755 |
| Binary files a/internal/slides/core/testdata/slides_core.wasm and b/internal/slides/core/testdata/slides_core.wasm differ |
diff --git a/internal/slides/credits/assets.json b/internal/slides/credits/assets.json| index d8f1b18..a6a114a 100644 |
| --- a/internal/slides/credits/assets.json |
| +++ b/internal/slides/credits/assets.json |
| @@ -4,9 +4,20 @@ |
| "core/Cargo.toml": "b0df969e01d7ba4711abe0f71dfede1174b640fe06440cd26738ca903e67d391", |
| "core/pdf/Cargo.lock": "9c9d1eb3c9d6cc0ba477ec19db6f240c3e22285354b85e9194fb6c36c7a88369", |
| "core/pdf/Cargo.toml": "f6d65a503805403ea73112c78408caf0505f06a3b6df4ba2d04374c4dea8c3bb", |
| + "core/vendor/fastrand-2.5.0/CHANGELOG.md": "d0ecc653658392738be0daccc920a5c3ffe6996c328a9aa8f26ce897a5db7293", |
| + "core/vendor/fastrand-2.5.0/Cargo.toml": "bff7c012eceb24c4e87e288fffc9216933d2fb5c4c14d0f992363800ccc9501c", |
| + "core/vendor/fastrand-2.5.0/LICENSE-APACHE": "a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2", |
| + "core/vendor/fastrand-2.5.0/LICENSE-MIT": "23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3", |
| + "core/vendor/fastrand-2.5.0/README.md": "5f3d251d8bc1c793284f4cc720453b280c1c04f968a70b7b36b78d6c1e5c9973", |
| + "core/vendor/fastrand-2.5.0/benches/bench.rs": "9613f3e9f893ef0c227c158be2c91d766e60b80ce11faf226ac490057ee38546", |
| + "core/vendor/fastrand-2.5.0/src/global_rng.rs": "f14c504601f9273bf6fa49621cc9dad2329092fd87d35fe8963e55d99f597de2", |
| + "core/vendor/fastrand-2.5.0/src/lib.rs": "858da6a3831589762ec2214df3f8e8b09a1262708fb08072f1cf13c1260d6ce1", |
| + "core/vendor/fastrand-2.5.0/tests/char.rs": "a530b41837f5bf43701d983ef0267d9b44779d455f24cbf30b881cd348de9ee1", |
| + "core/vendor/fastrand-2.5.0/tests/smoke.rs": "0f40e5fd5f382de66cf8ddb7f7e0b3e968d979de75d3658a185d22b11e8e5fc2", |
| "fixtures/package-lock.json": "76f1440474bba8e02e74409a1437ddb55ee8fcad5ba18a7a0744de1646fc9a01", |
| "fixtures/package.json": "995c5ffbcec5ffd822a8dddb96aa638d1ab57a7bbdfa73fd661e88458b41ea73", |
| - "internal/slides/core/testdata/slides_core.wasm": "90efd37fc0a94fdbdfd93c7c5327d9329f3fcdd28bb26d3801e41bed9eb1bd37", |
| + "internal/slides/core/testdata/slides_core.wasm": "e29842bf8249f3c981590288d48964b9207941da0524bdd731894da598656470", |
| + "internal/slides/credits/upstream/fastrand-vendor.json": "77953165e6238d83c12eb4fb419d100cf11cc8e54ae57291a386dc7667e58365", |
| "internal/slides/credits/upstream/krilla-LICENSE_APACHE": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", |
| "internal/slides/credits/upstream/krilla-LICENSE_MIT": "9d1eb142840c7acfd5511b4dd298cece3f0053f5809228906445cd8a3365592f", |
| "internal/slides/credits/upstream/krilla-NOTICE.md": "7aa87a70e18c9c160b5a14e24b46a8e407858b21fed635920c701657b4bd7976", |
| @@ -25,7 +36,7 @@ |
| "internal/slides/fonts/files/LiberationSerif-BoldItalic.ttf": "4b2635d2ec4d992373dcae577c742a98ecfd841ffc1b8a103b5f10db163dbc7a", |
| "internal/slides/fonts/files/LiberationSerif-Italic.ttf": "de18fe26337e03241952dca46398d5b66f3c5738d080bfd284f66e67b926f597", |
| "internal/slides/fonts/files/LiberationSerif-Regular.ttf": "9caef765d2e891c10dd73658894f01e660fe0c1c83e0bda7d6edf561d8f623d4", |
| - "internal/slides/pdfcore/testdata/slides_pdf.wasm": "38c9c096a704eb93bf68f63ec1e2fdd3fa603474fe3c0ecfc1827d7d9fb91a3d", |
| + "internal/slides/pdfcore/testdata/slides_pdf.wasm": "78f7dcd8e7fabeb1eef2b857ae432e681b176661c8b58d6b82b38621a1cf356b", |
| "internal/slides/static/busy.js": "b5be5c1c7239b066ec5d13e0c9a21a06c7c7a448542dc7d664a989f4589bae02", |
| "internal/slides/static/calendar.js": "dfa06d84768b8e99d1e50d9dca81caadacf2412db74ac4e432d78c29680bbdd2", |
| "internal/slides/static/datetime.js": "5aea0521b14f9164c14b75fdcc1ff9a5429d2f51d8d78161a4eebba0e41a1ea1", |
diff --git a/internal/slides/credits/notices.json b/internal/slides/credits/notices.json| index ed4da1d..0721ef5 100644 |
| --- a/internal/slides/credits/notices.json |
| +++ b/internal/slides/credits/notices.json |
| @@ -626,6 +626,17 @@ |
| } |
| ] |
| }, |
| + { |
| + "Name": "github.com/google/jsonschema-go", |
| + "Version": "v0.4.3", |
| + "SourceURL": "https://pkg.go.dev/github.com/google/jsonschema-go@v0.4.3", |
| + "Notices": [ |
| + { |
| + "Name": "LICENSE", |
| + "Text": "MIT License\n\nCopyright (c) 2025 JSON Schema Go Project Authors\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n" |
| + } |
| + ] |
| + }, |
| { |
| "Name": "github.com/google/uuid", |
| "Version": "v1.6.0", |
| @@ -665,6 +676,17 @@ |
| "SourceURL": "https://pkg.go.dev/github.com/keymaildev/signin@v0.1.1", |
| "Notices": [] |
| }, |
| + { |
| + "Name": "github.com/modelcontextprotocol/go-sdk", |
| + "Version": "v1.7.0", |
| + "SourceURL": "https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk@v1.7.0", |
| + "Notices": [ |
| + { |
| + "Name": "LICENSE", |
| + "Text": "The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 (\"Apache-2.0\"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0.\n\nContributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License.\n\nNo rights beyond those granted by the applicable original license are conveyed for such contributions.\n\n---\n\n Apache License\n Version 2.0, January 2004\n http://www.apache.org/licenses/\n\n TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n 1. Definitions.\n\n \"License\" shall mean the terms and conditions for use, reproduction,\n and distribution as defined by Sections 1 through 9 of this document.\n\n \"Licensor\" shall mean the copyright owner or entity authorized by\n the copyright owner that is granting the License.\n\n \"Legal Entity\" shall mean the union of the acting entity and all\n other entities that control, are controlled by, or are under common\n control with that entity. For the purposes of this definition,\n \"control\" means (i) the power, direct or indirect, to cause the\n direction or management of such entity, whether by contract or\n otherwise, or (ii) ownership of fifty percent (50%) or more of the\n outstanding shares, or (iii) beneficial ownership of such entity.\n\n \"You\" (or \"Your\") shall mean an individual or Legal Entity\n exercising permissions granted by this License.\n\n \"Source\" form shall mean the preferred form for making modifications,\n including but not limited to software source code, documentation\n source, and configuration files.\n\n \"Object\" form shall mean any form resulting from mechanical\n transformation or translation of a Source form, including but\n not limited to compiled object code, generated documentation,\n and conversions to other media types.\n\n \"Work\" shall mean the work of authorship, whether in Source or\n Object form, made available under the License, as indicated by a\n copyright notice that is included in or attached to the work\n (an example is provided in the Appendix below).\n\n \"Derivative Works\" shall mean any work, whether in Source or Object\n form, that is based on (or derived from) the Work and for which the\n editorial revisions, annotations, elaborations, or other modifications\n represent, as a whole, an original work of authorship. For the purposes\n of this License, Derivative Works shall not include works that remain\n separable from, or merely link (or bind by name) to the interfaces of,\n the Work and Derivative Works thereof.\n\n \"Contribution\" shall mean any work of authorship, including\n the original version of the Work and any modifications or additions\n to that Work or Derivative Works thereof, that is intentionally\n submitted to Licensor for inclusion in the Work by the copyright\n owner or by an individual or Legal Entity authorized to submit on behalf\n of the copyright owner. For the purposes of this definition, \"submitted\"\n means any form of electronic, verbal, or written communication sent\n to the Licensor or its representatives, including but not limited to\n communication on electronic mailing lists, source code control systems,\n and issue tracking systems that are managed by, or on behalf of, the\n Licensor for the purpose of discussing and improving the Work, but\n excluding communication that is conspicuously marked or otherwise\n designated in writing by the copyright owner as \"Not a Contribution.\"\n\n \"Contributor\" shall mean Licensor and any individual or Legal Entity\n on behalf of whom a Contribution has been received by Licensor and\n subsequently incorporated within the Work.\n\n 2. Grant of Copyright License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n copyright license to reproduce, prepare Derivative Works of,\n publicly display, publicly perform, sublicense, and distribute the\n Work and such Derivative Works in Source or Object form.\n\n 3. Grant of Patent License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n (except as stated in this section) patent license to make, have made,\n use, offer to sell, sell, import, and otherwise transfer the Work,\n where such license applies only to those patent claims licensable\n by such Contributor that are necessarily infringed by their\n Contribution(s) alone or by combination of their Contribution(s)\n with the Work to which such Contribution(s) was submitted. If You\n institute patent litigation against any entity (including a\n cross-claim or counterclaim in a lawsuit) alleging that the Work\n or a Contribution incorporated within the Work constitutes direct\n or contributory patent infringement, then any patent licenses\n granted to You under this License for that Work shall terminate\n as of the date such litigation is filed.\n\n 4. Redistribution. You may reproduce and distribute copies of the\n Work or Derivative Works thereof in any medium, with or without\n modifications, and in Source or Object form, provided that You\n meet the following conditions:\n\n (a) You must give any other recipients of the Work or\n Derivative Works a copy of this License; and\n\n (b) You must cause any modified files to carry prominent notices\n stating that You changed the files; and\n\n (c) You must retain, in the Source form of any Derivative Works\n that You distribute, all copyright, patent, trademark, and\n attribution notices from the Source form of the Work,\n excluding those notices that do not pertain to any part of\n the Derivative Works; and\n\n (d) If the Work includes a \"NOTICE\" text file as part of its\n distribution, then any Derivative Works that You distribute must\n include a readable copy of the attribution notices contained\n within such NOTICE file, excluding those notices that do not\n pertain to any part of the Derivative Works, in at least one\n of the following places: within a NOTICE text file distributed\n as part of the Derivative Works; within the Source form or\n documentation, if provided along with the Derivative Works; or,\n within a display generated by the Derivative Works, if and\n wherever such third-party notices normally appear. The contents\n of the NOTICE file are for informational purposes only and\n do not modify the License. You may add Your own attribution\n notices within Derivative Works that You distribute, alongside\n or as an addendum to the NOTICE text from the Work, provided\n that such additional attribution notices cannot be construed\n as modifying the License.\n\n You may add Your own copyright statement to Your modifications and\n may provide additional or different license terms and conditions\n for use, reproduction, or distribution of Your modifications, or\n for any such Derivative Works as a whole, provided Your use,\n reproduction, and distribution of the Work otherwise complies with\n the conditions stated in this License.\n\n 5. Submission of Contributions. Unless You explicitly state otherwise,\n any Contribution intentionally submitted for inclusion in the Work\n by You to the Licensor shall be under the terms and conditions of\n this License, without any additional terms or conditions.\n Notwithstanding the above, nothing herein shall supersede or modify\n the terms of any separate license agreement you may have executed\n with Licensor regarding such Contributions.\n\n 6. Trademarks. This License does not grant permission to use the trade\n names, trademarks, service marks, or product names of the Licensor,\n except as required for reasonable and customary use in describing the\n origin of the Work and reproducing the content of the NOTICE file.\n\n 7. Disclaimer of Warranty. Unless required by applicable law or\n agreed to in writing, Licensor provides the Work (and each\n Contributor provides its Contributions) on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n implied, including, without limitation, any warranties or conditions\n of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n PARTICULAR PURPOSE. You are solely responsible for determining the\n appropriateness of using or redistributing the Work and assume any\n risks associated with Your exercise of permissions under this License.\n\n 8. Limitation of Liability. In no event and under no legal theory,\n whether in tort (including negligence), contract, or otherwise,\n unless required by applicable law (such as deliberate and grossly\n negligent acts) or agreed to in writing, shall any Contributor be\n liable to You for damages, including any direct, indirect, special,\n incidental, or consequential damages of any character arising as a\n result of this License or out of the use or inability to use the\n Work (including but not limited to damages for loss of goodwill,\n work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses), even if such Contributor\n has been advised of the possibility of such damages.\n\n 9. Accepting Warranty or Additional Liability. While redistributing\n the Work or Derivative Works thereof, You may choose to offer,\n and charge a fee for, acceptance of support, warranty, indemnity,\n or other liability obligations and/or rights consistent with this\n License. However, in accepting such obligations, You may act only\n on Your own behalf and on Your sole responsibility, not on behalf\n of any other Contributor, and only if You agree to indemnify,\n defend, and hold each Contributor harmless for any liability\n incurred by, or claims asserted against, such Contributor by reason\n of your accepting any such warranty or additional liability.\n\n END OF TERMS AND CONDITIONS\n\n---\n\nMIT License\n\nCopyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n---\n\nCreative Commons Attribution 4.0 International (CC-BY-4.0)\n\nDocumentation in this project (excluding specifications) is licensed under\nCC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for\nthe full license text.\n" |
| + } |
| + ] |
| + }, |
| { |
| "Name": "github.com/remyoudompheng/bigfft", |
| "Version": "v0.0.0-20230129092748-24d4a6f8daec", |
| @@ -676,6 +698,39 @@ |
| } |
| ] |
| }, |
| + { |
| + "Name": "github.com/santhosh-tekuri/jsonschema/v6", |
| + "Version": "v6.0.3", |
| + "SourceURL": "https://pkg.go.dev/github.com/santhosh-tekuri/jsonschema/v6@v6.0.3", |
| + "Notices": [ |
| + { |
| + "Name": "LICENSE", |
| + "Text": "\n Apache License\n Version 2.0, January 2004\n http://www.apache.org/licenses/\n\n TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n 1. Definitions.\n\n \"License\" shall mean the terms and conditions for use, reproduction,\n and distribution as defined by Sections 1 through 9 of this document.\n\n \"Licensor\" shall mean the copyright owner or entity authorized by\n the copyright owner that is granting the License.\n\n \"Legal Entity\" shall mean the union of the acting entity and all\n other entities that control, are controlled by, or are under common\n control with that entity. For the purposes of this definition,\n \"control\" means (i) the power, direct or indirect, to cause the\n direction or management of such entity, whether by contract or\n otherwise, or (ii) ownership of fifty percent (50%) or more of the\n outstanding shares, or (iii) beneficial ownership of such entity.\n\n \"You\" (or \"Your\") shall mean an individual or Legal Entity\n exercising permissions granted by this License.\n\n \"Source\" form shall mean the preferred form for making modifications,\n including but not limited to software source code, documentation\n source, and configuration files.\n\n \"Object\" form shall mean any form resulting from mechanical\n transformation or translation of a Source form, including but\n not limited to compiled object code, generated documentation,\n and conversions to other media types.\n\n \"Work\" shall mean the work of authorship, whether in Source or\n Object form, made available under the License, as indicated by a\n copyright notice that is included in or attached to the work\n (an example is provided in the Appendix below).\n\n \"Derivative Works\" shall mean any work, whether in Source or Object\n form, that is based on (or derived from) the Work and for which the\n editorial revisions, annotations, elaborations, or other modifications\n represent, as a whole, an original work of authorship. For the purposes\n of this License, Derivative Works shall not include works that remain\n separable from, or merely link (or bind by name) to the interfaces of,\n the Work and Derivative Works thereof.\n\n \"Contribution\" shall mean any work of authorship, including\n the original version of the Work and any modifications or additions\n to that Work or Derivative Works thereof, that is intentionally\n submitted to Licensor for inclusion in the Work by the copyright owner\n or by an individual or Legal Entity authorized to submit on behalf of\n the copyright owner. For the purposes of this definition, \"submitted\"\n means any form of electronic, verbal, or written communication sent\n to the Licensor or its representatives, including but not limited to\n communication on electronic mailing lists, source code control systems,\n and issue tracking systems that are managed by, or on behalf of, the\n Licensor for the purpose of discussing and improving the Work, but\n excluding communication that is conspicuously marked or otherwise\n designated in writing by the copyright owner as \"Not a Contribution.\"\n\n \"Contributor\" shall mean Licensor and any individual or Legal Entity\n on behalf of whom a Contribution has been received by Licensor and\n subsequently incorporated within the Work.\n\n 2. Grant of Copyright License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n copyright license to reproduce, prepare Derivative Works of,\n publicly display, publicly perform, sublicense, and distribute the\n Work and such Derivative Works in Source or Object form.\n\n 3. Grant of Patent License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n (except as stated in this section) patent license to make, have made,\n use, offer to sell, sell, import, and otherwise transfer the Work,\n where such license applies only to those patent claims licensable\n by such Contributor that are necessarily infringed by their\n Contribution(s) alone or by combination of their Contribution(s)\n with the Work to which such Contribution(s) was submitted. If You\n institute patent litigation against any entity (including a\n cross-claim or counterclaim in a lawsuit) alleging that the Work\n or a Contribution incorporated within the Work constitutes direct\n or contributory patent infringement, then any patent licenses\n granted to You under this License for that Work shall terminate\n as of the date such litigation is filed.\n\n 4. Redistribution. You may reproduce and distribute copies of the\n Work or Derivative Works thereof in any medium, with or without\n modifications, and in Source or Object form, provided that You\n meet the following conditions:\n\n (a) You must give any other recipients of the Work or\n Derivative Works a copy of this License; and\n\n (b) You must cause any modified files to carry prominent notices\n stating that You changed the files; and\n\n (c) You must retain, in the Source form of any Derivative Works\n that You distribute, all copyright, patent, trademark, and\n attribution notices from the Source form of the Work,\n excluding those notices that do not pertain to any part of\n the Derivative Works; and\n\n (d) If the Work includes a \"NOTICE\" text file as part of its\n distribution, then any Derivative Works that You distribute must\n include a readable copy of the attribution notices contained\n within such NOTICE file, excluding those notices that do not\n pertain to any part of the Derivative Works, in at least one\n of the following places: within a NOTICE text file distributed\n as part of the Derivative Works; within the Source form or\n documentation, if provided along with the Derivative Works; or,\n within a display generated by the Derivative Works, if and\n wherever such third-party notices normally appear. The contents\n of the NOTICE file are for informational purposes only and\n do not modify the License. You may add Your own attribution\n notices within Derivative Works that You distribute, alongside\n or as an addendum to the NOTICE text from the Work, provided\n that such additional attribution notices cannot be construed\n as modifying the License.\n\n You may add Your own copyright statement to Your modifications and\n may provide additional or different license terms and conditions\n for use, reproduction, or distribution of Your modifications, or\n for any such Derivative Works as a whole, provided Your use,\n reproduction, and distribution of the Work otherwise complies with\n the conditions stated in this License.\n\n 5. Submission of Contributions. Unless You explicitly state otherwise,\n any Contribution intentionally submitted for inclusion in the Work\n by You to the Licensor shall be under the terms and conditions of\n this License, without any additional terms or conditions.\n Notwithstanding the above, nothing herein shall supersede or modify\n the terms of any separate license agreement you may have executed\n with Licensor regarding such Contributions.\n\n 6. Trademarks. This License does not grant permission to use the trade\n names, trademarks, service marks, or product names of the Licensor,\n except as required for reasonable and customary use in describing the\n origin of the Work and reproducing the content of the NOTICE file.\n\n 7. Disclaimer of Warranty. Unless required by applicable law or\n agreed to in writing, Licensor provides the Work (and each\n Contributor provides its Contributions) on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n implied, including, without limitation, any warranties or conditions\n of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n PARTICULAR PURPOSE. You are solely responsible for determining the\n appropriateness of using or redistributing the Work and assume any\n risks associated with Your exercise of permissions under this License.\n\n 8. Limitation of Liability. In no event and under no legal theory,\n whether in tort (including negligence), contract, or otherwise,\n unless required by applicable law (such as deliberate and grossly\n negligent acts) or agreed to in writing, shall any Contributor be\n liable to You for damages, including any direct, indirect, special,\n incidental, or consequential damages of any character arising as a\n result of this License or out of the use or inability to use the\n Work (including but not limited to damages for loss of goodwill,\n work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses), even if such Contributor\n has been advised of the possibility of such damages.\n\n 9. Accepting Warranty or Additional Liability. While redistributing\n the Work or Derivative Works thereof, You may choose to offer,\n and charge a fee for, acceptance of support, warranty, indemnity,\n or other liability obligations and/or rights consistent with this\n License. However, in accepting such obligations, You may act only\n on Your own behalf and on Your sole responsibility, not on behalf\n of any other Contributor, and only if You agree to indemnify,\n defend, and hold each Contributor harmless for any liability\n incurred by, or claims asserted against, such Contributor by reason\n of your accepting any such warranty or additional liability." |
| + } |
| + ] |
| + }, |
| + { |
| + "Name": "github.com/segmentio/asm", |
| + "Version": "v1.1.3", |
| + "SourceURL": "https://pkg.go.dev/github.com/segmentio/asm@v1.1.3", |
| + "Notices": [ |
| + { |
| + "Name": "LICENSE", |
| + "Text": "MIT License\n\nCopyright (c) 2021 Segment\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n" |
| + } |
| + ] |
| + }, |
| + { |
| + "Name": "github.com/segmentio/encoding", |
| + "Version": "v0.5.4", |
| + "SourceURL": "https://pkg.go.dev/github.com/segmentio/encoding@v0.5.4", |
| + "Notices": [ |
| + { |
| + "Name": "LICENSE", |
| + "Text": "MIT License\n\nCopyright (c) 2019 Segment.io, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n" |
| + } |
| + ] |
| + }, |
| { |
| "Name": "github.com/skip2/go-qrcode", |
| "Version": "v0.0.0-20200617195104-da1b6568686e", |
| @@ -702,6 +757,17 @@ |
| } |
| ] |
| }, |
| + { |
| + "Name": "github.com/yosida95/uritemplate/v3", |
| + "Version": "v3.0.2", |
| + "SourceURL": "https://pkg.go.dev/github.com/yosida95/uritemplate/v3@v3.0.2", |
| + "Notices": [ |
| + { |
| + "Name": "LICENSE", |
| + "Text": "Copyright (C) 2016, Kohei YOSHIDA <https://yosida95.com/>. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n * Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" |
| + } |
| + ] |
| + }, |
| { |
| "Name": "golang.org/x/image", |
| "Version": "v0.44.0", |
| @@ -713,6 +779,28 @@ |
| } |
| ] |
| }, |
| + { |
| + "Name": "golang.org/x/oauth2", |
| + "Version": "v0.35.0", |
| + "SourceURL": "https://pkg.go.dev/golang.org/x/oauth2@v0.35.0", |
| + "Notices": [ |
| + { |
| + "Name": "LICENSE", |
| + "Text": "Copyright 2009 The Go Authors.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n * Neither the name of Google LLC nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" |
| + } |
| + ] |
| + }, |
| + { |
| + "Name": "golang.org/x/sync", |
| + "Version": "v0.22.0", |
| + "SourceURL": "https://pkg.go.dev/golang.org/x/sync@v0.22.0", |
| + "Notices": [ |
| + { |
| + "Name": "LICENSE", |
| + "Text": "Copyright 2009 The Go Authors.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n * Neither the name of Google LLC nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" |
| + } |
| + ] |
| + }, |
| { |
| "Name": "golang.org/x/sys", |
| "Version": "v0.46.0", |
| @@ -735,6 +823,17 @@ |
| } |
| ] |
| }, |
| + { |
| + "Name": "golang.org/x/time", |
| + "Version": "v0.15.0", |
| + "SourceURL": "https://pkg.go.dev/golang.org/x/time@v0.15.0", |
| + "Notices": [ |
| + { |
| + "Name": "LICENSE", |
| + "Text": "Copyright 2009 The Go Authors.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n * Neither the name of Google LLC nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" |
| + } |
| + ] |
| + }, |
| { |
| "Name": "gorm.io/gorm", |
| "Version": "v1.31.2", |
diff --git a/internal/slides/credits/upstream/fastrand-vendor.json b/internal/slides/credits/upstream/fastrand-vendor.json| new file mode 100644 |
| index 0000000..257059d |
| --- /dev/null |
| +++ b/internal/slides/credits/upstream/fastrand-vendor.json |
| @@ -0,0 +1,19 @@ |
| +{ |
| + "name": "fastrand", |
| + "version": "2.5.0", |
| + "directory": "core/vendor/fastrand-2.5.0", |
| + "archive_sha256": "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223", |
| + "patch": "Parsed Cargo.toml removes only normal wasm-target getrandom features=[wasm_js]; dev dependency unchanged. All other vendored files match the upstream archive.", |
| + "files": { |
| + "CHANGELOG.md": "d0ecc653658392738be0daccc920a5c3ffe6996c328a9aa8f26ce897a5db7293", |
| + "Cargo.toml": "bff7c012eceb24c4e87e288fffc9216933d2fb5c4c14d0f992363800ccc9501c", |
| + "LICENSE-APACHE": "a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2", |
| + "LICENSE-MIT": "23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3", |
| + "README.md": "5f3d251d8bc1c793284f4cc720453b280c1c04f968a70b7b36b78d6c1e5c9973", |
| + "benches/bench.rs": "9613f3e9f893ef0c227c158be2c91d766e60b80ce11faf226ac490057ee38546", |
| + "src/global_rng.rs": "f14c504601f9273bf6fa49621cc9dad2329092fd87d35fe8963e55d99f597de2", |
| + "src/lib.rs": "858da6a3831589762ec2214df3f8e8b09a1262708fb08072f1cf13c1260d6ce1", |
| + "tests/char.rs": "a530b41837f5bf43701d983ef0267d9b44779d455f24cbf30b881cd348de9ee1", |
| + "tests/smoke.rs": "0f40e5fd5f382de66cf8ddb7f7e0b3e968d979de75d3658a185d22b11e8e5fc2" |
| + } |
| +} |
diff --git a/internal/slides/decks.go b/internal/slides/decks.go| index ce4e3e1..dc17ae5 100644 |
| --- a/internal/slides/decks.go |
| +++ b/internal/slides/decks.go |
| @@ -162,7 +162,11 @@ func opsJSON(ops []op) ([]byte, error) { |
| // deck is on the team rung" — the whole seam defeated by operator |
| // precedence. |
| func (a *app) visibleDecks(ctx context.Context, viewer User) *gorm.DB { |
| - g := a.db.G.WithContext(ctx).Model(&Deck{}) |
| + return visibleDecksOn(a.db.G.WithContext(ctx), viewer) |
| +} |
| + |
| +func visibleDecksOn(db *gorm.DB, viewer User) *gorm.DB { |
| + g := db.Model(&Deck{}) |
| if viewer.ID <= 0 { |
| // Never reached past RequireSession; refusing outright beats |
| // trusting every caller to have checked, because the value |
| @@ -321,44 +325,7 @@ var errDeckBusy = errors.New("slides: the deck moved while this update was being |
| // diverged from the document's meta. |
| func (a *app) applyOps(ctx context.Context, h *core.Handle, d *Deck, actor string, ops []byte, rowUpdates map[string]any) (*deck.Deck, error) { |
| err := a.db.G.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| - update, err := h.Ops(ctx, ops) |
| - if err != nil { |
| - return fmt.Errorf("slides: apply ops to deck %s: %w", d.Sqid, err) |
| - } |
| - |
| - next := d.Seq + 1 |
| - if err := tx.Create(&DeckUpdate{ |
| - DeckID: d.ID, |
| - Seq: next, |
| - Actor: actor, |
| - Bytes: update, |
| - CreatedAt: time.Now().UTC(), |
| - }).Error; err != nil { |
| - if errors.Is(err, gorm.ErrDuplicatedKey) { |
| - // Somebody else's update is already sitting at this |
| - // seq: the lost race, reported as the lost race. |
| - return errDeckBusy |
| - } |
| - return fmt.Errorf("slides: record deck %s update %d: %w", d.Sqid, next, err) |
| - } |
| - |
| - // Named columns off a map, never a bound struct (SKILL.md §4): |
| - // "seq" is always present so the WHERE ... AND seq = ? clause |
| - // above stays the sole optimistic lock, whether or not this |
| - // call is also renaming the deck. |
| - fields := map[string]any{"seq": next} |
| - for k, v := range rowUpdates { |
| - fields[k] = v |
| - } |
| - res := tx.Model(&Deck{}).Where("id = ? AND seq = ?", d.ID, d.Seq). |
| - Updates(fields) |
| - if res.Error != nil { |
| - return fmt.Errorf("slides: bump deck %s seq: %w", d.Sqid, res.Error) |
| - } |
| - if res.RowsAffected != 1 { |
| - return errDeckBusy |
| - } |
| - return nil |
| + return applyOpsOn(ctx, tx, h, d, actor, ops, rowUpdates) |
| }) |
| if err != nil { |
| return nil, err |
| @@ -390,6 +357,50 @@ func (a *app) applyOps(ctx context.Context, h *core.Handle, d *Deck, actor strin |
| return view, nil |
| } |
| +// applyOpsOn persists one canonical batch in its caller's transaction. |
| +// The caller owns the handle and discards it after rollback. No publication |
| +// or snapshots may occur here: the transaction has not committed. |
| +func applyOpsOn(ctx context.Context, tx *gorm.DB, h *core.Handle, d *Deck, actor string, ops []byte, rowUpdates map[string]any) error { |
| + update, err := h.Ops(ctx, ops) |
| + if err != nil { |
| + return fmt.Errorf("slides: apply ops to deck %s: %w", d.Sqid, err) |
| + } |
| + |
| + next := d.Seq + 1 |
| + if err := tx.Create(&DeckUpdate{ |
| + DeckID: d.ID, |
| + Seq: next, |
| + Actor: actor, |
| + Bytes: update, |
| + CreatedAt: time.Now().UTC(), |
| + }).Error; err != nil { |
| + if errors.Is(err, gorm.ErrDuplicatedKey) { |
| + // Somebody else's update is already sitting at this |
| + // seq: the lost race, reported as the lost race. |
| + return errDeckBusy |
| + } |
| + return fmt.Errorf("slides: record deck %s update %d: %w", d.Sqid, next, err) |
| + } |
| + |
| + // Named columns off a map, never a bound struct (SKILL.md §4): |
| + // "seq" is always present so the WHERE ... AND seq = ? clause |
| + // above stays the sole optimistic lock, whether or not this |
| + // call is also renaming the deck. |
| + fields := map[string]any{"seq": next} |
| + for k, v := range rowUpdates { |
| + fields[k] = v |
| + } |
| + res := tx.Model(&Deck{}).Where("id = ? AND seq = ?", d.ID, d.Seq). |
| + Updates(fields) |
| + if res.Error != nil { |
| + return fmt.Errorf("slides: bump deck %s seq: %w", d.Sqid, res.Error) |
| + } |
| + if res.RowsAffected != 1 { |
| + return errDeckBusy |
| + } |
| + return nil |
| +} |
| + |
| // editDeck is applyOps with the handle's whole life around it: open the |
| // deck, apply, close. One retry on errDeckBusy, from a freshly opened |
| // document — the batch applied nothing, so replaying it against the |
| @@ -423,6 +434,10 @@ func (a *app) editDeck(ctx context.Context, d *Deck, actor string, ops []byte, r |
| // document itself is empty at this point — the caller's first op batch |
| // is what puts anything in it. |
| func (a *app) createDeckRow(ctx context.Context, owner User, title, theme string) (Deck, error) { |
| + return createDeckRowOn(ctx, a.db.G, owner, title, theme) |
| +} |
| + |
| +func createDeckRowOn(ctx context.Context, db *gorm.DB, owner User, title, theme string) (Deck, error) { |
| now := time.Now().UTC() |
| var lastErr error |
| for attempt := 0; attempt < maxSqidAttempts; attempt++ { |
| @@ -439,7 +454,7 @@ func (a *app) createDeckRow(ctx context.Context, owner User, title, theme string |
| CreatedAt: now, |
| UpdatedAt: now, |
| } |
| - err = a.db.G.WithContext(ctx).Create(&d).Error |
| + err = db.WithContext(ctx).Create(&d).Error |
| if err == nil { |
| return d, nil |
| } |
diff --git a/internal/slides/handlers.go b/internal/slides/handlers.go| index 2de7561..602a28d 100644 |
| --- a/internal/slides/handlers.go |
| +++ b/internal/slides/handlers.go |
| @@ -3,6 +3,7 @@ package slides |
| import ( |
| "context" |
| "log/slog" |
| + "net/http" |
| "time" |
| "amadan.net/oficina/home/connect" |
| @@ -26,6 +27,8 @@ import ( |
| // The handlers themselves live beside what they serve: sign-in in |
| // auth.go, the deck screens in decks.go. |
| type app struct { |
| + agent http.Handler |
| + agentAccess *slideAgent |
| home *connect.Bridge |
| homeRoutes *connect.Routes |
| homeSessions *sessions.Sessions |
diff --git a/internal/slides/pdfcore/testdata/slides_pdf.wasm b/internal/slides/pdfcore/testdata/slides_pdf.wasm| index f46e7e9..49b1bcb 100755 |
| Binary files a/internal/slides/pdfcore/testdata/slides_pdf.wasm and b/internal/slides/pdfcore/testdata/slides_pdf.wasm differ |
diff --git a/scripts/build-pdf-wasm.sh b/scripts/build-pdf-wasm.sh| index 95e2ed0..2ed0659 100755 |
| --- a/scripts/build-pdf-wasm.sh |
| +++ b/scripts/build-pdf-wasm.sh |
| @@ -1,27 +1,62 @@ |
| #!/usr/bin/env bash |
| -# Build the PDF crate (core/pdf) for wazero, the same way build-wasm.sh |
| -# builds the CRDT core: plain wasm32 with a C ABI, no wasm-bindgen, no |
| -# wasm-pack, no host imports. |
| +# Build the core crate for wazero. No wasm-bindgen, no wasm-pack: the Go host |
| +# provides no JS glue, so the module must be plain wasm32 with a C ABI. |
| set -euo pipefail |
| cd "$(dirname "$0")/.." |
| -cargo clippy --manifest-path core/pdf/Cargo.toml --all-targets -- -D warnings |
| -# --lib only: the module shipped to wazero is the library crate. |
| -# |
| -# --remap-path-prefix (x2): see build-wasm.sh. rustc bakes the absolute |
| -# path of every panic site into the binary; remapping the registry and |
| -# this checkout to fixed placeholders makes the artefact reproducible |
| -# across machines and $HOMEs, which the gate's byte comparison against |
| -# the committed copy depends on. |
| -# |
| -# The root .cargo/config.toml's rustflags for this target (the getrandom |
| -# custom-backend cfg) are replaced, not extended, by an env RUSTFLAGS, so |
| -# they are repeated here. This crate has no getrandom in its graph (see |
| -# core/pdf/Cargo.toml) and the cfg is inert for it, but keeping the flags |
| -# identical to build-wasm.sh means the two modules are built under one set |
| -# of rules rather than two that could drift. |
| +# Lint the PDF renderer before building its standalone C ABI module. |
| +if [[ "${1:-}" != "--build-only" && "${1:-}" != "--canonical-build" ]]; then |
| + cargo clippy --manifest-path core/pdf/Cargo.toml --all-targets -- -D warnings |
| +fi |
| +# Rust/Cargo crate identities affect code ordering even after path remapping. |
| +# Build on Linux amd64 at fixed source/toolchain paths on every host. |
| +if [[ "${1:-}" == "--canonical-build" ]]; then |
| + [[ "$(uname -s)/$(uname -m)" == "Linux/x86_64" && "$(pwd)" == /work \ |
| + && "$CARGO_HOME" == /usr/local/cargo && "$RUSTUP_HOME" == /usr/local/rustup ]] \ |
| + || { echo "build-pdf-wasm: invalid canonical build environment" >&2; exit 1; } |
| + export CARGO_TARGET_DIR=/work/core/pdf/target RUSTUP_TOOLCHAIN=1.98.0 |
| +else |
| + out="core/pdf/target/wasm32-unknown-unknown/release/slides_pdf.wasm" |
| + mkdir -p "$(dirname "$out")" |
| + temporary=$(mktemp "${out}.XXXXXX") |
| + trap 'rm -f "$temporary"' EXIT |
| + if [[ "$(uname -s)/$(uname -m)" == "Linux/x86_64" ]] && command -v bwrap >/dev/null; then |
| + cargo_home=$(cd "${CARGO_HOME:-$HOME/.cargo}" && pwd) |
| + rustup_home=$(cd "${RUSTUP_HOME:-$HOME/.rustup}" && pwd) |
| + mkdir -p core/pdf/target/canonical-linux-amd64 |
| + bwrap --tmpfs / \ |
| + --ro-bind /usr /usr --tmpfs /usr/local \ |
| + --ro-bind /bin /bin --ro-bind /lib /lib --ro-bind /lib64 /lib64 \ |
| + --ro-bind /etc /etc --bind /tmp /tmp --proc /proc --dev /dev \ |
| + --ro-bind "$(pwd)" /work \ |
| + --bind "$(pwd)/core/pdf/target/canonical-linux-amd64" /work/core/pdf/target \ |
| + --bind "$cargo_home" /usr/local/cargo --ro-bind "$rustup_home" /usr/local/rustup \ |
| + --chdir /work --setenv CARGO_HOME /usr/local/cargo --setenv RUSTUP_HOME /usr/local/rustup \ |
| + --setenv PATH /usr/local/cargo/bin:/usr/local/bin:/usr/bin:/bin \ |
| + bash -ec './scripts/build-pdf-wasm.sh --canonical-build >&2; cat core/pdf/target/wasm32-unknown-unknown/release/slides_pdf.wasm' > "$temporary" |
| + else |
| + command -v docker >/dev/null || { echo "build-pdf-wasm: install Docker, or bubblewrap on Linux amd64" >&2; exit 1; } |
| + target_key=$(printf %s "$(pwd)" | shasum -a 256 | cut -c1-16) |
| + docker run --rm --platform linux/amd64 \ |
| + --mount "type=bind,source=$(pwd),target=/work,readonly" \ |
| + --mount "type=volume,source=oficina-slides-pdf-wasm-target-${target_key},target=/work/core/pdf/target" \ |
| + --mount type=volume,source=oficina-slides-pdf-wasm-cargo,target=/usr/local/cargo \ |
| + --mount type=volume,source=oficina-slides-pdf-wasm-rustup,target=/usr/local/rustup \ |
| + --workdir /work \ |
| + rust@sha256:8aea3a845c48caac4091a8d0e6494d213061f8f014dc2f5a5f1a88a1a8c9f301 \ |
| + bash -ec 'rustup target add wasm32-unknown-unknown >&2; ./scripts/build-pdf-wasm.sh --canonical-build >&2; cat core/pdf/target/wasm32-unknown-unknown/release/slides_pdf.wasm' > "$temporary" |
| + fi |
| + mv "$temporary" "$out" |
| + exit 0 |
| +fi |
| +# Ship only the PDF library. Fixed path remapping and stripped symbols keep |
| +# diagnostics and local crate identities independent of the checkout location. |
| +# The custom getrandom cfg is inert for the PDF dependency graph, but retains |
| +# the workspace wasm configuration when RUSTFLAGS replaces config-file flags. |
| registry_root="${CARGO_HOME:-$HOME/.cargo}/registry/src" |
| workspace_root="$(pwd)" |
| -export RUSTFLAGS="--cfg getrandom_backend=\"custom\" --remap-path-prefix=${registry_root}=/cargo-registry-src --remap-path-prefix=${workspace_root}=/slides-pdf" |
| +# Cargo also puts local path dependency identities into mangled debug names. |
| +# Remove that optional symbol section so identical code reproduces across worktrees. |
| +export RUSTFLAGS="-C strip=symbols --cfg getrandom_backend=\"custom\" --remap-path-prefix=${registry_root}=/cargo-registry-src --remap-path-prefix=${workspace_root}=/slides-pdf" |
| cargo build --release --manifest-path core/pdf/Cargo.toml --target wasm32-unknown-unknown --locked --lib |
| out="core/pdf/target/wasm32-unknown-unknown/release/slides_pdf.wasm" |
| [ -f "$out" ] || { echo "build-pdf-wasm: no artifact at $out" >&2; exit 1; } |
diff --git a/scripts/build-wasm.sh b/scripts/build-wasm.sh| index c56cdfe..dbd11b1 100755 |
| --- a/scripts/build-wasm.sh |
| +++ b/scripts/build-wasm.sh |
| @@ -8,12 +8,55 @@ cd "$(dirname "$0")/.." |
| # Doc::with_client_id() both draw entropy this build has no safe source |
| # for. A doc comment alone has been wrong, or gotten around, more than |
| # once; this is the actual enforcement. |
| -cargo clippy --manifest-path core/Cargo.toml --all-targets -- -D warnings -D clippy::disallowed_methods |
| -# --lib only: the wasm module shipped to wazero is the library crate. Any |
| -# native tooling this crate ever grows under src/bin would not be part of |
| -# that artifact and would not define the __getrandom_v03_custom symbol |
| -# itself, so building it for wasm32 would fail to link -- it isn't meant to |
| -# run there. |
| +if [[ "${1:-}" != "--build-only" && "${1:-}" != "--canonical-build" ]]; then |
| + cargo clippy --manifest-path core/Cargo.toml --all-targets -- -D warnings -D clippy::disallowed_methods |
| +fi |
| +# Rust/Cargo crate identities affect code ordering even after path remapping. |
| +# Build on Linux amd64 at fixed source/toolchain paths on every host. |
| +if [[ "${1:-}" == "--canonical-build" ]]; then |
| + [[ "$(uname -s)/$(uname -m)" == "Linux/x86_64" && "$(pwd)" == /work \ |
| + && "$CARGO_HOME" == /usr/local/cargo && "$RUSTUP_HOME" == /usr/local/rustup ]] \ |
| + || { echo "build-wasm: invalid canonical build environment" >&2; exit 1; } |
| + export CARGO_TARGET_DIR=/work/core/target RUSTUP_TOOLCHAIN=1.98.0 |
| +else |
| + out="core/target/wasm32-unknown-unknown/release/slides_core.wasm" |
| + mkdir -p "$(dirname "$out")" |
| + temporary=$(mktemp "${out}.XXXXXX") |
| + trap 'rm -f "$temporary"' EXIT |
| + if [[ "$(uname -s)/$(uname -m)" == "Linux/x86_64" ]] && command -v bwrap >/dev/null; then |
| + cargo_home=$(cd "${CARGO_HOME:-$HOME/.cargo}" && pwd) |
| + rustup_home=$(cd "${RUSTUP_HOME:-$HOME/.rustup}" && pwd) |
| + mkdir -p core/target/canonical-linux-amd64 |
| + bwrap --tmpfs / \ |
| + --ro-bind /usr /usr --tmpfs /usr/local \ |
| + --ro-bind /bin /bin --ro-bind /lib /lib --ro-bind /lib64 /lib64 \ |
| + --ro-bind /etc /etc --bind /tmp /tmp --proc /proc --dev /dev \ |
| + --ro-bind "$(pwd)" /work \ |
| + --bind "$(pwd)/core/target/canonical-linux-amd64" /work/core/target \ |
| + --bind "$cargo_home" /usr/local/cargo --ro-bind "$rustup_home" /usr/local/rustup \ |
| + --chdir /work --setenv CARGO_HOME /usr/local/cargo --setenv RUSTUP_HOME /usr/local/rustup \ |
| + --setenv PATH /usr/local/cargo/bin:/usr/local/bin:/usr/bin:/bin \ |
| + bash -ec './scripts/build-wasm.sh --canonical-build >&2; cat core/target/wasm32-unknown-unknown/release/slides_core.wasm' > "$temporary" |
| + else |
| + command -v docker >/dev/null || { echo "build-wasm: install Docker, or bubblewrap on Linux amd64" >&2; exit 1; } |
| + target_key=$(printf %s "$(pwd)" | shasum -a 256 | cut -c1-16) |
| + docker run --rm --platform linux/amd64 \ |
| + --mount "type=bind,source=$(pwd),target=/work,readonly" \ |
| + --mount "type=volume,source=oficina-slides-core-wasm-target-${target_key},target=/work/core/target" \ |
| + --mount type=volume,source=oficina-slides-core-wasm-cargo,target=/usr/local/cargo \ |
| + --mount type=volume,source=oficina-slides-core-wasm-rustup,target=/usr/local/rustup \ |
| + --workdir /work \ |
| + rust@sha256:8aea3a845c48caac4091a8d0e6494d213061f8f014dc2f5a5f1a88a1a8c9f301 \ |
| + bash -ec 'rustup target add wasm32-unknown-unknown >&2; ./scripts/build-wasm.sh --canonical-build >&2; cat core/target/wasm32-unknown-unknown/release/slides_core.wasm' > "$temporary" |
| + fi |
| + mv "$temporary" "$out" |
| + exit 0 |
| +fi |
| +# --lib only: the wasm module shipped to wazero is the library crate. Native |
| +# tooling under src/bin (e.g. emit_update, used from the host side of |
| +# wire-gate.sh) is never part of that artifact and does not define the |
| +# __getrandom_v03_custom symbol itself, so building it for wasm32 fails to |
| +# link -- it was never meant to run there. |
| # |
| # --remap-path-prefix (x2): rustc embeds the absolute source path of every |
| # panic site (Location::caller()) into the binary. Left alone, that means |
| @@ -36,7 +79,9 @@ cargo clippy --manifest-path core/Cargo.toml --all-targets -- -D warnings -D cli |
| # it has to be repeated here alongside the remap flags. |
| registry_root="${CARGO_HOME:-$HOME/.cargo}/registry/src" |
| workspace_root="$(pwd)" |
| -export RUSTFLAGS="--cfg getrandom_backend=\"custom\" --remap-path-prefix=${registry_root}=/cargo-registry-src --remap-path-prefix=${workspace_root}=/slides-core" |
| +# Cargo also puts local path dependency identities into mangled debug names. |
| +# Remove that optional symbol section so identical code reproduces across worktrees. |
| +export RUSTFLAGS="-C strip=symbols --cfg getrandom_backend=\"custom\" --remap-path-prefix=${registry_root}=/cargo-registry-src --remap-path-prefix=${workspace_root}=/slides-core" |
| cargo build --release --manifest-path core/Cargo.toml --target wasm32-unknown-unknown --locked --lib |
| out="core/target/wasm32-unknown-unknown/release/slides_core.wasm" |
| [ -f "$out" ] || { echo "build-wasm: no artifact at $out" >&2; exit 1; } |
diff --git a/scripts/credits.py b/scripts/credits.py| index ad816ae..090baeb 100755 |
| --- a/scripts/credits.py |
| +++ b/scripts/credits.py |
| @@ -12,7 +12,7 @@ from html.parser import HTMLParser |
| ROOT = Path(__file__).resolve().parent.parent |
| OUT = ROOT / 'internal/slides/credits' |
| ENV = os.environ | {'GOPRIVATE': 'amadan.net/oficina/estilo.git'} |
| -EXCLUDE = ','.join(['amadan.net/oficina/estilo.git', 'amadan.net/oficina/home/handoff', 'amadan.net/oficina/home/connect']) |
| +EXCLUDE = ','.join(['amadan.net/oficina/estilo.git', 'amadan.net/oficina/home/handoff', 'amadan.net/oficina/home/connect', 'amadan.net/oficina/agent-access.git']) |
| def run(args, cwd=ROOT, env=ENV): |
| @@ -25,7 +25,7 @@ def digest(path): |
| def inputs(): |
| files = [ROOT / p for p in ['core/Cargo.toml', 'core/Cargo.lock', 'core/pdf/Cargo.toml', 'core/pdf/Cargo.lock', 'rust-toolchain.toml', 'fixtures/package.json', 'fixtures/package-lock.json', 'internal/slides/core/testdata/slides_core.wasm', 'internal/slides/pdfcore/testdata/slides_pdf.wasm']] |
| - for pattern in ['internal/slides/static/*.js', 'internal/slides/fonts/files/*', 'internal/slides/static/fonts/*', 'internal/slides/credits/upstream/*']: |
| + for pattern in ['internal/slides/static/*.js', 'internal/slides/fonts/files/*', 'internal/slides/static/fonts/*', 'internal/slides/credits/upstream/*', 'core/vendor/fastrand-2.5.0/**/*']: |
| files.extend(ROOT.glob(pattern)) |
| return {str(p.relative_to(ROOT)): digest(p) for p in sorted(files) if p.is_file()} |
| @@ -67,6 +67,27 @@ class NoticeText(HTMLParser): |
| self.parts.append('\n') |
| +def verified_vendor(package): |
| + record = json.loads((OUT / 'upstream/fastrand-vendor.json').read_text()) |
| + directory = ROOT / 'core/vendor/fastrand-2.5.0' |
| + manifest = Path(package['manifest_path']) |
| + if (package['source'] is not None or package['name'] != 'fastrand' |
| + or package['version'] != '2.5.0' |
| + or manifest != directory / 'Cargo.toml' |
| + or manifest.resolve() != directory / 'Cargo.toml'): |
| + raise ValueError('unverified Cargo source replacement') |
| + files = {} |
| + for path in directory.rglob('*'): |
| + if path.is_symlink(): |
| + raise ValueError('vendored source must not contain symlinks') |
| + if path.is_file(): |
| + files[str(path.relative_to(directory))] = digest(path) |
| + # This reviewed manifest is anchored to the recorded upstream crate archive. |
| + # Its only source difference is the documented Cargo feature patch. |
| + if files != record['files']: |
| + raise ValueError('vendored source differs from verified upstream patch') |
| + |
| + |
| def asset_inventory(): |
| fixtures = ROOT / 'fixtures' |
| run(['npm', 'ci', '--ignore-scripts', '--no-audit', '--no-fund'], cwd=fixtures) |
| @@ -119,7 +140,7 @@ console.log(JSON.stringify([...inputs])); |
| package = packages[identity] |
| if identity != metadata['resolve']['root']: |
| if package['source'] != 'registry+https://github.com/rust-lang/crates.io-index': |
| - raise ValueError('unverified Cargo source replacement') |
| + verified_vendor(package) |
| selected[(package['name'], package['version'])] = package |
| for key in sorted(selected): |
| package = selected[key] |