Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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);
45 changes: 45 additions & 0 deletions API/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -1001,6 +1002,7 @@ model ClientDomain {
agreementSignatures AgreementSignature[]
delegationMappings ConfidentialDelegationMapping[]
salesResearchJobGrants SalesResearchJobGrant[]
agentConnectionGrants AgentConnectionGrant[]

@@index([status])
@@map("client_domains")
Expand Down Expand Up @@ -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")

Expand Down Expand Up @@ -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 {
Expand Down
86 changes: 86 additions & 0 deletions API/src/routes/auth/agent-connection-grants.ts
Original file line number Diff line number Diff line change
@@ -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;
});
}
2 changes: 2 additions & 0 deletions API/src/routes/auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -66,6 +67,7 @@ export function registerAuthRoutes(app: FastifyInstance): void {
registerAuthRevokeRoute(app);
registerAuthTokenExchangeRoute(app);
registerSalesResearchJobGrantRoutes(app);
registerAgentConnectionGrantRoutes(app);
registerAuthVerifyCodeRoute(app);
registerAuthVerifyEmailRoute(app);
}
Expand Down
14 changes: 14 additions & 0 deletions API/src/routes/auth/rate-limit-keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
await agentConnectionGrantDomainLimiter(request);
}

function isConfidentialTokenExchange(request: FastifyRequest): boolean {
return bodyString(request, 'grant_type') === TOKEN_EXCHANGE_GRANT_TYPE;
}
Expand Down
3 changes: 3 additions & 0 deletions API/src/routes/org/organisation-route.shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion API/src/routes/org/organisations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) =>
Expand All @@ -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) },
Expand Down
10 changes: 10 additions & 0 deletions API/src/routes/root/llm-agent-grants.ts
Original file line number Diff line number Diff line change
@@ -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. 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 <PUBLIC_BASE_URL>/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.
`;
Loading
Loading