From 61a72ccb3847606b15ffe5589351d29d3f0b3f3b Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 22 Nov 2026 22:10:52 +0000 Subject: [PATCH 1/2] Add agent connection grants for programs connected to a product A program a person connects to a product (an MCP client) was pinned to that person's session proof and died at its absolute sign-in deadline however much it was used. An agent connection grant is issued from a live session proof for one person, organisation and team, then lives on a 90-day idle clock that only the program's own use slides, under an optional organisation ceiling. Every renewal rechecks revocation, the credential epoch, active user and role, organisation and team membership, unpaid seats, the product mapping, SSO policy generation and, for SSO grants, the connection, external identity and provisioning. The new agent.connection mapping scope is the per-product switch and can never be minted through /auth/token. Grants carry no assurance id and cannot pass for a session proof; their resource tokens carry agent_connection. Co-Authored-By: Claude Opus 5.5 --- .../migration.sql | 63 ++++ API/prisma/schema.prisma | 45 +++ .../routes/auth/agent-connection-grants.ts | 86 ++++++ API/src/routes/auth/index.ts | 2 + API/src/routes/auth/rate-limit-keys.ts | 14 + .../routes/org/organisation-route.shared.ts | 3 + API/src/routes/org/organisations.ts | 3 +- API/src/routes/root/llm-agent-grants.ts | 10 + API/src/routes/root/llm.ts | 3 +- .../routes/root/schema.auth-agent-grants.ts | 51 ++++ API/src/routes/root/schema.auth.ts | 2 + API/src/routes/root/schema.org.ts | 2 + ...agent-connection-grant-evidence.service.ts | 64 +++++ .../agent-connection-grant.service.ts | 269 ++++++++++++++++++ .../confidential-delegation.service.ts | 13 + .../services/oauth/access-token.service.ts | 3 + API/src/services/org-context.service.ts | 7 +- API/src/services/org-sso-policy.service.ts | 10 +- API/src/services/organisation.resolve.ts | 2 + API/src/services/organisation.service.base.ts | 3 + .../organisation.service.organisation.ts | 13 + .../agent-connection-grant.test.ts | 195 +++++++++++++ API/tests/unit/auth-rate-limit-global.test.ts | 5 +- .../ConfidentialDelegationFormDialog.tsx | 6 + Admin/src/schemas/confidential-delegation.ts | 1 + 25 files changed, 870 insertions(+), 5 deletions(-) create mode 100644 API/prisma/migrations/20261122200000_agent_connection_grants/migration.sql create mode 100644 API/src/routes/auth/agent-connection-grants.ts create mode 100644 API/src/routes/root/llm-agent-grants.ts create mode 100644 API/src/routes/root/schema.auth-agent-grants.ts create mode 100644 API/src/services/agent-connection-grant-evidence.service.ts create mode 100644 API/src/services/agent-connection-grant.service.ts create mode 100644 API/tests/integration/agent-connection-grant.test.ts diff --git a/API/prisma/migrations/20261122200000_agent_connection_grants/migration.sql b/API/prisma/migrations/20261122200000_agent_connection_grants/migration.sql new file mode 100644 index 000000000..553bd13e4 --- /dev/null +++ b/API/prisma/migrations/20261122200000_agent_connection_grants/migration.sql @@ -0,0 +1,63 @@ +ALTER TYPE "ConfidentialDelegationScope" ADD VALUE IF NOT EXISTS 'agent.connection'; + +ALTER TABLE "organisations" ADD COLUMN "agent_connection_max_days" INTEGER; +ALTER TABLE "organisations" ADD CONSTRAINT "organisations_agent_connection_max_days_check" + CHECK ("agent_connection_max_days" IS NULL OR "agent_connection_max_days" BETWEEN 1 AND 3650); + +CREATE TABLE "agent_connection_grants" ( + "id" TEXT NOT NULL, + "client_domain_id" TEXT NOT NULL, + "request_id" UUID NOT NULL, + "connection_id" VARCHAR(160) NOT NULL, + "source_domain" VARCHAR(255) NOT NULL, + "subject_id" VARCHAR(256) NOT NULL, + "org_id" VARCHAR(256) NOT NULL, + "team_id" VARCHAR(256) NOT NULL, + "token_version" INTEGER NOT NULL, + "origin_token_jti" VARCHAR(256) NOT NULL, + "product" VARCHAR(100) NOT NULL, + "resource" VARCHAR(2048) NOT NULL, + "binding_hash" CHAR(64) NOT NULL, + "source_assurance_id" TEXT NOT NULL, + "method" VARCHAR(20) NOT NULL, + "sso_connection_id" TEXT, + "sso_connection_revision" INTEGER, + "sso_connection_generation" INTEGER, + "external_identity_id" TEXT, + "mfa_source" TEXT NOT NULL, + "amr" TEXT[], + "policy_generation" INTEGER NOT NULL, + "idle_expires_at" TIMESTAMPTZ(3) NOT NULL, + "last_touched_at" TIMESTAMPTZ(3) NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "revoked_at" TIMESTAMPTZ(3), + CONSTRAINT "agent_connection_grants_pkey" PRIMARY KEY ("id"), + CONSTRAINT "agent_connection_grants_method_check" CHECK ("method" IN ('independent', 'sso')) +); + +CREATE UNIQUE INDEX "agent_connection_grants_client_domain_id_request_id_key" + ON "agent_connection_grants"("client_domain_id", "request_id"); +CREATE INDEX "agent_connection_grants_subject_id_token_version_idx" + ON "agent_connection_grants"("subject_id", "token_version"); +CREATE INDEX "agent_connection_grants_org_id_team_id_idx" + ON "agent_connection_grants"("org_id", "team_id"); + +ALTER TABLE "agent_connection_grants" ADD CONSTRAINT "agent_connection_grants_client_domain_id_fkey" + FOREIGN KEY ("client_domain_id") REFERENCES "client_domains"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +REVOKE ALL ON TABLE agent_connection_grants FROM PUBLIC; +DO $$ +BEGIN + IF EXISTS (SELECT FROM pg_roles WHERE rolname = 'uoa_app') THEN + REVOKE ALL ON TABLE agent_connection_grants FROM uoa_app; + END IF; + IF EXISTS (SELECT FROM pg_roles WHERE rolname = 'uoa_admin') THEN + GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE agent_connection_grants TO uoa_admin; + END IF; +END +$$; + +ALTER TABLE agent_connection_grants ENABLE ROW LEVEL SECURITY; +ALTER TABLE agent_connection_grants FORCE ROW LEVEL SECURITY; +CREATE POLICY agent_connection_grants_deny_app ON agent_connection_grants + FOR ALL TO uoa_app USING (false) WITH CHECK (false); diff --git a/API/prisma/schema.prisma b/API/prisma/schema.prisma index aad846bca..3dbed3da1 100644 --- a/API/prisma/schema.prisma +++ b/API/prisma/schema.prisma @@ -446,6 +446,7 @@ enum ConfidentialDelegationScope { MEMORY_READ @map("memory.read") MEMORY_WRITE @map("memory.write") SESSION_BROKER @map("session:broker") + AGENT_CONNECTION @map("agent.connection") } model User { @@ -1001,6 +1002,7 @@ model ClientDomain { agreementSignatures AgreementSignature[] delegationMappings ConfidentialDelegationMapping[] salesResearchJobGrants SalesResearchJobGrant[] + agentConnectionGrants AgentConnectionGrant[] @@index([status]) @@map("client_domains") @@ -1401,6 +1403,8 @@ model Organisation { // only after an owner/admin approves) | "disabled" (only owner/admin may invite). Validated at the // app layer, not the DB, matching the org_features JSON pattern. memberInvites String @default("allowed") @map("member_invites") + // Optional absolute lifetime for agent connection grants, in days from issue. Null: idle expiry only. + agentConnectionMaxDays Int? @map("agent_connection_max_days") createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") @@ -3597,6 +3601,47 @@ model BillingJobComputeRenewal { @@map("billing_job_compute_renewals") } +// A program a person connected to a product (an MCP client), as one person in one +// organisation team. Issued only from a live session proof; afterwards it lives on its +// own idle clock and never passes for a session proof or a human presence check. +// The source proof's evidence is copied so renewal can recheck SSO connection, +// external identity, provisioning and policy generation after the session has ended. +model AgentConnectionGrant { + id String @id @default(uuid()) + clientDomainId String @map("client_domain_id") + requestId String @map("request_id") @db.Uuid + connectionId String @map("connection_id") @db.VarChar(160) + sourceDomain String @map("source_domain") @db.VarChar(255) + subjectId String @map("subject_id") @db.VarChar(256) + orgId String @map("org_id") @db.VarChar(256) + teamId String @map("team_id") @db.VarChar(256) + tokenVersion Int @map("token_version") + originTokenJti String @map("origin_token_jti") @db.VarChar(256) + product String @db.VarChar(100) + resource String @db.VarChar(2048) + bindingHash String @map("binding_hash") @db.Char(64) + sourceAssuranceId String @map("source_assurance_id") + method String @db.VarChar(20) + connectionRef String? @map("sso_connection_id") + connectionRevision Int? @map("sso_connection_revision") + connectionGeneration Int? @map("sso_connection_generation") + externalIdentityId String? @map("external_identity_id") + mfaSource String @map("mfa_source") + amr String[] + policyGeneration Int @map("policy_generation") + idleExpiresAt DateTime @map("idle_expires_at") @db.Timestamptz(3) + lastTouchedAt DateTime @map("last_touched_at") @db.Timestamptz(3) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + revokedAt DateTime? @map("revoked_at") @db.Timestamptz(3) + + clientDomain ClientDomain @relation(fields: [clientDomainId], references: [id], onDelete: Cascade) + + @@unique([clientDomainId, requestId]) + @@index([subjectId, tokenVersion]) + @@index([orgId, teamId]) + @@map("agent_connection_grants") +} + // A bounded continuation authority captured from one fresh SalesNerd team // assertion. It is independent of DeepWater's Ledger-runtime-key grants. model SalesResearchJobGrant { diff --git a/API/src/routes/auth/agent-connection-grants.ts b/API/src/routes/auth/agent-connection-grants.ts new file mode 100644 index 000000000..f85fda5ba --- /dev/null +++ b/API/src/routes/auth/agent-connection-grants.ts @@ -0,0 +1,86 @@ +import type { FastifyInstance, FastifyRequest } from 'fastify'; +import { z } from 'zod'; + +import { configVerifier } from '../../middleware/config-verifier.js'; +import { requireDomainHashAuth } from '../../middleware/domain-hash-auth.js'; +import { + issueAgentConnectionGrant, + renewAgentConnectionGrant, + revokeAgentConnectionGrant, +} from '../../services/agent-connection-grant.service.js'; +import { AppError } from '../../utils/errors.js'; +import { agentConnectionGrantRateLimiter } from './rate-limit-keys.js'; + +const Uuid = z.string().uuid(); +const IssueBody = z.object({ + request_id: Uuid, + connection_id: z.string().min(1).max(160), + product: z.string().min(1).max(100), + resource: z.string().min(1).max(2048), + subject_token: z.string().min(1).max(16 * 1024), + subject_token_type: z.literal('urn:ietf:params:oauth:token-type:jwt'), +}).strict(); +const RenewBody = z.object({ + request_id: Uuid, + touch: z.boolean(), + resource: z.string().min(1).max(2048).optional(), + scope: z.string().min(1).max(200).optional(), +}).strict(); +const RevokeBody = z.object({ request_id: Uuid }).strict(); +const GrantParams = z.object({ grantHandle: Uuid }).strict(); + +function appBinding(request: FastifyRequest) { + const domain = request.config?.domain; + const clientDomainId = request.domainAuthClientDomainId; + if (!domain || !clientDomainId) throw new AppError('UNAUTHORIZED', 401); + return { sourceDomain: domain, clientDomainId }; +} + +function config(request: FastifyRequest) { + if (!request.config) throw new AppError('BAD_REQUEST', 400, 'MISSING_CONFIG'); + return request.config; +} + +/** Backend-only grants for programs a person connected to a product (docs: GET /llm, "Agent connection grants"). */ +export function registerAgentConnectionGrantRoutes(app: FastifyInstance): void { + const preHandler = [configVerifier, requireDomainHashAuth, agentConnectionGrantRateLimiter]; + + app.post('/auth/agent-grants', { preHandler }, async (request, reply) => { + const body = IssueBody.parse(request.body); + if (!request.configJwt) throw new AppError('BAD_REQUEST', 400, 'MISSING_CONFIG'); + const result = await issueAgentConnectionGrant({ + ...appBinding(request), configJwt: request.configJwt, config: config(request), + requestId: body.request_id, connectionId: body.connection_id, product: body.product, + resource: body.resource, subjectToken: body.subject_token, + }, { prisma: request.adminDb }); + reply.header('Cache-Control', 'no-store').header('Pragma', 'no-cache'); + reply.code(result.created ? 201 : 200); + return { grant_handle: result.grantHandle, idle_expires_at: result.idleExpiresAt, + expires_at: result.expiresAt }; + }); + + app.post('/auth/agent-grants/:grantHandle/renew', { preHandler }, async (request, reply) => { + const body = RenewBody.parse(request.body); + const { grantHandle } = GrantParams.parse(request.params); + const result = await renewAgentConnectionGrant({ + grantHandle, ...appBinding(request), config: config(request), requestId: body.request_id, + touch: body.touch, resource: body.resource, scope: body.scope, + }, { prisma: request.adminDb }); + reply.header('Cache-Control', 'no-store').header('Pragma', 'no-cache'); + return { + idle_expires_at: result.idleExpiresAt, expires_at: result.expiresAt, org: result.org, + ...(result.resourceToken ? { access_token: result.resourceToken.accessToken, token_type: 'Bearer', + expires_in: result.resourceToken.expiresIn, resource: result.resourceToken.resource, + scope: result.resourceToken.scope } : {}), + }; + }); + + app.post('/auth/agent-grants/:grantHandle/revoke', { preHandler }, async (request, reply) => { + const body = RevokeBody.parse(request.body); + const { grantHandle } = GrantParams.parse(request.params); + const result = await revokeAgentConnectionGrant({ grantHandle, ...appBinding(request), + requestId: body.request_id }, { prisma: request.adminDb }); + reply.header('Cache-Control', 'no-store').header('Pragma', 'no-cache'); + return result; + }); +} diff --git a/API/src/routes/auth/index.ts b/API/src/routes/auth/index.ts index acd2658a6..4d6138eef 100644 --- a/API/src/routes/auth/index.ts +++ b/API/src/routes/auth/index.ts @@ -27,6 +27,7 @@ import { registerAuthStartRoute } from './auth-start.js'; import { registerAuthTeamInviteLinkRoute } from './team-invite-link.js'; import { registerAuthTokenExchangeRoute } from './token-exchange.js'; import { registerSalesResearchJobGrantRoutes } from './job-grants.js'; +import { registerAgentConnectionGrantRoutes } from './agent-connection-grants.js'; import { registerAuthVerifyCodeRoute } from './auth-verify-code.js'; import { registerAuthVerifyEmailRoute } from './verify-email.js'; import { registerAuthSocialRoute } from './social.js'; @@ -66,6 +67,7 @@ export function registerAuthRoutes(app: FastifyInstance): void { registerAuthRevokeRoute(app); registerAuthTokenExchangeRoute(app); registerSalesResearchJobGrantRoutes(app); + registerAgentConnectionGrantRoutes(app); registerAuthVerifyCodeRoute(app); registerAuthVerifyEmailRoute(app); } diff --git a/API/src/routes/auth/rate-limit-keys.ts b/API/src/routes/auth/rate-limit-keys.ts index 4798e7608..4c8964aca 100644 --- a/API/src/routes/auth/rate-limit-keys.ts +++ b/API/src/routes/auth/rate-limit-keys.ts @@ -166,6 +166,20 @@ export async function confidentialJobGrantRateLimiter(request: FastifyRequest): await confidentialJobGrantDomainLimiter(request); } +const agentConnectionGrantDomainLimiter = createRateLimiter({ + limit: 3000, + windowMs: MINUTE_MS, + keyBuilder: (request) => { + const domain = normalizePart(request.config?.domain); + return domain ? `auth:agent-grant:domain:${hashPart(domain)}` : ''; + }, +}); + +/** Agent connection grants renew on connected programs' calls; backend-only, after config and app auth. */ +export async function agentConnectionGrantRateLimiter(request: FastifyRequest): Promise { + await agentConnectionGrantDomainLimiter(request); +} + function isConfidentialTokenExchange(request: FastifyRequest): boolean { return bodyString(request, 'grant_type') === TOKEN_EXCHANGE_GRANT_TYPE; } diff --git a/API/src/routes/org/organisation-route.shared.ts b/API/src/routes/org/organisation-route.shared.ts index ef9d317f8..5b0a5d05b 100644 --- a/API/src/routes/org/organisation-route.shared.ts +++ b/API/src/routes/org/organisation-route.shared.ts @@ -41,6 +41,9 @@ export const OrgBodySchema = z.object({ // Member-initiated invite policy (design §4.7, Phase 4) — owner/admin only; omitted leaves the // current setting unchanged. Validated against the allowed vocabulary at the service layer. member_invites: z.enum(['allowed', 'admin_approval', 'disabled']).optional(), + // Absolute lifetime of a connected program's agent grant, in days; null clears it (idle expiry + // only); omitted leaves it unchanged. Owner/admin only (organisation.manage). + agent_connection_max_days: z.number().int().min(1).max(3650).nullable().optional(), // Team icon (design §11.3, gap-fix A Task 3) — owner/admin only (same PUT authorization); // omitted leaves the current icon unchanged, `null` clears it. https-only, ≤2048 chars enforced // at the service layer (`normalizeIconUrl`) with a generic error otherwise. diff --git a/API/src/routes/org/organisations.ts b/API/src/routes/org/organisations.ts index 6a70d496f..1d096ece9 100644 --- a/API/src/routes/org/organisations.ts +++ b/API/src/routes/org/organisations.ts @@ -187,7 +187,7 @@ export function registerOrganisationRoutes(app: FastifyInstance) { const config = requireVerifiedConfig(request); const orgId = getOrgIdFromParams(request.params); - const { name, member_invites, icon_url, slug } = OrgBodySchema.parse(request.body ?? {}); + const { name, member_invites, icon_url, slug, agent_connection_max_days } = OrgBodySchema.parse(request.body ?? {}); setTenantContextFromRequest(request, { orgId, userId: tenantUserId(request) }); const org = await request.withTenantTx((tx) => @@ -200,6 +200,7 @@ export function registerOrganisationRoutes(app: FastifyInstance) { config, memberInvites: member_invites, iconUrl: icon_url, + agentConnectionMaxDays: agent_connection_max_days, slug, }, { prisma: asPrismaClient(tx) }, diff --git a/API/src/routes/root/llm-agent-grants.ts b/API/src/routes/root/llm-agent-grants.ts new file mode 100644 index 000000000..aa788a81a --- /dev/null +++ b/API/src/routes/root/llm-agent-grants.ts @@ -0,0 +1,10 @@ +export const llmAgentGrantsMarkdown = `## Agent connection grants + +A product that lets a person connect an outside program (an MCP client such as ChatGPT, Claude or a CLI agent) to their account holds one agent connection grant per connected program and team, instead of pinning the program to the person's session and its absolute sign-in deadline. A UOA superuser enables it per product with a confidential delegation mapping for the product's own API resource that lists the agent.connection scope; that scope can never be requested through /auth/token. + +Issue with POST /auth/agent-grants?config_url=... using the product's domain-hash bearer and a fresh RS256 subject assertion (aud /auth/agent-grants) that carries the person's live assurance_ref for the exact organisation and team. Send request_id (one UUID per connection and team), connection_id, product and resource. A lost-response retry with the same request_id and binding returns the same grant_handle. Persist the handle encrypted; it is useful only with the product's own credentials. + +Renew with POST /auth/agent-grants/:grantHandle/renew and {request_id, touch}. Send touch=true only when the connected program itself presents its credential; at most once an hour this moves the 90-day idle deadline. Reconciliation, revocation intake and background work send touch=false, so an unused connection still lapses. Each renewal returns the person's current org context and rechecks the credential epoch, active user and role, organisation and team membership, unpaid seats, the product mapping, the SSO policy generation and, for SSO grants, the connection, external identity and provisioning. Add resource and scope to receive a 120-second resource token for a mapped downstream resource (ai.invoke, billing.read, memory.read, memory.write); it carries agent_connection, never an assurance id. Organisation owners may set agent_connection_max_days on PUT /org/organisations/:orgId as an absolute ceiling; null leaves idle expiry only. + +A grant is never a session proof: it cannot pass account control, step-up, brokering, token provisioning or another grant's issue. Revoke with POST /auth/agent-grants/:grantHandle/revoke and {request_id}; revocation is idempotent and needs no current membership. +`; diff --git a/API/src/routes/root/llm.ts b/API/src/routes/root/llm.ts index 67b84bc35..b8d12ea31 100644 --- a/API/src/routes/root/llm.ts +++ b/API/src/routes/root/llm.ts @@ -27,6 +27,7 @@ import { llmIntegrationMarkdown2 } from './llm-integration-2.js'; import { llmRostersMarkdown } from './llm-integration-rosters.js'; import { llmIntroMarkdown } from './llm-intro.js'; import { llmJobGrantsMarkdown } from './llm-job-grants.js'; +import { llmAgentGrantsMarkdown } from './llm-agent-grants.js'; import { jobComputeContinuationMarkdown } from './schema.job-compute-continuation.js'; import { publicTeamLookupMarkdown } from './schema.public-team-lookup.js'; import { llmSettingsMarkdown } from './llm-settings.js'; @@ -58,7 +59,7 @@ Backend token responses after new completed independent authorization carry assu Proof-bearing team-switch grants validate the original source and current target policy, then return non-consuming 403 INTERACTION_REQUIRED before rotation. Retain the current session and restart normal target-bound authorization, which creates a separate exact-target family/proof. Never rebind an old holder or extend its original deadline. Deploy genuine fresh proof issuance before a strict consumer; raising the producer minimum floor is a separately reviewed legacy cutover, not a prerequisite for new independent proof issuance. ## DeepTest Nessie executor inference permission Platform superusers set the default-deny User.deeptestNessieInferenceAllowed property in User detail > Security or PATCH /internal/admin/users/:userId/deeptest-nessie-inference with {allowed:boolean}. DeepTest calls POST /apps/v1/deeptest/nessie-inference-access with {product:"deeptest",organisation_id,team_id,user_id}, its own customer_lifecycle X-UOA-App-Key and fresh RS256 X-UOA-Actor. The actor requires exact endpoint audience (no legacy fallback), exact subject/org/team and current nonnegative safe-integer tv. UOA rechecks active identity, memberships and key/service, returning only {allowed:boolean}, private/no-store. Check before every dispatch; errors deny and positive caching is forbidden. This grant does not authorize source access, external material transfer or live testing. -${llmJobGrantsMarkdown}\n## Entity access and deletion (2026-10-03) +${llmJobGrantsMarkdown}\n${llmAgentGrantsMarkdown}\n## Entity access and deletion (2026-10-03) Lifecycle ACTIVE/DISABLED/ARCHIVED/DELETING/DELETED is distinct from membership. Parent disable denies descendant access without changing child state; no superuser bypass. Offline products must introspect or bound JWT expiry to honor revocation. See /api lifecycle and endpoint schemas. Admin templates have scoped plain customer text and revision snapshots; internal notes never reach account-status proof. Access-status diagnostics are disabled by default: the auth-server environment must explicitly set AUTH_ACCESS_STATUS_ENABLED=true to show Check access status and enable all four website/native start/verify endpoints. False or unset returns 404 before configuration/client lookup, mail, challenge or proof work, including previously issued proof redemption. DEBUG_ENABLED, signed product config, URL parameters and browser storage cannot enable it. When enabled, POST /auth/lifecycle-status/start and verify use signed config_url, mailbox code and enrolled TOTP solely to read authorized reasons, never to log in. Native clients use /oauth/lifecycle-status/start and verify with registered client_id and exact redirect_uri; current app revision binds the proof. Shared team archive: POST /org/organisations/:orgId/teams/:teamId/archive with {request_id:UUID,deletion_held:true} requires a fresh exact-team person and live organisation teams.manage capability. It archives across products without erasure or an organisation cascade. GET /domain/team-archives/:id is an initiating-product-only receipt after session revocation. STOPPING_BILLING is pending; ARCHIVED confirms future team billing stopped. Permanent deletion remains held and cannot run. Shared organisation billing and sibling teams remain independent. Platform-admin lifecycle endpoints provide preview, typed confirmation, durable jobs and progress. RETAIN_REFERENCE removes PII/credentials and exposes history as {id,deleted:true,name:"Deleted user"} via authorized /domain/historical-users/:id. ERASE_REFERENCE erases mutable identity references; immutable financial/signing evidence may retain restricted IDs/stubs, explicitly inventoried. Ownership must transfer first for retained organisations. Explicit TEAM deletion preserves even a now-empty organisation and active org owner/admin authority for Create team recovery; shared/dependent accounts and captured financial evidence/holds survive. ORGANISATION deletion is a separate explicit operation. Legacy expanded TEAM jobs return409 DELETION_TEAM_SCOPE_RECONCILIATION_REQUIRED before delivery/execution and require reviewed reconciliation. Active collection/capabilities must close or transfer before confirmation. Old direct organisation/team DELETE routes now return 409 ENTITY_DELETION_WORKFLOW_REQUIRED. Products authenticate their exact registered domain bearer to GET /domain/deletion-jobs?domain=... and POST /domain/deletion-jobs/:id/acknowledge?domain=... with {revision,outcome:"PURGED"|"RETAINED_EVIDENCE"}. Honor effectiveScope/effectiveTargetId, teamIds and committed accountsToDelete; replies acknowledge committed cleanup, never merely receipt. Keep only UOA references and product-owned data. Pending or unknown product inventory blocks completion; this repository does not deploy other product adapters. The pull response is {data:[jobs]}. Retained-evidence acknowledgements may include up to30 {label,count,reason} summaries, without unrelated PII; missing summaries are shown as details unavailable. The credential is rechecked under the product policy lock at acknowledgement. Admin retries finish bounded leased UOA cleanup stages only after all acknowledgements; READY after a retry means more stages remain. diff --git a/API/src/routes/root/schema.auth-agent-grants.ts b/API/src/routes/root/schema.auth-agent-grants.ts new file mode 100644 index 000000000..6d856ada7 --- /dev/null +++ b/API/src/routes/root/schema.auth-agent-grants.ts @@ -0,0 +1,51 @@ +import type { EndpointSchema } from './schema.js'; + +const auth = 'verified config_url and the calling product’s existing domain-hash bearer'; + +export const agentConnectionGrantEndpoints: EndpointSchema[] = [ + { + method: 'POST', path: '/auth/agent-grants', + description: 'Create or recover the grant for one program a person connected to the product, in one organisation team.', + auth, query: { config_url: 'signed app config whose domain matches the authenticated bearer' }, + body: { + request_id: 'UUID the product generates once per (connection, team) before issue; exact retries recover the same grant.', + connection_id: 'The product’s own id for the connected program, 1–160 of [A-Za-z0-9._:-].', + product: 'Product name of an enabled confidential delegation mapping that lists agent.connection.', + resource: 'Exact resource of that mapping (the product’s own API).', + subject_token: 'Fresh source-config RS256 assertion, aud=PUBLIC_BASE_URL+/auth/agent-grants, with active org/team, sub/tv/jti and the person’s live assurance_ref for that exact team.', + subject_token_type: 'urn:ietf:params:oauth:token-type:jwt', + }, + response: { + grant_handle: 'Opaque UUID; useful only with the same authenticated product domain credential and request_id.', + idle_expires_at: 'RFC3339; 90 days after issue, slid only by renewals with touch=true.', + expires_at: 'RFC3339; the earlier of idle_expires_at and the organisation’s agent_connection_max_days ceiling.', + '[status]': '201 first commit; 200 exact response-loss recovery.', + }, + notes: 'Requires a live, unexpired independent or SSO session proof for the exact organisation and team; recovery proofs are refused. The proof’s method, SSO connection revision/generation, external identity, MFA source, AMR and SSO policy generation are copied so renewals can recheck them after the session ends. agent.connection is never mintable through /auth/token.', + }, + { + method: 'POST', path: '/auth/agent-grants/:grantHandle/renew', + description: 'Recheck a connected program’s grant and return the person’s current organisation context, optionally with a short resource token.', + auth, query: { config_url: 'same signed app config and domain credential used to issue the grant' }, + body: { + request_id: 'original grant request UUID', + touch: 'boolean; true only when the connected program itself is presenting its credential. At most once an hour it moves idle_expires_at to now+90 days. Reconciliation, revocation intake and background work send false.', + 'resource?': 'with scope: an exact resource the product’s mapping allows for a downstream token', + 'scope?': 'with resource: space-delimited subset of ai.invoke, billing.read, memory.read, memory.write', + }, + response: { + idle_expires_at: 'RFC3339', expires_at: 'RFC3339, including the organisation ceiling', + org: 'org context for the grant’s organisation: org_id, tenant_slug, org_role, teams, team_roles', + 'access_token?': 'with resource/scope: RS256 resource token, max 120 seconds, carrying agent_connection {grant_handle, connection_id}; never an assurance_id', + }, + notes: 'Every renewal rechecks revocation, idle and organisation expiry, the credential epoch (password reset, 2FA change, logout anywhere end it), the product mapping, active user and source-domain role, active organisation and team membership, unpaid seats, the SSO policy generation, and for SSO grants the connection, external identity and enterprise provisioning. Generic 403 AGENT_GRANT_UNAVAILABLE on any failure. A grant never satisfies a session proof, account control, step-up, session brokering, token provisioning or another grant’s issue.', + }, + { + method: 'POST', path: '/auth/agent-grants/:grantHandle/revoke', + description: 'Revoke one connected program’s grant; repeats are idempotent.', + auth, query: { config_url: 'same signed app config and domain credential used to issue the grant' }, + body: { request_id: 'original grant request UUID' }, + response: { revoked: 'true' }, + notes: 'Serializes with renew and needs no current membership, so a product can always end what it holds.', + }, +]; diff --git a/API/src/routes/root/schema.auth.ts b/API/src/routes/root/schema.auth.ts index 017bcdffe..85724bb64 100644 --- a/API/src/routes/root/schema.auth.ts +++ b/API/src/routes/root/schema.auth.ts @@ -3,6 +3,7 @@ import { actionVerificationEndpoints } from './schema.action-verification.js'; import { authTokenEndpoint } from './schema.auth-token.js'; import { authEmailEndpoints } from './schema.auth-email.js'; import { salesResearchJobGrantEndpoints } from './schema.auth-job-grants.js'; +import { agentConnectionGrantEndpoints } from './schema.auth-agent-grants.js'; export const authEndpoints: EndpointSchema[] = [ { method: 'POST', path: '/auth/account-renewal/start', @@ -15,6 +16,7 @@ export const authEndpoints: EndpointSchema[] = [ body: { challengeId: 'UUID returned by start', code: 'six-digit mailbox code', twoFactorCode: 'six-digit TOTP when enabled' }, response: { 200: '{ ok: true } (non-enumerating)', 401: 'invalid or expired proof' } }, ...salesResearchJobGrantEndpoints, + ...agentConnectionGrantEndpoints, ...actionVerificationEndpoints, { method: 'POST', path: '/auth/session-broker/validate', description: 'Validate a direct Coder-to-Selkie short-lived session:broker capability against current UOA authority.', diff --git a/API/src/routes/root/schema.org.ts b/API/src/routes/root/schema.org.ts index c00263d25..57694f7a4 100644 --- a/API/src/routes/root/schema.org.ts +++ b/API/src/routes/root/schema.org.ts @@ -68,6 +68,8 @@ export const orgEndpoints: EndpointSchema[] = [ name: 'string (optional)', 'member_invites?': 'string — "allowed" (default) | "admin_approval" | "disabled"; same organisation.manage gate, omitted leaves it unchanged; gates the member-initiated invite endpoint', + 'agent_connection_max_days?': + 'integer 1–3650 | null — absolute lifetime of connected programs’ agent grants in days from issue; same organisation.manage gate; applies to existing grants on their next renewal; null clears it (90-day idle expiry only); omitted leaves it unchanged', 'icon_url?': 'string | null — external HTTPS URL only, max 2048 chars; same organisation.manage gate; omitted leaves the current icon unchanged, null clears it; non-https/oversized/invalid rejected with a generic error', }, diff --git a/API/src/services/agent-connection-grant-evidence.service.ts b/API/src/services/agent-connection-grant-evidence.service.ts new file mode 100644 index 000000000..29ae6c5e1 --- /dev/null +++ b/API/src/services/agent-connection-grant-evidence.service.ts @@ -0,0 +1,64 @@ +import type { PrismaClient } from '@prisma/client'; + +import { AppError } from '../utils/errors.js'; +import { assertIndependentSourceStillAdmitted } from './credential-admission.service.js'; +import { assertEnterpriseProvisioningActive } from './enterprise-identity-status.service.js'; + +/** + * The sign-in evidence an agent connection grant was issued from, copied off the live session + * proof at issue. The session itself may end long before the grant does, so renewal rechecks this + * evidence against the live authorities instead of the session row. + */ +export type AgentGrantEvidence = { + subjectId: string; + sourceDomain: string; + orgId: string; + method: string; + connectionRef: string | null; + connectionRevision: number | null; + connectionGeneration: number | null; + externalIdentityId: string | null; + mfaSource: string; + amr: string[]; + policyGeneration: number; +}; + +export type AgentGrantEvidenceDb = Pick; + +function unavailable(): never { + throw new AppError('FORBIDDEN', 403, 'AGENT_GRANT_UNAVAILABLE'); +} + +/** + * The same evidence rules a session proof is held to on every use, minus its session lifetime: + * an SSO policy change, a disabled or re-keyed enterprise connection, a deactivated or + * deprovisioned external identity, or an independent sign-in method the account no longer admits + * ends the grant. + */ +export async function assertAgentGrantEvidence(evidence: AgentGrantEvidence, db: AgentGrantEvidenceDb): Promise { + const policy = await db.orgSsoPolicy.findUnique({ where: { clientDomain_orgId: { + clientDomain: evidence.sourceDomain, orgId: evidence.orgId } } }); + if ((policy?.generation ?? 0) !== evidence.policyGeneration) unavailable(); + if (evidence.method === 'independent') { + await assertIndependentSourceStillAdmitted({ userId: evidence.subjectId, methods: evidence.amr, + personalFactorCompleted: evidence.mfaSource === 'uoa_totp' }, db as never); + return; + } + if (evidence.method !== 'sso' || !evidence.connectionRef || !evidence.externalIdentityId) unavailable(); + const [connection, identity] = await Promise.all([ + db.orgSsoConnection.findUnique({ where: { id: evidence.connectionRef } }), + db.externalIdentity.findUnique({ where: { id: evidence.externalIdentityId } }), + ]); + if (!connection || connection.status !== 'active' || connection.clientDomain !== evidence.sourceDomain + || connection.orgId !== evidence.orgId || connection.revision !== evidence.connectionRevision + || connection.generation !== evidence.connectionGeneration || identity?.status !== 'ACTIVE' + || identity.connectionId !== connection.id || identity.userId !== evidence.subjectId) unavailable(); + await assertEnterpriseProvisioningActive(connection.id, identity.id, evidence.subjectId, db); +} + +/** Whether a grant's evidence satisfies an organisation that requires SSO for this person. */ +export const agentGrantSatisfiesSsoPolicy = (evidence: AgentGrantEvidence, orgId: string): boolean => + evidence.method === 'sso' && evidence.orgId === orgId; diff --git a/API/src/services/agent-connection-grant.service.ts b/API/src/services/agent-connection-grant.service.ts new file mode 100644 index 000000000..1bed6a786 --- /dev/null +++ b/API/src/services/agent-connection-grant.service.ts @@ -0,0 +1,269 @@ +import { createHash } from 'node:crypto'; +import { Prisma, type PrismaClient } from '@prisma/client'; +import { z } from 'zod'; + +import { getPublicBaseUrl } from '../config/env.js'; +import { getAdminPrisma } from '../db/prisma.js'; +import { asPrismaClient } from '../db/tenant-context.js'; +import { AppError } from '../utils/errors.js'; +import { assertAgentGrantEvidence, type AgentGrantEvidence } from './agent-connection-grant-evidence.service.js'; +import { isAuthenticationEpochMismatchError, lockAndAssertAuthenticationEpoch } from './authentication-epoch.service.js'; +import { consumeConfidentialAssertion } from './confidential-assertion-use.service.js'; +import { resolveConfidentialDelegation } from './confidential-delegation.service.js'; +import { verifyConfidentialSubjectToken } from './confidential-token-exchange.service.js'; +import type { PublicRsaJwks } from './client-jwk.service.js'; +import { getActiveClientOrgContext, type OrgContext } from './org-context.service.js'; +import { signConfidentialAccessToken } from './oauth/access-token.service.js'; +import { lockProductTeamPolicyShared, lockTokenIssuanceProductPolicy } from './product-team-policy-lock.service.js'; +import { validateSessionAssurance } from './session-assurance.service.js'; + +/** + * A program a person connected to a product, as one person in one organisation team. + * + * Issued only from that person's live session proof. Afterwards it lives on an idle clock that + * only the program's own use moves (`touch`), optionally under the organisation's maximum + * lifetime, and is rechecked on every renewal against the credential epoch, account, product + * role, organisation and team membership, unpaid seats, the product mapping and the sign-in + * evidence it was issued from. It is never a session proof: it carries no assurance id, cannot + * satisfy account control, step-up, brokering or another grant's issue, and its resource tokens + * carry only the scopes the product's mapping lists. + */ + +export const AGENT_GRANT_AUDIENCE_PATH = '/auth/agent-grants'; +export const AGENT_GRANT_IDLE_MS = 90 * 24 * 60 * 60 * 1000; +export const AGENT_GRANT_TOUCH_INTERVAL_MS = 60 * 60 * 1000; +export const AGENT_GRANT_RESOURCE_TOKEN_TTL_SECONDS = 120; +const DAY_MS = 24 * 60 * 60 * 1000; + +const Uuid = z.string().uuid(); +const ConnectionId = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/u); +const Product = z.string().regex(/^[a-z][a-z0-9-]{0,99}$/u); +const Resource = z.string().url().max(2048); +/** Scopes a renewal may mint for a downstream resource. Never `agent.connection`, brokering or provisioning. */ +const RESOURCE_SCOPES = new Set(['ai.invoke', 'billing.read', 'memory.read', 'memory.write']); + +type Grant = NonNullable>>; +type Config = { org_features?: { enabled?: boolean; groups_enabled?: boolean } }; + +function unavailable(): never { + throw new AppError('FORBIDDEN', 403, 'AGENT_GRANT_UNAVAILABLE'); +} + +function invalidRequest(): never { + throw new AppError('BAD_REQUEST', 400, 'AGENT_GRANT_REQUEST_INVALID'); +} + +function requestConflict(): never { + throw new AppError('BAD_REQUEST', 409, 'AGENT_GRANT_REQUEST_CONFLICT'); +} + +function bindingHash(input: (string | number)[]): string { + return createHash('sha256').update(JSON.stringify(input), 'utf8').digest('hex'); +} + +function isRetryableTransactionConflict(error: unknown): boolean { + const candidate = error as { code?: string; meta?: { code?: string } }; + return ['P2002', 'P2034'].includes(candidate.code ?? '') + || (candidate.code === 'P2010' && candidate.meta?.code === '40001'); +} + +async function serializable(db: PrismaClient, action: (tx: Prisma.TransactionClient) => Promise): Promise { + for (let attempt = 0; attempt < 5; attempt += 1) { + try { + return await db.$transaction(action, { isolationLevel: Prisma.TransactionIsolationLevel.Serializable }); + } catch (error) { + if (!isRetryableTransactionConflict(error)) throw error; + if (attempt === 4) break; + await new Promise((resolve) => setTimeout(resolve, 15 * (attempt + 1))); + } + } + throw new AppError('INTERNAL', 503, 'AGENT_GRANT_RETRY_EXHAUSTED'); +} + +const evidenceOf = (row: Grant): AgentGrantEvidence => ({ + subjectId: row.subjectId, sourceDomain: row.sourceDomain, orgId: row.orgId, method: row.method, + connectionRef: row.connectionRef, connectionRevision: row.connectionRevision, + connectionGeneration: row.connectionGeneration, externalIdentityId: row.externalIdentityId, + mfaSource: row.mfaSource, amr: row.amr, policyGeneration: row.policyGeneration, +}); + +/** The organisation's absolute ceiling, read live so lowering it applies to existing grants. */ +async function maxExpiresAt(tx: Prisma.TransactionClient, orgId: string, createdAt: Date): Promise { + const org = await tx.organisation.findUnique({ where: { id: orgId }, select: { agentConnectionMaxDays: true } }); + return org?.agentConnectionMaxDays ? new Date(createdAt.getTime() + org.agentConnectionMaxDays * DAY_MS) : null; +} + +const effectiveExpiry = (idle: Date, max: Date | null): Date => + max && max.getTime() < idle.getTime() ? max : idle; + +/** Live authority for one person in one team, standing in for a session only where evidence allows. */ +async function currentAuthority(tx: Prisma.TransactionClient, args: { + clientDomainId: string; sourceDomain: string; config: Config; product: string; resource: string; + subjectId: string; orgId: string; teamId: string; tokenVersion: number; + assuranceId?: string; agentGrant?: AgentGrantEvidence; +}): Promise<{ email: string; org: OrgContext }> { + const prisma = asPrismaClient(tx); + try { + await lockAndAssertAuthenticationEpoch({ userId: args.subjectId, domain: args.sourceDomain, + credentialEpoch: args.tokenVersion }, { prisma: tx }); + } catch (error) { + if (isAuthenticationEpochMismatchError(error)) return unavailable(); + throw error; + } + await lockProductTeamPolicyShared(tx); + await lockTokenIssuanceProductPolicy({ clientDomainId: args.clientDomainId, domain: args.sourceDomain }, { prisma }); + await resolveConfidentialDelegation({ authenticatedClientDomainId: args.clientDomainId, + sourceDomain: args.sourceDomain, product: args.product, resource: args.resource, + scope: 'agent.connection', agentConnectionGrant: true }, { prisma }); + if (args.agentGrant) await assertAgentGrantEvidence(args.agentGrant, prisma); + const [user, domainRole, org] = await Promise.all([ + tx.user.findFirst({ where: { id: args.subjectId, lifecycleStatus: 'ACTIVE' }, select: { email: true } }), + tx.domainRole.findUnique({ where: { domain_userId: { domain: args.sourceDomain, userId: args.subjectId } }, + select: { role: true } }), + getActiveClientOrgContext({ userId: args.subjectId, domain: args.sourceDomain, orgId: args.orgId, + groupsEnabled: args.config.org_features?.groups_enabled, assuranceId: args.assuranceId, + agentGrant: args.agentGrant }, { crossProductPrisma: prisma, policyPrisma: prisma, prisma }), + ]); + if (!user?.email || !domainRole || !org || !org.teams.includes(args.teamId)) unavailable(); + return { email: user.email, org }; +} + +export async function issueAgentConnectionGrant( + params: { clientDomainId: string; sourceDomain: string; configJwt: string; config: Config; + requestId: string; connectionId: string; product: string; resource: string; subjectToken: string }, + deps: { prisma?: PrismaClient; now?: () => number; + fetchJwks?: (jwksUrl: string, opts: { expectedHost: string }) => Promise } = {}, +): Promise<{ grantHandle: string; idleExpiresAt: string; expiresAt: string; created: boolean }> { + if (!params.clientDomainId || !Uuid.safeParse(params.requestId).success + || !ConnectionId.safeParse(params.connectionId).success || !Product.safeParse(params.product).success + || !Resource.safeParse(params.resource).success) invalidRequest(); + const nowSeconds = deps.now?.() ?? Math.floor(Date.now() / 1000); + const assertion = await verifyConfidentialSubjectToken({ + subjectToken: params.subjectToken, configJwt: params.configJwt, sourceDomain: params.sourceDomain, + audience: `${getPublicBaseUrl()}${AGENT_GRANT_AUDIENCE_PATH}`, + }, { now: () => nowSeconds, fetchJwks: deps.fetchJwks }); + // A grant starts only from a person's live, proven sign-in in that exact team. + if (!assertion.active || assertion.source_domain !== params.sourceDomain || !assertion.verifiedAssuranceId) { + invalidRequest(); + } + const active = assertion.active; + const assuranceId = assertion.verifiedAssuranceId; + const now = new Date(nowSeconds * 1000); + const binding = bindingHash([params.clientDomainId, params.sourceDomain, params.requestId, params.connectionId, + assertion.sub, active.orgId, active.teamId, assertion.tv, params.product, params.resource]); + const db = deps.prisma ?? getAdminPrisma(); + const outcome = await serializable(db, async (tx) => { + const existing = await tx.agentConnectionGrant.findUnique({ where: { + clientDomainId_requestId: { clientDomainId: params.clientDomainId, requestId: params.requestId } } }); + if (existing && existing.bindingHash !== binding) requestConflict(); + const proof = await validateSessionAssurance({ id: assuranceId, userId: assertion.sub, + credentialEpoch: assertion.tv, clientDomain: params.sourceDomain, orgId: active.orgId, + teamId: active.teamId }, asPrismaClient(tx)); + if (proof.method !== 'independent' && proof.method !== 'sso') unavailable(); + await currentAuthority(tx, { clientDomainId: params.clientDomainId, sourceDomain: params.sourceDomain, + config: params.config, product: params.product, resource: params.resource, subjectId: assertion.sub, + orgId: active.orgId, teamId: active.teamId, tokenVersion: assertion.tv, assuranceId: proof.id }); + if (existing) { + // Lost-response recovery: the same request returns the same handle while it is alive. + const max = await maxExpiresAt(tx, existing.orgId, existing.createdAt); + if (existing.revokedAt || effectiveExpiry(existing.idleExpiresAt, max) <= now) unavailable(); + return { row: existing, max, created: false }; + } + await consumeConfidentialAssertion({ expiresAtEpochSeconds: assertion.exp, jti: assertion.jti, + sourceDomain: params.sourceDomain }, { prisma: asPrismaClient(tx), now: () => now }); + const row = await tx.agentConnectionGrant.create({ data: { + clientDomainId: params.clientDomainId, requestId: params.requestId, connectionId: params.connectionId, + sourceDomain: params.sourceDomain, subjectId: assertion.sub, orgId: active.orgId, teamId: active.teamId, + tokenVersion: assertion.tv, originTokenJti: assertion.jti, product: params.product, + resource: params.resource, bindingHash: binding, sourceAssuranceId: proof.id, method: proof.method, + connectionRef: proof.connectionId, connectionRevision: proof.connectionRevision, + connectionGeneration: proof.connectionGeneration, externalIdentityId: proof.externalIdentityId, + mfaSource: proof.mfaSource, amr: proof.amr, policyGeneration: proof.policyGeneration, + idleExpiresAt: new Date(now.getTime() + AGENT_GRANT_IDLE_MS), lastTouchedAt: now, createdAt: now, + } }); + return { row, max: await maxExpiresAt(tx, row.orgId, row.createdAt), created: true }; + }); + return { grantHandle: outcome.row.id, idleExpiresAt: outcome.row.idleExpiresAt.toISOString(), + expiresAt: effectiveExpiry(outcome.row.idleExpiresAt, outcome.max).toISOString(), created: outcome.created }; +} + +async function lockGrant(tx: Prisma.TransactionClient, handle: string, caller: { + clientDomainId: string; sourceDomain: string; requestId: string; +}): Promise { + await tx.$queryRaw(Prisma.sql`SELECT id FROM agent_connection_grants WHERE id = ${handle} FOR UPDATE`); + const row = await tx.agentConnectionGrant.findUnique({ where: { id: handle } }); + if (!row || row.clientDomainId !== caller.clientDomainId || row.sourceDomain !== caller.sourceDomain + || row.requestId !== caller.requestId) unavailable(); + return row; +} + +export type AgentGrantRenewal = { + idleExpiresAt: string; + expiresAt: string; + org: OrgContext; + resourceToken?: { accessToken: string; expiresIn: number; resource: string; scope: string }; +}; + +export async function renewAgentConnectionGrant( + params: { grantHandle: string; clientDomainId: string; sourceDomain: string; config: Config; + requestId: string; touch: boolean; resource?: string; scope?: string }, + deps: { prisma?: PrismaClient; now?: Date } = {}, +): Promise { + if (!Uuid.safeParse(params.grantHandle).success || !Uuid.safeParse(params.requestId).success + || (params.resource === undefined) !== (params.scope === undefined) + || (params.resource !== undefined && !Resource.safeParse(params.resource).success)) invalidRequest(); + const scopes = params.scope?.trim().split(/\s+/u) ?? []; + if (scopes.some((scope) => !RESOURCE_SCOPES.has(scope))) invalidRequest(); + const db = deps.prisma ?? getAdminPrisma(); + const now = deps.now ?? new Date(); + return serializable(db, async (tx) => { + const row = await lockGrant(tx, params.grantHandle, params); + const max = await maxExpiresAt(tx, row.orgId, row.createdAt); + if (row.revokedAt || effectiveExpiry(row.idleExpiresAt, max) <= now) unavailable(); + const current = await currentAuthority(tx, { clientDomainId: row.clientDomainId, sourceDomain: row.sourceDomain, + config: params.config, product: row.product, resource: row.resource, subjectId: row.subjectId, + orgId: row.orgId, teamId: row.teamId, tokenVersion: row.tokenVersion, agentGrant: evidenceOf(row) }); + let idleExpiresAt = row.idleExpiresAt; + // Only the program's own use keeps the grant alive; reconciliation and background work do not. + if (params.touch && now.getTime() - row.lastTouchedAt.getTime() >= AGENT_GRANT_TOUCH_INTERVAL_MS) { + idleExpiresAt = new Date(now.getTime() + AGENT_GRANT_IDLE_MS); + await tx.agentConnectionGrant.update({ where: { id: row.id }, data: { idleExpiresAt, lastTouchedAt: now } }); + } + const expiresAt = effectiveExpiry(idleExpiresAt, max); + const renewal: AgentGrantRenewal = { idleExpiresAt: idleExpiresAt.toISOString(), + expiresAt: expiresAt.toISOString(), org: current.org }; + if (!params.resource || !params.scope) return renewal; + const delegation = await resolveConfidentialDelegation({ authenticatedClientDomainId: row.clientDomainId, + sourceDomain: row.sourceDomain, product: row.product, resource: params.resource, scope: params.scope }, + { prisma: asPrismaClient(tx) }); + const nowSeconds = Math.floor(now.getTime() / 1000); + const tokenExpiresAt = Math.min(Math.floor(expiresAt.getTime() / 1000), + nowSeconds + AGENT_GRANT_RESOURCE_TOKEN_TTL_SECONDS); + if (tokenExpiresAt <= nowSeconds) unavailable(); + const accessToken = await signConfidentialAccessToken({ + subject: row.subjectId, credentialEpoch: row.tokenVersion, email: current.email, + sourceDomain: row.sourceDomain, product: delegation.product, resource: delegation.resource, + issuer: getPublicBaseUrl(), ttlSeconds: AGENT_GRANT_RESOURCE_TOKEN_TTL_SECONDS, + expiresAtEpochSeconds: tokenExpiresAt, scope: delegation.scope, org: current.org, + active: { orgId: row.orgId, teamId: row.teamId }, + agentConnection: { grant_handle: row.id, connection_id: row.connectionId }, + }); + return { ...renewal, resourceToken: { accessToken, expiresIn: tokenExpiresAt - nowSeconds, + resource: delegation.resource, scope: delegation.scope } }; + }); +} + +/** Idempotent; needs no current membership, so a product can always end what it holds. */ +export async function revokeAgentConnectionGrant( + params: { grantHandle: string; clientDomainId: string; sourceDomain: string; requestId: string }, + deps: { prisma?: PrismaClient; now?: Date } = {}, +): Promise<{ revoked: true }> { + if (!Uuid.safeParse(params.grantHandle).success || !Uuid.safeParse(params.requestId).success) invalidRequest(); + const db = deps.prisma ?? getAdminPrisma(); + const now = deps.now ?? new Date(); + await serializable(db, async (tx) => { + const row = await lockGrant(tx, params.grantHandle, params); + if (!row.revokedAt) await tx.agentConnectionGrant.update({ where: { id: row.id }, data: { revokedAt: now } }); + }); + return { revoked: true }; +} diff --git a/API/src/services/confidential-delegation.service.ts b/API/src/services/confidential-delegation.service.ts index 4ad722365..4bbd36f5c 100644 --- a/API/src/services/confidential-delegation.service.ts +++ b/API/src/services/confidential-delegation.service.ts @@ -30,6 +30,7 @@ export const CONFIDENTIAL_DELEGATION_SCOPES = [ 'memory.read', 'memory.write', 'session:broker', + 'agent.connection', ] as const; export type ConfidentialDelegationScopeName = (typeof CONFIDENTIAL_DELEGATION_SCOPES)[number]; @@ -40,6 +41,7 @@ const databaseScope = { 'memory.read': ConfidentialDelegationScope.MEMORY_READ, 'memory.write': ConfidentialDelegationScope.MEMORY_WRITE, 'session:broker': ConfidentialDelegationScope.SESSION_BROKER, + 'agent.connection': ConfidentialDelegationScope.AGENT_CONNECTION, } satisfies Record; const publicScope = { @@ -49,6 +51,7 @@ const publicScope = { [ConfidentialDelegationScope.MEMORY_READ]: 'memory.read', [ConfidentialDelegationScope.MEMORY_WRITE]: 'memory.write', [ConfidentialDelegationScope.SESSION_BROKER]: 'session:broker', + [ConfidentialDelegationScope.AGENT_CONNECTION]: 'agent.connection', } satisfies Record; type MutationActor = { @@ -396,6 +399,11 @@ export async function resolveConfidentialDelegation( product: string; resource: string; scope: string; + /** + * Only the agent connection grant service sets this. `agent.connection` is a + * product's permission to hold grants, never a scope a token exchange can mint. + */ + agentConnectionGrant?: boolean; }, deps?: { prisma?: PrismaClient }, ): Promise<{ @@ -442,6 +450,11 @@ export async function resolveConfidentialDelegation( product !== 'coder' || params.resource !== 'https://api.selkie.live' || requestedScopes.length !== 1)) { throw invalidDelegation(); } + const asksAgentConnection = requestedScopes.includes('agent.connection'); + if (asksAgentConnection !== Boolean(params.agentConnectionGrant) + || (asksAgentConnection && requestedScopes.length !== 1)) { + throw invalidDelegation(); + } const allowedScopes = new Set(scopeNamesFromDatabase(mapping.scopes)); if (requestedScopes.some((scope) => !allowedScopes.has(scope))) { throw invalidDelegation(); diff --git a/API/src/services/oauth/access-token.service.ts b/API/src/services/oauth/access-token.service.ts index ce99aeb30..795ed3d27 100644 --- a/API/src/services/oauth/access-token.service.ts +++ b/API/src/services/oauth/access-token.service.ts @@ -191,6 +191,8 @@ export type ConfidentialAccessTokenClaims = { purpose: 'research_job'; authorized_until: number; }; + /** A token minted from an agent connection grant, never from a person's session. */ + agentConnection?: { grant_handle: string; connection_id: string }; } & ConfidentialTeamClaims; /** @@ -222,6 +224,7 @@ export async function signConfidentialAccessToken( if (claims.actor) payload.act = claims.actor; if (claims.jobCompute) payload.job_compute = claims.jobCompute; if (claims.jobAuthorization) payload.job_authorization = claims.jobAuthorization; + if (claims.agentConnection) payload.agent_connection = claims.agentConnection; try { const token = new SignJWT(payload) diff --git a/API/src/services/org-context.service.ts b/API/src/services/org-context.service.ts index 83c50ade2..1927bfecc 100644 --- a/API/src/services/org-context.service.ts +++ b/API/src/services/org-context.service.ts @@ -1,3 +1,4 @@ +import type { AgentGrantEvidence } from './agent-connection-grant-evidence.service.js'; import type { PrismaClient } from '@prisma/client'; import { getEnv } from '../config/env.js'; @@ -53,6 +54,8 @@ export async function getActiveUserOrgContext( groupsEnabled?: boolean; /** Server-owned product policy only; callers must never derive this from browser input. */ allowCrossDomain?: boolean; + /** An agent connection grant's rechecked evidence, standing in for a session proof's SSO method only. */ + agentGrant?: AgentGrantEvidence; }, deps?: OrgContextDeps, ): Promise { @@ -87,7 +90,8 @@ export async function getActiveUserOrgContext( if (!orgMembership) return null; - await assertOrgAccessPolicy({ userId, domain, orgId: orgMembership.orgId, assuranceId: params.assuranceId, authenticationEvidenceId: params.authenticationEvidenceId }, prisma); + await assertOrgAccessPolicy({ userId, domain, orgId: orgMembership.orgId, assuranceId: params.assuranceId, + authenticationEvidenceId: params.authenticationEvidenceId, agentGrant: params.agentGrant }, prisma); // The function exposes only this person's unpaid seat scopes to this relying party; the // tenant connection has no read privileges on the underlying financial or credential tables. @@ -179,6 +183,7 @@ export async function getActiveClientOrgContext( domain: string; orgId: string; groupsEnabled?: boolean; + agentGrant?: AgentGrantEvidence; }, deps?: OrgContextDeps, ): Promise { diff --git a/API/src/services/org-sso-policy.service.ts b/API/src/services/org-sso-policy.service.ts index 72319203e..78435e3ed 100644 --- a/API/src/services/org-sso-policy.service.ts +++ b/API/src/services/org-sso-policy.service.ts @@ -1,3 +1,4 @@ +import { agentGrantSatisfiesSsoPolicy, type AgentGrantEvidence } from './agent-connection-grant-evidence.service.js'; import type { PrismaClient } from '@prisma/client'; import { getAdminPrisma } from '../db/prisma.js'; import { AppError } from '../utils/errors.js'; @@ -25,7 +26,9 @@ export async function enterpriseReadiness(clientDomain: string, db = getAdminPri /** The direct lookup invokes this seam too: callers cannot bypass policy via a lower-level helper. */ export async function assertOrgAccessPolicy( - binding: { userId: string; domain: string; orgId: string; assuranceId?: string; authenticationEvidenceId?: string; allowConsumedEvidence?: boolean }, + binding: { userId: string; domain: string; orgId: string; assuranceId?: string; authenticationEvidenceId?: string; allowConsumedEvidence?: boolean; + /** An agent connection grant's evidence, already rechecked by its renewal. Never a session proof. */ + agentGrant?: AgentGrantEvidence }, db: AssuranceDb & Pick = getAdminPrisma(), ): Promise { let evidence: Awaited> | undefined; @@ -54,6 +57,11 @@ export async function assertOrgAccessPolicy( } if (!governed) return; if (evidence?.provenance === 'sso' && evidence.orgId === binding.orgId) return; + if (binding.agentGrant) { + if (binding.agentGrant.subjectId === binding.userId && binding.agentGrant.sourceDomain === binding.domain + && agentGrantSatisfiesSsoPolicy(binding.agentGrant, binding.orgId)) return; + throw new AppError('FORBIDDEN', 403, 'SSO_TEAM_REAUTH_REQUIRED'); + } const proof = binding.assuranceId ? await db.sessionAssurance.findUnique({ where: { id: binding.assuranceId } }) : currentSessionAssurance(); if (!proof || proof.userId !== binding.userId || proof.clientDomain !== binding.domain || proof.orgId !== binding.orgId || proof.method !== 'sso') { diff --git a/API/src/services/organisation.resolve.ts b/API/src/services/organisation.resolve.ts index 0b06bcaf1..0a65cf7a9 100644 --- a/API/src/services/organisation.resolve.ts +++ b/API/src/services/organisation.resolve.ts @@ -9,6 +9,7 @@ const ORGANISATION_SELECT = { slug: true, ownerId: true, memberInvites: true, + agentConnectionMaxDays: true, iconUrl: true, createdAt: true, updatedAt: true, @@ -21,6 +22,7 @@ export type ResolvedOrganisationRow = { slug: string; ownerId: string; memberInvites?: string; + agentConnectionMaxDays?: number | null; iconUrl?: string | null; createdAt: Date; updatedAt: Date; diff --git a/API/src/services/organisation.service.base.ts b/API/src/services/organisation.service.base.ts index fbb455884..a451001e7 100644 --- a/API/src/services/organisation.service.base.ts +++ b/API/src/services/organisation.service.base.ts @@ -103,6 +103,7 @@ export type OrganisationRecord = { slug: string; ownerId: string | null; memberInvites: OrgMemberInvitesValue; + agentConnectionMaxDays: number | null; iconUrl: string | null; createdAt: Date; updatedAt: Date; @@ -255,6 +256,7 @@ export function toOrganisationRecord(row: { slug: string; ownerId: string | null; memberInvites?: string; + agentConnectionMaxDays?: number | null; iconUrl?: string | null; createdAt: Date; updatedAt: Date; @@ -266,6 +268,7 @@ export function toOrganisationRecord(row: { slug: row.slug, ownerId: row.ownerId, memberInvites: (row.memberInvites ?? 'allowed') as OrgMemberInvitesValue, + agentConnectionMaxDays: row.agentConnectionMaxDays ?? null, iconUrl: row.iconUrl ?? null, createdAt: row.createdAt, updatedAt: row.updatedAt, diff --git a/API/src/services/organisation.service.organisation.ts b/API/src/services/organisation.service.organisation.ts index 4f1ea0590..55e75d5e5 100644 --- a/API/src/services/organisation.service.organisation.ts +++ b/API/src/services/organisation.service.organisation.ts @@ -44,6 +44,7 @@ const ORGANISATION_SELECT = { slug: true, ownerId: true, memberInvites: true, + agentConnectionMaxDays: true, iconUrl: true, createdAt: true, updatedAt: true, @@ -325,6 +326,8 @@ export async function updateOrganisation( config: ClientConfig; memberInvites?: string; iconUrl?: string | null; + /** Absolute agent connection grant lifetime in days; null clears it, omitted leaves it. */ + agentConnectionMaxDays?: number | null; /** Deliberate re-slug. Omitted leaves the tenant's address untouched. */ slug?: string; }, @@ -376,6 +379,8 @@ export async function updateOrganisation( // Team icon (design §11.3, gap-fix A Task 3) — omitted leaves the current icon // unchanged; `null` clears it; validated https-only/≤2048 chars by normalizeIconUrl. ...(params.iconUrl !== undefined ? { iconUrl: normalizeIconUrl(params.iconUrl) } : {}), + ...(params.agentConnectionMaxDays !== undefined + ? { agentConnectionMaxDays: normalizeAgentConnectionMaxDays(params.agentConnectionMaxDays) } : {}), }, select: ORGANISATION_SELECT, })); @@ -392,12 +397,20 @@ export async function updateOrganisation( slug: updated.slug, ...(params.memberInvites !== undefined ? { memberInvites: updated.memberInvites } : {}), ...(params.iconUrl !== undefined ? { iconUrlSet: updated.iconUrl !== null } : {}), + ...(params.agentConnectionMaxDays !== undefined + ? { agentConnectionMaxDays: updated.agentConnectionMaxDays } : {}), }, }); return toOrganisationRecord(updated); } +function normalizeAgentConnectionMaxDays(value: number | null): number | null { + if (value === null) return null; + if (!Number.isInteger(value) || value < 1 || value > 3650) throw new AppError('BAD_REQUEST', 400); + return value; +} + export async function deleteOrganisation( params: { orgId: string; diff --git a/API/tests/integration/agent-connection-grant.test.ts b/API/tests/integration/agent-connection-grant.test.ts new file mode 100644 index 000000000..bc638a86d --- /dev/null +++ b/API/tests/integration/agent-connection-grant.test.ts @@ -0,0 +1,195 @@ +import { createHash, randomBytes, randomUUID } from 'node:crypto'; + +import { ConfidentialDelegationScope, Prisma, type PrismaClient } from '@prisma/client'; +import { createLocalJWKSet, exportJWK, generateKeyPair, jwtVerify, SignJWT, type JWK, type KeyLike } from 'jose'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +import { createTestDb } from '../helpers/test-db.js'; +import { getAccessTokenPublicJwks, resetAccessTokenKeyCache } from '../../src/services/oauth/access-token.service.js'; +import { + AGENT_GRANT_AUDIENCE_PATH, + AGENT_GRANT_IDLE_MS, + issueAgentConnectionGrant, + renewAgentConnectionGrant, + revokeAgentConnectionGrant, +} from '../../src/services/agent-connection-grant.service.js'; +import { resolveConfidentialDelegation } from '../../src/services/confidential-delegation.service.js'; + +const enabled = Boolean(process.env.DATABASE_URL); +const sourceDomain = 'app.nessie.test'; +const subjectId = 'agent-grant-subject'; +const orgId = 'agent-grant-org'; +const teamId = 'agent-grant-team'; +const product = 'nessie'; +const resource = 'https://api.nessie.test/mcp'; +const ledger = 'https://ledger.unlikeotherai.com'; +const baseUrl = 'https://authentication.unlikeotherai.com'; +const config = { org_features: { enabled: true, groups_enabled: false } }; +const DAY_MS = 24 * 60 * 60 * 1000; +const originalEnv = { + DATABASE_URL: process.env.DATABASE_URL, + PUBLIC_BASE_URL: process.env.PUBLIC_BASE_URL, + MCP_OAUTH_ACCESS_TOKEN_PRIVATE_JWK: process.env.MCP_OAUTH_ACCESS_TOKEN_PRIVATE_JWK, +}; + +describe.skipIf(!enabled)('agent connection grants', () => { + let db: PrismaClient; + let cleanup: () => Promise; + let sourcePrivateKey: KeyLike; + let sourcePublicJwk: JWK; + let clientDomainId: string; + let nowSeconds: number; + let assuranceRef: string; + + beforeAll(async () => { + const sourcePair = await generateKeyPair('RS256', { extractable: true }); + sourcePrivateKey = sourcePair.privateKey; + sourcePublicJwk = await exportJWK(sourcePair.publicKey); + Object.assign(sourcePublicJwk, { kid: 'agent-grant-source', alg: 'RS256', use: 'sig' }); + const resourcePair = await generateKeyPair('RS256', { extractable: true }); + const resourcePrivateJwk = await exportJWK(resourcePair.privateKey); + Object.assign(resourcePrivateJwk, { kid: 'agent-grant-resource', alg: 'RS256', use: 'sig' }); + + const handle = await createTestDb(); + if (!handle) throw new Error('DATABASE_URL is required'); + db = handle.prisma; + cleanup = handle.cleanup; + process.env.DATABASE_URL = handle.databaseUrl; + process.env.PUBLIC_BASE_URL = baseUrl; + process.env.MCP_OAUTH_ACCESS_TOKEN_PRIVATE_JWK = JSON.stringify(resourcePrivateJwk); + resetAccessTokenKeyCache(); + nowSeconds = Math.floor(Date.now() / 1000); + + await db.$transaction(async (tx) => { + await tx.$executeRawUnsafe('SET LOCAL session_replication_role = replica'); + await tx.$executeRaw(Prisma.sql`INSERT INTO users (id, email, user_key, name) VALUES + (${subjectId}, 'agent-grant@example.com', 'agent-grant@example.com', 'Grant test'), + ('agent-grant-owner', 'agent-owner@example.com', 'agent-owner@example.com', 'Owner')`); + await tx.$executeRaw(Prisma.sql`INSERT INTO organisations (id, domain, name, slug, owner_id, updated_at) + VALUES (${orgId}, ${sourceDomain}, 'Grant test', 'agent-grant', 'agent-grant-owner', CURRENT_TIMESTAMP)`); + await tx.$executeRaw(Prisma.sql`INSERT INTO teams (id, org_id, name, slug, updated_at) VALUES + (${teamId}, ${orgId}, 'Grant test', 'agent-grant', CURRENT_TIMESTAMP)`); + await tx.$executeRaw(Prisma.sql`INSERT INTO org_members (id, org_id, user_id, domain, role, updated_at) VALUES + ('agent-grant-org-member', ${orgId}, ${subjectId}, ${sourceDomain}, 'member', CURRENT_TIMESTAMP), + ('agent-grant-owner-member', ${orgId}, 'agent-grant-owner', ${sourceDomain}, 'owner', CURRENT_TIMESTAMP)`); + await tx.$executeRaw(Prisma.sql`INSERT INTO team_members (id, team_id, user_id, team_role, updated_at) VALUES + ('agent-grant-team-member', ${teamId}, ${subjectId}, 'member', CURRENT_TIMESTAMP)`); + await tx.domainRole.create({ data: { domain: sourceDomain, userId: subjectId, role: 'USER' } }); + }); + const clientDomain = await db.clientDomain.create({ data: { domain: sourceDomain, label: 'Nessie', + status: 'active' } }); + clientDomainId = clientDomain.id; + await db.confidentialDelegationMapping.createMany({ data: [ + { clientDomainId, product, resource, scopes: [ConfidentialDelegationScope.AGENT_CONNECTION] }, + { clientDomainId, product, resource: ledger, scopes: [ConfidentialDelegationScope.AI_INVOKE] }, + ] }); + // The approving person's live, remembered sign-in: a refresh family and its original proof. + const familyId = `agent-grant-family-${randomUUID()}`; + const expiresAt = new Date(Date.now() + 30 * DAY_MS); + await db.refreshToken.create({ data: { tokenHash: randomBytes(32).toString('hex'), familyId, + userId: subjectId, domain: sourceDomain, clientId: sourceDomain, configUrl: `https://${sourceDomain}/config`, + orgId, teamId, expiresAt } }); + assuranceRef = randomBytes(32).toString('base64url'); + await db.sessionAssurance.create({ data: { + referenceHash: createHash('sha256').update(assuranceRef).digest('hex'), userId: subjectId, + credentialEpoch: 0, clientDomain: sourceDomain, orgId, teamId, familyId, method: 'independent', + observedAt: new Date(), mfaSource: 'none', amr: ['password'], expiresAt, + } }); + }); + + afterAll(async () => { + for (const [key, value] of Object.entries(originalEnv)) { + if (value === undefined) Reflect.deleteProperty(process.env, key); + else process.env[key] = value; + } + resetAccessTokenKeyCache(); + if (cleanup) await cleanup(); + }); + + const fakeConfigJwt = () => `e30.${Buffer.from(JSON.stringify({ domain: sourceDomain, + jwks_url: `https://${sourceDomain}/.well-known/jwks.json` })).toString('base64url')}.not-checked`; + + const subjectToken = (withProof = true) => new SignJWT({ source_domain: sourceDomain, tv: 0, + active: { orgId, teamId }, ...(withProof ? { assurance_ref: assuranceRef } : {}) }) + .setProtectedHeader({ alg: 'RS256', kid: 'agent-grant-source', typ: 'JWT' }) + .setIssuer(sourceDomain).setAudience(`${baseUrl}${AGENT_GRANT_AUDIENCE_PATH}`).setSubject(subjectId) + .setIssuedAt(nowSeconds).setExpirationTime(nowSeconds + 45).setJti(randomUUID()).sign(sourcePrivateKey); + + const issue = async (requestId: string, overrides: { withProof?: boolean; connectionId?: string } = {}) => + issueAgentConnectionGrant({ clientDomainId, sourceDomain, configJwt: fakeConfigJwt(), config, requestId, + connectionId: overrides.connectionId ?? 'conn-1', product, resource, + subjectToken: await subjectToken(overrides.withProof ?? true) }, + { prisma: db, now: () => nowSeconds, fetchJwks: async () => ({ keys: [sourcePublicJwk] }) }); + + const renew = (grantHandle: string, requestId: string, at: number, extra: { touch?: boolean; + resource?: string; scope?: string } = {}) => renewAgentConnectionGrant({ grantHandle, clientDomainId, + sourceDomain, config, requestId, touch: extra.touch ?? true, resource: extra.resource, scope: extra.scope }, + { prisma: db, now: new Date(at) }); + + it('issues only from a live sign-in proof and recovers the same grant on retry', async () => { + await expect(issue(randomUUID(), { withProof: false })).rejects.toThrow('AGENT_GRANT_REQUEST_INVALID'); + const requestId = randomUUID(); + const first = await issue(requestId); + expect(first.created).toBe(true); + expect(new Date(first.idleExpiresAt).getTime()).toBe(nowSeconds * 1000 + AGENT_GRANT_IDLE_MS); + expect(await issue(requestId)).toEqual({ ...first, created: false }); + await expect(issue(requestId, { connectionId: 'conn-other' })).rejects.toThrow('AGENT_GRANT_REQUEST_CONFLICT'); + }); + + it('outlives the session, slides only on touch, and lapses after 90 unused days', async () => { + const requestId = randomUUID(); + const grant = await issue(requestId); + // The sign-in family ends: the grant does not depend on it after issue. + await db.refreshToken.updateMany({ where: { userId: subjectId }, data: { revokedAt: new Date() } }); + const issuedAt = nowSeconds * 1000; + const quiet = await renew(grant.grantHandle, requestId, issuedAt + 60 * DAY_MS, { touch: false }); + expect(quiet.idleExpiresAt).toBe(grant.idleExpiresAt); + expect(quiet.org.teams).toContain(teamId); + const used = await renew(grant.grantHandle, requestId, issuedAt + 80 * DAY_MS); + expect(new Date(used.idleExpiresAt).getTime()).toBe(issuedAt + 80 * DAY_MS + AGENT_GRANT_IDLE_MS); + await expect(renew(grant.grantHandle, requestId, issuedAt + 171 * DAY_MS)) + .rejects.toThrow('AGENT_GRANT_UNAVAILABLE'); + await db.refreshToken.updateMany({ where: { userId: subjectId }, data: { revokedAt: null } }); + }); + + it('honours the organisation ceiling and ends on epoch, team loss or revoke', async () => { + const requestId = randomUUID(); + const grant = await issue(requestId); + const issuedAt = nowSeconds * 1000; + await db.organisation.update({ where: { id: orgId }, data: { agentConnectionMaxDays: 10 } }); + await expect(renew(grant.grantHandle, requestId, issuedAt + 11 * DAY_MS)).rejects.toThrow('AGENT_GRANT_UNAVAILABLE'); + expect((await renew(grant.grantHandle, requestId, issuedAt + DAY_MS)).expiresAt) + .toBe(new Date(issuedAt + 10 * DAY_MS).toISOString()); + await db.organisation.update({ where: { id: orgId }, data: { agentConnectionMaxDays: null } }); + + await db.teamMember.update({ where: { id: 'agent-grant-team-member' }, data: { status: 'REMOVED' } }); + await expect(renew(grant.grantHandle, requestId, issuedAt)).rejects.toThrow('AGENT_GRANT_UNAVAILABLE'); + await db.teamMember.update({ where: { id: 'agent-grant-team-member' }, data: { status: 'ACTIVE' } }); + + await db.user.update({ where: { id: subjectId }, data: { tokenVersion: 1 } }); + await expect(renew(grant.grantHandle, requestId, issuedAt)).rejects.toThrow('AGENT_GRANT_UNAVAILABLE'); + await db.user.update({ where: { id: subjectId }, data: { tokenVersion: 0 } }); + + expect(await revokeAgentConnectionGrant({ grantHandle: grant.grantHandle, clientDomainId, sourceDomain, + requestId }, { prisma: db })).toEqual({ revoked: true }); + await expect(renew(grant.grantHandle, requestId, issuedAt)).rejects.toThrow('AGENT_GRANT_UNAVAILABLE'); + }); + + it('mints only mapped downstream scopes and never agent.connection itself', async () => { + const requestId = randomUUID(); + const grant = await issue(requestId); + const at = nowSeconds * 1000; + const renewed = await renew(grant.grantHandle, requestId, at, { resource: ledger, scope: 'ai.invoke' }); + const { payload } = await jwtVerify(renewed.resourceToken!.accessToken, + createLocalJWKSet(await getAccessTokenPublicJwks()), { issuer: baseUrl, audience: ledger }); + expect(payload).toMatchObject({ sub: subjectId, scope: 'ai.invoke', active: { orgId, teamId }, + agent_connection: { grant_handle: grant.grantHandle, connection_id: 'conn-1' } }); + expect(payload).not.toHaveProperty('assurance_id'); + await expect(renew(grant.grantHandle, requestId, at, { resource, scope: 'agent.connection' })) + .rejects.toThrow('AGENT_GRANT_REQUEST_INVALID'); + await expect(renew(grant.grantHandle, requestId, at, { resource: ledger, scope: 'token.provision' })) + .rejects.toThrow('AGENT_GRANT_REQUEST_INVALID'); + await expect(resolveConfidentialDelegation({ authenticatedClientDomainId: clientDomainId, sourceDomain, + product, resource, scope: 'agent.connection' }, { prisma: db })).rejects.toThrow(); + }); +}); diff --git a/API/tests/unit/auth-rate-limit-global.test.ts b/API/tests/unit/auth-rate-limit-global.test.ts index c36f6820d..044ca3055 100644 --- a/API/tests/unit/auth-rate-limit-global.test.ts +++ b/API/tests/unit/auth-rate-limit-global.test.ts @@ -85,6 +85,7 @@ async function globalKeys(): Promise> { tokenExchangePreAuthRateLimiter: { globalKey: 'auth:token-exchange:global' }, confidentialTokenExchangeDomainRateLimiter: { globalKey: null }, confidentialJobGrantRateLimiter: { globalKey: null }, + agentConnectionGrantRateLimiter: { globalKey: null }, twoFactorVerifyRateLimiter: { globalKey: 'auth:twofa-verify:global' }, twoFactorSetupRateLimiter: { globalKey: 'auth:twofa-setup:global' }, twoFactorEnrollRateLimiter: { globalKey: 'auth:twofa-enroll:global' }, @@ -196,7 +197,9 @@ describe('auth limiters global ceiling', () => { ? 'email:send' : name === 'confidentialJobGrantRateLimiter' ? 'auth:job-grant' - : `auth:${name === 'revokeRateLimiter' ? 'revoke' : 'token-exchange:confidential'}`; + : name === 'agentConnectionGrantRateLimiter' + ? 'auth:agent-grant' + : `auth:${name === 'revokeRateLimiter' ? 'revoke' : 'token-exchange:confidential'}`; const probe = createRateLimiter({ keyBuilder: () => `${prefix}:global`, limit: 1, diff --git a/Admin/src/features/admin/ConfidentialDelegationFormDialog.tsx b/Admin/src/features/admin/ConfidentialDelegationFormDialog.tsx index 386abd8da..9b1589cb2 100644 --- a/Admin/src/features/admin/ConfidentialDelegationFormDialog.tsx +++ b/Admin/src/features/admin/ConfidentialDelegationFormDialog.tsx @@ -56,6 +56,12 @@ const scopeOptions: Array<{ description: 'Allows Coder (coder.unlikeotherai.com, product coder) to broker Selkie sessions at exactly https://api.selkie.live. Select only this scope.', }, + { + value: 'agent.connection', + label: 'Agent connections', + description: + 'Allows the product to hold idle-expiring grants for programs a person connects to it, at its own API resource above. Never mintable as a token.', + }, ]; const emptyValues: ConfidentialDelegationFormValues = { diff --git a/Admin/src/schemas/confidential-delegation.ts b/Admin/src/schemas/confidential-delegation.ts index a627f7418..96ee88253 100644 --- a/Admin/src/schemas/confidential-delegation.ts +++ b/Admin/src/schemas/confidential-delegation.ts @@ -7,6 +7,7 @@ export const ConfidentialDelegationScopeSchema = z.enum([ 'memory.read', 'memory.write', 'session:broker', + 'agent.connection', ]); export const ConfidentialDelegationScopesSchema = z From 14686bd740570664f475d2b01faaea346bf76b90 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 22 Nov 2026 22:17:54 +0000 Subject: [PATCH 2/2] Turn agent connection grants on for Nessie from the start Nessie at api.nessie.works holds agent connection grants for https://api.nessie.works/mcp without an operator mapping, as a first-party product. Other products still need an enabled agent.connection mapping. Co-Authored-By: Claude Opus 5.5 --- API/src/routes/root/llm-agent-grants.ts | 2 +- .../routes/root/schema.auth-agent-grants.ts | 4 ++-- .../agent-connection-grant.service.ts | 22 ++++++++++++++++--- .../agent-connection-grant.test.ts | 13 +++++++++++ 4 files changed, 35 insertions(+), 6 deletions(-) diff --git a/API/src/routes/root/llm-agent-grants.ts b/API/src/routes/root/llm-agent-grants.ts index aa788a81a..4bc8bd5e3 100644 --- a/API/src/routes/root/llm-agent-grants.ts +++ b/API/src/routes/root/llm-agent-grants.ts @@ -1,6 +1,6 @@ export const llmAgentGrantsMarkdown = `## Agent connection grants -A product that lets a person connect an outside program (an MCP client such as ChatGPT, Claude or a CLI agent) to their account holds one agent connection grant per connected program and team, instead of pinning the program to the person's session and its absolute sign-in deadline. A UOA superuser enables it per product with a confidential delegation mapping for the product's own API resource that lists the agent.connection scope; that scope can never be requested through /auth/token. +A product that lets a person connect an outside program (an MCP client such as ChatGPT, Claude or a CLI agent) to their account holds one agent connection grant per connected program and team, instead of pinning the program to the person's session and its absolute sign-in deadline. Nessie (source domain api.nessie.works, product nessie, resource https://api.nessie.works/mcp) has it on from the start as a first-party product. Any other product needs a UOA superuser to add a confidential delegation mapping for its own API resource that lists the agent.connection scope; that scope can never be requested through /auth/token. Issue with POST /auth/agent-grants?config_url=... using the product's domain-hash bearer and a fresh RS256 subject assertion (aud /auth/agent-grants) that carries the person's live assurance_ref for the exact organisation and team. Send request_id (one UUID per connection and team), connection_id, product and resource. A lost-response retry with the same request_id and binding returns the same grant_handle. Persist the handle encrypted; it is useful only with the product's own credentials. diff --git a/API/src/routes/root/schema.auth-agent-grants.ts b/API/src/routes/root/schema.auth-agent-grants.ts index 6d856ada7..f1bec7a40 100644 --- a/API/src/routes/root/schema.auth-agent-grants.ts +++ b/API/src/routes/root/schema.auth-agent-grants.ts @@ -10,8 +10,8 @@ export const agentConnectionGrantEndpoints: EndpointSchema[] = [ body: { request_id: 'UUID the product generates once per (connection, team) before issue; exact retries recover the same grant.', connection_id: 'The product’s own id for the connected program, 1–160 of [A-Za-z0-9._:-].', - product: 'Product name of an enabled confidential delegation mapping that lists agent.connection.', - resource: 'Exact resource of that mapping (the product’s own API).', + product: 'nessie (first-party, on by default at api.nessie.works), or the product of an enabled confidential delegation mapping that lists agent.connection.', + resource: 'https://api.nessie.works/mcp for Nessie, or the exact resource of that mapping (the product’s own API).', subject_token: 'Fresh source-config RS256 assertion, aud=PUBLIC_BASE_URL+/auth/agent-grants, with active org/team, sub/tv/jti and the person’s live assurance_ref for that exact team.', subject_token_type: 'urn:ietf:params:oauth:token-type:jwt', }, diff --git a/API/src/services/agent-connection-grant.service.ts b/API/src/services/agent-connection-grant.service.ts index 1bed6a786..b1766dafd 100644 --- a/API/src/services/agent-connection-grant.service.ts +++ b/API/src/services/agent-connection-grant.service.ts @@ -35,6 +35,20 @@ export const AGENT_GRANT_TOUCH_INTERVAL_MS = 60 * 60 * 1000; export const AGENT_GRANT_RESOURCE_TOKEN_TTL_SECONDS = 120; const DAY_MS = 24 * 60 * 60 * 1000; +/** + * First-party products that hold agent connection grants without an operator mapping: on from the + * start, at exactly this source domain and resource. Any other product needs an enabled + * `agent.connection` mapping. + */ +export const FIRST_PARTY_AGENT_CONNECTIONS: Readonly> = { + nessie: { sourceDomain: 'api.nessie.works', resource: 'https://api.nessie.works/mcp' }, +}; + +const isFirstPartyAgentConnection = (product: string, sourceDomain: string, resource: string): boolean => { + const binding = FIRST_PARTY_AGENT_CONNECTIONS[product]; + return Boolean(binding && binding.sourceDomain === sourceDomain && binding.resource === resource); +}; + const Uuid = z.string().uuid(); const ConnectionId = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/u); const Product = z.string().regex(/^[a-z][a-z0-9-]{0,99}$/u); @@ -112,9 +126,11 @@ async function currentAuthority(tx: Prisma.TransactionClient, args: { } await lockProductTeamPolicyShared(tx); await lockTokenIssuanceProductPolicy({ clientDomainId: args.clientDomainId, domain: args.sourceDomain }, { prisma }); - await resolveConfidentialDelegation({ authenticatedClientDomainId: args.clientDomainId, - sourceDomain: args.sourceDomain, product: args.product, resource: args.resource, - scope: 'agent.connection', agentConnectionGrant: true }, { prisma }); + if (!isFirstPartyAgentConnection(args.product, args.sourceDomain, args.resource)) { + await resolveConfidentialDelegation({ authenticatedClientDomainId: args.clientDomainId, + sourceDomain: args.sourceDomain, product: args.product, resource: args.resource, + scope: 'agent.connection', agentConnectionGrant: true }, { prisma }); + } if (args.agentGrant) await assertAgentGrantEvidence(args.agentGrant, prisma); const [user, domainRole, org] = await Promise.all([ tx.user.findFirst({ where: { id: args.subjectId, lifecycleStatus: 'ACTIVE' }, select: { email: true } }), diff --git a/API/tests/integration/agent-connection-grant.test.ts b/API/tests/integration/agent-connection-grant.test.ts index bc638a86d..28cd1bd59 100644 --- a/API/tests/integration/agent-connection-grant.test.ts +++ b/API/tests/integration/agent-connection-grant.test.ts @@ -9,6 +9,7 @@ import { getAccessTokenPublicJwks, resetAccessTokenKeyCache } from '../../src/se import { AGENT_GRANT_AUDIENCE_PATH, AGENT_GRANT_IDLE_MS, + FIRST_PARTY_AGENT_CONNECTIONS, issueAgentConnectionGrant, renewAgentConnectionGrant, revokeAgentConnectionGrant, @@ -192,4 +193,16 @@ describe.skipIf(!enabled)('agent connection grants', () => { await expect(resolveConfidentialDelegation({ authenticatedClientDomainId: clientDomainId, sourceDomain, product, resource, scope: 'agent.connection' }, { prisma: db })).rejects.toThrow(); }); + + it('needs an enabled mapping for a product that is not first-party', async () => { + expect(FIRST_PARTY_AGENT_CONNECTIONS.nessie).toEqual({ sourceDomain: 'api.nessie.works', + resource: 'https://api.nessie.works/mcp' }); + const requestId = randomUUID(); + const grant = await issue(requestId); + const where = { clientDomainId_product_resource: { clientDomainId, product, resource } }; + await db.confidentialDelegationMapping.update({ where, data: { enabled: false } }); + await expect(renew(grant.grantHandle, requestId, nowSeconds * 1000)).rejects.toThrow(); + await db.confidentialDelegationMapping.update({ where, data: { enabled: true } }); + expect((await renew(grant.grantHandle, requestId, nowSeconds * 1000)).org.teams).toContain(teamId); + }); });