oficina / meet Public

Add delegated calls, roster authority checks and durable scheduling reservations

Prompts:

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

Squashed from feat/agent-access into main.
codex agent, operated by paul@keymail.dev ef2335e9df94bf9be1561fcbb1335c87e7c6e4ca parent 7baaea2
38 files changed, +2,419 −20
  • Makefile +3 −2
  • README.md +15 −0
  • cmd/calls-contract/main.go +17 −0
  • cmd/calls/main.go +2 −0
  • docs/superpowers/specs/2026-09-07-meet-design.md +55 −0
  • docs/superpowers/specs/2026-10-25-agent-response-authorization.md +13 −0
  • docs/superpowers/specs/2026-10-25-delegation-hardening.md +24 −0
  • docs/superpowers/specs/2026-11-01-schedule-reservation-and-roster.md +65 −0
  • go.mod +13 −3
  • go.sum +26 −2
  • internal/calls/agents.go +3 −0
  • internal/calls/app.go +22 −11
  • internal/calls/config.go +5 −0
  • internal/calls/credits/notices.json +99 −0
  • internal/calls/credits_inventory_test.go +1 −1
  • internal/calls/delegated.go +159 −0
  • internal/calls/delegated_attribution_test.go +50 −0
  • internal/calls/delegated_authority.go +89 −0
  • internal/calls/delegated_authority_test.go +153 −0
  • internal/calls/delegated_boundaries_test.go +158 −0
  • internal/calls/delegated_continuity_test.go +85 −0
  • internal/calls/delegated_create.go +142 −0
  • internal/calls/delegated_migrations/migrations/0001_connections.sql +2 −0
  • internal/calls/delegated_migrations/migrations/0002_authority.sql +4 −0
  • internal/calls/delegated_migrations/migrations/0003_schedule.sql +1 −0
  • internal/calls/delegated_operations.go +43 −0
  • internal/calls/delegated_read.go +118 −0
  • internal/calls/delegated_recorder_test.go +12 −0
  • internal/calls/delegated_response.go +85 −0
  • internal/calls/delegated_response_test.go +234 −0
  • internal/calls/delegated_review_test.go +184 −0
  • internal/calls/delegated_schedule.go +72 −0
  • internal/calls/delegated_schedule_test.go +165 −0
  • internal/calls/delegated_team.go +69 −0
  • internal/calls/delegated_test.go +222 −0
  • internal/calls/store.go +1 −1
  • internal/calls/team_guard_test.go +3 −0
  • internal/calls/team_host.go +5 −0

CI failed — run details

landed from feat/agent-access

diff --git a/Makefile b/Makefile
index 5e8fe46..795a27f 100644
--- a/Makefile
+++ b/Makefile
@@ -1,4 +1,5 @@
-export GOPRIVATE := $(GOPRIVATE),amadan.net/oficina/estilo.git
+export GOTOOLCHAIN := go1.26.5
+export GOPRIVATE := $(GOPRIVATE),amadan.net/oficina/estilo.git,amadan.net/oficina/agent-access.git
# The gate's toolchain. TestCreditsMatchProductionDependencies puts the Go
# version into the credits inventory, so the gate refuses any toolchain
@@ -234,6 +235,6 @@ credits:
go build -o "$$notices_tmp/notices" amadan.net/oficina/estilo.git/cmd/oficina-notices; \
GOOS=linux GOARCH=arm64 CGO_ENABLED=0 "$$notices_tmp/notices" \
-package ./cmd/calls -lucide -onest \
- -exclude amadan.net/oficina/estilo.git,amadan.net/oficina/home/connect,amadan.net/oficina/home/handoff,amadan.net/oficina/home/roster,amadan.net/oficina/home/teammode \
+ -exclude amadan.net/oficina/agent-access.git,amadan.net/oficina/estilo.git,amadan.net/oficina/home/connect,amadan.net/oficina/home/handoff,amadan.net/oficina/home/roster,amadan.net/oficina/home/teammode \
> "$$notices_tmp/notices.json"; \
mv "$$notices_tmp/notices.json" internal/calls/credits/notices.json
diff --git a/README.md b/README.md
index 3863229..136af6b 100644
--- a/README.md
+++ b/README.md
@@ -213,3 +213,18 @@ person's own standing in this meeting without a second sign-in, in whatever
browser they happen to be using. An app already signed in as someone who can
join the meeting uses its own session and needs no browser. Browser joining
remains available when the app is not installed.
+
+## Oficina delegated connection
+
+The opt-in suite API exposes five descriptors through `calls-contract`:
+`calls_list_meetings`, `calls_get_meeting`, `calls_create_meeting`,
+`calls_get_join_link`, and `calls_reserve_schedule`. Configure both
+`CALLS_AGENT_ISSUER` and `CALLS_AGENT_TEAM` alongside Home; in roster mode the
+agent team must match `CALLS_TEAM_ID`. A delegated request resolves an existing
+linked local account and checks its current permissions.
+
+The reservation operation supports the shared gateway's `calls_schedule`
+workflow. It binds a UUID to a keyed request fingerprint; app-owned receipts
+provide retry progress. It creates no meeting itself and sends no invitations.
+See the [reservation and roster contract](docs/superpowers/specs/2026-11-01-schedule-reservation-and-roster.md).
+This feature branch is not a claim that the production endpoint is enabled.
diff --git a/cmd/calls-contract/main.go b/cmd/calls-contract/main.go
new file mode 100644
index 0000000..7075253
--- /dev/null
+++ b/cmd/calls-contract/main.go
@@ -0,0 +1,17 @@
+package main
+
+import (
+ "amadan.net/oficina/calls/internal/calls"
+ "encoding/json"
+ "os"
+)
+
+func main() {
+ ops, err := calls.AgentContracts()
+ if err != nil {
+ os.Exit(1)
+ }
+ if json.NewEncoder(os.Stdout).Encode(ops) != nil {
+ os.Exit(1)
+ }
+}
diff --git a/cmd/calls/main.go b/cmd/calls/main.go
index b40f905..76e82ab 100644
--- a/cmd/calls/main.go
+++ b/cmd/calls/main.go
@@ -79,6 +79,8 @@ func run(logger, reportLogger *slog.Logger) error {
// none (nil when all are empty), verified against the Home
// credentials above before anything migrates (team_config.go).
Team: teammode.ConfigFromEnv("CALLS"),
+ AgentIssuer: os.Getenv("CALLS_AGENT_ISSUER"),
+ AgentTeam: os.Getenv("CALLS_AGENT_TEAM"),
Env: *env,
Origin: os.Getenv("CALLS_ORIGIN"),
InstanceKey: os.Getenv("CALLS_INSTANCE_KEY"),
diff --git a/docs/superpowers/specs/2026-09-07-meet-design.md b/docs/superpowers/specs/2026-09-07-meet-design.md
index 58b20d4..bed5f45 100644
--- a/docs/superpowers/specs/2026-09-07-meet-design.md
+++ b/docs/superpowers/specs/2026-09-07-meet-design.md
@@ -2981,6 +2981,61 @@ that costs it once the browser and the server are new.
Chromium's starts at full size, the same before and after) is WebKit's
bandwidth estimate, and is left alone.
+## Delegated Oficina connection — implementation draft, 2026-10-24
+
+The suite connection is an additional opt-in machine surface. Set both
+`CALLS_AGENT_ISSUER` and `CALLS_AGENT_TEAM` with Home configured; incomplete
+configuration refuses startup. `/api/v1/operations` and its named operations
+use app-audience credentials verified online by the Oficina connection service.
+They do not accept browser cookies or the existing `mt_` tokens. The existing
+meeting API and native browser authentication retain their current contracts.
+
+Each request resolves the opaque Home subject to an already linked person and
+rechecks member standing, selected team, and operation scope. It provisions no
+person or local agent credential. Membership remains team-wide for meetings,
+as on the existing API. The existing per-agent request budget also applies,
+keyed by a purpose-separated digest of Home subject and client.
+
+`calls_list_meetings` and `calls_get_meeting` require `calls:read`; lists use a
+bounded ID cursor, and neither exposes a guest invitation. `calls_create_meeting`
+requires `calls:write`, an explicit title and nonzero UUID `client_id`, with an
+optional RFC3339 start including its offset. It returns the member room URL and
+`invitations_sent: false`. Calendar events remain Calendar's responsibility.
+
+Creation uses the existing meeting store and defaults. Meeting, sealed invitation,
+creator attribution and retry receipt commit in one transaction. Receipt keys
+bind Home subject, client, team and UUID using a purpose-separated keyed digest;
+the request fingerprint is also keyed. A changed retry conflicts; a deleted
+meeting is never recreated by replay. Retrying an ended meeting returns its
+existing room ID without reopening it. Receipts contain no plaintext content.
+
+`connection:<digest>` is an additional attribution kind: the mapping contains
+an existing operator person ID and a sealed client label, never an access token.
+The meeting UI uses its existing agent badge and displays client~operator.
+It does not mint an `agents` row or reinterpret a Home subject as an address.
+
+`calls_get_join_link` requires the separate `calls:share` scope. It retrieves
+only a live invitation whose token is already sealed; it never mints or replaces
+one and does not revive an ended meeting. Legacy hash-only invitations remain
+available through their existing sharing flow. A join URL conveys invitation
+access, so tool descriptions state that it is for intended recipients. No tool
+joins call media, sends mail, ends a meeting, or replaces an invitation in this
+initial adapter. These remain explicit capability gaps.
+
+`go run ./cmd/calls-contract` exports the same operation contracts consumed by
+the suite API, CLI and MCP gateway. The temporary transport lives in the
+Oficina agent-access module and will converge with Rastrillo; this amendment
+does not claim upstream MCP compatibility or production deployment. Independent
+review and the repository's release checks remain required before merge.
+
+GPT-6 Astra approved the adapter and this amendment after correcting cursor
+integer overflow and moving content opening behind the store. Focused race
+checks pass. Nine effective adverse mutations fail for the intended reason:
+sharing scope, ended/revoked/hash-only invitation predicates, ignored creation
+failure, retry fingerprint, transactional operator check, cursor decoding, and
+bypassed Home linkage after unlink. Full CI and canary review remain release
+gates; this is source approval only.
+
### 15.28 §5.1, §5.3, §4.6, §15.23, §15.26 — a connection that stops working is mended, and an old app is named (2026-10-21)
**Why.** 21 October, about 14:41 UTC: Paul, on the Mac app (0.4.10) and
diff --git a/docs/superpowers/specs/2026-10-25-agent-response-authorization.md b/docs/superpowers/specs/2026-10-25-agent-response-authorization.md
new file mode 100644
index 0000000..2b0364f
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-25-agent-response-authorization.md
@@ -0,0 +1,13 @@
+# Guarded app HTTP responses
+
+Status: bounded design approved by GPT-6 Astra with the explicit continuity and fail-closed requirements below; implementation/evidence review pending. Follow-up to close the legacy adapters' response-emission gap. Docs, Sheets and Slides already have app-owned guarded emission; Calendar, Calls and Memoria still use direct Registry.HTTP output.
+
+Add a separate Registry.HTTPGuarded(initial Verifier, recheck Verifier, guard ResponseGuard) entry point. Existing HTTP behavior stays for the connection gateway and compatibility. A nonnil app guard is mandatory. Initial verification may include local admission and one rate-limit charge. Rechecks use the original underlying credential verifier, never the rate-limiting wrapper. Preserve the exact bearer and Subject/Client/Grant; require the original operation's scope and input team on each check. Discovery must retain the originally disclosed team/scope set (revoked facts cannot be emitted). Registry.Call and schemas remain the single invocation path, executed exactly once.
+
+Before serializing success, bound it to MaxPayload. The app callback receives the request context, original principal, operation name, input and result, and revalidates current local identity plus permissions for every returned resource. It must not execute a write, refresh a token or replay the operation. Call original-verifier plus app guard immediately before headers and each at-most-64-KiB write with a five-second context/write deadline (shortened to caller deadline). Fail safely before headers; abort partial HTTP bodies with ErrAbortHandler and exact Content-Length. Do not silently tolerate a transport without write-deadline support. Failure bodies contain no app result. Check the elapsed context deadline after every verifier and guard callback, including callbacks that return nil.
+
+Adapter state is per request, captured before domain execution, and retains stable local person ID/address plus the returned resource set. Calendar rechecks current calendar readability and archive state; event reads/creation capture the event and calendar IDs, then re-read the live event and reject deletion or any change to its captured calendar coordinate, and free/busy must carry calendar provenance from the same range expansion that produced its spans. Calls rechecks local membership and meeting existence; invitation responses additionally require the exact originally returned invitation to remain live and its meeting unended. Memoria checks current Home/local admission, exact live chunk/document pairs, and current sibling custody for the returned revisions. Sibling checks use the existing custody interface without replaying search or recording duplicate breaker statistics. Locally owned created notes require the same current document/receipt identity. Missing or incomplete resource provenance fails closed. Memoria freezes the original sibling item/revision coordinates; current coordinates must still match, and every original candidate must receive an explicit VISIBLE/renderable custody disposition. Missing, short, or non-renderable dispositions fail closed. Never filter a selected response midway through emission. No second model call and no repeated mutation.
+
+Tests use actual HTTP transport to prove revocation/permission loss after the first chunk truncates the body, plus preheader rejection, successful-principal continuity, metadata revocation, deadline failure/timeout, single domain invocation, and one Calls rate charge. App tests distinguish loss of local identity, item permission, invitation revocation, missing/stale chunks and changed sibling visibility. Writer-boundary regression tests must remain discriminating now that a later response guard could mask a missing transaction guard. Effective mutants omit preheader versus chunk checks independently and each app's resource guard. Run full shared and affected app CI/race checks, independent source/evidence review, then exact module pins.
+
+Consumer pins shared module 4b94ff9. Design approval: GPT-6 Astra. App implementation/evidence review is recorded in the existing agent-access branch discussion. Source and tests are additive to the already reviewed create/retry authority boundary; direct completed-retry tests prevent later HTTP checks masking missing transaction checks.
diff --git a/docs/superpowers/specs/2026-10-25-delegation-hardening.md b/docs/superpowers/specs/2026-10-25-delegation-hardening.md
new file mode 100644
index 0000000..4b3432e
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-25-delegation-hardening.md
@@ -0,0 +1,24 @@
+# Delegated Calls mutation authority
+
+Status: bounded design approved by GPT-6 Astra on 2026-10-25 in the joint
+Memoria/Calendar/Calls review. Implementation review, CI and canary remain.
+
+Bind the receipt key, exact Home issuer, delegation issuer and instance team in
+a keyed singleton marker. Adopt only under writer reservation when both receipt
+and connection-attribution tables are empty. Check at enablement and before each
+mutation's receipt lookup; changed or missing binding requires explicit migration.
+Both issuers enter receipt and attribution coordinates.
+
+Retain a private request callback to the original credential's underlying
+verifier. Compare subject, client, grant, team and calls:write. Never call local
+DB or rate-limit wrappers inside the writer transaction. Check delegation and
+the transaction-local Home link/person/current membership after reserving the
+writer and again immediately before commit, including completed retries. Missing
+callback refuses. Meeting, invitation, attribution and receipt remain atomic.
+Malformed Unicode fails before lossy JSON decoding.
+
+Tests must distinguish initial versus final checks, completed retry checks,
+post-mount marker tampering, changed verifier principals, current unlink and
+membership loss, and failure rollback. Test reopened databases and immutable
+configuration, then run adverse mutations and full CI. Existing direct
+Registry.HTTP read emission remains a separate response-revalidation gap.
diff --git a/docs/superpowers/specs/2026-11-01-schedule-reservation-and-roster.md b/docs/superpowers/specs/2026-11-01-schedule-reservation-and-roster.md
new file mode 100644
index 0000000..7ca41b0
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-01-schedule-reservation-and-roster.md
@@ -0,0 +1,65 @@
+# Delegated scheduling reservations and roster integration
+
+Status: implemented on feat/agent-access; independent GPT-6 Astra specification
+review approved the shared scheduling design, and GPT-6 Astra
+`notes_calendar_editing` approved this Calls integration after source review and
+eight effective behavioral mutations. No deployment or main merge is claimed.
+
+## Contract
+
+`calls_reserve_schedule` requires calls:write, the configured team, a canonical
+nonzero UUID client_id, and a lowercase 64-character SHA-256 fingerprint. It
+returns `{reserved:true}`. The shared gateway fingerprints the versioned typed
+workflow request before any agenda, meeting or event effect. Calls stores only
+purpose-separated keyed coordinate/content fingerprints. The coordinate binds
+both issuers, Home subject, client, team, operation and UUID. A changed request
+conflicts. Reservation creates no content, invitation or local agent identity.
+
+The writer reservation, immutable authority marker, linked person and original
+credential checks precede lookup/write. A final authority check runs for both
+fresh and completed reservations. Existing schedule rows prevent adoption of a
+missing marker. Each destination app's atomic create receipt owns progress;
+there is no central workflow-content store or cross-app transaction.
+
+## Reconciliation with current main
+
+Current main's roster mode remains authoritative. Delegated requests require an
+already linked local account via ResolveOn; browser Home-only provisioning is
+not a delegated side effect. Initial membership captures one roster Access.
+Writer and response checks retain that same lease, and transaction-local stores
+retain the team runtime. No roster network fetch happens under the writer.
+The real response writer clamps deadlines to the captured lease, including the
+host's lease when disclosing an invitation. Final checks follow database reads.
+
+A meeting attributed to `connection:<digest>` stands on the stored operator
+person, just as an existing local agent's meeting stands on its operator.
+Invitation reads check the host's current standing and preserve the exact live
+sealed invitation. An unknown roster answer is unavailable, never nonmembership.
+Agent team configuration must match roster team configuration before migration.
+Existing non-team admission behavior remains covered by the delegated suite.
+
+## Evidence
+
+New tests cover concurrent reservation retries, changed request conflicts,
+client isolation, keyed-only storage, absence of content side effects, marker
+loss, transaction rollback, team removal/expiry, and connection host resolution.
+The independent review adds direct fresh/replay final-writer tests, transaction
+team-guard rollback, real socket deadline clamping and a direct post-query lease
+check that cannot be masked by the transport's independent guard.
+
+Eight selected faults each caused behavioral failures: accepting changed
+fingerprints; dropping final reservation authority; adopting orphaned schedule
+rows; losing the team runtime in reservation or meeting transactions; omitting
+socket deadline clamping; omitting the post-query standing check; and losing
+connection-operator host resolution. Restored focused race tests pass.
+The enumerated team-write gate includes both delegated write operations.
+
+The shared three-app HTTPS acceptance uses this real Calls handler and sealed
+store alongside real Docs and Calendar. It passes lost-response resumption,
+exact replay, changed request conflict, readable cross-app references and
+revocation. This is private fixture evidence, not live four-client acceptance.
+
+Final restored-tree validation: `TMPDIR=/tmp make ci` passed (vet, formatting,
+all Go packages and migration agreement); `TMPDIR=/tmp make race` passed all
+internal packages, including the call hub and end-to-end call tests. The
+independent reviewer approved the final write-inventory/documentation delta.
diff --git a/go.mod b/go.mod
index 7878397..4e9c4ca 100644
--- a/go.mod
+++ b/go.mod
@@ -3,13 +3,16 @@ module amadan.net/oficina/calls
go 1.26.0
require (
+ amadan.net/oficina/agent-access.git v0.0.0-20261025011012-4b94ff9e8a8d
amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d
- amadan.net/oficina/home/connect v0.0.0-20261028171508-67c12e39a9d2
+ amadan.net/oficina/home/connect v0.0.0-20261030223040-6d99b0ccc542
amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d
amadan.net/oficina/home/roster v0.0.0-20261028171508-67c12e39a9d2
amadan.net/oficina/home/teammode v0.0.0-20261028171508-67c12e39a9d2
amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060
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/keymaildev/signin v0.1.1
golang.org/x/crypto v0.56.0
gorm.io/gorm v1.31.2
@@ -20,16 +23,23 @@ require (
github.com/BurntSushi/toml v1.6.0 // indirect
github.com/carlosframework/rastrillo v0.23.0 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
- github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 // indirect
- github.com/google/uuid v1.6.0 // indirect
+ github.com/google/jsonschema-go v0.4.3 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
+ github.com/modelcontextprotocol/go-sdk v1.7.0 // 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
golang.org/x/mod v0.38.0 // indirect
+ golang.org/x/oauth2 v0.35.0 // indirect
+ golang.org/x/sync v0.22.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/text v0.41.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 47975ca..a997cb9 100644
--- a/go.sum
+++ b/go.sum
@@ -1,7 +1,9 @@
+amadan.net/oficina/agent-access.git v0.0.0-20261025011012-4b94ff9e8a8d h1:bSsf1NXVhXTfLLB9J7a5v9CqzdKj8CALHZ6W3H7A/4M=
+amadan.net/oficina/agent-access.git v0.0.0-20261025011012-4b94ff9e8a8d/go.mod h1:Ph9PIa3VE1IEaUzZiQH6D+IQ6HThWWGfVr0ecMMgrFA=
amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d h1:p9+01xRdBD7s1viTINgQ6XoDD5ghOxYubD7FNcjhBTw=
amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
-amadan.net/oficina/home/connect v0.0.0-20261028171508-67c12e39a9d2 h1:MPO8MRkk+tT2k+95fZPJ0JStnmAKUCKiVoPbfBVTk6E=
-amadan.net/oficina/home/connect v0.0.0-20261028171508-67c12e39a9d2/go.mod h1:ix81eFV87yE9f2SXiRuxYCVM4lAgTRC5YoQMiH3+TDk=
+amadan.net/oficina/home/connect v0.0.0-20261030223040-6d99b0ccc542 h1:b2JT0B0Y+5sTsCmVhX6cywCRdGd9s3lRP8wpqOytlbM=
+amadan.net/oficina/home/connect v0.0.0-20261030223040-6d99b0ccc542/go.mod h1:ix81eFV87yE9f2SXiRuxYCVM4lAgTRC5YoQMiH3+TDk=
amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d h1:8RTZkLQnyxvH2g0RMovhN/m2LN9D8qb+kBfqdBeqq+s=
amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k=
amadan.net/oficina/home/roster v0.0.0-20261028171508-67c12e39a9d2 h1:yKUTS0nOiVw7ktHpTin0bCcUDLFjmMjpW6CsHIZzZKk=
@@ -22,6 +24,8 @@ 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/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
+github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY=
@@ -36,6 +40,12 @@ 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/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
+github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
+github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
+github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -52,16 +62,28 @@ 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/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/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=
golang.org/x/crypto v0.56.0 h1:GUh5Ii4J5jtcseSMiRqr1jXCNHoxjeV9Fmekc2oLy6Y=
golang.org/x/crypto v0.56.0/go.mod h1:OMW5y6CY9l38uPLmxU6l6pwcXp1obtLo3e6gT7gQR2I=
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
+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=
@@ -69,6 +91,8 @@ golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
+golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
+golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
diff --git a/internal/calls/agents.go b/internal/calls/agents.go
index 059ca15..92653aa 100644
--- a/internal/calls/agents.go
+++ b/internal/calls/agents.go
@@ -220,6 +220,9 @@ func (s *store) withOperator(ctx context.Context, ag Agent, err error) (Agent, P
// the raw actor string rather than failing the whole list, logged the
// way store.title logs an unreadable title.
func (s *store) creatorLabel(ctx context.Context, actor string) string {
+ if strings.HasPrefix(actor, "connection:") {
+ return s.delegatedCreator(ctx, strings.TrimPrefix(actor, "connection:"))
+ }
kind, rest, found := strings.Cut(actor, ":")
if !found {
return actor
diff --git a/internal/calls/app.go b/internal/calls/app.go
index ec624b2..7af20ec 100644
--- a/internal/calls/app.go
+++ b/internal/calls/app.go
@@ -32,17 +32,19 @@ import (
// app holds what every handler needs.
type app struct {
// signinMail is the queue sign-in links go through (signin_mail.go).
- signinMail *mailQueue
- db *db.DB
- cfg resolved
- sealer *seal.Sealer
- store *store
- logger *slog.Logger
- auth *rauth.Auth
- home *homeIntegration
- nativeAuth *nativeAuthorization
- linkBudget *budget
- outsiderBudget *budget
+ signinMail *mailQueue
+ db *db.DB
+ cfg resolved
+ sealer *seal.Sealer
+ store *store
+ logger *slog.Logger
+ auth *rauth.Auth
+ home *homeIntegration
+ delegated http.Handler
+ agentIssuer, agentTeam string
+ nativeAuth *nativeAuthorization
+ linkBudget *budget
+ outsiderBudget *budget
// overBudget counts outsider sign-in attempts the budgets refused,
// for sweepHourly to report: never logged on the response path.
overBudget atomic.Int64
@@ -483,6 +485,11 @@ func build(ctx context.Context, d *db.DB, cfg Config) (*http.ServeMux, *app, err
return nil, nil, fmt.Errorf("calls: team mode: %w", err)
}
+ if err := a.wireDelegated(); err != nil {
+ a.signinMail.close()
+ return nil, nil, err
+ }
+
if err := a.wireNativeAuth(); err != nil {
a.signinMail.close()
return nil, nil, err
@@ -511,6 +518,10 @@ func build(ctx context.Context, d *db.DB, cfg Config) (*http.ServeMux, *app, err
// page. apiRoutes says why that is safe — this surface honours no
// cookie, so there is no ambient credential for CSRF to protect.
r.Group(a.apiRoutes)
+ if a.delegated != nil {
+ r.Handle("/api/v1/operations", a.delegated)
+ r.Handle("/api/v1/operations/*", a.delegated)
+ }
// The team readiness probe: unauthenticated, outside every session
// middleware, and {"team_mode":false} with team mode off.
r.Get(teammode.ProbePath, a.teamProbe)
diff --git a/internal/calls/config.go b/internal/calls/config.go
index 34136a7..ae1cacd 100644
--- a/internal/calls/config.go
+++ b/internal/calls/config.go
@@ -39,6 +39,8 @@ type Config struct {
// Production leaves both nil.
teamTransport http.RoundTripper
teamClock roster.Clock
+ AgentIssuer string
+ AgentTeam string
// Env is "development" or anything else (treated as production).
Env string
// Origin is the app's external origin, scheme included
@@ -127,6 +129,9 @@ type resolved struct {
}
func resolve(cfg Config) (resolved, error) {
+ if err := validateDelegatedConfig(cfg); err != nil {
+ return resolved{}, err
+ }
if cfg.Logger == nil {
cfg.Logger = slog.Default()
}
diff --git a/internal/calls/credits/notices.json b/internal/calls/credits/notices.json
index 9eb07c9..6ea672c 100644
--- a/internal/calls/credits/notices.json
+++ b/internal/calls/credits/notices.json
@@ -107,6 +107,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",
@@ -146,6 +157,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",
@@ -157,6 +179,50 @@
}
]
},
+ {
+ "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/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 \u003chttps://yosida95.com/\u003e. 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/crypto",
"Version": "v0.56.0",
@@ -168,6 +234,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.47.0",
@@ -190,6 +278,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/calls/credits_inventory_test.go b/internal/calls/credits_inventory_test.go
index bd4821e..71ca8c8 100644
--- a/internal/calls/credits_inventory_test.go
+++ b/internal/calls/credits_inventory_test.go
@@ -60,7 +60,7 @@ func TestCreditsMatchProductionDependencies(t *testing.T) {
if err != nil {
t.Fatal("production dependency graph unavailable", err)
}
- inventory, err := catalog.Collect(bytes.NewReader(raw), map[string]bool{"amadan.net/oficina/estilo.git": true, "amadan.net/oficina/home/handoff": true, "amadan.net/oficina/home/connect": true, "amadan.net/oficina/home/roster": true, "amadan.net/oficina/home/teammode": true})
+ inventory, err := catalog.Collect(bytes.NewReader(raw), map[string]bool{"amadan.net/oficina/agent-access.git": true, "amadan.net/oficina/estilo.git": true, "amadan.net/oficina/home/handoff": true, "amadan.net/oficina/home/connect": true, "amadan.net/oficina/home/roster": true, "amadan.net/oficina/home/teammode": true})
if err != nil {
t.Fatal(err)
}
diff --git a/internal/calls/delegated.go b/internal/calls/delegated.go
new file mode 100644
index 0000000..ea6f887
--- /dev/null
+++ b/internal/calls/delegated.go
@@ -0,0 +1,159 @@
+package calls
+
+import (
+ "context"
+ "embed"
+ "encoding/json"
+ "errors"
+ strictjson "github.com/go-json-experiment/json"
+ "gorm.io/gorm"
+ "io/fs"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/connect/linkstore"
+ "amadan.net/oficina/home/teammode"
+ "amadan.net/rastrillo/rastrillo/migrate"
+)
+
+//go:embed delegated_migrations/migrations/*.sql
+var delegatedFiles embed.FS
+var delegatedSchema = func() *migrate.Set {
+ sub, _ := fs.Sub(delegatedFiles, "delegated_migrations")
+ return migrate.MustFromFS(sub, "calls_agent_access")
+}()
+
+func validateDelegatedConfig(cfg Config) error {
+ if cfg.AgentIssuer == "" && cfg.AgentTeam == "" {
+ return nil
+ }
+ if cfg.Home == nil || cfg.AgentIssuer == "" || cfg.AgentTeam == "" || len(cfg.AgentTeam) > 64 {
+ return errors.New("calls: incomplete agent configuration")
+ }
+ if cfg.Team != nil && cfg.AgentTeam != cfg.Team.TeamID {
+ return errors.New("calls: agent and roster teams differ")
+ }
+ _, err := access.NewRemoteVerifier(cfg.AgentIssuer, cfg.Origin+"/api/v1", cfg.Home.Issuer)
+ return err
+}
+func (a *app) wireDelegated() error {
+ if a.cfg.AgentIssuer == "" {
+ return nil
+ }
+ v, err := access.NewRemoteVerifier(a.cfg.AgentIssuer, a.cfg.Origin+"/api/v1", a.cfg.Home.Issuer)
+ if err != nil {
+ return err
+ }
+ return a.mountDelegated(v, a.cfg.AgentIssuer, a.cfg.AgentTeam)
+}
+func (a *app) mountDelegated(v access.Verifier, issuer, team string) error {
+ if a.cfg.Team != nil && (a.team == nil || team != a.cfg.Team.TeamID) {
+ return errors.New("calls: agent and roster teams differ")
+ }
+ if _, err := migrate.Apply(context.Background(), a.db, delegatedSchema); err != nil {
+ return err
+ }
+ a.agentIssuer, a.agentTeam = issuer, team
+ if a.cfg.Home == nil || issuer == "" {
+ return errors.New("calls: agent authority unavailable")
+ }
+ if err := a.db.G.Transaction(func(tx *gorm.DB) error { return a.bindDelegated(tx) }); err != nil {
+ return err
+ }
+ reg, err := access.NewRegistry(a.delegatedOperations(team)...)
+ if err != nil {
+ return err
+ }
+ a.delegated = a.delegatedBoundary(v, reg.HTTPGuarded(access.VerifyFunc(func(ctx context.Context, token string) (access.Principal, error) {
+ p, err := v.Verify(ctx, token)
+ if err != nil {
+ return access.Principal{}, err
+ }
+ if _, err = a.delegatedPerson(ctx, p, team); err != nil {
+ return access.Principal{}, err
+ }
+ coordinate, _ := json.Marshal([]string{p.Subject, p.Client})
+ key, err := a.sealer.Fingerprint("connection.rate.v1", string(coordinate))
+ if err != nil {
+ return access.Principal{}, err
+ }
+ if ok, _ := a.apiLimiter.allow("connection:"+key, a.store.now()); !ok {
+ return access.Principal{}, access.Fail("rate_limited", "Calls request limit reached. Try again later.")
+ }
+ return p, nil
+ }), v, a.delegatedResponse))
+ return nil
+}
+func (a *app) delegatedPerson(ctx context.Context, p access.Principal, team string) (Person, error) {
+ allowed := false
+ for _, t := range p.Teams {
+ allowed = allowed || t == team
+ }
+ if !allowed || p.Subject == "" || p.Client == "" || len(p.Client) > 256 || p.Grant == "" || a.home == nil {
+ return Person{}, access.Fail("forbidden", "This connection cannot access Calls.")
+ }
+ linked, err := a.home.bridge.ResolveOn(ctx, a.db.G.Statement.ConnPool, p.Subject)
+ if errors.Is(err, linkstore.ErrStorage) {
+ return Person{}, access.Fail("unavailable", "Account verification is unavailable.")
+ }
+ if err != nil {
+ return Person{}, access.Fail("forbidden", "Link an admitted Calls account to Home first.")
+ }
+ person, ok, err := a.store.personByID(ctx, linked.ID)
+ if err != nil {
+ return Person{}, access.Fail("unavailable", "Account verification is unavailable.")
+ }
+ if !ok || linked.ID <= 0 || linked.Label == "" || person.Email != linked.Label {
+ return Person{}, access.Fail("forbidden", "This account cannot access Calls.")
+ }
+ if err := a.delegatedStanding(ctx, p.Subject, person, true); err != nil {
+ return Person{}, err
+ }
+ if state, ok := ctx.Value(delegatedResponseKey{}).(*delegatedResponseState); ok {
+ if state.person.ID != 0 && (state.person.ID != person.ID || state.person.Email != person.Email) {
+ return Person{}, access.Fail("forbidden", "The linked identity changed.")
+ }
+ state.person = person
+ }
+ return person, nil
+}
+func delegatedFailure(err error) error {
+ if err == nil {
+ return nil
+ }
+ var f access.Failure
+ if errors.As(err, &f) {
+ return f
+ }
+ return access.Fail("unavailable", "Calls is unavailable. Try again.")
+}
+func (a *app) delegatedGuard(team, scope string, fn func(context.Context, access.Principal, Person, json.RawMessage) (any, error)) func(context.Context, access.Principal, json.RawMessage) (any, error) {
+ return func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) {
+ 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 != team || !p.Allows(team, scope) {
+ return nil, access.Fail("forbidden", "This connection cannot access that team.")
+ }
+ person, err := a.delegatedPerson(ctx, p, team)
+ if err != nil {
+ return nil, err
+ }
+ if a.cfg.Team != nil {
+ state, _ := ctx.Value(delegatedResponseKey{}).(*delegatedResponseState)
+ if state == nil {
+ return nil, access.Fail("unavailable", "Team authority is unavailable.")
+ }
+ ctx = teammode.WithAccess(ctx, state.standing)
+ }
+ out, err := fn(ctx, p, person, raw)
+ if err == nil {
+ if state, ok := ctx.Value(delegatedResponseKey{}).(*delegatedResponseState); ok {
+ state.selected = true
+ }
+ }
+ return out, delegatedFailure(err)
+ }
+}
diff --git a/internal/calls/delegated_attribution_test.go b/internal/calls/delegated_attribution_test.go
new file mode 100644
index 0000000..0642b59
--- /dev/null
+++ b/internal/calls/delegated_attribution_test.go
@@ -0,0 +1,50 @@
+package calls
+
+import (
+ "context"
+ "encoding/json"
+ "strconv"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ access "amadan.net/oficina/agent-access.git"
+)
+
+func TestDelegatedActorNamespaceAndSingleRateCharge(t *testing.T) {
+ f, p := linkedDelegated(t)
+ var checks atomic.Int64
+ if e := f.app.mountDelegated(access.VerifyFunc(func(context.Context, string) (access.Principal, error) { checks.Add(1); return *p, nil }), f.app.agentIssuer, "acme"); e != nil {
+ t.Fatal(e)
+ }
+ now := time.Now()
+ f.app.store.clk.set(func() time.Time { return now })
+ if rec := delegatedCall(f.app, "calls_create_meeting", delegatedInputForTest()); rec.Code != 200 {
+ t.Fatal(rec.Code, rec.Body.String())
+ }
+ if checks.Load() < 3 {
+ t.Fatal("write did not reverify delegation")
+ }
+ person, e := f.app.delegatedPerson(t.Context(), *p, "acme")
+ if e != nil {
+ t.Fatal(e)
+ }
+ raw, _ := json.Marshal([]string{f.app.cfg.Home.Issuer, f.app.agentIssuer, p.Subject, p.Client, "acme", strconv.FormatInt(person.ID, 10)})
+ want, e := f.app.sealer.Fingerprint("connection.actor.v1", string(raw))
+ if e != nil {
+ t.Fatal(e)
+ }
+ var got string
+ if e = f.app.db.Writer().QueryRow("SELECT coordinate FROM calls_connections").Scan(&got); e != nil || got != want {
+ t.Fatal("actor namespace mismatch", e)
+ }
+ // One creation plus 59 reads exhaust exactly the 60-request allowance.
+ for i := 0; i < 59; i++ {
+ if rec := delegatedCall(f.app, "calls_list_meetings", map[string]any{"team": "acme"}); rec.Code != 200 {
+ t.Fatal("one request charged repeatedly", i, rec.Code)
+ }
+ }
+ if rec := delegatedCall(f.app, "calls_list_meetings", map[string]any{"team": "acme"}); rec.Code != 429 {
+ t.Fatal("request not charged", rec.Code)
+ }
+}
diff --git a/internal/calls/delegated_authority.go b/internal/calls/delegated_authority.go
new file mode 100644
index 0000000..f979e9a
--- /dev/null
+++ b/internal/calls/delegated_authority.go
@@ -0,0 +1,89 @@
+package calls
+
+import (
+ "context"
+ "crypto/hmac"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "strings"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/connect/linkstore"
+ "gorm.io/gorm"
+)
+
+type delegatedBoundaryKey struct{}
+type delegatedRecheck func(context.Context, access.Principal) error
+
+func (a *app) delegatedBoundary(verifier access.Verifier, next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ parts := strings.Fields(r.Header.Get("Authorization"))
+ token := ""
+ if len(parts) == 2 {
+ token = parts[1]
+ }
+ check := delegatedRecheck(func(ctx context.Context, p access.Principal) error {
+ current, e := verifier.Verify(ctx, token)
+ if e != nil {
+ return e
+ }
+ if current.Subject != p.Subject || current.Client != p.Client || current.Grant != p.Grant || !current.Allows(a.agentTeam, "calls:write") {
+ return access.Fail("forbidden", "This connection is no longer authorized.")
+ }
+ return nil
+ })
+ state := &delegatedResponseState{}
+ ctx := context.WithValue(r.Context(), delegatedResponseKey{}, state)
+ next.ServeHTTP(&delegatedLeaseWriter{ResponseWriter: w, state: state, team: a.cfg.Team != nil}, r.WithContext(context.WithValue(ctx, delegatedBoundaryKey{}, check)))
+ })
+}
+func (a *app) bindDelegated(tx *gorm.DB) error {
+ raw, _ := json.Marshal([]string{a.cfg.Home.Issuer, a.agentIssuer, a.agentTeam})
+ want, e := a.sealer.Fingerprint("connection.authority.v1", string(raw))
+ if e != nil {
+ return e
+ }
+ if e = tx.Exec("INSERT INTO calls_agent_state(id,keycheck) SELECT 1,? WHERE NOT EXISTS(SELECT 1 FROM calls_agent_meetings) AND NOT EXISTS(SELECT 1 FROM calls_connections) AND NOT EXISTS(SELECT 1 FROM calls_agent_schedules) ON CONFLICT(id) DO NOTHING", want).Error; e != nil {
+ return e
+ }
+ var got string
+ if e = tx.Raw("SELECT keycheck FROM calls_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 *app) checkDelegatedWriter(ctx context.Context, tx *gorm.DB, p access.Principal, expected Person) error {
+ check, ok := ctx.Value(delegatedBoundaryKey{}).(delegatedRecheck)
+ if !ok || check == nil {
+ return access.Fail("forbidden", "Agent authority is unavailable.")
+ }
+ if e := check(ctx, p); e != nil {
+ return e
+ }
+ person, e := a.home.bridge.ResolveOn(ctx, tx.Statement.ConnPool, p.Subject)
+ if errors.Is(e, linkstore.ErrRefused) {
+ return access.Fail("forbidden", "The linked identity is unavailable.")
+ }
+ if e != nil {
+ return e
+ }
+ if person.ID != expected.ID || person.Label != expected.Email {
+ return access.Fail("forbidden", "The linked identity changed.")
+ }
+ id := person.ID
+
+ currentStore := *a.store
+ currentStore.g = tx
+ current, exists, e := currentStore.personByID(ctx, id)
+ if e != nil {
+ return e
+ }
+ if !exists || current.Email != expected.Email {
+ return access.Fail("forbidden", "This account is no longer admitted.")
+ }
+ return a.delegatedStanding(ctx, p.Subject, current, false)
+}
diff --git a/internal/calls/delegated_authority_test.go b/internal/calls/delegated_authority_test.go
new file mode 100644
index 0000000..9e48a2a
--- /dev/null
+++ b/internal/calls/delegated_authority_test.go
@@ -0,0 +1,153 @@
+package calls
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/calls/internal/calls/seal"
+ "amadan.net/rastrillo/rastrillo/db"
+ "gorm.io/gorm"
+)
+
+func TestDelegatedPrecommitAuthority(t *testing.T) {
+ for _, mode := range []string{"reserved-revoke", "final-revoke", "binding", "unlink", "member"} {
+ t.Run(mode, func(t *testing.T) {
+ f, p := linkedDelegated(t)
+ var checks atomic.Int64
+ if e := f.app.mountDelegated(access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ n := checks.Add(1)
+ if mode == "reserved-revoke" && n >= 2 || mode == "final-revoke" && n >= 3 {
+ return access.Principal{}, access.Fail("unauthenticated", "Revoked.")
+ }
+ return *p, nil
+ }), f.app.agentIssuer, "acme"); e != nil {
+ t.Fatal(e)
+ }
+ trigger := ""
+ switch mode {
+ case "reserved-revoke":
+ trigger = "CREATE TRIGGER body_must_not_run BEFORE INSERT ON meetings BEGIN SELECT RAISE(ABORT,'body attempted'); END"
+ case "unlink":
+ trigger = "CREATE TRIGGER lose_authority AFTER UPDATE OF meeting_id ON calls_agent_meetings BEGIN DELETE FROM home_identity_links; END"
+ case "binding":
+ trigger = "CREATE TRIGGER lose_binding AFTER INSERT ON meetings BEGIN UPDATE home_identity_links SET person_binding='broken'; END"
+ case "member":
+ trigger = "CREATE TRIGGER lose_authority AFTER UPDATE OF meeting_id ON calls_agent_meetings BEGIN UPDATE persons SET anonymous=1; END"
+ }
+ if trigger != "" {
+ if _, e := f.app.db.Writer().Exec(trigger); e != nil {
+ t.Fatal(e)
+ }
+ }
+ rec := delegatedCall(f.app, "calls_create_meeting", delegatedInputForTest())
+ if rec.Code != 401 && rec.Code != 403 {
+ t.Fatal("lost authority committed", mode, rec.Code, rec.Body.String())
+ }
+ for _, table := range []string{"meetings", "meeting_links", "calls_connections", "calls_agent_meetings"} {
+ var n int
+ if e := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM " + table).Scan(&n); e != nil || n != 0 {
+ t.Fatal("partial meeting", table, n, e)
+ }
+ }
+ })
+ }
+}
+func TestDelegatedAuthorityBindingRestart(t *testing.T) {
+ f, p := linkedDelegated(t)
+ input := delegatedInputForTest()
+ first := delegatedCall(f.app, "calls_create_meeting", input)
+ if first.Code != 200 {
+ t.Fatal(first.Code)
+ }
+ var path string
+ if e := f.app.db.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path); e != nil {
+ t.Fatal(e)
+ }
+ f.app.signinMail.close()
+ f.app.db.Close()
+ d, e := db.Open(path, f.app.logger)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer d.Close()
+ restarted := newHomeRouterFixtureWith(t, d, f.app.logger, f.key, f.app.cfg.Home)
+ if e = restarted.app.mountDelegated(access.VerifyFunc(func(context.Context, string) (access.Principal, error) { return *p, nil }), f.app.agentIssuer, "acme"); e != nil {
+ t.Fatal(e)
+ }
+ rec := delegatedCall(restarted.app, "calls_create_meeting", input)
+ if rec.Code != 200 || rec.Body.String() != first.Body.String() {
+ t.Fatal("restart changed receipt", rec.Code, rec.Body.String())
+ }
+ a := restarted.app
+ for _, kind := range []string{"issuer", "home", "team", "key"} {
+ t.Run(kind, func(t *testing.T) {
+ oldIssuer, oldHome, oldTeam, oldSeal := a.agentIssuer, a.cfg.Home.Issuer, a.agentTeam, a.sealer
+ defer func() {
+ a.agentIssuer = oldIssuer
+ a.cfg.Home.Issuer = oldHome
+ a.agentTeam = oldTeam
+ a.sealer = oldSeal
+ }()
+ switch kind {
+ case "issuer":
+ a.agentIssuer = "https://other-connect.test"
+ case "home":
+ a.cfg.Home.Issuer = "https://other-home.test"
+ case "team":
+ a.agentTeam = "green"
+ case "key":
+ a.sealer, _ = seal.New(bytes.Repeat([]byte{29}, 32))
+ }
+ if e := a.db.G.Transaction(func(tx *gorm.DB) error { return a.bindDelegated(tx) }); e == nil {
+ t.Fatal("authority change accepted")
+ }
+ })
+ }
+ if _, e = a.db.Writer().Exec("DELETE FROM calls_agent_state"); e != nil {
+ t.Fatal(e)
+ }
+ if e = a.db.G.Transaction(func(tx *gorm.DB) error { return a.bindDelegated(tx) }); e == nil {
+ t.Fatal("existing receipts adopted without marker")
+ }
+ // Test each preexisting table independently, so either missing predicate fails.
+ if e = a.db.G.Transaction(func(tx *gorm.DB) error {
+ if e := tx.Exec("DELETE FROM calls_connections").Error; e != nil {
+ return e
+ }
+ if e := a.bindDelegated(tx); e == nil {
+ t.Fatal("receipt-only state adopted without marker")
+ }
+ return gorm.ErrInvalidTransaction // restore attribution for the next case
+ }); e != gorm.ErrInvalidTransaction {
+ t.Fatal(e)
+ }
+ // Attribution alone must also prevent marker adoption.
+ if _, e = a.db.Writer().Exec("DELETE FROM calls_agent_meetings"); e != nil {
+ t.Fatal(e)
+ }
+ if e = a.db.G.Transaction(func(tx *gorm.DB) error { return a.bindDelegated(tx) }); e == nil {
+ t.Fatal("existing attribution adopted without marker")
+ }
+}
+func TestDelegatedRejectsMalformedUnicode(t *testing.T) {
+ f, _ := linkedDelegated(t)
+ input := delegatedInputForTest()
+ input["title"] = "REPLACEME"
+ raw, _ := json.Marshal(input)
+ for _, bad := range []string{`\ud800`, string([]byte{255})} {
+ r := httptest.NewRequest("POST", homeTestOrigin+"/api/v1/operations/calls_create_meeting", strings.NewReader(strings.Replace(string(raw), "REPLACEME", bad, 1)))
+ r.Header.Set("Content-Type", "application/json")
+ r.Header.Set("Authorization", "Bearer fixture")
+ w := httptest.NewRecorder()
+ f.app.delegated.ServeHTTP(responseRecorder{w}, r)
+ if w.Code != 422 {
+ t.Fatal("malformed meeting Unicode", w.Code)
+ }
+ }
+}
diff --git a/internal/calls/delegated_boundaries_test.go b/internal/calls/delegated_boundaries_test.go
new file mode 100644
index 0000000..986e75a
--- /dev/null
+++ b/internal/calls/delegated_boundaries_test.go
@@ -0,0 +1,158 @@
+package calls
+
+import (
+ "encoding/json"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestDelegatedPaginationAndClientIsolation(t *testing.T) {
+ f, p := linkedDelegated(t)
+ input := delegatedInputForTest()
+ for _, client := range []string{"one", "two", "three"} {
+ p.Client = client
+ if w := delegatedCall(f.app, "calls_create_meeting", input); w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ }
+ var after int64
+ seen := map[string]bool{}
+ for i := 0; i < 3; i++ {
+ w := delegatedCall(f.app, "calls_list_meetings", map[string]any{"team": "acme", "limit": 1, "after": after})
+ if w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ var out struct {
+ Meetings []struct {
+ Sqid string `json:"sqid"`
+ } `json:"meetings"`
+ Next int64 `json:"next_after"`
+ More bool `json:"has_more"`
+ }
+ if json.Unmarshal(w.Body.Bytes(), &out) != nil || len(out.Meetings) != 1 || out.More != (i < 2) || out.Next <= after || seen[out.Meetings[0].Sqid] {
+ t.Fatal("bad pagination", w.Body.String())
+ }
+ seen[out.Meetings[0].Sqid] = true
+ after = out.Next
+ }
+ if w := delegatedCall(f.app, "calls_get_meeting", map[string]any{"team": "acme", "sqid": "23456789ab"}); w.Code != 404 {
+ t.Fatal("missing meeting", w.Code)
+ }
+ for id := range seen {
+ w := delegatedCall(f.app, "calls_get_meeting", map[string]any{"team": "acme", "sqid": id})
+ if w.Code != 200 || !strings.Contains(w.Body.String(), input["title"].(string)) {
+ t.Fatal("read missing content", w.Code, w.Body.String())
+ }
+ }
+}
+func TestDelegatedRateAndStorageFailure(t *testing.T) {
+ f, _ := linkedDelegated(t)
+ rate := false
+ for i := 0; i < 65; i++ {
+ w := delegatedCall(f.app, "calls_list_meetings", map[string]any{"team": "acme"})
+ if w.Code == 429 {
+ rate = true
+ break
+ }
+ if w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ }
+ if !rate {
+ t.Fatal("no rate limit")
+ }
+ if err := f.app.db.Close(); err != nil {
+ t.Fatal(err)
+ }
+ if w := delegatedCall(f.app, "calls_list_meetings", map[string]any{"team": "acme"}); w.Code != 503 {
+ t.Fatal("storage failure misreported", w.Code)
+ }
+}
+func TestDelegatedProductionRoutesStayOutsideBrowserAndLegacyAuth(t *testing.T) {
+ f := newHomeRouterFixture(t)
+ cfg := f.app.cfg.Config
+ cfg.AgentIssuer = "https://connect.example.test"
+ cfg.AgentTeam = "acme"
+ mux, _, err := buildForTest(t, f.app.db, cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, method := range []string{"GET", "POST"} {
+ path := "/api/v1/operations"
+ if method == "POST" {
+ path += "/calls_create_meeting"
+ }
+ r := httptest.NewRequest(method, homeTestOrigin+path, strings.NewReader(`{}`))
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(responseRecorder{w}, r)
+ if w.Code != 401 || !strings.Contains(w.Body.String(), `"code":"unauthenticated"`) {
+ t.Fatal("delegated route intercepted", w.Code, w.Body.String())
+ }
+ }
+ r := httptest.NewRequest("GET", homeTestOrigin+"/api/v1/meetings", nil)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(responseRecorder{w}, r)
+ if w.Code != 401 || !strings.Contains(w.Body.String(), `"error":"unauthorized"`) {
+ t.Fatal("legacy route changed", w.Code, w.Body.String())
+ }
+ cfg.AgentTeam = ""
+ if _, err := resolve(cfg); err == nil {
+ t.Fatal("partial config accepted")
+ }
+}
+
+func TestDelegatedCursorRejectsIntegerOverflow(t *testing.T) {
+ f, _ := linkedDelegated(t)
+ w := delegatedCall(f.app, "calls_list_meetings", map[string]any{"team": "acme", "after": json.Number("9223372036854775808")})
+ if w.Code != 422 {
+ t.Fatal("overflow silently reset cursor", w.Code, w.Body.String())
+ }
+}
+func TestDelegatedCreationRechecksOperatorInTransaction(t *testing.T) {
+ f, _ := linkedDelegated(t)
+ if _, err := f.app.db.Writer().Exec("CREATE TRIGGER change_operator BEFORE INSERT ON calls_agent_meetings BEGIN UPDATE persons SET anonymous=1; END"); err != nil {
+ t.Fatal(err)
+ }
+ if w := delegatedCall(f.app, "calls_create_meeting", delegatedInputForTest()); w.Code != 403 {
+ t.Fatal("stale operator admitted", w.Code, w.Body.String())
+ }
+ for _, table := range []string{"meetings", "calls_agent_meetings", "calls_connections"} {
+ var n int
+ if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM " + table).Scan(&n); err != nil || n != 0 {
+ t.Fatal("partial effect", table, n, err)
+ }
+ }
+ var anon bool
+ if err := f.app.db.Writer().QueryRow("SELECT anonymous FROM persons").Scan(&anon); err != nil || anon {
+ t.Fatal("transaction not rolled back", err)
+ }
+}
+func TestDelegatedJoinLinkRechecksCurrentInvitation(t *testing.T) {
+ f, _ := linkedDelegated(t)
+ w := delegatedCall(f.app, "calls_create_meeting", delegatedInputForTest())
+ if w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ var m struct {
+ Sqid string `json:"sqid"`
+ }
+ _ = json.Unmarshal(w.Body.Bytes(), &m)
+ input := map[string]any{"team": "acme", "sqid": m.Sqid}
+ if _, err := f.app.db.Writer().Exec("UPDATE meeting_links SET revoked_at=CURRENT_TIMESTAMP"); err != nil {
+ t.Fatal(err)
+ }
+ if w := delegatedCall(f.app, "calls_get_join_link", input); w.Code != 404 {
+ t.Fatal("revoked invitation disclosed", w.Code, w.Body.String())
+ }
+ if _, err := f.app.db.Writer().Exec("UPDATE meeting_links SET revoked_at=NULL,token_sealed=NULL"); err != nil {
+ t.Fatal(err)
+ }
+ if w := delegatedCall(f.app, "calls_get_join_link", input); w.Code != 404 {
+ t.Fatal("hash-only invitation fabricated", w.Code, w.Body.String())
+ }
+ var count int
+ if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM meeting_links").Scan(&count); err != nil || count != 1 {
+ t.Fatal("read created invitation", count, err)
+ }
+}
diff --git a/internal/calls/delegated_continuity_test.go b/internal/calls/delegated_continuity_test.go
new file mode 100644
index 0000000..b417a7b
--- /dev/null
+++ b/internal/calls/delegated_continuity_test.go
@@ -0,0 +1,85 @@
+package calls
+
+import (
+ "context"
+ "sync/atomic"
+ "testing"
+
+ access "amadan.net/oficina/agent-access.git"
+)
+
+func TestDelegatedMeetingRetryFinalCheckAndLiveMarker(t *testing.T) {
+ for _, mode := range []string{"retry-final", "marker-create", "marker-retry"} {
+ t.Run(mode, func(t *testing.T) {
+ f, p := linkedDelegated(t)
+ input := delegatedInputForTest()
+ if rec := delegatedCall(f.app, "calls_create_meeting", input); rec.Code != 200 {
+ t.Fatal(rec.Code)
+ }
+ want := 503
+ if mode == "retry-final" {
+ want = 401
+ var checks atomic.Int64
+ if e := f.app.mountDelegated(access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ if checks.Add(1) >= 3 {
+ return access.Principal{}, access.Fail("unauthenticated", "Revoked.")
+ }
+ return *p, nil
+ }), f.app.agentIssuer, "acme"); e != nil {
+ t.Fatal(e)
+ }
+ } else {
+ if _, e := f.app.db.Writer().Exec("UPDATE calls_agent_state SET keycheck='damaged'"); e != nil {
+ t.Fatal(e)
+ }
+ if mode == "marker-create" {
+ input["client_id"] = "15bb7913-1316-4b96-bc3a-4b4cded1ded4"
+ }
+ }
+ if rec := delegatedCall(f.app, "calls_create_meeting", input); rec.Code != want {
+ t.Fatal("boundary ignored", mode, rec.Code, rec.Body.String())
+ }
+ for _, table := range []string{"meetings", "calls_agent_meetings"} {
+ var n int
+ if e := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM " + table).Scan(&n); e != nil || n != 1 {
+ t.Fatal("retry wrote extra effect", n, e)
+ }
+ }
+ })
+ }
+}
+func TestDelegatedMeetingVerifierContinuity(t *testing.T) {
+ for _, field := range []string{"subject", "client", "grant", "team", "scope"} {
+ t.Run(field, func(t *testing.T) {
+ f, p := linkedDelegated(t)
+ var checks atomic.Int64
+ if e := f.app.mountDelegated(access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ current := *p
+ if checks.Add(1) > 1 {
+ switch field {
+ case "subject":
+ current.Subject = "different"
+ case "client":
+ current.Client = "different"
+ case "grant":
+ current.Grant = "different"
+ case "team":
+ current.Teams = []string{"green"}
+ case "scope":
+ current.Scopes = []string{"calls:read"}
+ }
+ }
+ return current, nil
+ }), f.app.agentIssuer, "acme"); e != nil {
+ t.Fatal(e)
+ }
+ if rec := delegatedCall(f.app, "calls_create_meeting", delegatedInputForTest()); rec.Code != 403 {
+ t.Fatal("changed principal accepted", field, rec.Code)
+ }
+ var n int
+ if e := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM meetings").Scan(&n); e != nil || n != 0 {
+ t.Fatal("changed principal wrote", n, e)
+ }
+ })
+ }
+}
diff --git a/internal/calls/delegated_create.go b/internal/calls/delegated_create.go
new file mode 100644
index 0000000..161e08f
--- /dev/null
+++ b/internal/calls/delegated_create.go
@@ -0,0 +1,142 @@
+package calls
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "strconv"
+ "strings"
+ "time"
+
+ access "amadan.net/oficina/agent-access.git"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+type delegatedCreateInput struct {
+ Team string `json:"team"`
+ ClientID string `json:"client_id"`
+ Title string `json:"title"`
+ StartsAt string `json:"starts_at"`
+}
+
+func (a *app) delegatedCreate(ctx context.Context, p access.Principal, person Person, raw json.RawMessage) (any, error) {
+ var in delegatedCreateInput
+ if json.Unmarshal(raw, &in) != nil {
+ return nil, access.Fail("invalid", "Invalid meeting input.")
+ }
+ id, err := uuid.Parse(in.ClientID)
+ if err != nil || id == uuid.Nil || id.String() != in.ClientID {
+ return nil, access.Fail("invalid", "Supply a nonzero UUID client_id.")
+ }
+ if strings.TrimSpace(in.Title) == "" || titleTooLong(in.Title) {
+ return nil, access.Fail("invalid", "Supply a meeting title within the length limit.")
+ }
+ var starts *time.Time
+ if in.StartsAt != "" {
+ v, err := time.Parse(time.RFC3339, in.StartsAt)
+ if err != nil {
+ return nil, access.Fail("invalid", "Supply starts_at as RFC3339 with an explicit offset.")
+ }
+ v = v.UTC()
+ starts = &v
+ }
+ in.ClientID = id.String()
+ coordinates, _ := json.Marshal([]string{a.cfg.Home.Issuer, a.agentIssuer, p.Subject, p.Client, in.Team, in.ClientID})
+ payload, _ := json.Marshal(in)
+ key, err := a.sealer.Fingerprint("connection.receipt.v1", string(coordinates))
+ if err != nil {
+ return nil, err
+ }
+ content, err := a.sealer.Fingerprint("connection.content.v1", string(payload))
+ if err != nil {
+ return nil, err
+ }
+ var meeting Meeting
+ err = a.store.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if e := a.bindDelegated(tx); e != nil {
+ return e
+ }
+ if e := a.checkDelegatedWriter(ctx, tx, p, person); e != nil {
+ return e
+ }
+ if err := tx.Exec("INSERT INTO calls_agent_meetings(coordinate,content) VALUES(?,?) ON CONFLICT(coordinate) DO NOTHING", key, content).Error; err != nil {
+ return err
+ }
+ current := *a.store
+ current.g = tx
+ operator, ok, err := current.personByID(ctx, person.ID)
+ if err != nil {
+ return err
+ }
+ if !ok || operator.Email != person.Email {
+ return access.Fail("forbidden", "This account cannot access Calls.")
+ }
+ if err := a.delegatedStanding(ctx, p.Subject, operator, false); err != nil {
+ return err
+ }
+ var saved string
+ var mid sql.NullInt64
+ if err = tx.Raw("SELECT content,meeting_id FROM calls_agent_meetings WHERE coordinate=?", key).Row().Scan(&saved, &mid); err != nil {
+ return err
+ }
+ if saved != content {
+ return access.Fail("conflict", "This client_id was already used with different meeting fields.")
+ }
+ if mid.Valid {
+ if err = tx.Where("id=?", mid.Int64).Take(&meeting).Error; err == gorm.ErrRecordNotFound {
+ return access.Fail("not_found", "This meeting is unavailable.")
+ }
+ if err != nil {
+ return err
+ }
+ return a.checkDelegatedWriter(ctx, tx, p, person)
+ }
+ actor, err := current.delegatedActor(ctx, p, a.cfg.Home.Issuer, a.agentIssuer, in.Team, operator)
+ if err != nil {
+ return err
+ }
+ meeting, _, err = current.createMeeting(ctx, strings.TrimSpace(in.Title), starts, actor)
+ if err != nil {
+ return err
+ }
+ if e := tx.Exec("UPDATE calls_agent_meetings SET meeting_id=? WHERE coordinate=?", meeting.ID, key).Error; e != nil {
+ return e
+ }
+ return a.checkDelegatedWriter(ctx, tx, p, person)
+ })
+ if err != nil {
+ return nil, err
+ }
+ captureDelegatedMeeting(ctx, meeting)
+ return map[string]any{"sqid": meeting.Sqid, "url": a.cfg.Origin + "/m/" + meeting.Sqid, "invitations_sent": false}, nil
+}
+func (s *store) delegatedActor(ctx context.Context, p access.Principal, homeIssuer, issuer, team string, operator Person) (string, error) {
+ raw, _ := json.Marshal([]string{homeIssuer, issuer, p.Subject, p.Client, team, strconv.FormatInt(operator.ID, 10)})
+ key, err := s.sealer.Fingerprint("connection.actor.v1", string(raw))
+ if err != nil {
+ return "", err
+ }
+ label, err := s.sealer.SealString("connection.client.v1", p.Client)
+ if err != nil {
+ return "", err
+ }
+ err = s.g.WithContext(ctx).Exec("INSERT INTO calls_connections(coordinate,operator_person_id,client_sealed) VALUES(?,?,?) ON CONFLICT(coordinate) DO NOTHING", key, operator.ID, label).Error
+ return "connection:" + key, err
+}
+func (s *store) delegatedCreator(ctx context.Context, key string) string {
+ var operatorID int64
+ var sealed []byte
+ if err := s.g.WithContext(ctx).Raw("SELECT operator_person_id,client_sealed FROM calls_connections WHERE coordinate=?", key).Row().Scan(&operatorID, &sealed); err != nil {
+ return "Oficina agent"
+ }
+ label, err := s.sealer.OpenString("connection.client.v1", sealed)
+ if err != nil {
+ return "Oficina agent"
+ }
+ operator, ok, err := s.personByID(ctx, operatorID)
+ if err != nil || !ok {
+ return "Oficina agent"
+ }
+ return label + "~" + operator.Email
+}
diff --git a/internal/calls/delegated_migrations/migrations/0001_connections.sql b/internal/calls/delegated_migrations/migrations/0001_connections.sql
new file mode 100644
index 0000000..929f044
--- /dev/null
+++ b/internal/calls/delegated_migrations/migrations/0001_connections.sql
@@ -0,0 +1,2 @@
+CREATE TABLE calls_connections (coordinate TEXT PRIMARY KEY, operator_person_id INTEGER NOT NULL, client_sealed BLOB NOT NULL);
+CREATE TABLE calls_agent_meetings (coordinate TEXT PRIMARY KEY, content TEXT NOT NULL, meeting_id INTEGER);
diff --git a/internal/calls/delegated_migrations/migrations/0002_authority.sql b/internal/calls/delegated_migrations/migrations/0002_authority.sql
new file mode 100644
index 0000000..72727e2
--- /dev/null
+++ b/internal/calls/delegated_migrations/migrations/0002_authority.sql
@@ -0,0 +1,4 @@
+CREATE TABLE calls_agent_state (
+ id INTEGER PRIMARY KEY CHECK(id=1),
+ keycheck TEXT NOT NULL
+);
diff --git a/internal/calls/delegated_migrations/migrations/0003_schedule.sql b/internal/calls/delegated_migrations/migrations/0003_schedule.sql
new file mode 100644
index 0000000..cc92a12
--- /dev/null
+++ b/internal/calls/delegated_migrations/migrations/0003_schedule.sql
@@ -0,0 +1 @@
+CREATE TABLE calls_agent_schedules (coordinate TEXT PRIMARY KEY, content TEXT NOT NULL);
diff --git a/internal/calls/delegated_operations.go b/internal/calls/delegated_operations.go
new file mode 100644
index 0000000..a2fc1f9
--- /dev/null
+++ b/internal/calls/delegated_operations.go
@@ -0,0 +1,43 @@
+package calls
+
+import (
+ access "amadan.net/oficina/agent-access.git"
+ "encoding/json"
+)
+
+func delegatedObject(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 delegatedString(max int) map[string]any {
+ return map[string]any{"type": "string", "maxLength": max}
+}
+func delegatedInput(props map[string]any, required ...string) json.RawMessage {
+ props["team"] = map[string]any{"type": "string", "minLength": 1, "maxLength": 64}
+ return delegatedObject(props, append([]string{"team"}, required...)...)
+}
+
+var delegatedMeetingSchema = delegatedObject(map[string]any{"sqid": delegatedString(10), "title": delegatedString(200), "starts_at": map[string]any{"type": []string{"string", "null"}}, "ended_at": map[string]any{"type": []string{"string", "null"}}, "created_by": delegatedString(1024), "url": delegatedString(2048)}, "sqid", "title", "starts_at", "ended_at", "created_by", "url")
+
+func (a *app) delegatedOperations(team string) []access.Operation {
+ return []access.Operation{
+ a.delegatedScheduleOperation(team),
+ {Name: "calls_list_meetings", Description: "List this team's meetings visible to a current member. Page with after/next_after; has_more says whether more remain. No invitation tokens or call media are returned.", Scope: "calls:read", ReadOnly: true, Idempotent: true, Input: delegatedInput(map[string]any{"after": map[string]any{"type": "integer", "minimum": 0, "maximum": int64(9223372036854775807)}, "limit": map[string]any{"type": "integer", "minimum": 1, "maximum": 100}}), Output: delegatedObject(map[string]any{"meetings": map[string]any{"type": "array", "items": delegatedMeetingSchema}, "next_after": map[string]any{"type": "integer", "minimum": 0}, "has_more": map[string]any{"type": "boolean"}}, "meetings", "next_after", "has_more"), Invoke: a.delegatedGuard(team, "calls:read", a.delegatedList)},
+ {Name: "calls_get_meeting", Description: "Read a meeting and its member room URL. Does not disclose a guest invitation or grant access to call media.", Scope: "calls:read", ReadOnly: true, Idempotent: true, Input: delegatedInput(map[string]any{"sqid": delegatedString(10)}, "sqid"), Output: delegatedMeetingSchema, Invoke: a.delegatedGuard(team, "calls:read", a.delegatedGet)},
+ {Name: "calls_create_meeting", Description: "Create a meeting, optionally with an RFC3339 starts_at including an explicit offset. Reuse a nonzero UUID client_id only for retries with identical fields. Returns the member room URL; creates no Calendar event and sends no invitations.", Scope: "calls:write", Idempotent: true, Input: delegatedInput(map[string]any{"client_id": map[string]any{"type": "string", "minLength": 36, "maxLength": 36}, "title": delegatedString(200), "starts_at": delegatedString(35)}, "client_id", "title"), Output: delegatedObject(map[string]any{"sqid": delegatedString(10), "url": delegatedString(2048), "invitations_sent": map[string]any{"const": false}}, "sqid", "url", "invitations_sent"), Invoke: a.delegatedGuard(team, "calls:write", a.delegatedCreate)},
+ {Name: "calls_get_join_link", Description: "Retrieve an existing live guest invitation URL. This URL grants invitation access: share only with intended recipients. Requires calls:share. Never creates, replaces or sends a link; unavailable for ended meetings or old invitations without a recoverable token.", Scope: "calls:share", ReadOnly: true, Idempotent: true, Input: delegatedInput(map[string]any{"sqid": delegatedString(10)}, "sqid"), Output: delegatedObject(map[string]any{"sqid": delegatedString(10), "join_url": delegatedString(2048)}, "sqid", "join_url"), Invoke: a.delegatedGuard(team, "calls:share", a.delegatedJoinLink)},
+ }
+}
+func AgentContracts() ([]access.Operation, error) {
+ a := &app{}
+ ops := a.delegatedOperations("contract")
+ scopes := []string{}
+ for _, o := range ops {
+ scopes = append(scopes, o.Scope)
+ }
+ r, err := access.NewRegistry(ops...)
+ if err != nil {
+ return nil, err
+ }
+ return r.List(access.Principal{Subject: "contract", Teams: []string{"contract"}, Scopes: scopes}), nil
+}
diff --git a/internal/calls/delegated_read.go b/internal/calls/delegated_read.go
new file mode 100644
index 0000000..39b2eca
--- /dev/null
+++ b/internal/calls/delegated_read.go
@@ -0,0 +1,118 @@
+package calls
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/calls/internal/calls/seal"
+ "amadan.net/oficina/home/roster"
+ "gorm.io/gorm"
+)
+
+func (a *app) delegatedList(ctx context.Context, _ access.Principal, _ Person, raw json.RawMessage) (any, error) {
+ var in struct {
+ After int64 `json:"after"`
+ Limit int `json:"limit"`
+ }
+ if json.Unmarshal(raw, &in) != nil {
+ return nil, access.Fail("invalid", "Invalid pagination fields.")
+ }
+ if in.Limit == 0 {
+ in.Limit = 50
+ }
+ var meetings []Meeting
+ if err := a.store.g.WithContext(ctx).Where("id>?", in.After).Order("id ASC").Limit(in.Limit + 1).Find(&meetings).Error; err != nil {
+ return nil, err
+ }
+ more := len(meetings) > in.Limit
+ if more {
+ meetings = meetings[:in.Limit]
+ }
+ out := []any{}
+ var next int64
+ for _, m := range meetings {
+ body, err := a.delegatedMeeting(ctx, m)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, body)
+ next = m.ID
+ }
+ return map[string]any{"meetings": out, "next_after": next, "has_more": more}, nil
+}
+func (a *app) delegatedMeeting(ctx context.Context, m Meeting) (any, error) {
+ title, err := a.store.delegatedTitle(m)
+ if err != nil {
+ return nil, err
+ }
+ captureDelegatedMeeting(ctx, m)
+ return map[string]any{"sqid": m.Sqid, "title": title, "starts_at": apiTime(m.StartsAt), "ended_at": apiTime(m.EndedAt), "created_by": a.store.creatorLabel(ctx, m.CreatedBy), "url": a.cfg.Origin + "/m/" + m.Sqid}, nil
+}
+func (a *app) delegatedLookup(ctx context.Context, raw json.RawMessage) (Meeting, error) {
+ var in struct {
+ Sqid string `json:"sqid"`
+ }
+ _ = json.Unmarshal(raw, &in)
+ if !validSqid(in.Sqid) {
+ return Meeting{}, access.Fail("not_found", "This meeting is unavailable.")
+ }
+ m, ok, err := a.store.meetingBySqid(ctx, in.Sqid)
+ if err != nil {
+ return m, err
+ }
+ if !ok {
+ return m, access.Fail("not_found", "This meeting is unavailable.")
+ }
+ return m, nil
+}
+func (a *app) delegatedGet(ctx context.Context, _ access.Principal, _ Person, raw json.RawMessage) (any, error) {
+ m, err := a.delegatedLookup(ctx, raw)
+ if err != nil {
+ return nil, err
+ }
+ return a.delegatedMeeting(ctx, m)
+}
+func (a *app) delegatedJoinLink(ctx context.Context, _ access.Principal, _ Person, raw json.RawMessage) (any, error) {
+ m, err := a.delegatedLookup(ctx, raw)
+ if err != nil {
+ return nil, err
+ }
+ if a.cfg.Team != nil {
+ host, standing := a.meetingStands(ctx, m)
+ if standing == roster.Unknown {
+ return nil, access.Fail("unavailable", "Meeting host standing is unavailable.")
+ }
+ if standing != roster.Member {
+ return nil, access.Fail("not_found", "This invitation is unavailable.")
+ }
+ if s, ok := ctx.Value(delegatedResponseKey{}).(*delegatedResponseState); ok {
+ s.host = host
+ }
+ }
+ // One query rechecks the meeting and link together. Reading never mints or
+ // replaces a legacy hash-only invitation. An ended meeting has no live link.
+ var link MeetingLink
+ err = a.store.g.WithContext(ctx).Table("meeting_links").Select("meeting_links.*").Joins("JOIN meetings ON meetings.id=meeting_links.meeting_id").Where("meetings.id=? AND meetings.ended_at IS NULL AND meeting_links.revoked_at IS NULL AND length(meeting_links.token_sealed)>0", m.ID).Order("meeting_links.id DESC").Take(&link).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, access.Fail("not_found", "No current shareable invitation is available.")
+ }
+ if err != nil {
+ return nil, err
+ }
+ token, err := a.sealer.OpenString(seal.PurposeMeetingLink, link.TokenSealed)
+ if err != nil {
+ return nil, err
+ }
+ captureDelegatedMeeting(ctx, m)
+ if state, ok := ctx.Value(delegatedResponseKey{}).(*delegatedResponseState); ok {
+ state.invitation = &link
+ }
+ return map[string]any{"sqid": m.Sqid, "join_url": a.linkURL(token)}, nil
+}
+
+// delegatedTitle keeps content opening in the store and refuses corrupt ciphertext.
+func (s *store) delegatedTitle(m Meeting) (string, error) {
+ return s.sealer.OpenString(seal.PurposeMeetingTitle, m.TitleSealed)
+}
diff --git a/internal/calls/delegated_recorder_test.go b/internal/calls/delegated_recorder_test.go
new file mode 100644
index 0000000..b7e6c32
--- /dev/null
+++ b/internal/calls/delegated_recorder_test.go
@@ -0,0 +1,12 @@
+package calls
+
+import (
+ "net/http/httptest"
+ "time"
+)
+
+// Unit request fixtures use an in-memory transport. Real HTTP deadline and
+// truncation behavior is exercised separately.
+type responseRecorder struct{ *httptest.ResponseRecorder }
+
+func (responseRecorder) SetWriteDeadline(time.Time) error { return nil }
diff --git a/internal/calls/delegated_response.go b/internal/calls/delegated_response.go
new file mode 100644
index 0000000..8e98c07
--- /dev/null
+++ b/internal/calls/delegated_response.go
@@ -0,0 +1,85 @@
+package calls
+
+import (
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/roster"
+ "amadan.net/oficina/home/teammode"
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "gorm.io/gorm"
+)
+
+type delegatedResponseKey struct{}
+type delegatedResponseState struct {
+ person Person
+ selected bool
+ meetings []Meeting
+ invitation *MeetingLink
+ standing *teammode.Access
+ subject string
+ host *teammode.Access
+}
+
+func captureDelegatedMeeting(ctx context.Context, m Meeting) {
+ if s, ok := ctx.Value(delegatedResponseKey{}).(*delegatedResponseState); ok {
+ s.meetings = append(s.meetings, m)
+ }
+}
+func (a *app) delegatedResponse(ctx context.Context, p access.Principal, name string, _ json.RawMessage, result any) error {
+ s, ok := ctx.Value(delegatedResponseKey{}).(*delegatedResponseState)
+ if !ok || s.person.ID == 0 || name != "" && !s.selected {
+ return access.Fail("forbidden", "Response authority is unavailable.")
+ }
+ if name != "" {
+ value, ok := result.(map[string]any)
+ if !ok {
+ return access.Fail("forbidden", "Meeting provenance is unavailable.")
+ }
+ if name == "calls_reserve_schedule" {
+ if value["reserved"] != true || len(s.meetings) != 0 {
+ return access.Fail("forbidden", "Schedule provenance is unavailable.")
+ }
+ } else if name == "calls_list_meetings" {
+ rows, ok := value["meetings"].([]any)
+ if !ok || len(rows) != len(s.meetings) {
+ return access.Fail("forbidden", "Meeting provenance is unavailable.")
+ }
+ } else if len(s.meetings) != 1 {
+ return access.Fail("forbidden", "Meeting provenance is unavailable.")
+ }
+ }
+ if _, err := a.delegatedPerson(ctx, p, a.agentTeam); err != nil {
+ return err
+ }
+ for _, selected := range s.meetings {
+ m, ok, err := a.store.meetingBySqid(ctx, selected.Sqid)
+ if err != nil {
+ return delegatedFailure(err)
+ }
+ if !ok || m.ID != selected.ID {
+ return access.Fail("not_found", "This meeting is unavailable.")
+ }
+ }
+ if name == "calls_get_join_link" && s.invitation == nil {
+ return access.Fail("forbidden", "Invitation authority is unavailable.")
+ }
+ if selected := s.invitation; selected != nil {
+ if a.cfg.Team != nil && (s.host == nil || s.host.State() != roster.Member) {
+ return access.Fail("unavailable", "Invitation authority is unavailable.")
+ }
+ var link MeetingLink
+ err := a.store.g.WithContext(ctx).Table("meeting_links").Select("meeting_links.*").Joins("JOIN meetings ON meetings.id=meeting_links.meeting_id").Where("meeting_links.id=? AND meeting_links.meeting_id=? AND meeting_links.revoked_at IS NULL AND meetings.ended_at IS NULL", selected.ID, selected.MeetingID).Take(&link).Error
+ if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
+ return delegatedFailure(err)
+ }
+ if err != nil || !bytes.Equal(link.TokenSealed, selected.TokenSealed) {
+ return access.Fail("not_found", "This invitation is unavailable.")
+ }
+ }
+ if s.invitation != nil && a.cfg.Team != nil && (s.host == nil || s.host.State() != roster.Member) {
+ return access.Fail("unavailable", "Invitation authority is unavailable.")
+ }
+ return a.delegatedStanding(ctx, p.Subject, s.person, false)
+}
diff --git a/internal/calls/delegated_response_test.go b/internal/calls/delegated_response_test.go
new file mode 100644
index 0000000..dd828ab
--- /dev/null
+++ b/internal/calls/delegated_response_test.go
@@ -0,0 +1,234 @@
+package calls
+
+import (
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/calls/internal/calls/seal"
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+type delegatedStreamWriter struct {
+ http.ResponseWriter
+ after func()
+}
+
+func (w delegatedStreamWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }
+func (w delegatedStreamWriter) Write(b []byte) (int, error) {
+ n, e := w.ResponseWriter.Write(b)
+ w.after()
+ return n, e
+}
+func delegatedLiveCall(t *testing.T, h http.Handler, name string, input any) (int, []byte, error) {
+ t.Helper()
+ server := httptest.NewServer(h)
+ defer server.Close()
+ raw, _ := json.Marshal(input)
+ req, _ := http.NewRequest("POST", server.URL+"/api/v1/operations/"+name, bytes.NewReader(raw))
+ req.Header.Set("Authorization", "Bearer fixture")
+ req.Header.Set("Content-Type", "application/json")
+ resp, e := server.Client().Do(req)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer resp.Body.Close()
+ body, e := io.ReadAll(resp.Body)
+ return resp.StatusCode, body, e
+}
+func TestDelegatedResponseExactInvitation(t *testing.T) {
+ for _, kind := range []string{"revoked-with-another-live", "ended", "ciphertext", "unlink", "deleted"} {
+ t.Run(kind, func(t *testing.T) {
+ f, p := linkedDelegated(t)
+ w := delegatedCall(f.app, "calls_create_meeting", delegatedInputForTest())
+ if w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ var created struct{ Sqid string }
+ json.Unmarshal(w.Body.Bytes(), &created)
+ var selected MeetingLink
+ if e := f.app.db.G.Order("id DESC").First(&selected).Error; e != nil {
+ t.Fatal(e)
+ }
+ var checks atomic.Int32
+ v := access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ if checks.Add(1) == 2 {
+ var e error
+ switch kind {
+ case "revoked-with-another-live":
+ e = f.app.db.G.Exec("UPDATE meeting_links SET revoked_at=? WHERE id=?", time.Now(), selected.ID).Error
+ replacement := selected
+ replacement.ID = 0
+ replacement.TokenHash = "different-live-link"
+ if e == nil {
+ e = f.app.db.G.Create(&replacement).Error
+ }
+ case "ended":
+ e = f.app.db.G.Exec("UPDATE meetings SET ended_at=? WHERE id=?", time.Now(), selected.MeetingID).Error
+ case "ciphertext":
+ sealed, err := f.app.sealer.SealString(seal.PurposeMeetingLink, "new-token")
+ if err != nil {
+ return access.Principal{}, err
+ }
+ e = f.app.db.G.Exec("UPDATE meeting_links SET token_sealed=? WHERE id=?", sealed, selected.ID).Error
+ case "unlink":
+ e = f.app.db.G.Exec("DELETE FROM home_identity_links").Error
+ case "deleted":
+ e = f.app.db.G.Exec("DELETE FROM meeting_links WHERE id=?", selected.ID).Error
+ }
+ if e != nil {
+ return access.Principal{}, e
+ }
+ }
+ return *p, nil
+ })
+ if e := f.app.mountDelegated(v, f.app.agentIssuer, "acme"); e != nil {
+ t.Fatal(e)
+ }
+ status, body, e := delegatedLiveCall(t, f.app.delegated, "calls_get_join_link", map[string]any{"team": "acme", "sqid": created.Sqid})
+ if e != nil || status != 403 && status != 404 || strings.Contains(string(body), "join_url") {
+ t.Fatalf("%d %s %v", status, body, e)
+ }
+ })
+ }
+}
+func TestDelegatedResponseStreamRechecksMembership(t *testing.T) {
+ f, _ := linkedDelegated(t)
+ w := delegatedCall(f.app, "calls_create_meeting", delegatedInputForTest())
+ if w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ var m Meeting
+ if e := f.app.db.G.First(&m).Error; e != nil {
+ t.Fatal(e)
+ }
+ title, e := f.app.sealer.SealString(seal.PurposeMeetingTitle, strings.Repeat("🗓", 200))
+ if e != nil {
+ t.Fatal(e)
+ }
+ for i := 0; i < 100; i++ {
+ clone := m
+ clone.ID = 0
+ clone.Sqid = fmt.Sprintf("%010d", i+1)
+ clone.TitleSealed = title
+ if e := f.app.db.G.Create(&clone).Error; e != nil {
+ t.Fatal(e)
+ }
+ }
+ var writes atomic.Int32
+ h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ f.app.delegated.ServeHTTP(delegatedStreamWriter{w, func() {
+ if writes.Add(1) == 1 {
+ if e := f.app.db.G.Exec("DELETE FROM home_identity_links").Error; e != nil {
+ t.Error(e)
+ }
+ }
+ }}, r)
+ })
+ status, body, e := delegatedLiveCall(t, h, "calls_list_meetings", map[string]any{"team": "acme", "limit": 100})
+ if status != 200 || e == nil || len(body) != 64<<10 {
+ t.Fatalf("%d %d %v", status, len(body), e)
+ }
+}
+
+func TestDelegatedRetryFinalGuardWithoutResponseMask(t *testing.T) {
+ f, p := linkedDelegated(t)
+ input := delegatedInputForTest()
+ if w := delegatedCall(f.app, "calls_create_meeting", input); w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ person, err := f.app.delegatedPerson(t.Context(), *p, "acme")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var checks int
+ ctx := context.WithValue(t.Context(), delegatedBoundaryKey{}, delegatedRecheck(func(context.Context, access.Principal) error {
+ checks++
+ if checks == 2 {
+ return access.Fail("unauthenticated", "Revoked.")
+ }
+ return nil
+ }))
+ raw, _ := json.Marshal(input)
+ _, err = f.app.delegatedCreate(ctx, *p, person, raw)
+ if err == nil || access.SafeFailure(err).Code != "unauthenticated" || checks != 2 {
+ t.Fatalf("retry final guard: %v checks=%d", err, checks)
+ }
+}
+
+func TestDelegatedDiscoveryRechecksLocalIdentity(t *testing.T) {
+ for _, path := range []string{"connection", "operations"} {
+ t.Run(path, func(t *testing.T) {
+ f, p := linkedDelegated(t)
+ var checks atomic.Int32
+ v := access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ if checks.Add(1) == 2 {
+ if err := f.app.db.G.Exec("DELETE FROM home_identity_links").Error; err != nil {
+ return access.Principal{}, err
+ }
+ }
+ return *p, nil
+ })
+ if err := f.app.mountDelegated(v, f.app.agentIssuer, "acme"); err != nil {
+ t.Fatal(err)
+ }
+ server := httptest.NewServer(f.app.delegated)
+ defer server.Close()
+ req, _ := http.NewRequest("GET", server.URL+"/api/v1/"+path, nil)
+ req.Header.Set("Authorization", "Bearer fixture")
+ resp, err := server.Client().Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ body, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != 403 || strings.Contains(string(body), "acme") || strings.Contains(string(body), "operations") {
+ t.Fatalf("%d %s", resp.StatusCode, body)
+ }
+ })
+ }
+}
+
+func TestDelegatedResponseMeetingDeletion(t *testing.T) {
+ for _, name := range []string{"calls_get_meeting", "calls_list_meetings"} {
+ t.Run(name, func(t *testing.T) {
+ f, p := linkedDelegated(t)
+ w := delegatedCall(f.app, "calls_create_meeting", delegatedInputForTest())
+ if w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ var created struct{ Sqid string }
+ json.Unmarshal(w.Body.Bytes(), &created)
+ var checks atomic.Int32
+ v := access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ if checks.Add(1) == 2 {
+ if err := f.app.db.G.Exec("DELETE FROM meeting_links").Error; err != nil {
+ return access.Principal{}, err
+ }
+ if err := f.app.db.G.Exec("DELETE FROM meetings").Error; err != nil {
+ return access.Principal{}, err
+ }
+ }
+ return *p, nil
+ })
+ if err := f.app.mountDelegated(v, f.app.agentIssuer, "acme"); err != nil {
+ t.Fatal(err)
+ }
+ input := map[string]any{"team": "acme"}
+ if name == "calls_get_meeting" {
+ input["sqid"] = created.Sqid
+ }
+ status, body, err := delegatedLiveCall(t, f.app.delegated, name, input)
+ if err != nil || status != 404 || strings.Contains(string(body), "delegated_title") {
+ t.Fatalf("%d %s %v", status, body, err)
+ }
+ })
+ }
+}
diff --git a/internal/calls/delegated_review_test.go b/internal/calls/delegated_review_test.go
new file mode 100644
index 0000000..8fb164f
--- /dev/null
+++ b/internal/calls/delegated_review_test.go
@@ -0,0 +1,184 @@
+package calls
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "testing"
+ "time"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/roster"
+ "amadan.net/oficina/home/teammode"
+ "gorm.io/gorm"
+)
+
+func linkedDelegatedTeamReview(t *testing.T) (*teamFixture, access.Principal) {
+ t.Helper()
+ f := newTeamFixture(t)
+ subject := teamSubject('a')
+ f.dir.Set(subject, "member")
+ f.refreshed()
+ f.local(t)
+ if w := f.get("/account/home"); w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ start := homeRedirect(t, f.post("/account/home", ""))
+ homeRedirect(t, f.exchange(t, start, subject))
+ homeRedirect(t, f.post("/account/home/confirm", ""))
+ p := access.Principal{Subject: subject, Client: "review", Grant: "grant", Teams: []string{f.cfg.Team.TeamID}, Scopes: []string{"calls:read", "calls:write", "calls:share"}}
+ if err := f.app.mountDelegated(access.VerifyFunc(func(context.Context, string) (access.Principal, error) { return p, nil }), "https://connect.example.test", f.cfg.Team.TeamID); err != nil {
+ t.Fatal(err)
+ }
+ return f, p
+}
+
+func TestDelegatedReviewReservationFinalGuard(t *testing.T) {
+ for _, replay := range []bool{false, true} {
+ t.Run(map[bool]string{false: "fresh", true: "replay"}[replay], func(t *testing.T) {
+ f, p := linkedDelegated(t)
+ input := scheduleReservation()
+ if replay {
+ if w := delegatedCall(f.app, "calls_reserve_schedule", input); w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ }
+ person, err := f.app.delegatedPerson(t.Context(), *p, "acme")
+ if err != nil {
+ t.Fatal(err)
+ }
+ checks := 0
+ ctx := context.WithValue(t.Context(), delegatedBoundaryKey{}, delegatedRecheck(func(context.Context, access.Principal) error {
+ checks++
+ if checks == 2 {
+ return access.Fail("unauthenticated", "Revoked.")
+ }
+ return nil
+ }))
+ raw, _ := json.Marshal(input)
+ _, err = f.app.delegatedReserveSchedule(ctx, *p, person, raw)
+ if err == nil || access.SafeFailure(err).Code != "unauthenticated" || checks != 2 {
+ t.Fatalf("reservation final authority: %v checks=%d", err, checks)
+ }
+ var count int64
+ if err := f.app.db.G.Table("calls_agent_schedules").Count(&count).Error; err != nil {
+ t.Fatal(err)
+ }
+ want := int64(0)
+ if replay {
+ want = 1
+ }
+ if count != want {
+ t.Fatal("reservation rollback changed receipt count", count, want)
+ }
+ })
+ }
+}
+
+func TestDelegatedReviewTransactionKeepsTeamGuard(t *testing.T) {
+ for _, operation := range []string{"calls_reserve_schedule", "calls_create_meeting"} {
+ t.Run(operation, func(t *testing.T) {
+ f, _ := linkedDelegatedTeamReview(t)
+ input := scheduleReservation()
+ if operation == "calls_create_meeting" {
+ input = delegatedInputForTest()
+ }
+ input["team"] = f.cfg.Team.TeamID
+ teamGuard = f.lapsingGuard
+ defer func() { teamGuard = teammode.Guard }()
+ if w := delegatedCall(f.app, operation, input); w.Code != 503 {
+ t.Fatal("transaction lost roster guard", w.Code, w.Body.String())
+ }
+ for _, table := range []string{"calls_agent_schedules", "calls_agent_meetings", "calls_connections", "meetings", "meeting_links"} {
+ var count int64
+ if err := f.app.db.G.Table(table).Count(&count).Error; err != nil || count != 0 {
+ t.Fatal("lapsed transaction left effects", table, count, err)
+ }
+ }
+ })
+ }
+}
+
+type delegatedReviewDeadlineObserver struct {
+ http.ResponseWriter
+ budgets chan time.Duration
+}
+
+func (w *delegatedReviewDeadlineObserver) Unwrap() http.ResponseWriter { return w.ResponseWriter }
+func (w *delegatedReviewDeadlineObserver) SetWriteDeadline(d time.Time) error {
+ if !d.IsZero() {
+ w.budgets <- time.Until(d)
+ }
+ return http.NewResponseController(w.ResponseWriter).SetWriteDeadline(d)
+}
+
+func TestDelegatedReviewSocketDeadlineUsesRosterLease(t *testing.T) {
+ f, p := linkedDelegatedTeamReview(t)
+ standing := f.app.team.Access(t.Context(), p.Subject)
+ f.dir.SetDown(true)
+ f.clock.Step(standing.Remaining() - 250*time.Millisecond)
+ budgets := make(chan time.Duration, 16)
+ h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ f.app.delegated.ServeHTTP(&delegatedReviewDeadlineObserver{w, budgets}, r)
+ })
+ status, body, err := delegatedLiveCall(t, h, "calls_list_meetings", map[string]any{"team": f.cfg.Team.TeamID})
+ if status != 200 || err != nil {
+ t.Fatal(status, string(body), err)
+ }
+ close(budgets)
+ n := 0
+ for d := range budgets {
+ n++
+ if d <= 0 || d > 300*time.Millisecond {
+ t.Fatal("socket deadline exceeds captured lease", d)
+ }
+ }
+ if n == 0 {
+ t.Fatal("no socket deadline")
+ }
+}
+
+func TestDelegatedReviewResponseRechecksAfterDatabaseRead(t *testing.T) {
+ f, p := linkedDelegatedTeamReview(t)
+ input := delegatedInputForTest()
+ input["team"] = f.cfg.Team.TeamID
+ w := delegatedCall(f.app, "calls_create_meeting", input)
+ if w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ var created struct{ Sqid string }
+ if err := json.Unmarshal(w.Body.Bytes(), &created); err != nil {
+ t.Fatal(err)
+ }
+ lapsed := false
+ const callback = "review:lapse_after_response_read"
+ if err := f.app.db.G.Callback().Query().After("gorm:query").Register(callback, func(tx *gorm.DB) {
+ state, _ := tx.Statement.Context.Value(delegatedResponseKey{}).(*delegatedResponseState)
+ if !lapsed && tx.Statement.Table == "meetings" && state != nil && len(state.meetings) > 0 {
+ lapsed = true
+ f.dir.SetDown(true)
+ f.clock.Step(roster.MaximumAge + time.Second)
+ }
+ }); err != nil {
+ t.Fatal(err)
+ }
+ defer f.app.db.G.Callback().Query().Remove(callback)
+ // Exercise the response callback directly: the transport deadline guard
+ // must not conceal an omitted final check in this callback.
+ state := &delegatedResponseState{}
+ ctx := context.WithValue(t.Context(), delegatedResponseKey{}, state)
+ person, err := f.app.delegatedPerson(ctx, p, f.cfg.Team.TeamID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw, _ := json.Marshal(map[string]any{"team": f.cfg.Team.TeamID, "sqid": created.Sqid})
+ result, err := f.app.delegatedGet(ctx, p, person, raw)
+ if err != nil {
+ t.Fatal(err)
+ }
+ state.selected = true
+ err = f.app.delegatedResponse(ctx, p, "calls_get_meeting", raw, result)
+ if !lapsed || err == nil || access.SafeFailure(err).Code != "unavailable" {
+ t.Fatal("response escaped after roster lease expired during query", lapsed, err)
+ }
+}
diff --git a/internal/calls/delegated_schedule.go b/internal/calls/delegated_schedule.go
new file mode 100644
index 0000000..6b541dd
--- /dev/null
+++ b/internal/calls/delegated_schedule.go
@@ -0,0 +1,72 @@
+package calls
+
+import (
+ "context"
+ "encoding/hex"
+ "encoding/json"
+ "strings"
+
+ access "amadan.net/oficina/agent-access.git"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+// Only a keyed fingerprint is retained. Each destination's atomic create
+// receipt owns progress; the connection service retains no workflow data.
+func (a *app) delegatedReserveSchedule(ctx context.Context, p access.Principal, person Person, raw json.RawMessage) (any, error) {
+ var in struct {
+ Team string `json:"team"`
+ ClientID string `json:"client_id"`
+ Fingerprint string `json:"fingerprint"`
+ }
+ if json.Unmarshal(raw, &in) != nil {
+ return nil, access.Fail("invalid", "Invalid schedule reservation.")
+ }
+ id, err := uuid.Parse(in.ClientID)
+ digest, e := hex.DecodeString(in.Fingerprint)
+ if err != nil || id == uuid.Nil || id.String() != in.ClientID || e != nil || len(digest) != 32 || strings.ToLower(in.Fingerprint) != in.Fingerprint {
+ return nil, access.Fail("invalid", "Supply a canonical UUID and SHA-256 fingerprint.")
+ }
+ coordinates, _ := json.Marshal([]string{a.cfg.Home.Issuer, a.agentIssuer, p.Subject, p.Client, in.Team, "calls_reserve_schedule", in.ClientID})
+ key, err := a.sealer.Fingerprint("connection.schedule.coordinate.v1", string(coordinates))
+ if err != nil {
+ return nil, err
+ }
+ content, err := a.sealer.Fingerprint("connection.schedule.content.v1", in.Fingerprint)
+ if err != nil {
+ return nil, err
+ }
+ err = a.store.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if err := a.bindDelegated(tx); err != nil {
+ return err
+ }
+ if err := a.checkDelegatedWriter(ctx, tx, p, person); err != nil {
+ return err
+ }
+ current := *a.store
+ current.g = tx
+ return current.guard(ctx, func() error {
+ if err := tx.Exec("INSERT INTO calls_agent_schedules(coordinate,content) VALUES(?,?) ON CONFLICT(coordinate) DO NOTHING", key, content).Error; err != nil {
+ return err
+ }
+ var saved string
+ if err := tx.Raw("SELECT content FROM calls_agent_schedules WHERE coordinate=?", key).Row().Scan(&saved); err != nil {
+ return err
+ }
+ if saved != content {
+ return access.Fail("conflict", "This schedule client_id was used with different arguments.")
+ }
+ return a.checkDelegatedWriter(ctx, tx, p, person)
+ })
+ })
+ if err != nil {
+ return nil, err
+ }
+ return map[string]any{"reserved": true}, nil
+}
+
+func (a *app) delegatedScheduleOperation(team string) access.Operation {
+ return access.Operation{Name: "calls_reserve_schedule", Description: "Reserve a fingerprint for a resumable schedule. Creates no meeting or event and sends no invitations. Reuse the UUID and fingerprint only for the same workflow.", Scope: "calls:write", Idempotent: true,
+ Input: delegatedInput(map[string]any{"client_id": delegatedString(36), "fingerprint": map[string]any{"type": "string", "pattern": "^[0-9a-f]{64}$"}}, "client_id", "fingerprint"),
+ Output: delegatedObject(map[string]any{"reserved": map[string]any{"const": true}}, "reserved"), Invoke: a.delegatedGuard(team, "calls:write", a.delegatedReserveSchedule)}
+}
diff --git a/internal/calls/delegated_schedule_test.go b/internal/calls/delegated_schedule_test.go
new file mode 100644
index 0000000..d157d41
--- /dev/null
+++ b/internal/calls/delegated_schedule_test.go
@@ -0,0 +1,165 @@
+package calls
+
+import (
+ access "amadan.net/oficina/agent-access.git"
+ "context"
+ "encoding/json"
+ "gorm.io/gorm"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+func scheduleReservation() map[string]any {
+ return map[string]any{"team": "acme", "client_id": "3395dd82-455b-46ae-a758-a7fb1484f3e6", "fingerprint": strings.Repeat("a", 64)}
+}
+func TestDelegatedScheduleReservation(t *testing.T) {
+ f, p := linkedDelegated(t)
+ input := scheduleReservation()
+ var wg sync.WaitGroup
+ for range 5 {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ w := delegatedCall(f.app, "calls_reserve_schedule", input)
+ if w.Code != 200 {
+ t.Errorf("reserve %d %s", w.Code, w.Body.String())
+ }
+ }()
+ }
+ wg.Wait()
+ var count int
+ if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM calls_agent_schedules").Scan(&count); err != nil || count != 1 {
+ t.Fatal(count, err)
+ }
+ var coordinate, content string
+ if err := f.app.db.Writer().QueryRow("SELECT coordinate,content FROM calls_agent_schedules").Scan(&coordinate, &content); err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(coordinate, input["client_id"].(string)) || content == input["fingerprint"] {
+ t.Fatal("unkeyed workflow storage")
+ }
+ for _, table := range []string{"meetings", "calls_connections", "calls_agent_meetings", "meeting_links"} {
+ if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM " + table).Scan(&count); err != nil || count != 0 {
+ t.Fatal(table, count, err)
+ }
+ }
+ input["fingerprint"] = strings.Repeat("b", 64)
+ if w := delegatedCall(f.app, "calls_reserve_schedule", input); w.Code != 409 {
+ t.Fatal("changed workflow accepted", w.Code)
+ }
+ p.Client = "different-client"
+ if w := delegatedCall(f.app, "calls_reserve_schedule", input); w.Code != 200 {
+ t.Fatal("client not isolated", w.Code)
+ }
+ if err := f.app.db.G.Exec("DELETE FROM calls_agent_state").Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := f.app.db.G.Transaction(func(tx *gorm.DB) error { return f.app.bindDelegated(tx) }); err == nil {
+ t.Fatal("orphaned reservation adopted")
+ }
+}
+func TestDelegatedScheduleReservationFinalAuthority(t *testing.T) {
+ f, _ := linkedDelegated(t)
+ if err := f.app.db.G.Exec("CREATE TRIGGER revoke_schedule AFTER INSERT ON calls_agent_schedules BEGIN DELETE FROM home_identity_links; END").Error; err != nil {
+ t.Fatal(err)
+ }
+ if w := delegatedCall(f.app, "calls_reserve_schedule", scheduleReservation()); w.Code != 403 {
+ t.Fatal("revoked reservation committed", w.Code, w.Body.String())
+ }
+ var count int64
+ if err := f.app.db.G.Table("calls_agent_schedules").Count(&count).Error; err != nil || count != 0 {
+ t.Fatal(count, err)
+ }
+}
+func TestSuiteInteropFixture(t *testing.T) {
+ dir := os.Getenv("OFICINA_INTEROP_DIR")
+ if dir == "" {
+ t.Skip("cross-app harness only")
+ }
+ f, p := linkedDelegated(t)
+ p.Client = "oficina-interop"
+ p.Grant = "interop-grant"
+ server := httptest.NewTLSServer(f.app.delegated)
+ defer server.Close()
+ b, _ := json.Marshal(map[string]any{"url": server.URL, "origin": f.app.cfg.Origin})
+ if err := os.WriteFile(filepath.Join(dir, "calls.json"), b, 0600); err != nil {
+ t.Fatal(err)
+ }
+ deadline := time.NewTimer(2 * time.Minute)
+ defer deadline.Stop()
+ tick := time.NewTicker(100 * time.Millisecond)
+ defer tick.Stop()
+ for {
+ select {
+ case <-deadline.C:
+ t.Fatal("cross-app harness timed out")
+ case <-t.Context().Done():
+ t.Fatal(t.Context().Err())
+ case <-tick.C:
+ if _, err := os.Stat(filepath.Join(dir, "stop")); err == nil {
+ return
+ }
+ }
+ }
+}
+func TestDelegatedScheduleTeamStanding(t *testing.T) {
+ for _, mode := range []string{"member", "removed", "expired"} {
+ t.Run(mode, func(t *testing.T) {
+ f := newTeamFixture(t)
+ subject := teamSubject('a')
+ f.dir.Set(subject, "member")
+ f.refreshed()
+ f.local(t)
+ if w := f.get("/account/home"); w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ start := homeRedirect(t, f.post("/account/home", ""))
+ homeRedirect(t, f.exchange(t, start, subject))
+ homeRedirect(t, f.post("/account/home/confirm", ""))
+ p := access.Principal{Subject: subject, Client: "workflow", Grant: "grant", Teams: []string{f.cfg.Team.TeamID}, Scopes: []string{"calls:read", "calls:write", "calls:share"}}
+ if err := f.app.mountDelegated(access.VerifyFunc(func(context.Context, string) (access.Principal, error) { return p, nil }), "https://connect.example.test", f.cfg.Team.TeamID); err != nil {
+ t.Fatal(err)
+ }
+ if mode == "removed" {
+ f.removed(subject)
+ }
+ if mode == "expired" {
+ f.expired()
+ }
+ in := scheduleReservation()
+ in["team"] = f.cfg.Team.TeamID
+ w := delegatedCall(f.app, "calls_reserve_schedule", in)
+ want := 200
+ if mode == "removed" {
+ want = 403
+ }
+ if mode == "expired" {
+ want = 503
+ }
+ if w.Code != want {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ if mode == "member" {
+ in := delegatedInputForTest()
+ in["team"] = f.cfg.Team.TeamID
+ w := delegatedCall(f.app, "calls_create_meeting", in)
+ if w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ var out struct{ Sqid string }
+ if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
+ t.Fatal(err)
+ }
+ w = delegatedCall(f.app, "calls_get_join_link", map[string]any{"team": f.cfg.Team.TeamID, "sqid": out.Sqid})
+ if w.Code != 200 {
+ t.Fatal("connection operator host not resolved", w.Code, w.Body.String())
+ }
+ }
+ })
+ }
+}
diff --git a/internal/calls/delegated_team.go b/internal/calls/delegated_team.go
new file mode 100644
index 0000000..3fe4752
--- /dev/null
+++ b/internal/calls/delegated_team.go
@@ -0,0 +1,69 @@
+package calls
+
+import (
+ "context"
+ "net/http"
+ "time"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/roster"
+ "amadan.net/oficina/home/teammode"
+)
+
+// Capture standing once, before the writer. Neither retries, final authority
+// checks nor response emission may refresh an expired decision.
+func (a *app) delegatedStanding(ctx context.Context, subject string, person Person, capture bool) error {
+ if a.cfg.Team == nil {
+ if a.isMember(person) {
+ return nil
+ }
+ return access.Fail("forbidden", "This account cannot access Calls.")
+ }
+ state, _ := ctx.Value(delegatedResponseKey{}).(*delegatedResponseState)
+ if a.team == nil || state == nil {
+ return access.Fail("unavailable", "Team authority is unavailable.")
+ }
+ if state.subject == "" && capture {
+ state.subject, state.standing = subject, a.team.Access(ctx, subject)
+ }
+ if state.subject != subject || state.standing == nil || state.standing.Subject() != subject {
+ return access.Fail("forbidden", "The linked identity changed.")
+ }
+ switch state.standing.State() {
+ case roster.Member:
+ return nil
+ case roster.NotMember:
+ return access.Fail("forbidden", "This account cannot access Calls.")
+ default:
+ return access.Fail("unavailable", "Team membership cannot be verified now.")
+ }
+}
+
+type delegatedLeaseWriter struct {
+ http.ResponseWriter
+ state *delegatedResponseState
+ team bool
+}
+
+func (w *delegatedLeaseWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }
+func (w *delegatedLeaseWriter) SetWriteDeadline(deadline time.Time) error {
+ if w.team && !deadline.IsZero() {
+ if w.state == nil || w.state.standing == nil {
+ return access.Fail("unavailable", "Team authority is unavailable.")
+ }
+ for _, standing := range []*teammode.Access{w.state.standing, w.state.host} {
+ if standing == nil {
+ continue
+ }
+ now := time.Now()
+ remaining := standing.Remaining()
+ if remaining <= 0 {
+ return access.Fail("unavailable", "Team membership cannot be verified now.")
+ }
+ if until := now.Add(remaining); until.Before(deadline) {
+ deadline = until
+ }
+ }
+ }
+ return http.NewResponseController(w.ResponseWriter).SetWriteDeadline(deadline)
+}
diff --git a/internal/calls/delegated_test.go b/internal/calls/delegated_test.go
new file mode 100644
index 0000000..a3ca17d
--- /dev/null
+++ b/internal/calls/delegated_test.go
@@ -0,0 +1,222 @@
+package calls
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "sync"
+ "testing"
+
+ access "amadan.net/oficina/agent-access.git"
+)
+
+func linkedDelegated(t *testing.T) (*homeRouterFixture, *access.Principal) {
+ t.Helper()
+ f := newHomeRouterFixture(t)
+ f.link(t)
+ p := &access.Principal{Subject: "opaque-home-alice", Client: "integration-agent-251a75", Grant: "grant-one", Teams: []string{"acme"}, Scopes: []string{"calls:read", "calls:write", "calls:share"}}
+ if err := f.app.mountDelegated(access.VerifyFunc(func(context.Context, string) (access.Principal, error) { return *p, nil }), "https://connect.example.test", "acme"); err != nil {
+ t.Fatal(err)
+ }
+ return f, p
+}
+func delegatedCall(a *app, name string, input any) *httptest.ResponseRecorder {
+ raw, _ := json.Marshal(input)
+ r := httptest.NewRequest("POST", homeTestOrigin+"/api/v1/operations/"+name, bytes.NewReader(raw))
+ r.Header.Set("Authorization", "Bearer fixture")
+ r.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ a.delegated.ServeHTTP(responseRecorder{w}, r)
+ return w
+}
+func delegatedInputForTest() map[string]any {
+ return map[string]any{"team": "acme", "client_id": "3395dd82-455b-46ae-a758-a7fb1484f3e6", "title": "delegated_title_5405cbdca192", "starts_at": "2026-11-01T10:00:00+00:00"}
+}
+func TestDelegatedMeetingAtomicRetryAndSealing(t *testing.T) {
+ f, p := linkedDelegated(t)
+ input := delegatedInputForTest()
+ w := delegatedCall(f.app, "calls_create_meeting", input)
+ if w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ var result struct {
+ Sqid string `json:"sqid"`
+ }
+ if json.Unmarshal(w.Body.Bytes(), &result) != nil || !validSqid(result.Sqid) {
+ t.Fatal(w.Body.String())
+ }
+ var wg sync.WaitGroup
+ for i := 0; i < 5; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ r := delegatedCall(f.app, "calls_create_meeting", input)
+ if r.Code != 200 || r.Body.String() != w.Body.String() {
+ t.Errorf("retry: %d %s", r.Code, r.Body.String())
+ }
+ }()
+ }
+ wg.Wait()
+ for _, table := range []string{"meetings", "meeting_links", "calls_agent_meetings", "calls_connections"} {
+ var n int
+ if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM " + table).Scan(&n); err != nil || n != 1 {
+ t.Fatal(table, n, err)
+ }
+ }
+ input["title"] = "changed"
+ if r := delegatedCall(f.app, "calls_create_meeting", input); r.Code != 409 {
+ t.Fatal("changed retry", r.Code)
+ }
+ input["title"] = "delegated_title_5405cbdca192"
+ m, ok, err := f.app.store.meetingBySqid(t.Context(), result.Sqid)
+ if err != nil || !ok {
+ t.Fatal(err)
+ }
+ view, err := f.app.store.meetingViewOf(t.Context(), m)
+ if err != nil || !view.ByAgent || view.CreatedByPrincipal != p.Client+"~alice@example.test" {
+ t.Fatal("lost agent attribution", view, err)
+ }
+ r := delegatedCall(f.app, "calls_get_join_link", map[string]any{"team": "acme", "sqid": m.Sqid})
+ if r.Code != 200 {
+ t.Fatal(r.Code, r.Body.String())
+ }
+ var invitation struct {
+ URL string `json:"join_url"`
+ }
+ _ = json.Unmarshal(r.Body.Bytes(), &invitation)
+ token := invitation.URL[strings.LastIndex(invitation.URL, "/")+1:]
+ if _, _, ok, err := f.app.store.liveLink(t.Context(), token); err != nil || !ok {
+ t.Fatal("invalid invitation", err)
+ }
+ coords, _ := json.Marshal([]string{f.app.cfg.Home.Issuer, f.app.agentIssuer, p.Subject, p.Client, "acme", input["client_id"].(string)})
+ want, err := f.app.sealer.Fingerprint("connection.receipt.v1", string(coords))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var saved string
+ if err = f.app.db.Writer().QueryRow("SELECT coordinate FROM calls_agent_meetings").Scan(&saved); err != nil || saved != want {
+ t.Fatal("receipt binding", err)
+ }
+ var names string
+ if err = f.app.db.Writer().QueryRow("SELECT group_concat(name,',') FROM pragma_table_info('calls_agent_meetings')").Scan(&names); err != nil || names != "coordinate,content,meeting_id" {
+ t.Fatal("receipt stores extra data", names, err)
+ }
+ var seq int
+ var dbName, path string
+ if err = f.app.db.Writer().QueryRow("PRAGMA database_list").Scan(&seq, &dbName, &path); err != nil {
+ t.Fatal(err)
+ }
+ check := func() {
+ for _, suffix := range []string{"", "-wal"} {
+ raw, err := os.ReadFile(path + suffix)
+ if os.IsNotExist(err) {
+ continue
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, canary := range []string{input["title"].(string), token, p.Client} {
+ if bytes.Contains(raw, []byte(canary)) {
+ t.Fatal("plaintext in SQLite", suffix)
+ }
+ }
+ }
+ }
+ check()
+ if _, err = f.app.db.Writer().Exec("PRAGMA wal_checkpoint(TRUNCATE)"); err != nil {
+ t.Fatal(err)
+ }
+ check()
+ if _, err = f.app.store.endMeeting(t.Context(), m.ID, actorFor(Person{ID: 1})); err != nil {
+ t.Fatal(err)
+ }
+ // A stale unrevoked invitation must not bypass the meeting ended check.
+ if _, err = f.app.db.Writer().Exec("UPDATE meeting_links SET revoked_at=NULL"); err != nil {
+ t.Fatal(err)
+ }
+ if r := delegatedCall(f.app, "calls_get_join_link", map[string]any{"team": "acme", "sqid": m.Sqid}); r.Code != 404 {
+ t.Fatal("ended invitation", r.Code)
+ }
+ if r := delegatedCall(f.app, "calls_create_meeting", input); r.Code != 200 {
+ t.Fatal("ended retry", r.Code)
+ }
+ if err = f.app.db.G.Delete(&Meeting{}, m.ID).Error; err != nil {
+ t.Fatal(err)
+ }
+ if r := delegatedCall(f.app, "calls_create_meeting", input); r.Code != 404 {
+ t.Fatal("deleted retry", r.Code)
+ }
+}
+func TestDelegatedIdentityScopeAndCurrentMembership(t *testing.T) {
+ f, p := linkedDelegated(t)
+ original := *p
+ input := delegatedInputForTest()
+ for _, change := range []func(){func() { p.Subject = "unknown" }, func() { p.Client = "" }, func() { p.Grant = "" }, func() { p.Teams = []string{"other"} }, func() { p.Scopes = []string{"calls:read"} }, func() { f.app.cfg.allow = allowlist{} }} {
+ change()
+ if w := delegatedCall(f.app, "calls_create_meeting", input); w.Code != 403 {
+ t.Fatal("unauthorized creation", w.Code, w.Body.String())
+ }
+ *p = original
+ f.app.cfg.allow = allowlist{addrs: map[string]struct{}{"alice@example.test": {}}}
+ }
+ var n int
+ if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM meetings").Scan(&n); err != nil || n != 0 {
+ t.Fatal("denial wrote", n, err)
+ }
+ p.Teams = []string{"acme", "other"}
+ input["team"] = "other"
+ if w := delegatedCall(f.app, "calls_create_meeting", input); w.Code != 403 {
+ t.Fatal("other configured team", w.Code)
+ }
+ *p = original
+ input["team"] = "acme"
+ w := delegatedCall(f.app, "calls_create_meeting", input)
+ if w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ var m struct {
+ Sqid string `json:"sqid"`
+ }
+ _ = json.Unmarshal(w.Body.Bytes(), &m)
+ p.Scopes = []string{"calls:read", "calls:write"}
+ if w := delegatedCall(f.app, "calls_get_join_link", map[string]any{"team": "acme", "sqid": m.Sqid}); w.Code != 403 {
+ t.Fatal("sharing scope bypass", w.Code)
+ }
+ r := httptest.NewRequest("GET", homeTestOrigin+"/api/v1/operations", nil)
+ for _, c := range f.cookies {
+ r.AddCookie(c)
+ }
+ w = httptest.NewRecorder()
+ f.app.delegated.ServeHTTP(responseRecorder{w}, r)
+ if w.Code != http.StatusUnauthorized {
+ t.Fatal("cookie authorized", w.Code)
+ }
+ if _, err := f.app.db.Writer().Exec("DELETE FROM home_identity_links"); err != nil {
+ t.Fatal(err)
+ }
+ if w := delegatedCall(f.app, "calls_list_meetings", map[string]any{"team": "acme"}); w.Code != 403 {
+ t.Fatal("unlink did not revoke", w.Code)
+ }
+ if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM persons").Scan(&n); err != nil || n != 1 {
+ t.Fatal("auto-provisioned", n, err)
+ }
+}
+func TestDelegatedLinkFailureRollsBackEverything(t *testing.T) {
+ f, _ := linkedDelegated(t)
+ if _, err := f.app.db.Writer().Exec("CREATE TRIGGER reject_link BEFORE INSERT ON meeting_links BEGIN SELECT RAISE(ABORT,'fixture'); END"); err != nil {
+ t.Fatal(err)
+ }
+ if w := delegatedCall(f.app, "calls_create_meeting", delegatedInputForTest()); w.Code != 503 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ for _, table := range []string{"meetings", "meeting_links", "calls_agent_meetings", "calls_connections"} {
+ var n int
+ if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM " + table).Scan(&n); err != nil || n != 0 {
+ t.Fatal("partial transaction", table, n, err)
+ }
+ }
+}
diff --git a/internal/calls/store.go b/internal/calls/store.go
index 8eab01f..3f722bb 100644
--- a/internal/calls/store.go
+++ b/internal/calls/store.go
@@ -215,7 +215,7 @@ func (s *store) meetingViewOfCached(ctx context.Context, m Meeting, labels map[s
Title: s.title(m),
LinkPresent: n > 0,
CreatedByPrincipal: by,
- ByAgent: strings.HasPrefix(m.CreatedBy, "agent:"),
+ ByAgent: strings.HasPrefix(m.CreatedBy, "agent:") || strings.HasPrefix(m.CreatedBy, "connection:"),
}, nil
}
diff --git a/internal/calls/team_guard_test.go b/internal/calls/team_guard_test.go
index eec211b..73b649d 100644
--- a/internal/calls/team_guard_test.go
+++ b/internal/calls/team_guard_test.go
@@ -185,6 +185,9 @@ func (w *teamWriteWorld) routes() []writeRoute {
// as a member (not an owner) and as a guest on the member's meetings,
// each change the database.
func TestTeamEveryWriteRouteRefusesALapseBeforeCommit(t *testing.T) {
+ // Delegated routes require an existing linked local account rather than
+ // this browser fixture's Home-only account. Keep them in the write inventory.
+ t.Run("delegated API writes", TestDelegatedReviewTransactionKeepsTeamGuard)
w := newTeamWriteWorld(t)
f := w.f
defer func() { teamGuard = teammode.Guard }()
diff --git a/internal/calls/team_host.go b/internal/calls/team_host.go
index 73f7d92..be0b32a 100644
--- a/internal/calls/team_host.go
+++ b/internal/calls/team_host.go
@@ -49,6 +49,11 @@ func (a *app) hostOf(ctx context.Context, m Meeting) (id int64, ok bool, err err
if !found {
return 0, false, nil
}
+ if kind == "connection" {
+ var operator int64
+ err := a.store.g.WithContext(ctx).Raw("SELECT operator_person_id FROM calls_connections WHERE coordinate=?", rest).Scan(&operator).Error
+ return operator, operator > 0, err
+ }
n, perr := strconv.ParseInt(rest, 10, 64)
if perr != nil {
return 0, false, nil