diff --git a/cloudflare/packages/worker/README.md b/cloudflare/packages/worker/README.md index 4639dbfe4..7e5f2a653 100644 --- a/cloudflare/packages/worker/README.md +++ b/cloudflare/packages/worker/README.md @@ -135,6 +135,25 @@ curl -sS -X DELETE https://subrouter.cmux.dev/tenant/accounts/$ACCOUNT_ID \ OAuth uploads schedule the existing Durable Object alarm refresh path. Rotated refresh tokens are persisted in the tenant DO. +## Local Egress Credential Leases + +`POST /tenant/leases` selects a team account, refreshes it centrally when +needed, and returns an access-only five-minute lease. The response never +contains a provider refresh token or ID token. The caller sends the provider +request from its own machine, then reports the result to +`POST /tenant/leases/:id/events`. + +`POST /tenant/accounts?adopt=1` and the matching repair route force one central +OAuth refresh before acknowledging the credential. This rotates refresh +custody away from the source laptop without making a model or usage request +from Cloudflare. + +Refreshes are single-flight per account. A response that proves the refresh +chain invalid, or leaves rotation ambiguous after a transport or parse failure, +freezes the account until `POST /tenant/accounts/:id/repair` replaces it. +Blocked accounts are removed from routing, so another healthy team credential +can serve the lease. + ## Admin Tenant Data Tenant-scoped admin reads require an explicit `?tenant=`: diff --git a/cloudflare/packages/worker/src/contract.ts b/cloudflare/packages/worker/src/contract.ts index c541c86a7..41fbbf731 100644 --- a/cloudflare/packages/worker/src/contract.ts +++ b/cloudflare/packages/worker/src/contract.ts @@ -14,6 +14,7 @@ export interface AccountCredentials { readonly tokenEndpoint?: string readonly clientId?: string readonly lastRefreshAt?: number + readonly credentialGeneration?: number readonly refreshFailure?: OAuthRefreshFailure readonly usageUrl?: string readonly [key: string]: unknown @@ -581,7 +582,7 @@ export const refreshOAuthCredentials = async ( if (!force && !credentialNeedsRefresh(credentials, now)) { return { credentials, refreshed: false } } - if (credentials.refreshFailure && terminalRefreshFailure(credentials.refreshFailure)) { + if (credentials.refreshFailure && blockingRefreshFailure(credentials.refreshFailure)) { throw new Error(credentials.refreshFailure.message) } if (providerForAccount(kind) === "claude") { @@ -625,6 +626,7 @@ const refreshCodexCredentials = async ( idToken: payload.id_token, ...(expiresAt !== undefined ? { expiresAt } : {}), lastRefreshAt: now, + credentialGeneration: (credentials.credentialGeneration ?? 0) + 1, }, refreshed: true, } @@ -669,6 +671,7 @@ const refreshClaudeCredentials = async ( : {}), ...(expiresAt !== undefined ? { expiresAt } : {}), lastRefreshAt: now, + credentialGeneration: (credentials.credentialGeneration ?? 0) + 1, }, refreshed: true, } @@ -680,12 +683,17 @@ const parseRefreshJSON = (body: string): Record & { id_token?: string expires_in?: number } => { - const payload = JSON.parse(body) as Record - return payload + try { + return JSON.parse(body) as Record + } catch { + // JSON parser errors may quote the provider body. Never let an echoed + // credential become part of the persisted refresh-failure record. + throw new Error("OAuth refresh response was not valid JSON") + } } const refreshError = (status: number, body: string): Error => { - let message = body.trim() + let message = "provider rejected the refresh" let providerCode: string | undefined let providerType: string | undefined try { @@ -693,20 +701,44 @@ const refreshError = (status: number, body: string): Error => { error?: { message?: string; code?: string; type?: string } | string } if (typeof payload.error === "string") { - message = payload.error + providerCode = sanitizedTerminalRefreshCode(payload.error) + message = providerCode ?? message } else if (payload.error) { - message = payload.error.message ?? message providerCode = payload.error.code providerType = payload.error.type + providerCode = + sanitizedTerminalRefreshCode( + providerCode, + providerType, + payload.error.message, + ) ?? providerCode + message = providerCode ?? providerType ?? message } } catch { - // Keep the raw provider body in the error message. + // Provider response bodies can contain echoed credentials. Status is enough + // to diagnose this failure without persisting an untrusted body. } const error = new Error(`OAuth refresh failed (${status}): ${message}`) Object.assign(error, { status, providerCode, providerType }) return error } +const sanitizedTerminalRefreshCode = ( + ...values: ReadonlyArray +): string | undefined => { + const combined = values.filter(Boolean).join(" ").toLowerCase() + if (combined.includes("invalid_grant") || combined.includes("invalid grant")) { + return "invalid_grant" + } + if ( + combined.includes("refresh_token") || + combined.includes("refresh token") + ) { + return "invalid_refresh_token" + } + return undefined +} + export const refreshFailureFromError = ( error: unknown, now = Date.now() @@ -724,8 +756,23 @@ export const refreshFailureFromError = ( export const terminalRefreshFailure = (failure: OAuthRefreshFailure): boolean => { if (failure.status !== 400 && failure.status !== 401) return false const combined = `${failure.providerCode ?? ""} ${failure.message}`.toLowerCase() - return combined.includes("refresh_token") || combined.includes("refresh token") -} + return ( + combined.includes("invalid_grant") || + combined.includes("invalid grant") || + combined.includes("refresh_token") || + combined.includes("refresh token") + ) +} + +// A transport failure or malformed success response is ambiguous: the provider +// may have rotated the refresh token before the response was lost. Retrying that +// old token can invalidate the only recoverable credential chain, so central +// refresh stops and asks for repair instead of guessing. +export const uncertainRefreshFailure = (failure: OAuthRefreshFailure): boolean => + failure.status === 0 + +export const blockingRefreshFailure = (failure: OAuthRefreshFailure): boolean => + terminalRefreshFailure(failure) || uncertainRefreshFailure(failure) export const jwtExpiryMillis = (token: string | undefined): number | null => { if (!token) return null diff --git a/cloudflare/packages/worker/src/index.ts b/cloudflare/packages/worker/src/index.ts index 8aaaf8183..9c6e690a9 100644 --- a/cloudflare/packages/worker/src/index.ts +++ b/cloudflare/packages/worker/src/index.ts @@ -7,6 +7,8 @@ import { } from "@subrouter/core" import { authModeForAccount, + blockingRefreshFailure, + credentialExpiresAt, credentialNeedsRefresh, fetchProviderUsage, isOAuthKind, @@ -21,7 +23,6 @@ import { setUpstreamAuthHeaders, stripSubrouterHeaders, stickySessionId, - terminalRefreshFailure, upstreamURLForRequest, usageStatus, type AccountCredentials, @@ -66,6 +67,7 @@ interface RouteInput { readonly preferAccountId?: string readonly model?: string readonly quotaKey?: string + readonly requiredAuthMode?: "oauth" | "apikey" } interface UsageInput { @@ -74,6 +76,69 @@ interface UsageInput { readonly accountId: string } +interface CredentialLeaseInput extends RouteInput { + readonly upstreamProvider: UpstreamProvider +} + +interface CredentialLeaseOutput { + readonly leaseId: string + readonly accountId: string + readonly provider: UpstreamProvider + readonly authMode: "oauth" | "apikey" + readonly token: string + readonly providerAccountId?: string + readonly label: string + readonly email?: string + readonly credentialGeneration: number + readonly issuedAt: string + readonly expiresAt: string + readonly credentialExpiresAt?: string +} + +type CredentialLeaseOutcome = + | "success" + | "unauthorized" + | "forbidden" + | "rate_limited" + | "provider_error" + +interface CredentialLeaseEventInput { + readonly orgId?: string + readonly leaseId: string + readonly outcome: CredentialLeaseOutcome + readonly statusCode?: number + readonly scope?: "account" | "quota" + readonly retryAt?: number +} + +interface CredentialLeaseRow { + readonly [key: string]: SqlStorageValue + readonly id: string + readonly org_id: string + readonly account_id: string + readonly agent_type: string + readonly session_id: string + readonly quota_key: string + readonly provider: string + readonly credential_generation: number + readonly issued_at: number + readonly expires_at: number + readonly last_outcome: string | null + readonly last_status_code: number | null + readonly reported_at: number | null +} + +interface CredentialQuotaCooldownRow { + readonly [key: string]: SqlStorageValue + readonly org_id: string + readonly account_id: string + readonly quota_key: string + readonly started_at: number + readonly until_at: number + readonly last_status_code: number | null + readonly consecutive_errors: number +} + interface TotpConfig { readonly seed: string readonly digits?: number @@ -95,6 +160,7 @@ interface UpsertAccountInput { interface TenantAccountUploadInput { readonly validate: boolean + readonly adopt: boolean readonly account: UpsertAccountInput } @@ -112,6 +178,12 @@ interface TenantAccountOutput { type UpstreamProvider = "claude" | "codex" type WaitUntil = (promise: Promise) => void +const credentialLeaseTTLms = 5 * 60 * 1000 +const quotaCooldownBaseMs = 60 * 1000 +const quotaCooldownMaxMs = 15 * 60 * 1000 +const quotaCooldownAbsoluteMaxMs = 8 * 24 * 60 * 60 * 1000 +const credentialLeaseRetentionMs = 24 * 60 * 60 * 1000 + interface AccountHealthOutput { readonly ok: boolean readonly lastQuotaErrorAt?: string @@ -146,6 +218,7 @@ interface StoredAccount extends Account { readonly lastQuotaErrorAt?: number readonly lastQuotaErrorCode?: string readonly consecutiveQuotaErrors?: number + readonly credentialBlocked?: boolean } interface RouteOutput { @@ -411,6 +484,109 @@ const parseUsageInput = async (request: Request): Promise return input } +const parseCredentialLeaseInput = async ( + request: Request, + orgId: string +): Promise => { + const record = await parseJsonRecord(request) + if (record instanceof Response) return record + + const upstreamProvider = nonEmptyString(record["provider"]) + if (upstreamProvider !== "codex" && upstreamProvider !== "claude") { + return json({ error: "provider must be codex or claude" }, { status: 400 }) + } + const sessionId = nonEmptyString(record["sessionId"]) + if (!sessionId || sessionId.length > 512) { + return json({ error: "sessionId is required" }, { status: 400 }) + } + const agentType = + normalizeAgentType(nonEmptyString(record["agentType"])) || + upstreamProvider + const userEmail = nonEmptyString(record["userEmail"]) + const preferAccountId = nonEmptyString(record["preferAccountId"]) + const model = nonEmptyString(record["model"]) + const requiredAuthModeValue = nonEmptyString(record["requiredAuthMode"]) + if ( + requiredAuthModeValue && + requiredAuthModeValue !== "oauth" && + requiredAuthModeValue !== "apikey" + ) { + return json( + { error: "requiredAuthMode must be oauth or apikey" }, + { status: 400 }, + ) + } + const requiredAuthMode = + requiredAuthModeValue === "oauth" || requiredAuthModeValue === "apikey" + ? requiredAuthModeValue + : undefined + + return { + orgId, + upstreamProvider, + agentType, + sessionId, + ...(userEmail ? { userEmail } : {}), + ...(preferAccountId ? { preferAccountId } : {}), + ...(model ? { model } : {}), + ...(requiredAuthMode ? { requiredAuthMode } : {}), + } +} + +const parseCredentialLeaseEventInput = async ( + request: Request, + orgId: string, + leaseId: string +): Promise => { + const record = await parseJsonRecord(request) + if (record instanceof Response) return record + const outcome = nonEmptyString(record["outcome"]) + if ( + outcome !== "success" && + outcome !== "unauthorized" && + outcome !== "forbidden" && + outcome !== "rate_limited" && + outcome !== "provider_error" + ) { + return json({ error: "invalid lease outcome" }, { status: 400 }) + } + const rawStatus = record["statusCode"] + if ( + rawStatus !== undefined && + (typeof rawStatus !== "number" || + !Number.isInteger(rawStatus) || + rawStatus < 100 || + rawStatus > 599) + ) { + return json({ error: "invalid statusCode" }, { status: 400 }) + } + const rawScope = nonEmptyString(record["scope"]) + if ( + rawScope !== null && + rawScope !== "account" && + rawScope !== "quota" + ) { + return json({ error: "invalid cooldown scope" }, { status: 400 }) + } + const rawRetryAt = record["retryAt"] + if ( + rawRetryAt !== undefined && + (typeof rawRetryAt !== "number" || + !Number.isSafeInteger(rawRetryAt) || + rawRetryAt < 0) + ) { + return json({ error: "invalid retryAt" }, { status: 400 }) + } + return { + orgId, + leaseId, + outcome, + ...(rawStatus !== undefined ? { statusCode: rawStatus } : {}), + ...(rawScope !== null ? { scope: rawScope } : {}), + ...(rawRetryAt !== undefined ? { retryAt: rawRetryAt } : {}), + } +} + const parseUpsertAccountInput = async ( request: Request ): Promise => { @@ -471,7 +647,8 @@ const parseTenantAccountUploadInput = async ( try { const input = accountInputForTenantUpload(provider, label, tenantId, record) const validate = new URL(request.url).searchParams.get("validate") === "1" - return { validate, account: input } + const adopt = new URL(request.url).searchParams.get("adopt") === "1" + return { validate, adopt, account: input } } catch (error) { return json({ error: String((error as Error).message ?? error) }, { status: 400 }) } @@ -616,6 +793,12 @@ const safeTenantAccount = ( } const accountHealth = (account: StoredAccount): AccountHealthOutput => { + if (account.credentialBlocked) { + return { + ok: false, + message: "Credential requires repair before it can be leased.", + } + } if (!account.lastQuotaErrorAt) return { ok: true } return { ok: false, @@ -845,8 +1028,71 @@ const rowToAccount = (row: AccountRow): StoredAccount => ({ ...(row.consecutive_quota_errors !== null ? { consecutiveQuotaErrors: row.consecutive_quota_errors } : {}), + ...(!row.enabled || accountRowRefreshBlocked(row) + ? { credentialBlocked: true } + : {}), }) +const accountRowRefreshBlocked = (row: AccountRow): boolean => { + if (!isOAuthKind(row.kind as AccountKind)) return false + if (!row.credentials_json) return false + try { + const credentials = JSON.parse( + row.credentials_json + ) as AccountCredentials + return Boolean( + credentials.refreshFailure && + blockingRefreshFailure(credentials.refreshFailure) + ) + } catch { + return true + } +} + +const accountRowQuotaCoolingDown = ( + row: AccountRow, + now: number, +): boolean => { + if (row.last_quota_error_at === null) return false + const failures = Math.max(1, row.consecutive_quota_errors ?? 1) + const multiplier = 2 ** Math.min(failures - 1, 8) + const cooldown = Math.min( + quotaCooldownMaxMs, + quotaCooldownBaseMs * multiplier, + ) + return now < row.last_quota_error_at + cooldown +} + +const accountRowCanIssueCredentialLease = ( + row: AccountRow, + now: number, + allowQuotaCooldown = false, +): boolean => { + if ( + accountRowRefreshBlocked(row) || + (!allowQuotaCooldown && accountRowQuotaCoolingDown(row, now)) + ) { + return false + } + if (!isOAuthKind(row.kind as AccountKind) || !row.credentials_json) { + return true + } + try { + const credentials = JSON.parse( + row.credentials_json, + ) as AccountCredentials + const expiresAt = credentialExpiresAt(credentials) + return !( + credentials.accessToken && + !credentials.refreshToken && + expiresAt !== null && + expiresAt < now + credentialLeaseTTLms + ) + } catch { + return false + } +} + const quotaRowsToRecord = ( rows: ReadonlyArray ): AccountModelQuotas => { @@ -1473,6 +1719,35 @@ export class SubrouterDurableObject extends DurableObject { ON transcript_events(org_id, agent_type, session_id, event_id); CREATE INDEX IF NOT EXISTS transcript_events_org_time_idx ON transcript_events(org_id, timestamp); + CREATE TABLE IF NOT EXISTS credential_leases( + id TEXT PRIMARY KEY, + org_id TEXT NOT NULL, + account_id TEXT NOT NULL, + agent_type TEXT NOT NULL, + session_id TEXT NOT NULL, + quota_key TEXT NOT NULL, + provider TEXT NOT NULL, + credential_generation INTEGER NOT NULL, + issued_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + last_outcome TEXT, + last_status_code INTEGER, + reported_at INTEGER + ); + CREATE INDEX IF NOT EXISTS credential_leases_org_expiry_idx + ON credential_leases(org_id, expires_at); + CREATE TABLE IF NOT EXISTS credential_quota_cooldowns( + org_id TEXT NOT NULL, + account_id TEXT NOT NULL, + quota_key TEXT NOT NULL, + started_at INTEGER NOT NULL, + until_at INTEGER NOT NULL, + last_status_code INTEGER, + consecutive_errors INTEGER NOT NULL DEFAULT 1, + PRIMARY KEY (org_id, account_id, quota_key) + ); + CREATE INDEX IF NOT EXISTS credential_quota_cooldowns_expiry_idx + ON credential_quota_cooldowns(org_id, until_at); CREATE TABLE IF NOT EXISTS lifecycle( id INTEGER PRIMARY KEY CHECK (id = 1), draining INTEGER NOT NULL DEFAULT 0, @@ -1484,11 +1759,13 @@ export class SubrouterDurableObject extends DurableObject { this.ensureAccountHealthColumns() this.ctx.blockConcurrencyWhile(async () => { + this.pruneCredentialLeases(Date.now()) await this.scheduleNextRefreshAlarm() }) } override async alarm(): Promise { + this.pruneCredentialLeases(Date.now()) await this.refreshOAuthAccounts(false) await this.scheduleNextRefreshAlarm() } @@ -1592,6 +1869,15 @@ export class SubrouterDurableObject extends DurableObject { } async route(input: RouteInput): Promise { + return this.routeWithOptions(input) + } + + private async routeWithOptions( + input: RouteInput, + options: { + readonly allowPreferredQuotaCooldown?: boolean + } = {}, + ): Promise { const orgId = this.resolveOrgId(input.orgId) const agentType = this.resolveAgentType(input.agentType) const sessionId = stickySessionId( @@ -1600,6 +1886,7 @@ export class SubrouterDurableObject extends DurableObject { ) const quotaKey = this.resolveQuotaKey(input) const upstreamProvider = this.resolveUpstreamProvider(input) + const requiredAuthMode = input.requiredAuthMode const routedAt = Date.now() const sql = this.ctx.storage.sql @@ -1614,7 +1901,15 @@ export class SubrouterDurableObject extends DurableObject { ) .toArray()[0] const stickyAccount = sticky - ? this.getEligibleAccount(sql, orgId, sticky.account_id, quotaKey, true, upstreamProvider) + ? this.getEligibleAccount( + sql, + orgId, + sticky.account_id, + quotaKey, + true, + upstreamProvider, + requiredAuthMode, + ) : null if (stickyAccount) { this.recordRouteMetadata(sql, routedAt, stickyAccount.id, sessionId) @@ -1626,7 +1921,16 @@ export class SubrouterDurableObject extends DurableObject { } const preferredAccount = input.preferAccountId - ? this.getEligibleAccount(sql, orgId, input.preferAccountId, quotaKey, true, upstreamProvider) + ? this.getEligibleAccount( + sql, + orgId, + input.preferAccountId, + quotaKey, + true, + upstreamProvider, + requiredAuthMode, + options.allowPreferredQuotaCooldown === true, + ) : null if (preferredAccount) { this.rememberSticky(sql, orgId, agentType, quotaKey, sessionId, preferredAccount.id, input.userEmail) @@ -1639,7 +1943,13 @@ export class SubrouterDurableObject extends DurableObject { } } - const eligible = this.listEligibleAccounts(sql, orgId, quotaKey, upstreamProvider) + const eligible = this.listEligibleAccounts( + sql, + orgId, + quotaKey, + upstreamProvider, + requiredAuthMode, + ) if (eligible.length === 0) { const providerLabel = upstreamProvider ? `${upstreamProvider} ` : "" throw new Error(`no eligible ${providerLabel}${quotaKey} subrouter account for org ${orgId}`) @@ -1657,7 +1967,12 @@ export class SubrouterDurableObject extends DurableObject { async routeForProxy( input: RouteInput ): Promise { - const routed = await this.route(input) + // An explicitly selected legacy-proxy account may make a recovery probe + // while cooling down. Sticky and pooled routing still avoid it, and + // credential leases never bypass the cooldown. + const routed = await this.routeWithOptions(input, { + allowPreferredQuotaCooldown: Boolean(input.preferAccountId), + }) const row = await this.refreshAccountIfExpired( routed.account.orgId, routed.account.id, @@ -1676,6 +1991,291 @@ export class SubrouterDurableObject extends DurableObject { } } + async issueCredentialLease( + input: CredentialLeaseInput + ): Promise { + const routed = await this.route(input) + const now = Date.now() + let row = this.getAccountRow( + this.ctx.storage.sql, + routed.account.orgId, + routed.account.id, + true + ) + if (!row) throw new Error("selected account disappeared") + + let credentials = row.credentials_json + ? (JSON.parse(row.credentials_json) as AccountCredentials) + : undefined + const kind = row.kind as AccountKind + const currentCredentialExpiry = credentialExpiresAt(credentials) + if ( + isOAuthKind(kind) && + (!currentCredentialExpiry || + currentCredentialExpiry < now + credentialLeaseTTLms) + ) { + try { + row = await this.refreshAccountIfExpired( + routed.account.orgId, + routed.account.id, + true + ) + } catch (error) { + const failed = this.getAccountRow( + this.ctx.storage.sql, + routed.account.orgId, + routed.account.id, + true + ) + if (failed && accountRowRefreshBlocked(failed)) { + // A terminal or ambiguous refresh failure removes this account from + // eligibility. Route the same request again so another healthy team + // credential can carry it without exposing the broken chain. + const { + preferAccountId: _failedPreferredAccount, + ...retryInput + } = input + return this.issueCredentialLease(retryInput) + } + throw error + } + if (!row) throw new Error("selected account disappeared") + credentials = row.credentials_json + ? (JSON.parse(row.credentials_json) as AccountCredentials) + : undefined + } + + const token = isOAuthKind(kind) + ? credentials?.accessToken + : credentials?.apiKey + if (!token) { + throw new Error("selected account has no usable credential") + } + + const credentialExpiry = credentialExpiresAt(credentials) + if ( + isOAuthKind(kind) && + credentialExpiry !== null && + credentialExpiry < now + credentialLeaseTTLms + ) { + throw new Error("selected account credential expires before the lease") + } + + const leaseId = crypto.randomUUID() + const expiresAt = now + credentialLeaseTTLms + const generation = credentials?.credentialGeneration ?? 0 + this.pruneCredentialLeases(now) + this.ctx.storage.sql.exec( + `INSERT INTO credential_leases( + id, + org_id, + account_id, + agent_type, + session_id, + quota_key, + provider, + credential_generation, + issued_at, + expires_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + leaseId, + routed.account.orgId, + routed.account.id, + this.resolveAgentType(input.agentType), + stickySessionId( + this.resolveAgentType(input.agentType), + this.requireNonEmpty(input.sessionId, "sessionId") + ), + routed.quotaKey, + input.upstreamProvider, + generation, + now, + expiresAt + ) + await this.scheduleNextRefreshAlarm() + + const safe = safeGoAccount({ + ...this.accountFromRow(row), + ...(credentials ? { credentials } : {}), + }) + return { + leaseId, + accountId: row.id, + provider: input.upstreamProvider, + authMode: authModeForAccount(kind), + token, + ...(credentials?.accountId + ? { providerAccountId: credentials.accountId } + : {}), + label: row.label, + ...(safe.email ? { email: safe.email } : {}), + credentialGeneration: generation, + issuedAt: new Date(now).toISOString(), + expiresAt: new Date(expiresAt).toISOString(), + ...(credentialExpiry !== null + ? { credentialExpiresAt: new Date(credentialExpiry).toISOString() } + : {}), + } + } + + async recordCredentialLeaseEvent( + input: CredentialLeaseEventInput + ): Promise<{ ok: true; refreshState?: "refreshed" }> { + const orgId = this.resolveOrgId(input.orgId) + const leaseId = this.requireNonEmpty(input.leaseId, "leaseId") + const lease = this.ctx.storage.sql + .exec( + `SELECT * FROM credential_leases WHERE id = ? AND org_id = ?`, + leaseId, + orgId + ) + .toArray()[0] + if (!lease) throw new Error("credential lease not found") + + const now = Date.now() + this.ctx.storage.sql.exec( + `UPDATE credential_leases + SET last_outcome = ?, last_status_code = ?, reported_at = ? + WHERE id = ? AND org_id = ?`, + input.outcome, + input.statusCode ?? null, + now, + leaseId, + orgId + ) + + const mutatesAccountState = + input.outcome === "success" || + input.outcome === "forbidden" || + input.outcome === "rate_limited" || + input.outcome === "unauthorized" + const current = mutatesAccountState + ? this.getAccountRow( + this.ctx.storage.sql, + orgId, + lease.account_id, + true + ) + : undefined + const currentCredentials = current?.credentials_json + ? (JSON.parse(current.credentials_json) as AccountCredentials) + : undefined + if ( + mutatesAccountState && + (currentCredentials?.credentialGeneration ?? 0) !== + lease.credential_generation + ) { + return { ok: true } + } + + if (input.outcome === "success") { + await this.clearAccountQuotaError({ + orgId, + accountId: lease.account_id, + successfulLeaseIssuedAt: lease.issued_at, + }) + this.clearCredentialQuotaCooldown( + orgId, + lease.account_id, + lease.quota_key, + lease.issued_at, + ) + return { ok: true } + } + if (input.outcome === "rate_limited") { + this.recordCredentialQuotaCooldown({ + orgId, + accountId: lease.account_id, + quotaKey: input.scope === "quota" ? lease.quota_key : "*", + statusCode: input.statusCode ?? 429, + retryAt: input.retryAt, + now, + }) + this.ctx.storage.sql.exec( + `DELETE FROM session_assignments + WHERE org_id = ? AND agent_type = ? AND quota_key = ? + AND session_id = ? AND account_id = ?`, + orgId, + lease.agent_type, + lease.quota_key, + lease.session_id, + lease.account_id + ) + return { ok: true } + } + if (input.outcome === "forbidden") { + if (input.statusCode !== 403) { + return { ok: true } + } + this.recordCredentialQuotaCooldown({ + orgId, + accountId: lease.account_id, + quotaKey: input.scope === "account" ? "*" : lease.quota_key, + statusCode: input.statusCode, + now, + }) + this.ctx.storage.sql.exec( + `DELETE FROM session_assignments + WHERE org_id = ? AND agent_type = ? AND quota_key = ? + AND session_id = ? AND account_id = ?`, + orgId, + lease.agent_type, + lease.quota_key, + lease.session_id, + lease.account_id, + ) + return { ok: true } + } + if (input.outcome === "unauthorized") { + if (input.statusCode !== 401) { + return { ok: true } + } + if (current && !isOAuthKind(current.kind as AccountKind)) { + // API keys cannot be refreshed. Remove a rejected key from routing + // until a team manager repairs it in place. + this.ctx.storage.sql.exec( + `UPDATE accounts SET enabled = 0, updated_at = ? + WHERE id = ? AND org_id = ?`, + now, + lease.account_id, + orgId + ) + this.ctx.storage.sql.exec( + `DELETE FROM session_assignments + WHERE org_id = ? AND account_id = ?`, + orgId, + lease.account_id + ) + return { ok: true } + } + if (current && !currentCredentials?.refreshToken) { + // Legacy access-only OAuth rows can serve until their access token is + // rejected. At that point central refresh is impossible, so freeze the + // row instead of leasing the same known-bad token forever. + this.updateAccountCredentials(orgId, lease.account_id, { + ...currentCredentials, + refreshFailure: { + at: now, + status: 401, + message: + "provider rejected the access token and the central refresh token is missing", + providerCode: "missing_refresh_token", + }, + }) + this.ctx.storage.sql.exec( + `DELETE FROM session_assignments + WHERE org_id = ? AND account_id = ?`, + orgId, + lease.account_id + ) + return { ok: true } + } + await this.refreshAccountIfExpired(orgId, lease.account_id, true) + return { ok: true, refreshState: "refreshed" } + } + return { ok: true } + } + async recordUsage(input: UsageInput): Promise<{ ok: true }> { const orgId = this.resolveOrgId(input.orgId) const sessionId = this.requireNonEmpty(input.sessionId, "sessionId") @@ -1801,6 +2401,70 @@ export class SubrouterDurableObject extends DurableObject { return { account } } + async adoptAccountCredentials(input: { + readonly orgId?: string + readonly accountId: string + }): Promise<{ account: StoredAccount }> { + const orgId = this.resolveOrgId(input.orgId) + const accountId = this.requireNonEmpty(input.accountId, "accountId") + const row = this.getAccountRow( + this.ctx.storage.sql, + orgId, + accountId, + false + ) + if (!row) throw new Error("account not found") + if (isOAuthKind(row.kind as AccountKind)) { + const before = row.credentials_json + ? (JSON.parse(row.credentials_json) as AccountCredentials) + : undefined + const expectedGeneration = before?.credentialGeneration ?? 0 + let refreshed = await this.refreshAccountIfExpired( + orgId, + accountId, + true, + false, + ) + let after = refreshed?.credentials_json + ? (JSON.parse(refreshed.credentials_json) as AccountCredentials) + : undefined + // A refresh started before repair may have owned the single-flight slot. + // Once it settles, refresh the current replacement chain exactly once. + if ((after?.credentialGeneration ?? 0) === expectedGeneration) { + refreshed = await this.refreshAccountIfExpired( + orgId, + accountId, + true, + false, + ) + after = refreshed?.credentials_json + ? (JSON.parse(refreshed.credentials_json) as AccountCredentials) + : undefined + } + if ( + (after?.credentialGeneration ?? 0) !== expectedGeneration + 1 + ) { + throw new Error("credential changed during central adoption") + } + } + this.ctx.storage.sql.exec( + `UPDATE accounts SET enabled = 1, updated_at = ? + WHERE id = ? AND org_id = ?`, + Date.now(), + accountId, + orgId, + ) + const account = this.getAccount( + this.ctx.storage.sql, + orgId, + accountId, + false + ) + if (!account) throw new Error("account disappeared during adoption") + await this.scheduleNextRefreshAlarm() + return { account } + } + async listAccounts(orgId: string): Promise<{ accounts: ReadonlyArray }> { return { accounts: this.ctx.storage.sql @@ -1839,10 +2503,81 @@ export class SubrouterDurableObject extends DurableObject { orgId, accountId ) + sql.exec( + "DELETE FROM credential_leases WHERE org_id = ? AND account_id = ?", + orgId, + accountId + ) + sql.exec( + "DELETE FROM credential_quota_cooldowns WHERE org_id = ? AND account_id = ?", + orgId, + accountId + ) await this.scheduleNextRefreshAlarm() return { ok: true } } + async repairAccount(input: { + readonly orgId?: string + readonly accountId: string + readonly replacement: UpsertAccountInput + }): Promise<{ account: StoredAccount }> { + const orgId = this.resolveOrgId(input.orgId) + const accountId = this.requireNonEmpty(input.accountId, "accountId") + const existing = this.getAccountRow( + this.ctx.storage.sql, + orgId, + accountId, + false + ) + if (!existing) throw new Error("account not found") + if (existing.kind !== input.replacement.kind) { + throw new Error("replacement provider does not match account") + } + const existingCredentials = existing.credentials_json + ? (JSON.parse(existing.credentials_json) as AccountCredentials) + : undefined + const replacementCredentials = input.replacement.credentials + ? { + ...input.replacement.credentials, + credentialGeneration: + (existingCredentials?.credentialGeneration ?? 0) + 1, + refreshFailure: undefined, + } + : undefined + const repaired = await this.upsertAccount({ + ...input.replacement, + id: accountId, + orgId, + label: input.replacement.label || existing.label, + rateLimitRemaining: undefined, + ...(replacementCredentials + ? { credentials: replacementCredentials } + : {}), + }) + this.ctx.storage.sql.exec( + `DELETE FROM session_assignments + WHERE org_id = ? AND account_id = ?`, + orgId, + accountId + ) + // Reports from an access token issued before repair must not refresh or + // penalize the replacement credential chain. + this.ctx.storage.sql.exec( + `DELETE FROM credential_leases + WHERE org_id = ? AND account_id = ?`, + orgId, + accountId + ) + this.ctx.storage.sql.exec( + `DELETE FROM credential_quota_cooldowns + WHERE org_id = ? AND account_id = ?`, + orgId, + accountId + ) + return repaired + } + async accountStatuses(orgId: string, forceRefresh: boolean): Promise> { const rows = this.ctx.storage.sql .exec( @@ -1984,13 +2719,108 @@ export class SubrouterDurableObject extends DurableObject { return { ok: true } } + private recordCredentialQuotaCooldown(input: { + readonly orgId: string + readonly accountId: string + readonly quotaKey: string + readonly statusCode: number + readonly retryAt?: number + readonly now: number + }): void { + const current = this.ctx.storage.sql + .exec( + `SELECT * FROM credential_quota_cooldowns + WHERE org_id = ? AND account_id = ? AND quota_key = ?`, + input.orgId, + input.accountId, + input.quotaKey, + ) + .toArray()[0] + const previousFailures = + current && current.until_at > input.now + ? current.consecutive_errors + : 0 + const failures = previousFailures + 1 + const fallbackCooldown = Math.min( + quotaCooldownMaxMs, + quotaCooldownBaseMs * 2 ** Math.min(failures - 1, 8), + ) + const requestedUntil = input.retryAt ?? input.now + fallbackCooldown + const boundedUntil = Math.max( + input.now, + Math.min(requestedUntil, input.now + quotaCooldownAbsoluteMaxMs), + ) + this.ctx.storage.sql.exec( + `INSERT INTO credential_quota_cooldowns( + org_id, + account_id, + quota_key, + started_at, + until_at, + last_status_code, + consecutive_errors + ) VALUES (?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(org_id, account_id, quota_key) DO UPDATE SET + started_at = excluded.started_at, + until_at = MAX( + credential_quota_cooldowns.until_at, + excluded.until_at + ), + last_status_code = excluded.last_status_code, + consecutive_errors = excluded.consecutive_errors`, + input.orgId, + input.accountId, + input.quotaKey, + input.now, + boundedUntil, + input.statusCode, + failures, + ) + } + + private clearCredentialQuotaCooldown( + orgId: string, + accountId: string, + quotaKey: string, + successfulLeaseIssuedAt: number, + ): void { + this.ctx.storage.sql.exec( + `DELETE FROM credential_quota_cooldowns + WHERE org_id = ? AND account_id = ? + AND quota_key IN ('*', ?) + AND started_at < ?`, + orgId, + accountId, + quotaKey, + successfulLeaseIssuedAt, + ) + } + async clearAccountQuotaError(input: { readonly orgId?: string readonly accountId: string + readonly successfulLeaseIssuedAt?: number }): Promise<{ ok: true }> { const orgId = this.resolveOrgId(input.orgId) const accountId = this.requireNonEmpty(input.accountId, "accountId") const now = Date.now() + if (input.successfulLeaseIssuedAt !== undefined) { + this.ctx.storage.sql.exec( + `UPDATE accounts + SET last_quota_error_at = NULL, + last_quota_error_code = NULL, + consecutive_quota_errors = 0, + updated_at = ? + WHERE id = ? AND org_id = ? + AND last_quota_error_at IS NOT NULL + AND last_quota_error_at < ?`, + now, + accountId, + orgId, + input.successfulLeaseIssuedAt + ) + return { ok: true } + } this.ctx.storage.sql.exec( `UPDATE accounts SET last_quota_error_at = NULL, @@ -2178,8 +3008,10 @@ export class SubrouterDurableObject extends DurableObject { sql: SqlStorage, orgId: string, quotaKey: string, - upstreamProvider: UpstreamProvider | undefined + upstreamProvider: UpstreamProvider | undefined, + requiredAuthMode: "oauth" | "apikey" | undefined, ): StoredAccount[] { + const now = Date.now() return sql .exec( `SELECT * FROM accounts @@ -2188,10 +3020,26 @@ export class SubrouterDurableObject extends DurableObject { orgId ) .toArray() + .filter( + (row) => + accountRowCanIssueCredentialLease(row, now) && + !this.credentialQuotaCoolingDown( + sql, + orgId, + row.id, + quotaKey, + now, + ) + ) .map((row) => this.accountFromRow(row)) - .filter((account) => - accountMatchesUpstreamProvider(account, upstreamProvider) && - accountHasQuotaForModel(account, quotaKey) + .filter( + (account) => + accountMatchesUpstreamProvider(account, upstreamProvider) && + ( + requiredAuthMode === undefined || + authModeForAccount(account.kind) === requiredAuthMode + ) && + accountHasQuotaForModel(account, quotaKey) ) } @@ -2201,11 +3049,35 @@ export class SubrouterDurableObject extends DurableObject { accountId: string, quotaKey: string, enabledOnly: boolean, - upstreamProvider: UpstreamProvider | undefined + upstreamProvider: UpstreamProvider | undefined, + requiredAuthMode: "oauth" | "apikey" | undefined, + allowQuotaCooldown = false, ): StoredAccount | null { - const account = this.getAccount(sql, orgId, accountId, enabledOnly) + const row = this.getAccountRow(sql, orgId, accountId, enabledOnly) + if ( + !row || + !accountRowCanIssueCredentialLease( + row, + Date.now(), + allowQuotaCooldown, + ) || + this.credentialQuotaCoolingDown( + sql, + orgId, + accountId, + quotaKey, + Date.now(), + ) + ) { + return null + } + const account = this.accountFromRow(row) if (!account) return null return accountMatchesUpstreamProvider(account, upstreamProvider) && + ( + requiredAuthMode === undefined || + authModeForAccount(account.kind) === requiredAuthMode + ) && accountHasQuotaForModel(account, quotaKey) ? account : null @@ -2221,6 +3093,30 @@ export class SubrouterDurableObject extends DurableObject { return row ? this.accountFromRow(row) : null } + private credentialQuotaCoolingDown( + sql: SqlStorage, + orgId: string, + accountId: string, + quotaKey: string, + now: number, + ): boolean { + return ( + sql + .exec( + `SELECT COUNT(*) AS count + FROM credential_quota_cooldowns + WHERE org_id = ? AND account_id = ? + AND quota_key IN ('*', ?) + AND until_at > ?`, + orgId, + accountId, + quotaKey, + now, + ) + .one().count > 0 + ) + } + private getAccountRow( sql: SqlStorage, orgId: string, @@ -2240,9 +3136,15 @@ export class SubrouterDurableObject extends DurableObject { private async refreshAccountIfExpired( orgId: string, accountId: string, - force: boolean + force: boolean, + enabledOnly = true, ): Promise { - const row = this.getAccountRow(this.ctx.storage.sql, orgId, accountId, true) + const row = this.getAccountRow( + this.ctx.storage.sql, + orgId, + accountId, + enabledOnly, + ) if (!row) return null const key = `${orgId}:${accountId}` const existing = this.refreshInFlight.get(key) @@ -2261,24 +3163,36 @@ export class SubrouterDurableObject extends DurableObject { const kind = row.kind as AccountKind if (!isOAuthKind(kind) || !row.credentials_json) return row const credentials = JSON.parse(row.credentials_json) as AccountCredentials + const expectedGeneration = credentials.credentialGeneration ?? 0 if (!credentials.accessToken || !credentials.refreshToken) return row if (!force && !credentialNeedsRefresh(credentials)) return row try { const refreshed = await refreshOAuthCredentials(kind, credentials, force) if (!refreshed.refreshed) return row - this.updateAccountCredentials(row.id, refreshed.credentials) - return { - ...row, - credentials_json: JSON.stringify(refreshed.credentials), - } + return this.updateAccountCredentialsIfGeneration( + row.org_id, + row.id, + expectedGeneration, + refreshed.credentials, + ) ?? this.getAccountRow( + this.ctx.storage.sql, + row.org_id, + row.id, + false, + ) ?? row } catch (error) { const failure = refreshFailureFromError(error) const nextCredentials = { ...credentials, refreshFailure: failure, } - if (terminalRefreshFailure(failure)) { - this.updateAccountCredentials(row.id, nextCredentials) + if (blockingRefreshFailure(failure)) { + this.updateAccountCredentialsIfGeneration( + row.org_id, + row.id, + expectedGeneration, + nextCredentials, + ) } throw error } @@ -2332,17 +3246,59 @@ export class SubrouterDurableObject extends DurableObject { } private updateAccountCredentials( + orgId: string, accountId: string, credentials: AccountCredentials ): void { this.ctx.storage.sql.exec( `UPDATE accounts SET credentials_json = ?, updated_at = ? - WHERE id = ?`, + WHERE id = ? AND org_id = ?`, JSON.stringify(credentials), Date.now(), - accountId + accountId, + orgId + ) + } + + private updateAccountCredentialsIfGeneration( + orgId: string, + accountId: string, + expectedGeneration: number, + credentials: AccountCredentials, + ): AccountRow | null { + const current = this.ctx.storage.sql + .exec( + "SELECT * FROM accounts WHERE id = ? AND org_id = ?", + accountId, + orgId, + ) + .toArray()[0] + if (!current) return null + const currentCredentials = current.credentials_json + ? (JSON.parse(current.credentials_json) as AccountCredentials) + : undefined + if ( + (currentCredentials?.credentialGeneration ?? 0) !== expectedGeneration + ) { + return null + } + const credentialsJSON = JSON.stringify(credentials) + const updatedAt = Date.now() + this.ctx.storage.sql.exec( + `UPDATE accounts + SET credentials_json = ?, updated_at = ? + WHERE id = ? AND org_id = ?`, + credentialsJSON, + updatedAt, + accountId, + orgId, ) + return { + ...current, + credentials_json: credentialsJSON, + updated_at: updatedAt, + } } private async scheduleNextRefreshAlarm(): Promise { @@ -2350,6 +3306,7 @@ export class SubrouterDurableObject extends DurableObject { .exec( `SELECT * FROM accounts WHERE kind IN ('codex_oauth', 'anthropic_oauth') + AND enabled = 1 AND credentials_json IS NOT NULL` ) .toArray() @@ -2357,7 +3314,10 @@ export class SubrouterDurableObject extends DurableObject { const now = Date.now() for (const row of rows) { const credentials = JSON.parse(row.credentials_json ?? "{}") as AccountCredentials - if (credentials.refreshFailure && terminalRefreshFailure(credentials.refreshFailure)) { + if ( + credentials.refreshFailure && + blockingRefreshFailure(credentials.refreshFailure) + ) { continue } const candidate = nextRefreshAt(credentials, now) @@ -2365,6 +3325,20 @@ export class SubrouterDurableObject extends DurableObject { next = candidate } } + const leaseExpiry = this.ctx.storage.sql + .exec<{ expires_at: number | null }>( + "SELECT MIN(expires_at) AS expires_at FROM credential_leases" + ) + .toArray()[0]?.expires_at + if (leaseExpiry !== null && leaseExpiry !== undefined) { + const cleanupAt = Math.max( + now + 1_000, + leaseExpiry + credentialLeaseRetentionMs, + ) + if (next === null || cleanupAt < next) { + next = cleanupAt + } + } if (next === null) { await this.ctx.storage.deleteAlarm() return @@ -2375,6 +3349,17 @@ export class SubrouterDurableObject extends DurableObject { } } + private pruneCredentialLeases(now: number): void { + this.ctx.storage.sql.exec( + "DELETE FROM credential_leases WHERE expires_at <= ?", + now - credentialLeaseRetentionMs, + ) + this.ctx.storage.sql.exec( + "DELETE FROM credential_quota_cooldowns WHERE until_at <= ?", + now - credentialLeaseRetentionMs, + ) + } + private accountFromRow(row: AccountRow): StoredAccount { const quotas = this.modelQuotasForAccount(row.id) return { @@ -3693,6 +4678,48 @@ const handleFetch = async ( } } + if (url.pathname === "/tenant/leases" && request.method === "POST") { + const tenant = await authorizeTenant(request, env, telemetry) + if (tenant instanceof Response) return tenant + if (tenant.legacy) { + return json({ error: "Tenant key required" }, { status: 401 }) + } + const input = await parseCredentialLeaseInput(request, tenant.tenantId) + if (input instanceof Response) return input + try { + return json(await tenantActor(env, tenant).issueCredentialLease(input)) + } catch (error) { + if (telemetry) telemetry.errorType = errorTypeFor(error) + return errorJson(error, 409) + } + } + + const tenantLeaseEventMatch = url.pathname.match( + /^\/tenant\/leases\/([^/]+)\/events$/ + ) + if (tenantLeaseEventMatch && request.method === "POST") { + const tenant = await authorizeTenant(request, env, telemetry) + if (tenant instanceof Response) return tenant + if (tenant.legacy) { + return json({ error: "Tenant key required" }, { status: 401 }) + } + const leaseId = decodeURIComponent(tenantLeaseEventMatch[1]!) + const input = await parseCredentialLeaseEventInput( + request, + tenant.tenantId, + leaseId + ) + if (input instanceof Response) return input + try { + return json( + await tenantActor(env, tenant).recordCredentialLeaseEvent(input) + ) + } catch (error) { + if (telemetry) telemetry.errorType = errorTypeFor(error) + return errorJson(error, 404) + } + } + if (url.pathname === "/tenant/accounts" && request.method === "POST") { const tenant = await authorizeTenant(request, env, telemetry) if (tenant instanceof Response) return tenant @@ -3711,7 +4738,17 @@ const handleFetch = async ( } const actor = tenantActor(env, tenant) try { - const { account } = await actor.upsertAccount(input.account) + let { account } = await actor.upsertAccount({ + ...input.account, + ...(input.adopt ? { enabled: false } : {}), + }) + if (input.adopt) { + const adopted = await actor.adoptAccountCredentials({ + orgId: tenant.tenantId, + accountId: account.id, + }) + account = adopted.account + } return json(safeTenantAccount(account, validation)) } catch (error) { if (telemetry) telemetry.errorType = errorTypeFor(error) @@ -3729,6 +4766,56 @@ const handleFetch = async ( return json({ accounts: accounts.map((account) => safeTenantAccount(account)) }) } + const tenantAccountRepairMatch = url.pathname.match( + /^\/tenant\/accounts\/([^/]+)\/repair$/ + ) + if (tenantAccountRepairMatch && request.method === "POST") { + const tenant = await authorizeTenant(request, env, telemetry) + if (tenant instanceof Response) return tenant + if (tenant.legacy) { + return json({ error: "Tenant key required" }, { status: 401 }) + } + const accountId = decodeURIComponent(tenantAccountRepairMatch[1]!) + const input = await parseTenantAccountUploadInput( + request, + tenant.tenantId + ) + if (input instanceof Response) return input + const validation = input.validate + ? await validateTenantAccountUpload(input.account, { + timeoutMs: validationTimeoutMs(env), + }) + : undefined + if (validation === "failed") { + return json( + { error: "Account validation failed", validation }, + { status: 400 } + ) + } + try { + const actor = tenantActor(env, tenant) + let { account } = await actor.repairAccount({ + orgId: tenant.tenantId, + accountId, + replacement: { + ...input.account, + ...(input.adopt ? { enabled: false } : {}), + }, + }) + if (input.adopt) { + const adopted = await actor.adoptAccountCredentials({ + orgId: tenant.tenantId, + accountId, + }) + account = adopted.account + } + return json(safeTenantAccount(account, validation)) + } catch (error) { + if (telemetry) telemetry.errorType = errorTypeFor(error) + return errorJson(error, 400) + } + } + const tenantAccountDeleteMatch = url.pathname.match(/^\/tenant\/accounts\/([^/]+)$/) if (tenantAccountDeleteMatch && request.method === "DELETE") { const tenant = await authorizeTenant(request, env, telemetry) diff --git a/cloudflare/packages/worker/src/telemetry.ts b/cloudflare/packages/worker/src/telemetry.ts index a8154dc91..92d61115f 100644 --- a/cloudflare/packages/worker/src/telemetry.ts +++ b/cloudflare/packages/worker/src/telemetry.ts @@ -107,7 +107,14 @@ export const routePatternForRequest = ( if (path === "/usage") return "/usage" if (path === "/status") return "/status" if (path === "/tenant/accounts") return "/tenant/accounts" + if (/^\/tenant\/accounts\/[^/]+\/repair$/.test(path)) { + return "/tenant/accounts/:id/repair" + } if (/^\/tenant\/accounts\/[^/]+$/.test(path)) return "/tenant/accounts/:id" + if (path === "/tenant/leases") return "/tenant/leases" + if (/^\/tenant\/leases\/[^/]+\/events$/.test(path)) { + return "/tenant/leases/:id/events" + } if (path === "/admin/tenants") return "/admin/tenants" if (/^\/admin\/tenants\/[^/]+\/revoke$/.test(path)) return "/admin/tenants/:id/revoke" if (/^\/admin\/tenants\/[^/]+\/rotate$/.test(path)) return "/admin/tenants/:id/rotate" diff --git a/cloudflare/packages/worker/test/contract.test.ts b/cloudflare/packages/worker/test/contract.test.ts index 5fe55a70e..a35632c59 100644 --- a/cloudflare/packages/worker/test/contract.test.ts +++ b/cloudflare/packages/worker/test/contract.test.ts @@ -1,9 +1,11 @@ import { describe, expect, test } from "bun:test" import { accountStatus, + blockingRefreshFailure, credentialNeedsRefresh, fetchProviderUsage, refreshOAuthCredentials, + refreshFailureFromError, parseProxyRouteInput, redactedUpstreamURL, safeGoAccount, @@ -219,6 +221,133 @@ describe("subrouter Durable Object contract", () => { expect(refreshed.credentials.expiresAt).toBe(now + 3_600_000) }) + test("invalid_grant is terminal and raw refresh bodies are never persisted", async () => { + const secret = "sk-refresh-response-secret" + let caught: unknown + try { + await refreshOAuthCredentials( + "codex_oauth", + { + accessToken: "expired", + refreshToken: "old-refresh", + expiresAt: 1, + }, + true, + (async () => + new Response( + JSON.stringify({ + error: "invalid_grant", + detail: secret, + }), + { status: 400 }, + )) as unknown as typeof fetch, + ) + } catch (error) { + caught = error + } + const failure = refreshFailureFromError(caught) + expect(blockingRefreshFailure(failure)).toBe(true) + expect(JSON.stringify(failure)).not.toContain(secret) + }) + + test("object-shaped invalid refresh messages stay terminal without persisting raw text", async () => { + const secret = "raw-provider-detail-that-must-not-persist" + let caught: unknown + try { + await refreshOAuthCredentials( + "codex_oauth", + { + accessToken: "expired", + refreshToken: "old-refresh", + expiresAt: 1, + }, + true, + (async () => + new Response( + JSON.stringify({ + error: { + type: "invalid_request_error", + message: `The refresh token is invalid. ${secret}`, + }, + }), + { status: 400 }, + )) as unknown as typeof fetch, + ) + } catch (error) { + caught = error + } + const failure = refreshFailureFromError(caught) + expect(blockingRefreshFailure(failure)).toBe(true) + expect(JSON.stringify(failure)).not.toContain(secret) + }) + + test("an ambiguous refresh freezes the old rotation token", async () => { + let attempts = 0 + let caught: unknown + try { + await refreshOAuthCredentials( + "codex_oauth", + { + accessToken: "expired", + refreshToken: "rotation-token", + expiresAt: 1, + }, + true, + (async () => { + attempts++ + throw new TypeError("connection reset after write") + }) as unknown as typeof fetch, + ) + } catch (error) { + caught = error + } + const failure = refreshFailureFromError(caught) + expect(blockingRefreshFailure(failure)).toBe(true) + + await expect( + refreshOAuthCredentials( + "codex_oauth", + { + accessToken: "expired", + refreshToken: "rotation-token", + expiresAt: 1, + refreshFailure: failure, + }, + true, + (async () => { + attempts++ + return Response.json({ access_token: "must-not-happen" }) + }) as unknown as typeof fetch, + ), + ).rejects.toThrow() + expect(attempts).toBe(1) + }) + + test("malformed refresh responses never persist response snippets", async () => { + const secret = "sk-response-body-secret" + let caught: unknown + try { + await refreshOAuthCredentials( + "anthropic_oauth", + { + accessToken: "expired", + refreshToken: "rotation-token", + expiresAt: 1, + }, + true, + (async () => + new Response(`{"access_token":"${secret}"`, { + status: 200, + })) as unknown as typeof fetch, + ) + } catch (error) { + caught = error + } + const failure = refreshFailureFromError(caught) + expect(failure.status).toBe(0) + expect(JSON.stringify(failure)).not.toContain(secret) + }) + test("codex usage fetch parses base and model-family windows", async () => { const calls: Request[] = [] const fetcher = async (input: RequestInfo | URL, init?: RequestInit) => { diff --git a/cloudflare/packages/worker/test/credential-lease.test.ts b/cloudflare/packages/worker/test/credential-lease.test.ts new file mode 100644 index 000000000..9179c8a64 --- /dev/null +++ b/cloudflare/packages/worker/test/credential-lease.test.ts @@ -0,0 +1,1232 @@ +import { afterEach, describe, expect, test } from "bun:test" +import { + adminToken, + cleanupWorkers, + createTenant, + startWorker, +} from "./helpers/worker.ts" + +const servers: Array<{ stop: () => void }> = [] + +afterEach(async () => { + await cleanupWorkers() + for (const server of servers.splice(0)) server.stop() +}) + +describe("tenant credential leases", () => { + test("refreshes centrally once, returns access-only leases, and persists rotation", async () => { + const refreshTokens: string[] = [] + let refreshCount = 0 + const tokenServer = Bun.serve({ + port: 0, + async fetch(request) { + const form = new URLSearchParams(await request.text()) + refreshTokens.push(form.get("refresh_token") ?? "") + refreshCount++ + return Response.json({ + access_token: `claude-access-${refreshCount}`, + refresh_token: `claude-refresh-${refreshCount}`, + expires_in: 3600, + }) + }, + }) + servers.push(tokenServer) + + const worker = await startWorker() + const tenant = await createTenant(worker.baseURL, "Lease Tenant") + const uploaded = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + label: "shared@example.com", + claudeAiOauth: { + accessToken: "claude-access-expired", + refreshToken: "claude-refresh-original", + expiresAt: Date.now() - 60_000, + tokenEndpoint: `${tokenServer.url.origin}/token`, + }, + }), + }) + expect(uploaded.status).toBe(200) + + const [first, second] = await Promise.all([ + requestLease(worker.baseURL, tenant.key, "session-a"), + requestLease(worker.baseURL, tenant.key, "session-b"), + ]) + expect(first.response.status).toBe(200) + expect(second.response.status).toBe(200) + expect(refreshCount).toBe(1) + expect(first.body.token).toBe("claude-access-1") + expect(second.body.token).toBe("claude-access-1") + expect(first.body.authMode).toBe("oauth") + expect(first.body.provider).toBe("claude") + expect(first.body.credentialGeneration).toBe(1) + expect(Date.parse(first.body.expiresAt) - Date.parse(first.body.issuedAt)).toBe(5 * 60 * 1000) + + const serialized = JSON.stringify([first.body, second.body]) + expect(serialized).not.toContain("claude-refresh") + expect(serialized).not.toContain("idToken") + expect(serialized).not.toContain("refreshToken") + + const unauthorized = await fetch( + `${worker.baseURL}/tenant/leases/${encodeURIComponent(first.body.leaseId)}/events`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ outcome: "unauthorized", statusCode: 401 }), + }, + ) + expect(unauthorized.status).toBe(200) + const unauthorizedBody = await unauthorized.json() as { + ok: boolean + refreshState: string + } + expect(unauthorizedBody).toEqual({ ok: true, refreshState: "refreshed" }) + expect(refreshTokens).toEqual([ + "claude-refresh-original", + "claude-refresh-1", + ]) + + const staleUnauthorized = await fetch( + `${worker.baseURL}/tenant/leases/${encodeURIComponent(second.body.leaseId)}/events`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ outcome: "unauthorized", statusCode: 401 }), + }, + ) + expect(staleUnauthorized.status).toBe(200) + const staleUnauthorizedBody = await staleUnauthorized.json() as { + ok: boolean + } + expect(staleUnauthorizedBody).toEqual({ ok: true }) + expect(refreshCount).toBe(2) + + const staleRateLimited = await fetch( + `${worker.baseURL}/tenant/leases/${encodeURIComponent(second.body.leaseId)}/events`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + outcome: "rate_limited", + statusCode: 429, + }), + }, + ) + expect(staleRateLimited.status).toBe(200) + + const current = await requestLease( + worker.baseURL, + tenant.key, + "session-current", + ) + expect(current.response.status).toBe(200) + expect(current.body.token).toBe("claude-access-2") + + const currentRateLimited = await fetch( + `${worker.baseURL}/tenant/leases/${encodeURIComponent(current.body.leaseId)}/events`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + outcome: "rate_limited", + statusCode: 429, + }), + }, + ) + expect(currentRateLimited.status).toBe(200) + + const staleSuccess = await fetch( + `${worker.baseURL}/tenant/leases/${encodeURIComponent(second.body.leaseId)}/events`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ outcome: "success", statusCode: 200 }), + }, + ) + expect(staleSuccess.status).toBe(200) + + const afterStaleSuccess = await requestLease( + worker.baseURL, + tenant.key, + "session-after-stale-success", + ) + expect(afterStaleSuccess.response.status).toBe(409) + }, 60_000) + + test("adopts an OAuth refresh chain before acknowledging upload", async () => { + let refreshCount = 0 + const tokenServer = Bun.serve({ + port: 0, + fetch() { + refreshCount++ + return Response.json({ + access_token: "central-access", + refresh_token: "central-refresh", + expires_in: 3600, + }) + }, + }) + servers.push(tokenServer) + + const worker = await startWorker() + const tenant = await createTenant(worker.baseURL, "Adoption") + const uploaded = await fetch( + `${worker.baseURL}/tenant/accounts?adopt=1`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + label: "adopt@example.com", + claudeAiOauth: { + accessToken: "laptop-access", + refreshToken: "laptop-refresh", + expiresAt: Date.now() + 60 * 60 * 1000, + tokenEndpoint: `${tokenServer.url.origin}/token`, + }, + }), + }, + ) + expect(uploaded.status).toBe(200) + expect(refreshCount).toBe(1) + const uploadedText = await uploaded.text() + expect(uploadedText).not.toContain("central-access") + expect(uploadedText).not.toContain("central-refresh") + + const lease = await requestLease(worker.baseURL, tenant.key, "adopted") + expect(lease.response.status).toBe(200) + expect(lease.body.token).toBe("central-access") + expect(lease.body.credentialGeneration).toBe(1) + expect(refreshCount).toBe(1) + }, 60_000) + + test("keeps a failed OAuth adoption out of credential routing", async () => { + const tokenServer = Bun.serve({ + port: 0, + fetch() { + return new Response("temporary provider failure", { status: 500 }) + }, + }) + servers.push(tokenServer) + + const worker = await startWorker() + const tenant = await createTenant(worker.baseURL, "Failed adoption") + const uploaded = await fetch( + `${worker.baseURL}/tenant/accounts?adopt=1`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + label: "must stay disabled", + claudeAiOauth: { + accessToken: "unadopted-laptop-access", + refreshToken: "unadopted-laptop-refresh", + expiresAt: Date.now() + 60 * 60 * 1000, + tokenEndpoint: `${tokenServer.url.origin}/token`, + }, + }), + }, + ) + expect(uploaded.status).toBe(400) + + const lease = await requestLease( + worker.baseURL, + tenant.key, + "failed-adoption", + ) + expect(lease.response.status).toBe(409) + expect(JSON.stringify(lease.body)).not.toContain("unadopted-laptop-access") + }, 60_000) + + test("honors an OAuth-only lease requirement over a preferred API key", async () => { + const worker = await startWorker() + const tenant = await createTenant(worker.baseURL, "OAuth-only lease") + const apiKeyResponse = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "openai-apikey", + label: "API key", + apiKey: "sk-api-key-must-not-reach-chatgpt", + }), + }) + const apiKey = await apiKeyResponse.json() as { id: string } + expect(apiKeyResponse.status).toBe(200) + const oauthAccess = `header.${ + btoa(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600 })) + .replaceAll("+", "-") + .replaceAll("/", "_") + .replaceAll("=", "") + }.signature` + const oauthResponse = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "codex", + label: "OAuth", + tokens: { + accessToken: oauthAccess, + refreshToken: "oauth-refresh", + idToken: "oauth-id", + accountID: "oauth-account", + expiresAt: Date.now() + 60 * 60 * 1000, + }, + }), + }) + expect(oauthResponse.status).toBe(200) + + const lease = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "codex", + requiredAuthMode: "oauth", + agentType: "codex", + sessionId: "chatgpt-backend", + preferAccountId: apiKey.id, + }), + }) + const body = await lease.json() as { authMode?: string; token?: string } + expect(lease.status).toBe(200) + expect(body.authMode).toBe("oauth") + expect(body.token).toBe(oauthAccess) + }, 60_000) + + test("rejects lease events from another tenant", async () => { + const worker = await startWorker() + const owner = await createTenant(worker.baseURL, "Owner") + const attacker = await createTenant(worker.baseURL, "Attacker") + const uploaded = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(owner.key), + body: JSON.stringify({ + provider: "anthropic-apikey", + label: "shared key", + apiKey: "sk-ant-lease-test", + }), + }) + expect(uploaded.status).toBe(200) + + const lease = await requestLease(worker.baseURL, owner.key, "session-owner") + expect(lease.response.status).toBe(200) + const crossTenant = await fetch( + `${worker.baseURL}/tenant/leases/${encodeURIComponent(lease.body.leaseId)}/events`, + { + method: "POST", + headers: tenantHeaders(attacker.key), + body: JSON.stringify({ outcome: "success", statusCode: 200 }), + }, + ) + expect(crossTenant.status).toBe(404) + expect(await crossTenant.text()).not.toContain("sk-ant-lease-test") + }, 60_000) + + test("deleting an account removes its retained credential leases", async () => { + const worker = await startWorker() + const tenant = await createTenant(worker.baseURL, "Lease cleanup") + const uploaded = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "anthropic-apikey", + label: "delete me", + apiKey: "sk-ant-delete-me", + }), + }) + const account = await uploaded.json() as { id: string } + expect(uploaded.status).toBe(200) + + const lease = await requestLease( + worker.baseURL, + tenant.key, + "lease-before-delete", + ) + expect(lease.response.status).toBe(200) + const deleted = await fetch( + `${worker.baseURL}/tenant/accounts/${encodeURIComponent(account.id)}`, + { + method: "DELETE", + headers: tenantHeaders(tenant.key), + }, + ) + expect(deleted.status).toBe(200) + + const staleEvent = await fetch( + `${worker.baseURL}/tenant/leases/${encodeURIComponent(lease.body.leaseId)}/events`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ outcome: "success", statusCode: 200 }), + }, + ) + expect(staleEvent.status).toBe(404) + }, 60_000) + + test("removes a rejected API key from routing until it is repaired", async () => { + const worker = await startWorker() + const tenant = await createTenant(worker.baseURL, "Rejected API key") + const first = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "anthropic-apikey", + label: "rejected", + apiKey: "sk-ant-rejected", + }), + }) + const firstBody = await first.json() as { id: string } + expect(first.status).toBe(200) + const second = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "anthropic-apikey", + label: "healthy", + apiKey: "sk-ant-healthy", + }), + }) + expect(second.status).toBe(200) + + const rejectedLease = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "rejected-key", + preferAccountId: firstBody.id, + }), + }) + const rejectedLeaseBody = await rejectedLease.json() as { + leaseId: string + token: string + } + expect(rejectedLease.status).toBe(200) + expect(rejectedLeaseBody.token).toBe("sk-ant-rejected") + + const unauthorized = await fetch( + `${worker.baseURL}/tenant/leases/${encodeURIComponent(rejectedLeaseBody.leaseId)}/events`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ outcome: "unauthorized", statusCode: 401 }), + }, + ) + expect(unauthorized.status).toBe(200) + + const accounts = await fetch(`${worker.baseURL}/tenant/accounts`, { + headers: tenantHeaders(tenant.key), + }) + const accountsBody = await accounts.json() as { + accounts: Array<{ id: string; health: { ok: boolean; message?: string } }> + } + expect( + accountsBody.accounts.find((account) => account.id === firstBody.id)?.health, + ).toEqual({ + ok: false, + message: "Credential requires repair before it can be leased.", + }) + + const replacement = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "healthy-key", + preferAccountId: firstBody.id, + }), + }) + const replacementBody = await replacement.json() as { token: string } + expect(replacement.status).toBe(200) + expect(replacementBody.token).toBe("sk-ant-healthy") + }, 60_000) + + test("does not quarantine an API key for an ordinary forbidden request", async () => { + const worker = await startWorker() + const tenant = await createTenant(worker.baseURL, "Model forbidden") + const first = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "anthropic-apikey", + label: "model-scoped", + apiKey: "sk-ant-model-scoped", + }), + }) + const firstBody = await first.json() as { id: string } + expect(first.status).toBe(200) + const second = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "anthropic-apikey", + label: "fallback", + apiKey: "sk-ant-model-fallback", + }), + }) + expect(second.status).toBe(200) + + const lease = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "forbidden-first", + preferAccountId: firstBody.id, + model: "claude-opus-4-8", + }), + }) + const leaseBody = await lease.json() as { leaseId: string; token: string } + expect(lease.status).toBe(200) + expect(leaseBody.token).toBe("sk-ant-model-scoped") + + const forbidden = await fetch( + `${worker.baseURL}/tenant/leases/${encodeURIComponent(leaseBody.leaseId)}/events`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ outcome: "unauthorized", statusCode: 403 }), + }, + ) + expect(forbidden.status).toBe(200) + + const retry = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "forbidden-retry", + preferAccountId: firstBody.id, + model: "claude-sonnet-4-6", + }), + }) + const retryBody = await retry.json() as { token: string } + expect(retry.status).toBe(200) + expect(retryBody.token).toBe("sk-ant-model-scoped") + }, 60_000) + + test("rotates a forbidden model without disabling the shared key", async () => { + const worker = await startWorker() + const tenant = await createTenant(worker.baseURL, "Forbidden model") + const first = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "anthropic-apikey", + label: "partially allowed", + apiKey: "sk-ant-partially-allowed", + }), + }) + const firstBody = await first.json() as { id: string } + expect(first.status).toBe(200) + const second = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "anthropic-apikey", + label: "model fallback", + apiKey: "sk-ant-forbidden-fallback", + }), + }) + expect(second.status).toBe(200) + + const opus = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "forbidden-opus", + preferAccountId: firstBody.id, + model: "claude-opus-4-8", + }), + }) + const opusBody = await opus.json() as { leaseId: string; token: string } + expect(opus.status).toBe(200) + expect(opusBody.token).toBe("sk-ant-partially-allowed") + + const forbidden = await fetch( + `${worker.baseURL}/tenant/leases/${encodeURIComponent(opusBody.leaseId)}/events`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ outcome: "forbidden", statusCode: 403 }), + }, + ) + expect(forbidden.status).toBe(200) + + const sonnet = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "forbidden-sonnet", + preferAccountId: firstBody.id, + model: "claude-sonnet-4-6", + }), + }) + const sonnetBody = await sonnet.json() as { token: string } + expect(sonnet.status).toBe(200) + expect(sonnetBody.token).toBe("sk-ant-partially-allowed") + + const opusRetry = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "forbidden-opus-retry", + preferAccountId: firstBody.id, + model: "claude-opus-4-8", + }), + }) + const opusRetryBody = await opusRetry.json() as { token: string } + expect(opusRetry.status).toBe(200) + expect(opusRetryBody.token).toBe("sk-ant-forbidden-fallback") + }, 60_000) + + test("applies account-scoped forbidden cooldowns across models", async () => { + const worker = await startWorker() + const tenant = await createTenant(worker.baseURL, "Forbidden account") + const first = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "anthropic-apikey", + label: "organization disabled", + apiKey: "sk-ant-organization-disabled", + }), + }) + const firstBody = await first.json() as { id: string } + expect(first.status).toBe(200) + const second = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "anthropic-apikey", + label: "account fallback", + apiKey: "sk-ant-account-fallback", + }), + }) + expect(second.status).toBe(200) + + const opus = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "forbidden-account-opus", + preferAccountId: firstBody.id, + model: "claude-opus-4-8", + }), + }) + const opusBody = await opus.json() as { leaseId: string; token: string } + expect(opus.status).toBe(200) + expect(opusBody.token).toBe("sk-ant-organization-disabled") + + const forbidden = await fetch( + `${worker.baseURL}/tenant/leases/${encodeURIComponent(opusBody.leaseId)}/events`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + outcome: "forbidden", + statusCode: 403, + scope: "account", + }), + }, + ) + expect(forbidden.status).toBe(200) + + const sonnet = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "forbidden-account-sonnet", + preferAccountId: firstBody.id, + model: "claude-sonnet-4-6", + }), + }) + const sonnetBody = await sonnet.json() as { token: string } + expect(sonnet.status).toBe(200) + expect(sonnetBody.token).toBe("sk-ant-account-fallback") + }, 60_000) + + test("honors model-scoped cooldowns and provider reset times", async () => { + const worker = await startWorker() + const tenant = await createTenant(worker.baseURL, "Scoped cooldown") + const first = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "anthropic-apikey", + label: "scoped", + apiKey: "sk-ant-scoped", + }), + }) + const firstBody = await first.json() as { id: string } + expect(first.status).toBe(200) + const second = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "anthropic-apikey", + label: "fallback", + apiKey: "sk-ant-scoped-fallback", + }), + }) + expect(second.status).toBe(200) + + const opus = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "scoped-opus-first", + preferAccountId: firstBody.id, + model: "claude-opus-4-8", + }), + }) + const opusBody = await opus.json() as { leaseId: string; token: string } + expect(opus.status).toBe(200) + expect(opusBody.token).toBe("sk-ant-scoped") + + const opusLimited = await fetch( + `${worker.baseURL}/tenant/leases/${encodeURIComponent(opusBody.leaseId)}/events`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + outcome: "rate_limited", + statusCode: 429, + scope: "quota", + quotaKey: "opus", + retryAt: Date.now() + 60 * 60 * 1000, + }), + }, + ) + expect(opusLimited.status).toBe(200) + + const sonnet = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "scoped-sonnet", + preferAccountId: firstBody.id, + model: "claude-sonnet-4-6", + }), + }) + const sonnetBody = await sonnet.json() as { leaseId: string; token: string } + expect(sonnet.status).toBe(200) + expect(sonnetBody.token).toBe("sk-ant-scoped") + + const opusFallback = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "scoped-opus-fallback", + preferAccountId: firstBody.id, + model: "claude-opus-4-8", + }), + }) + const opusFallbackBody = await opusFallback.json() as { token: string } + expect(opusFallback.status).toBe(200) + expect(opusFallbackBody.token).toBe("sk-ant-scoped-fallback") + + const alreadyReset = await fetch( + `${worker.baseURL}/tenant/leases/${encodeURIComponent(sonnetBody.leaseId)}/events`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + outcome: "rate_limited", + statusCode: 429, + scope: "quota", + quotaKey: "sonnet", + retryAt: Date.now() - 1, + }), + }, + ) + expect(alreadyReset.status).toBe(200) + + const afterReset = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "scoped-sonnet-reset", + preferAccountId: firstBody.id, + model: "claude-sonnet-4-6", + }), + }) + const afterResetBody = await afterReset.json() as { token: string } + expect(afterReset.status).toBe(200) + expect(afterResetBody.token).toBe("sk-ant-scoped") + }, 60_000) + + test("routes around an account whose central refresh needs repair", async () => { + let refreshCount = 0 + const tokenServer = Bun.serve({ + port: 0, + fetch() { + refreshCount++ + return Response.json( + { error: "invalid_grant", error_description: "repair required" }, + { status: 400 }, + ) + }, + }) + servers.push(tokenServer) + + const worker = await startWorker() + const tenant = await createTenant(worker.baseURL, "Refresh fallback") + const broken = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + label: "broken oauth", + claudeAiOauth: { + accessToken: "expired-access", + refreshToken: "broken-refresh", + expiresAt: Date.now() - 60_000, + tokenEndpoint: `${tokenServer.url.origin}/token`, + }, + }), + }) + const brokenBody = await broken.json() as { id: string } + expect(broken.status).toBe(200) + const healthy = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "anthropic-apikey", + label: "healthy fallback", + apiKey: "sk-ant-healthy-fallback", + }), + }) + expect(healthy.status).toBe(200) + + const lease = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "refresh-fallback", + preferAccountId: brokenBody.id, + }), + }) + const leaseBody = await lease.json() as { + authMode: string + token: string + } + expect(lease.status).toBe(200) + expect(leaseBody.authMode).toBe("apikey") + expect(leaseBody.token).toBe("sk-ant-healthy-fallback") + expect(refreshCount).toBe(1) + + const second = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "refresh-fallback-2", + preferAccountId: brokenBody.id, + }), + }) + expect(second.status).toBe(200) + expect(refreshCount).toBe(1) + }, 60_000) + + test("routes around an access-only OAuth credential that cannot cover the lease", async () => { + const worker = await startWorker() + const tenant = await createTenant(worker.baseURL, "Access-only fallback") + const accountId = "access-only-oauth" + const accessOnly = await fetch(`${worker.baseURL}/admin/accounts`, { + method: "POST", + headers: { + Authorization: `Bearer ${adminToken}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ + id: accountId, + orgId: tenant.id, + kind: "anthropic_oauth", + label: "expiring access only", + credentials: { + accessToken: "access-only-near-expiry", + expiresAt: Date.now() + 30_000, + }, + }), + }) + expect(accessOnly.status).toBe(200) + const healthy = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "anthropic-apikey", + label: "healthy fallback", + apiKey: "sk-ant-access-only-fallback", + }), + }) + expect(healthy.status).toBe(200) + + const lease = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "access-only-fallback", + preferAccountId: accountId, + }), + }) + const body = await lease.json() as { token?: string } + expect(lease.status).toBe(200) + expect(body.token).toBe("sk-ant-access-only-fallback") + }, 60_000) + + test("cools down a rate-limited account before issuing another lease", async () => { + const worker = await startWorker() + const tenant = await createTenant(worker.baseURL, "Rate-limit cooldown") + const first = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "anthropic-apikey", + label: "rate limited", + apiKey: "sk-ant-rate-limited", + }), + }) + const firstBody = await first.json() as { id: string } + expect(first.status).toBe(200) + const second = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "anthropic-apikey", + label: "healthy", + apiKey: "sk-ant-cooldown-fallback", + }), + }) + expect(second.status).toBe(200) + + const firstLease = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "rate-limit-first", + preferAccountId: firstBody.id, + }), + }) + const firstLeaseBody = await firstLease.json() as { + leaseId: string + token: string + } + expect(firstLease.status).toBe(200) + expect(firstLeaseBody.token).toBe("sk-ant-rate-limited") + + const concurrentLease = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "rate-limit-concurrent", + preferAccountId: firstBody.id, + }), + }) + const concurrentLeaseBody = await concurrentLease.json() as { + leaseId: string + token: string + } + expect(concurrentLease.status).toBe(200) + expect(concurrentLeaseBody.token).toBe("sk-ant-rate-limited") + + const event = await fetch( + `${worker.baseURL}/tenant/leases/${encodeURIComponent(firstLeaseBody.leaseId)}/events`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ outcome: "rate_limited", statusCode: 429 }), + }, + ) + expect(event.status).toBe(200) + + const lateSuccess = await fetch( + `${worker.baseURL}/tenant/leases/${encodeURIComponent(concurrentLeaseBody.leaseId)}/events`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ outcome: "success", statusCode: 200 }), + }, + ) + expect(lateSuccess.status).toBe(200) + + const replacement = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "rate-limit-replacement", + preferAccountId: firstBody.id, + }), + }) + const replacementBody = await replacement.json() as { token?: string } + expect(replacement.status).toBe(200) + expect(replacementBody.token).toBe("sk-ant-cooldown-fallback") + }, 60_000) + + test("repairs an OAuth account in place and leases only the replacement access token", async () => { + const worker = await startWorker() + const tenant = await createTenant(worker.baseURL, "Repair") + const future = Date.now() + 60 * 60 * 1000 + const created = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + label: "Repair me", + claudeAiOauth: { + accessToken: "old-access", + refreshToken: "old-refresh", + expiresAt: future, + }, + }), + }) + const createdBody = await created.json() as { id: string } + expect(created.status).toBe(200) + const oldLease = await requestLease( + worker.baseURL, + tenant.key, + "pre-repair-session", + ) + expect(oldLease.response.status).toBe(200) + expect(oldLease.body.credentialGeneration).toBe(0) + + const repaired = await fetch( + `${worker.baseURL}/tenant/accounts/${encodeURIComponent(createdBody.id)}/repair`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + label: "Repair me", + claudeAiOauth: { + accessToken: "replacement-access", + refreshToken: "replacement-refresh", + expiresAt: future, + }, + }), + }, + ) + expect(repaired.status).toBe(200) + const repairedText = await repaired.text() + expect(repairedText).not.toContain("replacement-access") + expect(repairedText).not.toContain("replacement-refresh") + + const staleEvent = await fetch( + `${worker.baseURL}/tenant/leases/${encodeURIComponent(oldLease.body.leaseId)}/events`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ outcome: "unauthorized", statusCode: 401 }), + }, + ) + expect(staleEvent.status).toBe(404) + + const lease = await fetch(`${worker.baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId: "repair-session", + preferAccountId: createdBody.id, + }), + }) + const leaseBody = await lease.json() as { + accountId: string + token: string + credentialGeneration: number + } + expect(lease.status).toBe(200) + expect(leaseBody.accountId).toBe(createdBody.id) + expect(leaseBody.token).toBe("replacement-access") + expect(leaseBody.credentialGeneration).toBe(1) + }, 60_000) + + test("does not let an in-flight old refresh overwrite a repaired credential", async () => { + let signalOldRefreshStarted: (() => void) | undefined + const oldRefreshStarted = new Promise((resolve) => { + signalOldRefreshStarted = resolve + }) + let releaseOldRefresh: (() => void) | undefined + const oldRefreshReleased = new Promise((resolve) => { + releaseOldRefresh = resolve + }) + const oldTokenServer = Bun.serve({ + port: 0, + async fetch() { + signalOldRefreshStarted?.() + await oldRefreshReleased + return Response.json({ + access_token: "old-refresh-result", + refresh_token: "old-refresh-chain", + expires_in: 3600, + }) + }, + }) + servers.push(oldTokenServer) + + let signalReplacementRefreshStarted: (() => void) | undefined + const replacementRefreshStarted = new Promise((resolve) => { + signalReplacementRefreshStarted = resolve + }) + let replacementRefreshCount = 0 + const replacementTokenServer = Bun.serve({ + port: 0, + fetch() { + replacementRefreshCount++ + signalReplacementRefreshStarted?.() + return Response.json({ + access_token: "replacement-refresh-result", + refresh_token: "replacement-refresh-chain", + expires_in: 3600, + }) + }, + }) + servers.push(replacementTokenServer) + + const worker = await startWorker() + const tenant = await createTenant(worker.baseURL, "Concurrent repair") + const created = await fetch(`${worker.baseURL}/tenant/accounts`, { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + label: "Race", + claudeAiOauth: { + accessToken: "old-expired", + refreshToken: "old-refresh", + expiresAt: Date.now() - 60_000, + tokenEndpoint: `${oldTokenServer.url.origin}/token`, + }, + }), + }) + const createdBody = await created.json() as { id: string } + expect(created.status).toBe(200) + + const oldLeasePromise = requestLease( + worker.baseURL, + tenant.key, + "old-refresh-in-flight", + ) + await oldRefreshStarted + + const repairPromise = fetch( + `${worker.baseURL}/tenant/accounts/${encodeURIComponent(createdBody.id)}/repair?adopt=1`, + { + method: "POST", + headers: tenantHeaders(tenant.key), + body: JSON.stringify({ + provider: "claude", + label: "Race", + claudeAiOauth: { + accessToken: "replacement-before-adoption", + refreshToken: "replacement-refresh", + expiresAt: Date.now() + 60 * 60 * 1000, + tokenEndpoint: `${replacementTokenServer.url.origin}/token`, + }, + }), + }, + ) + await Promise.race([ + replacementRefreshStarted, + Bun.sleep(50), + ]) + expect(replacementRefreshCount).toBe(0) + releaseOldRefresh?.() + + const [repaired, oldLease] = await Promise.all([ + repairPromise, + oldLeasePromise, + ]) + expect(repaired.status).toBe(200) + expect(oldLease.response.status).toBe(200) + + const finalLease = await requestLease( + worker.baseURL, + tenant.key, + "after-repair", + ) + expect(finalLease.response.status).toBe(200) + expect(finalLease.body.token).toBe("replacement-refresh-result") + expect(replacementRefreshCount).toBe(1) + }, 60_000) +}) + +const requestLease = async ( + baseURL: string, + tenantKey: string, + sessionId: string, +): Promise<{ + response: Response + body: { + leaseId: string + token: string + provider: string + authMode: string + credentialGeneration: number + issuedAt: string + expiresAt: string + } +}> => { + const response = await fetch(`${baseURL}/tenant/leases`, { + method: "POST", + headers: tenantHeaders(tenantKey), + body: JSON.stringify({ + provider: "claude", + agentType: "claude", + sessionId, + }), + }) + return { + response, + body: await response.json() as { + leaseId: string + token: string + provider: string + authMode: string + credentialGeneration: number + issuedAt: string + expiresAt: string + }, + } +} + +const tenantHeaders = (tenantKey: string): HeadersInit => ({ + Authorization: `Bearer ${tenantKey}`, + "Content-Type": "application/json", +}) diff --git a/cmd/subrouter/cloud_mode_test.go b/cmd/subrouter/cloud_mode_test.go new file mode 100644 index 000000000..c04b675f9 --- /dev/null +++ b/cmd/subrouter/cloud_mode_test.go @@ -0,0 +1,697 @@ +package main + +import ( + "bytes" + "context" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/manaflow-ai/subrouter/internal/accounts" + agentclaude "github.com/manaflow-ai/subrouter/internal/agents/claude" + "github.com/manaflow-ai/subrouter/internal/broker" +) + +func saveReadyCloudConfig(t *testing.T) { + t.Helper() + path := filepath.Join(t.TempDir(), "cloud.json") + t.Setenv("SUBROUTER_CLOUD_CONFIG", path) + if err := broker.SaveConfig(path, broker.Config{ + BaseURL: "https://cmux.test", + AccessToken: "stack-access", + RefreshToken: "stack-refresh", + TeamID: "team-a", + TeamName: "Team A", + }); err != nil { + t.Fatal(err) + } +} + +func TestCloudCodexAlwaysUsesLocalProxy(t *testing.T) { + saveReadyCloudConfig(t) + local := healthServer(t, 200) + t.Setenv("SUBROUTER_LOCAL_BASE_URL", local.URL+"/v1") + + store := srServerStore{Path: filepath.Join(t.TempDir(), "servers.json")} + if err := store.save(srServerFile{ + Default: "remote", + Servers: []srServerConfig{{ + Name: "remote", + URL: "http://remote.example:31415", + }}, + }); err != nil { + t.Fatal(err) + } + var warnings bytes.Buffer + got, err := codexBaseURLWithFallback(store, &warnings) + if err != nil { + t.Fatal(err) + } + if got != local.URL+"/v1" { + t.Fatalf("base URL = %q, want local proxy", got) + } + if strings.Contains(warnings.String(), "remote.example") { + t.Fatalf("cloud mode should not probe or fall back through the legacy remote: %q", warnings.String()) + } +} + +func TestTeamServerKeepsDedicatedProxyAuthenticationForRemoteOverride(t *testing.T) { + saveReadyCloudConfig(t) + t.Setenv("SUBROUTER_CODEX_BASE_URL", "https://remote.example/v1") + + store := srServerStore{Path: filepath.Join(t.TempDir(), "servers.json")} + if _, err := codexBaseURLWithFallback(store, nil); err == nil || + !strings.Contains(err.Error(), "team credentials") { + t.Fatalf("remote team pin error = %v, want a local-only rejection", err) + } + config, err := cloudModeConfig() + if err != nil { + t.Fatal(err) + } + if token := cloudServerProxyToken(config); token != config.LocalProxyToken { + t.Fatal("server proxy token did not use the dedicated local secret") + } +} + +func TestTeamProxyNeverSendsStackTokenToALocalURLOverride(t *testing.T) { + config := broker.Config{ + BaseURL: "https://cmux.test", + AccessToken: "stack-access", + RefreshToken: "stack-refresh", + TeamID: "team-a", + LocalProxyToken: "dedicated-local-secret", + } + t.Setenv("SUBROUTER_LOCAL_BASE_URL", "https://attacker.example/v1") + + if token := cloudClientProxyToken( + config, + "https://attacker.example/v1", + ); token != "" { + t.Fatal("remote override received a non-empty proxy token") + } +} + +func TestTeamProxyUsesDedicatedLocalSecret(t *testing.T) { + path := filepath.Join(t.TempDir(), "cloud.json") + if err := broker.SaveConfig(path, broker.Config{ + BaseURL: "https://cmux.test", + AccessToken: "stack-access", + RefreshToken: "stack-refresh", + TeamID: "team-a", + }); err != nil { + t.Fatal(err) + } + config, err := broker.LoadConfig(path) + if err != nil { + t.Fatal(err) + } + got := cloudServerProxyToken(config) + if got == "" { + t.Fatal("persisted config has no dedicated local proxy secret") + } + if got == config.AccessToken { + t.Fatal("local proxy secret reused the Stack session token") + } +} + +func TestTeamCodexIgnoresMalformedLegacyServerStore(t *testing.T) { + saveReadyCloudConfig(t) + local := healthServer(t, http.StatusOK) + t.Setenv("SUBROUTER_LOCAL_BASE_URL", local.URL+"/v1") + + path := filepath.Join(t.TempDir(), "servers.json") + if err := os.WriteFile(path, []byte("{"), 0o600); err != nil { + t.Fatal(err) + } + got, err := codexBaseURLWithFallback(srServerStore{Path: path}, nil) + if err != nil { + t.Fatal(err) + } + if got != local.URL+"/v1" { + t.Fatalf("base URL = %q, want local proxy %q", got, local.URL+"/v1") + } +} + +func TestLocalCodexIgnoresMalformedLegacyServerStore(t *testing.T) { + configPath := filepath.Join(t.TempDir(), "cloud.json") + t.Setenv("SUBROUTER_CLOUD_CONFIG", configPath) + if err := broker.SaveConfig(configPath, broker.Config{ + CredentialSource: broker.CredentialSourceLocal, + }); err != nil { + t.Fatal(err) + } + local := healthServer(t, http.StatusOK) + t.Setenv("SUBROUTER_LOCAL_BASE_URL", local.URL+"/v1") + + path := filepath.Join(t.TempDir(), "servers.json") + if err := os.WriteFile(path, []byte("{"), 0o600); err != nil { + t.Fatal(err) + } + got, err := codexBaseURLWithFallback(srServerStore{Path: path}, nil) + if err != nil { + t.Fatal(err) + } + if got != local.URL+"/v1" { + t.Fatalf("base URL = %q, want local proxy %q", got, local.URL+"/v1") + } +} + +func TestBareSRUsesSelectedTeamInsteadOfLegacyRemote(t *testing.T) { + cloud := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet || r.URL.Path != "/api/subrouter/accounts" { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{ + "teamId":"team-a", + "accounts":[{ + "id":"codex-cloud", + "kind":"codex", + "label":"shared@example.com", + "health":{"ok":true} + }] + }`)) + })) + defer cloud.Close() + + path := filepath.Join(t.TempDir(), "cloud.json") + t.Setenv("SUBROUTER_CLOUD_CONFIG", path) + if err := broker.SaveConfig(path, broker.Config{ + BaseURL: cloud.URL, + AccessToken: "stack-access", + RefreshToken: "stack-refresh", + TeamID: "team-a", + TeamName: "Team A", + }); err != nil { + t.Fatal(err) + } + + remoteRequests := atomic.Int32{} + remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + remoteRequests.Add(1) + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/_subrouter/usage-status": + _, _ = w.Write([]byte(`[]`)) + case "/_subrouter/bedrock-cost": + _, _ = w.Write([]byte(`{"requests":0,"throttled":0}`)) + default: + http.NotFound(w, r) + } + })) + defer remote.Close() + + store := accounts.CodexStore{Dir: t.TempDir()} + if err := defaultSRServerStore(store).save(srServerFile{ + Default: "team", + Servers: []srServerConfig{{Name: "team", URL: remote.URL}}, + }); err != nil { + t.Fatal(err) + } + var out bytes.Buffer + runner := srRunner{ + program: "sr", + store: store, + out: &out, + errOut: &out, + client: remote.Client(), + } + if err := runner.run(context.Background(), nil); err != nil { + t.Fatal(err) + } + got := out.String() + if !strings.Contains(got, "Credential storage: team") || + !strings.Contains(got, "Team A") || + !strings.Contains(got, "shared@example.com") { + t.Fatalf("bare sr did not show the selected team vault:\n%s", got) + } + if strings.Contains(got, "Server: team") || remoteRequests.Load() != 0 { + t.Fatalf("bare sr contacted the stale legacy server (%d requests):\n%s", remoteRequests.Load(), got) + } +} + +func TestStorageLocalUsesLocalAccountsInsteadOfCloudOrLegacyRemote(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + path := filepath.Join(t.TempDir(), "cloud.json") + t.Setenv("SUBROUTER_CLOUD_CONFIG", path) + if err := broker.SaveConfig(path, broker.Config{ + BaseURL: "https://cmux.test", + AccessToken: "stack-access", + RefreshToken: "stack-refresh", + TeamID: "team-a", + TeamName: "Team A", + }); err != nil { + t.Fatal(err) + } + + remoteRequests := atomic.Int32{} + remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + remoteRequests.Add(1) + http.Error(w, "legacy remote must not be called", http.StatusInternalServerError) + })) + defer remote.Close() + + store := accounts.CodexStore{Dir: t.TempDir()} + if err := store.SaveStored(accounts.StoredCodexAccount{ + Email: "local@example.com", + AddedAt: time.Now().UTC().Format(time.RFC3339), + Auth: testCodexAuth("local@example.com", "acct_local"), + }); err != nil { + t.Fatal(err) + } + if err := defaultSRServerStore(store).save(srServerFile{ + Default: "team", + Servers: []srServerConfig{{Name: "team", URL: remote.URL}}, + }); err != nil { + t.Fatal(err) + } + + var out bytes.Buffer + runner := srRunner{ + program: "sr", + store: store, + out: &out, + errOut: &out, + client: remote.Client(), + } + if err := runner.run(context.Background(), []string{"storage", "local"}); err != nil { + t.Fatal(err) + } + out.Reset() + if err := runner.run(context.Background(), []string{"list"}); err != nil { + t.Fatal(err) + } + got := out.String() + if !strings.Contains(got, "local@example.com") { + t.Fatalf("local storage did not list the local account:\n%s", got) + } + if strings.Contains(got, "Server: team") || remoteRequests.Load() != 0 { + t.Fatalf("local storage contacted the legacy server (%d requests):\n%s", remoteRequests.Load(), got) + } +} + +func TestRecoveryCommandsSurviveMalformedCloudConfig(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + configPath := filepath.Join(t.TempDir(), "cloud.json") + if err := os.WriteFile(configPath, []byte("{"), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("SUBROUTER_CLOUD_CONFIG", configPath) + local := healthServer(t, http.StatusOK) + t.Setenv("SUBROUTER_LOCAL_BASE_URL", local.URL+"/v1") + + store := accounts.CodexStore{Dir: t.TempDir()} + var out bytes.Buffer + runner := srRunner{ + program: "sr", + store: store, + in: strings.NewReader(""), + out: &out, + errOut: &out, + client: local.Client(), + } + if err := runner.run(context.Background(), []string{"help"}); err != nil { + t.Fatalf("help: %v", err) + } + if !strings.Contains(out.String(), "sr login") { + t.Fatalf("help output missing recovery command:\n%s", out.String()) + } + out.Reset() + if err := runner.run(context.Background(), []string{"cleanup"}); err != nil { + t.Fatalf("cleanup: %v", err) + } + out.Reset() + if err := runner.run(context.Background(), []string{"doctor"}); err == nil { + t.Fatal("doctor unexpectedly passed a malformed config") + } + if !strings.Contains(out.String(), "credential storage") { + t.Fatalf("doctor did not diagnose the malformed config:\n%s", out.String()) + } + out.Reset() + if err := runner.run( + context.Background(), + []string{"storage", "local"}, + ); err != nil { + t.Fatalf("storage local recovery: %v", err) + } + recoveredConfig, err := broker.LoadConfig(configPath) + if err != nil { + t.Fatalf("load recovered config: %v", err) + } + if recoveredConfig.EffectiveCredentialSource() != + broker.CredentialSourceLocal { + t.Fatal("storage local did not replace the malformed config") + } + + if err := os.WriteFile(configPath, []byte("{"), 0o600); err != nil { + t.Fatal(err) + } + config, recovered, err := loadCloudConfigForLogin(configPath) + if err != nil { + t.Fatal(err) + } + if !recovered || config.BaseURL != broker.DefaultBaseURL { + t.Fatalf("login recovery = (%+v, %v), want a fresh default config", config, recovered) + } +} + +func TestTeamProxySkipsMalformedLocalCredentialStores(t *testing.T) { + codexStore := accounts.CodexStore{Dir: t.TempDir()} + accountsDir := filepath.Join(codexStore.StoreDir(), "accounts") + if err := os.MkdirAll(accountsDir, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile( + filepath.Join(accountsDir, "broken.json"), + []byte("{"), + 0o600, + ); err != nil { + t.Fatal(err) + } + claudeStore := agentclaude.Store{Dir: t.TempDir()} + + codexAccounts, claudeAccounts, err := loadProxyAccounts( + context.Background(), + true, + codexStore, + claudeStore, + ) + if err != nil { + t.Fatal(err) + } + if len(codexAccounts) != 0 || len(claudeAccounts) != 0 { + t.Fatalf( + "team proxy loaded local accounts: codex=%d claude=%d", + len(codexAccounts), + len(claudeAccounts), + ) + } +} + +func TestDirectCloudAPIKeyCanBeRepairedWithoutLocalCredential(t *testing.T) { + target := broker.SharedAccount{ + ID: "anthropic-key-a", + Kind: "anthropic-apikey", + Label: "shared production key", + } + var prompts bytes.Buffer + upload, err := replacementUploadForSharedAccount( + &target, + nil, + strings.NewReader("sk-ant-replacement\n"), + &prompts, + ) + if err != nil { + t.Fatal(err) + } + if got := upload["provider"]; got != "anthropic-apikey" { + t.Fatalf("provider = %v", got) + } + if got := upload["label"]; got != target.Label { + t.Fatalf("label = %v, want %q", got, target.Label) + } + if got := upload["apiKey"]; got != "sk-ant-replacement" { + t.Fatalf("api key = %v", got) + } + if strings.Contains(prompts.String(), "sk-ant-replacement") { + t.Fatal("replacement credential was echoed to output") + } +} + +func TestCloudClaudeEnvironmentRoutesLocallyWithoutProviderSecrets(t *testing.T) { + env := cloudClaudeEnvironment([]string{ + "PATH=/usr/bin", + "ANTHROPIC_BASE_URL=https://remote.example", + "ANTHROPIC_AUTH_TOKEN=old-token", + "ANTHROPIC_API_KEY=sk-ant-secret", + "CLAUDE_CODE_USE_BEDROCK=1", + }, "http://127.0.0.1:31415/v1", "stack-local-token") + joined := strings.Join(env, "\n") + for _, banned := range []string{ + "https://remote.example", + "old-token", + "sk-ant-secret", + "CLAUDE_CODE_USE_BEDROCK", + } { + if strings.Contains(joined, banned) { + t.Fatalf("cloud Claude env retained %q:\n%s", banned, joined) + } + } + for _, want := range []string{ + "ANTHROPIC_BASE_URL=http://127.0.0.1:31415", + "ANTHROPIC_AUTH_TOKEN=stack-local-token", + } { + if !strings.Contains(joined, want) { + t.Fatalf("cloud Claude env missing %q:\n%s", want, joined) + } + } +} + +func TestCloudCodexUsesAuthenticatedLocalProvider(t *testing.T) { + args := codexArgsWithLocalProxyToken( + []string{"exec", "hello"}, + "http://127.0.0.1:31415/v1", + "", + "", + "stack-local-token", + ) + joined := strings.Join(args, "\n") + for _, want := range []string{ + `model_provider="subrouter"`, + `model_providers.subrouter.env_key="SUBROUTER_CODEX_DUMMY_API_KEY"`, + } { + if !strings.Contains(joined, want) { + t.Fatalf("cloud Codex args missing %q:\n%s", want, joined) + } + } +} + +func TestUserSystemdUnitIsLoopbackAndCloudConfigured(t *testing.T) { + t.Setenv( + "SUBROUTER_CLOUD_CONFIG", + "/home/alice/private/subrouter-team.json", + ) + unit, err := renderUserSystemdUnit( + "/home/alice", + "/home/alice/.local/bin/subrouter", + ) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{ + "--addr 127.0.0.1:31415", + `--cloud-config "/home/alice/private/subrouter-team.json"`, + `BindReadOnlyPaths="/home/alice/private/subrouter-team.json"`, + "ProtectHome=read-only", + `"-/home/alice/.codex-accounts"`, + "UMask=0077", + } { + if !strings.Contains(unit, want) { + t.Fatalf("unit missing %q:\n%s", want, unit) + } + } + if strings.Contains(unit, "0.0.0.0") { + t.Fatalf("user daemon must not bind publicly:\n%s", unit) + } +} + +func TestUserSystemdUnitQuotesPathsWithSystemdSpecialCharacters(t *testing.T) { + home := `/home/Alice % "Ops"\station` + configPath := home + `/private/team config.json` + t.Setenv("SUBROUTER_CLOUD_CONFIG", configPath) + + unit, err := renderUserSystemdUnit( + home, + home+`/.local/bin/subrouter`, + ) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{ + `Environment="HOME=/home/Alice %% \"Ops\"\\station"`, + `ExecStart="/home/Alice %% \"Ops\"\\station/.local/bin/subrouter" serve`, + `--cloud-config "/home/Alice %% \"Ops\"\\station/private/team config.json"`, + `ReadWritePaths="/home/Alice %% \"Ops\"\\station/.subrouter"`, + `BindReadOnlyPaths="/home/Alice %% \"Ops\"\\station/private/team config.json"`, + } { + if !strings.Contains(unit, want) { + t.Fatalf("unit missing quoted path %q:\n%s", want, unit) + } + } +} + +func TestLocalAccountUploadsPreserveSupportedAPIKeyProviders(t *testing.T) { + stateDir := t.TempDir() + t.Setenv("SUBROUTER_STATE_DIR", stateDir) + store := accounts.CodexStore{Dir: filepath.Join(stateDir, "codex", "accounts")} + for _, account := range []accounts.StoredCodexAccount{ + { + Email: "apikey:openai", + Provider: accounts.ProviderCodex, + Auth: accounts.CodexAuthFile{ + AuthMode: "apikey", + OpenAIAPIKey: "sk-openai", + }, + }, + { + Email: "claude:anthropic", + Provider: accounts.ProviderClaude, + Auth: accounts.CodexAuthFile{ + AuthMode: "apikey", + OpenAIAPIKey: "sk-ant-anthropic", + }, + }, + { + Email: "kimi:unsupported", + Provider: accounts.ProviderKimi, + Auth: accounts.CodexAuthFile{ + AuthMode: "apikey", + OpenAIAPIKey: "sk-kimi", + }, + }, + { + Email: "zai:unsupported", + Provider: accounts.ProviderZAI, + Auth: accounts.CodexAuthFile{ + AuthMode: "apikey", + OpenAIAPIKey: "sk-zai", + }, + }, + } { + if err := store.SaveStored(account); err != nil { + t.Fatal(err) + } + } + + uploads, err := localAccountUploads(context.Background(), store) + if err != nil { + t.Fatal(err) + } + if len(uploads) != 2 { + t.Fatalf("upload count = %d, want 2 supported providers", len(uploads)) + } + providers := map[string]string{} + for _, upload := range uploads { + providers[upload.label], _ = upload.body["provider"].(string) + } + if providers["apikey:openai"] != "openai-apikey" { + t.Fatalf("OpenAI provider = %q", providers["apikey:openai"]) + } + if providers["claude:anthropic"] != "anthropic-apikey" { + t.Fatalf("Anthropic provider = %q", providers["claude:anthropic"]) + } +} + +func TestMatchCloudTeamPrefersExactIDAndRejectsAmbiguousOrUnusableNames( + t *testing.T, +) { + teams := []broker.Team{ + {ID: "other", Name: "team-id", Use: true}, + {ID: "team-id", Name: "Exact ID", Use: true}, + } + matched, err := matchCloudTeam(teams, "team-id") + if err != nil { + t.Fatal(err) + } + if matched.ID != "team-id" { + t.Fatalf("matched %q, want exact ID", matched.ID) + } + + if _, err := matchCloudTeam([]broker.Team{ + {ID: "a", Name: "Duplicate", Use: true}, + {ID: "b", Name: "Duplicate", Use: true}, + }, "Duplicate"); err == nil { + t.Fatal("duplicate exact team names must be ambiguous") + } + if _, err := matchCloudTeam([]broker.Team{ + {ID: "blocked", Name: "Blocked", ManageAccounts: true}, + }, "blocked"); err == nil { + t.Fatal("team without subrouter use permission was selected") + } +} + +func TestCloudModeConfigMissingIsLegacyMode(t *testing.T) { + t.Setenv("SUBROUTER_CLOUD_CONFIG", filepath.Join(t.TempDir(), "missing.json")) + config, err := cloudModeConfig() + if err != nil { + t.Fatal(err) + } + if config.Ready() { + t.Fatalf("missing config unexpectedly enabled cloud mode: %+v", config) + } +} + +func TestSelectLocalAccountUploadRequiresOneExactCanary(t *testing.T) { + uploads := []localAccountUpload{ + {kind: "codex", label: "alice@example.com"}, + {kind: "claude", label: "alice@example.com"}, + {kind: "codex", label: "bob@example.com"}, + } + + selected, err := selectLocalAccountUpload(uploads, "codex:alice@example.com") + if err != nil { + t.Fatal(err) + } + if len(selected) != 1 || + selected[0].kind != "codex" || + selected[0].label != "alice@example.com" { + t.Fatalf("selected = %+v", selected) + } + + if _, err := selectLocalAccountUpload(uploads, "alice@example.com"); err == nil { + t.Fatal("same-label accounts across providers must be ambiguous") + } + if _, err := selectLocalAccountUpload(uploads, "missing"); err == nil { + t.Fatal("missing selector unexpectedly matched an account") + } +} + +func TestBulkAccountImportRequiresExplicitConfirmation(t *testing.T) { + var uploads atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodGet && r.URL.Path == "/api/subrouter/accounts": + _, _ = w.Write([]byte(`{"accounts":[]}`)) + case r.Method == http.MethodPost && r.URL.Path == "/api/subrouter/accounts": + uploads.Add(1) + _, _ = w.Write([]byte( + `{"account":{"id":"acct-1","kind":"openai-apikey","label":"paid"}}`, + )) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + + store := accounts.CodexStore{Dir: t.TempDir()} + if _, _, err := store.AddAPIKey("paid", "sk-test-paid"); err != nil { + t.Fatal(err) + } + client := broker.NewClient(broker.Config{ + BaseURL: server.URL, + AccessToken: "stack-access", + RefreshToken: "stack-refresh", + TeamID: "team-a", + }) + var out bytes.Buffer + runner := srRunner{store: store, out: &out, errOut: &out} + + err := runner.cloudAccountImport( + context.Background(), + client, + []string{"--all"}, + ) + if err == nil || !strings.Contains(err.Error(), "--yes") { + t.Fatalf("bulk import error = %v, want --yes requirement", err) + } + if uploads.Load() != 0 { + t.Fatalf("bulk import uploaded %d accounts without confirmation", uploads.Load()) + } +} diff --git a/cmd/subrouter/codex.go b/cmd/subrouter/codex.go index 001c52ad1..eac7e2138 100644 --- a/cmd/subrouter/codex.go +++ b/cmd/subrouter/codex.go @@ -3,22 +3,29 @@ package main import ( "context" "fmt" + "io" "os" "os/exec" "strconv" "strings" "github.com/manaflow-ai/subrouter/internal/accounts" + "github.com/manaflow-ai/subrouter/internal/broker" "github.com/manaflow-ai/subrouter/session" ) const defaultCodexBaseURL = "http://127.0.0.1:31415/v1" func codex(args []string) error { - baseURL, err := codexBaseURL(defaultSRServerStore(accounts.DefaultCodexStore())) + baseURL, err := codexBaseURLWithFallback(defaultSRServerStore(accounts.DefaultCodexStore()), os.Stderr) if err != nil { return err } + cloudConfig, err := cloudModeConfig() + if err != nil { + return err + } + localProxyToken := cloudClientProxyToken(cloudConfig, baseURL) bin := envOrDefault("SUBROUTER_CODEX_BIN", "codex") userEmailRaw := os.Getenv("SUBROUTER_CODEX_USER_EMAIL") accountID := session.NormalizeAccountID(os.Getenv("SUBROUTER_CODEX_ACCOUNT_ID")) @@ -30,12 +37,28 @@ func codex(args []string) error { } } - cmd := exec.CommandContext(context.Background(), bin, codexArgs(args, baseURL, userEmail, accountID)...) + cmd := exec.CommandContext( + context.Background(), + bin, + codexArgsWithLocalProxyToken( + args, + baseURL, + userEmail, + accountID, + localProxyToken, + )..., + ) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr env := os.Environ() - if userEmail != "" || accountID != "" || codexModelArg(args) != "" { + if localProxyToken != "" { + env = upsertEnv( + env, + "SUBROUTER_CODEX_DUMMY_API_KEY", + localProxyToken, + ) + } else if userEmail != "" || accountID != "" || codexModelArg(args) != "" { env = upsertEnv(env, "SUBROUTER_CODEX_DUMMY_API_KEY", "subrouter") } cmd.Env = env @@ -67,6 +90,78 @@ func defaultCodexBaseURLFor(store srServerStore) (string, error) { return codexBaseURLForServer(server), nil } +// codexBaseURLWithFallback resolves the base URL for launching codex, then +// substitutes the local daemon when the configured server is unreachable. An +// explicit SUBROUTER_CODEX_BASE_URL or SUBROUTER_CODEX_SERVER is treated as a +// deliberate pin and is never overridden. +func codexBaseURLWithFallback(store srServerStore, warn io.Writer) (string, error) { + config, err := cloudModeConfig() + if err != nil { + return "", fmt.Errorf("load cmux.com login: %w", err) + } + source := config.EffectiveCredentialSource() + if source == broker.CredentialSourceTeam && !config.Ready() { + return "", fmt.Errorf("team credential storage requires login and a selected team; run '%s login'", programBase()) + } + if source == broker.CredentialSourceTeam || + source == broker.CredentialSourceLocal { + local := localBaseURL() + if strings.TrimSpace(os.Getenv("SUBROUTER_CODEX_BASE_URL")) != "" || + strings.TrimSpace(os.Getenv("SUBROUTER_CODEX_SERVER")) != "" { + pinned, pinErr := codexBaseURL(store) + if pinErr != nil { + return "", pinErr + } + if source == broker.CredentialSourceTeam && + !sameEndpoint(pinned, local) { + return "", fmt.Errorf( + "team credentials may only be sent through the local daemon at %s; unset SUBROUTER_CODEX_BASE_URL and SUBROUTER_CODEX_SERVER", + local, + ) + } + if source == broker.CredentialSourceLocal && + !sameEndpoint(pinned, local) { + return pinned, nil + } + } + if !ensureLocalHealthy( + context.Background(), + fallbackHTTPClient(), + local, + defaultDaemonStarter(), + warn, + ) { + return "", fmt.Errorf("local proxy is unavailable; run '%s doctor'", programBase()) + } + return local, nil + } + + baseURL, err := codexBaseURL(store) + if err != nil { + return "", err + } + if strings.TrimSpace(os.Getenv("SUBROUTER_CODEX_BASE_URL")) != "" || + strings.TrimSpace(os.Getenv("SUBROUTER_CODEX_SERVER")) != "" { + // A legacy pin is never substituted, but a local pin is still repaired. + local := localBaseURL() + if sameEndpoint(baseURL, local) && + !ensureLocalHealthy( + context.Background(), + fallbackHTTPClient(), + local, + defaultDaemonStarter(), + warn, + ) { + return "", fmt.Errorf( + "local proxy is unavailable; run '%s doctor'", + programBase(), + ) + } + return baseURL, nil + } + return withLocalFallback(context.Background(), fallbackHTTPClient(), baseURL, warn), nil +} + func codexBaseURLForNamedServer(store srServerStore, name string) (string, error) { if name == "local" || name == "localhost" { return defaultCodexBaseURL, nil @@ -90,8 +185,30 @@ func codexBaseURLForServer(server srServerConfig) string { } func codexArgs(args []string, baseURL, userEmail, accountID string) []string { + return codexArgsWithLocalProxyToken( + args, + baseURL, + userEmail, + accountID, + "", + ) +} + +func codexArgsWithLocalProxyToken( + args []string, + baseURL string, + userEmail string, + accountID string, + localProxyToken string, +) []string { model := codexModelArg(args) - configArgs := codexConfigArgs(baseURL, userEmail, accountID, model) + configArgs := codexConfigArgs( + baseURL, + userEmail, + accountID, + model, + localProxyToken != "", + ) if len(args) == 0 || strings.HasPrefix(args[0], "-") || !isKnownCodexCommand(args[0]) { return append(configArgs, args...) } @@ -104,8 +221,17 @@ func codexArgs(args []string, baseURL, userEmail, accountID string) []string { return out } -func codexConfigArgs(baseURL, userEmail, accountID, model string) []string { - if userEmail == "" && accountID == "" && model == "" { +func codexConfigArgs( + baseURL string, + userEmail string, + accountID string, + model string, + forceAuthenticatedProvider bool, +) []string { + if !forceAuthenticatedProvider && + userEmail == "" && + accountID == "" && + model == "" { return []string{"-c", "openai_base_url=" + strconv.Quote(baseURL)} } return []string{ diff --git a/cmd/subrouter/install_daemon.go b/cmd/subrouter/install_daemon.go index d0b36162c..5eb40f6a1 100644 --- a/cmd/subrouter/install_daemon.go +++ b/cmd/subrouter/install_daemon.go @@ -288,7 +288,26 @@ func defaultDaemonPath(installPath string) string { }, ":") } +func daemonCloudConfigPath(home string) (string, error) { + path := strings.TrimSpace(os.Getenv("SUBROUTER_CLOUD_CONFIG")) + if path == "" { + path = filepath.Join(home, ".config", "subrouter", "cloud.json") + } + if filepath.IsAbs(path) { + return filepath.Clean(path), nil + } + absolute, err := filepath.Abs(path) + if err != nil { + return "", fmt.Errorf("resolve cloud config path: %w", err) + } + return absolute, nil +} + func launchAgentPlist(config daemonConfig, home string) (string, error) { + cloudConfigPath, err := daemonCloudConfigPath(home) + if err != nil { + return "", err + } data := struct { Label string Home string @@ -301,6 +320,7 @@ func launchAgentPlist(config daemonConfig, home string) (string, error) { LogPath string ErrorLogPath string WorkingDirectory string + CloudConfigPath string }{ Label: escapeXMLString(config.Label), Home: escapeXMLString(home), @@ -313,6 +333,7 @@ func launchAgentPlist(config daemonConfig, home string) (string, error) { LogPath: escapeXMLString(filepath.Join(config.LogDir, "subrouter.log")), ErrorLogPath: escapeXMLString(filepath.Join(config.LogDir, "subrouter.err.log")), WorkingDirectory: escapeXMLString(config.WorkingDirectory), + CloudConfigPath: escapeXMLString(cloudConfigPath), } var out bytes.Buffer @@ -349,6 +370,8 @@ var launchAgentTemplate = template.Must(template.New("launch-agent").Parse(`serve --addr {{.Addr}} + --cloud-config + {{.CloudConfigPath}} {{if .HasTranscripts}}--transcripts {{.TranscriptsDir}} {{end}}--sr-switch-interval diff --git a/cmd/subrouter/install_daemon_test.go b/cmd/subrouter/install_daemon_test.go index 1c7c3f435..6aa84a259 100644 --- a/cmd/subrouter/install_daemon_test.go +++ b/cmd/subrouter/install_daemon_test.go @@ -9,6 +9,10 @@ import ( func TestLaunchAgentPlistUsesMacOSLocalDefaults(t *testing.T) { home := "/Users/alice" + t.Setenv( + "SUBROUTER_CLOUD_CONFIG", + "/Users/alice/private/subrouter-team.json", + ) config := daemonConfig{ Label: defaultDaemonLabel, Addr: "127.0.0.1:31415", @@ -30,6 +34,8 @@ func TestLaunchAgentPlistUsesMacOSLocalDefaults(t *testing.T) { "127.0.0.1:31415", "--sr-switch-interval", "10m", + "--cloud-config", + "/Users/alice/private/subrouter-team.json", "/Users/alice/fun/subrouter", } { if !strings.Contains(plist, want) { diff --git a/cmd/subrouter/install_systemd_test.go b/cmd/subrouter/install_systemd_test.go index ffb59922e..9bc1e367c 100644 --- a/cmd/subrouter/install_systemd_test.go +++ b/cmd/subrouter/install_systemd_test.go @@ -162,3 +162,21 @@ func TestReadDefaultValueUnquotesEnvFileValue(t *testing.T) { t.Fatalf("extra args = %q, want %q", got, want) } } + +func TestUserSystemdRefusesExistingSystemService(t *testing.T) { + dir := t.TempDir() + unitPath := filepath.Join(dir, "subrouter.service") + socketPath := filepath.Join(dir, "subrouter.socket") + if err := refuseSystemSystemdConflict(unitPath, socketPath); err != nil { + t.Fatalf("missing system service reported a conflict: %v", err) + } + if err := os.WriteFile(socketPath, []byte("[Socket]\n"), 0o600); err != nil { + t.Fatal(err) + } + err := refuseSystemSystemdConflict(unitPath, socketPath) + if err == nil || + !strings.Contains(err.Error(), "system-wide") || + !strings.Contains(err.Error(), "systemctl disable --now") { + t.Fatalf("conflict error = %v", err) + } +} diff --git a/cmd/subrouter/install_systemd_user.go b/cmd/subrouter/install_systemd_user.go new file mode 100644 index 000000000..b68b3c344 --- /dev/null +++ b/cmd/subrouter/install_systemd_user.go @@ -0,0 +1,178 @@ +package main + +import ( + "bytes" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "text/template" +) + +func userSystemdUnitPath(home, service string) string { + return filepath.Join(home, ".config", "systemd", "user", service+".service") +} + +func installUserSystemd( + home string, + runner commandRunner, + out io.Writer, +) error { + systemConfig := systemdConfig{ServiceName: defaultSystemdServiceName} + if err := refuseSystemSystemdConflict( + systemdUnitPath(systemConfig), + systemdSocketPath(systemConfig), + ); err != nil { + return err + } + binDir := filepath.Join(home, ".local", "bin") + installPath := filepath.Join(binDir, "subrouter") + configDir := filepath.Join(home, ".config", "subrouter") + stateDir := filepath.Join(home, ".subrouter") + unitPath := userSystemdUnitPath(home, defaultSystemdServiceName) + for _, dir := range []string{ + binDir, + configDir, + stateDir, + filepath.Dir(unitPath), + } { + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + } + if err := installCurrentExecutable(installPath); err != nil { + return err + } + for _, alias := range []string{"sr", "cx"} { + if err := installBinaryAlias( + installPath, + filepath.Join(binDir, alias), + ); err != nil { + return err + } + } + + unit, err := renderUserSystemdUnit(home, installPath) + if err != nil { + return err + } + if err := os.WriteFile(unitPath, []byte(unit), 0o600); err != nil { + return err + } + if err := runner.Run("systemctl", "--user", "daemon-reload"); err != nil { + return err + } + if err := runner.Run( + "systemctl", + "--user", + "enable", + "--now", + defaultSystemdServiceName, + ); err != nil { + return err + } + fmt.Fprintf(out, "Installed %s\n", installPath) + fmt.Fprintf(out, "Installed %s\n", unitPath) + fmt.Fprintf(out, "Started %s.service (user)\n", defaultSystemdServiceName) + return nil +} + +func renderUserSystemdUnit(home, installPath string) (string, error) { + configPath, err := daemonCloudConfigPath(home) + if err != nil { + return "", err + } + data := struct { + HomeEnvironment string + InstallPath string + ConfigPath string + StateDir string + ConfigDir string + CodexAccountsDir string + }{ + HomeEnvironment: systemdQuote("HOME=" + home), + InstallPath: systemdQuote(installPath), + ConfigPath: systemdQuote(configPath), + StateDir: systemdQuote(filepath.Join(home, ".subrouter")), + ConfigDir: systemdQuote(filepath.Join(home, ".config", "subrouter")), + CodexAccountsDir: systemdQuote("-" + filepath.Join(home, ".codex-accounts")), + } + var out bytes.Buffer + if err := userSystemdTemplate.Execute(&out, data); err != nil { + return "", err + } + return out.String(), nil +} + +func systemdQuote(value string) string { + var quoted strings.Builder + quoted.Grow(len(value) + 2) + quoted.WriteByte('"') + for _, character := range value { + switch character { + case '\\': + quoted.WriteString(`\\`) + case '"': + quoted.WriteString(`\"`) + case '%': + // Percent introduces a systemd specifier even inside quotes. + quoted.WriteString("%%") + case '\n': + quoted.WriteString(`\n`) + case '\r': + quoted.WriteString(`\r`) + case '\t': + quoted.WriteString(`\t`) + default: + quoted.WriteRune(character) + } + } + quoted.WriteByte('"') + return quoted.String() +} + +func refuseSystemSystemdConflict(unitPath, socketPath string) error { + var found []string + for _, path := range []string{unitPath, socketPath} { + if _, err := os.Stat(path); err == nil { + found = append(found, path) + } else if !os.IsNotExist(err) { + return fmt.Errorf("inspect existing system service %s: %w", path, err) + } + } + if len(found) == 0 { + return nil + } + return fmt.Errorf( + "existing system-wide Subrouter service conflicts with the per-user daemon (%s); run 'sudo systemctl disable --now subrouter.service subrouter.socket', remove or migrate the old units, then rerun 'sr setup'", + strings.Join(found, ", "), + ) +} + +var userSystemdTemplate = template.Must(template.New("systemd-user").Parse(`[Unit] +Description=Subrouter local credential proxy +After=network-online.target +Wants=network-online.target +StartLimitIntervalSec=60 +StartLimitBurst=5 + +[Service] +Type=simple +Environment={{.HomeEnvironment}} +ExecStart={{.InstallPath}} serve --addr 127.0.0.1:31415 --cloud-config {{.ConfigPath}} --sr-switch-interval 0 +Restart=on-failure +RestartSec=3 +TimeoutStopSec=10min +UMask=0077 +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=strict +ProtectHome=read-only +ReadWritePaths={{.StateDir}} {{.ConfigDir}} {{.CodexAccountsDir}} +BindReadOnlyPaths={{.ConfigPath}} +RestrictSUIDSGID=true + +[Install] +WantedBy=default.target +`)) diff --git a/cmd/subrouter/lifecycle.go b/cmd/subrouter/lifecycle.go new file mode 100644 index 000000000..6c1c919cf --- /dev/null +++ b/cmd/subrouter/lifecycle.go @@ -0,0 +1,269 @@ +package main + +import ( + "context" + "fmt" + "io" + "os" + "runtime" + "strings" + + "github.com/manaflow-ai/subrouter/internal/accounts" + "github.com/manaflow-ai/subrouter/internal/broker" +) + +// serviceController starts, stops and inspects the installed local daemon. The +// two implementations wrap launchd and systemd rather than managing processes +// directly, so `sr up` and a reboot converge on the same supervised state. +type serviceController interface { + start() error + stop() error + restart() error + // installed reports whether a unit or agent exists to act on. + installed() bool + // remove deletes the unit or agent definition after stopping it. + remove() error + // describe names the managed unit for user-facing messages. + describe() string +} + +// launchdController manages the per-user LaunchAgent written by install-daemon. +type launchdController struct { + label string + home string + runner commandRunner +} + +func (c launchdController) plist() string { return launchAgentPath(c.home, c.label) } + +func (c launchdController) installed() bool { + _, err := os.Stat(c.plist()) + return err == nil +} + +func (c launchdController) describe() string { return c.label } + +func (c launchdController) domain() string { + return fmt.Sprintf("gui/%d", os.Getuid()) +} + +func (c launchdController) start() error { + if err := c.runner.Run("launchctl", "bootstrap", c.domain(), c.plist()); err != nil { + // Already bootstrapped is not a failure; kickstart still brings it up. + return c.runner.Run("launchctl", "kickstart", "-k", c.domain()+"/"+c.label) + } + return nil +} + +func (c launchdController) stop() error { + return c.runner.Run("launchctl", "bootout", c.domain(), c.plist()) +} + +func (c launchdController) restart() error { + return restartLaunchAgent(c.plist(), c.label, c.runner) +} + +func (c launchdController) remove() error { + _ = c.runner.Run("launchctl", "bootout", c.domain(), c.plist()) + if err := os.Remove(c.plist()); err != nil && !os.IsNotExist(err) { + return err + } + return nil +} + +// systemdController manages the system service written by install-systemd. +type systemdController struct { + service string + home string + runner commandRunner +} + +func (c systemdController) userUnit() string { + return userSystemdUnitPath(c.home, c.service) +} + +func (c systemdController) userInstalled() bool { + _, err := os.Stat(c.userUnit()) + return err == nil +} + +func (c systemdController) systemInstalled() bool { + _, err := os.Stat(systemdUnitPath(systemdConfig{ServiceName: c.service})) + return err == nil +} + +func (c systemdController) installed() bool { + return c.userInstalled() || c.systemInstalled() +} + +func (c systemdController) describe() string { + if c.userInstalled() { + return c.service + ".service (user)" + } + return c.service + ".service" +} + +func (c systemdController) run(args ...string) error { + if c.userInstalled() { + args = append([]string{"--user"}, args...) + } + return c.runner.Run("systemctl", args...) +} + +func (c systemdController) start() error { + return c.run("start", c.service) +} + +func (c systemdController) stop() error { + return c.run("stop", c.service) +} + +func (c systemdController) restart() error { + return c.run("restart", c.service) +} + +func (c systemdController) remove() error { + userUnit := c.userInstalled() + run := func(args ...string) error { + if userUnit { + args = append([]string{"--user"}, args...) + } + return c.runner.Run("systemctl", args...) + } + _ = run("disable", "--now", c.service) + unit := systemdUnitPath(systemdConfig{ServiceName: c.service}) + if userUnit { + unit = c.userUnit() + } + if err := os.Remove(unit); err != nil && !os.IsNotExist(err) { + return err + } + return run("daemon-reload") +} + +// newServiceController picks the supervisor for the running OS. +func newServiceController() (serviceController, error) { + switch runtime.GOOS { + case "darwin": + home, err := os.UserHomeDir() + if err != nil { + return nil, err + } + return launchdController{label: defaultDaemonLabel, home: home, runner: commandRunner{}}, nil + case "linux": + home, err := os.UserHomeDir() + if err != nil { + return nil, err + } + return systemdController{ + service: defaultSystemdServiceName, + home: home, + runner: commandRunner{}, + }, nil + default: + return nil, fmt.Errorf("managing the local daemon is not supported on %s", runtime.GOOS) + } +} + +// runServerLifecycle implements `sr up`, `sr down` and `sr restart`. +func runServerLifecycle(action string, out io.Writer) error { + controller, err := newServiceController() + if err != nil { + return err + } + waitForReady := func() bool { + return waitForHealth(context.Background(), localBaseURL(), autostartTimeout) + } + return runServerLifecycleWith(controller, action, waitForReady, out) +} + +// runServerLifecycleWith performs a lifecycle action and waits for the local +// health endpoint before reporting a successful start or restart. +func runServerLifecycleWith( + controller serviceController, + action string, + waitForReady func() bool, + out io.Writer, +) error { + if !controller.installed() { + return fmt.Errorf("no local Subrouter daemon installed; run '%s setup' first", programBase()) + } + switch action { + case "up", "start": + if err := controller.start(); err != nil { + return fmt.Errorf("start %s: %w", controller.describe(), err) + } + if waitForReady != nil && !waitForReady() { + return fmt.Errorf("start %s: daemon did not become healthy", controller.describe()) + } + fmt.Fprintf(out, "started %s\n", controller.describe()) + case "down", "stop": + if err := controller.stop(); err != nil { + return fmt.Errorf("stop %s: %w", controller.describe(), err) + } + fmt.Fprintf(out, "stopped %s\n", controller.describe()) + case "restart": + if err := controller.restart(); err != nil { + return fmt.Errorf("restart %s: %w", controller.describe(), err) + } + if waitForReady != nil && !waitForReady() { + return fmt.Errorf("restart %s: daemon did not become healthy", controller.describe()) + } + fmt.Fprintf(out, "restarted %s\n", controller.describe()) + default: + return fmt.Errorf("unknown server action %q", action) + } + return nil +} + +// runServerHealth implements `sr up --check` style reporting: it prints whether +// the configured server and the local daemon each answer their health probe, so +// an operator can tell a routing problem from a dead host without curl. +func runServerHealth(ctx context.Context, out io.Writer) error { + client := fallbackHTTPClient() + local := localBaseURL() + fmt.Fprintf(out, "%-40s %s\n", local, healthLabel(serverHealthy(ctx, client, local))) + + configured, err := defaultCodexBaseURLForHealth() + if err != nil { + return err + } + if configured != "" && !sameEndpoint(configured, local) { + fmt.Fprintf(out, "%-40s %s\n", configured, healthLabel(serverHealthy(ctx, client, configured))) + } + return nil +} + +func healthLabel(ok bool) string { + if ok { + return "healthy" + } + return "UNREACHABLE" +} + +// defaultCodexBaseURLForHealth resolves the configured server without applying +// fallback, so the health report shows what is configured rather than what a +// probe would substitute. +func defaultCodexBaseURLForHealth() (string, error) { + config, err := cloudModeConfig() + if err != nil { + return "", err + } + if config.EffectiveCredentialSource() == broker.CredentialSourceTeam || + config.EffectiveCredentialSource() == broker.CredentialSourceLocal { + return localBaseURL(), nil + } + store := defaultSRServerStore(accounts.DefaultCodexStore()) + file, err := store.load() + if err != nil { + return "", err + } + if strings.TrimSpace(file.Default) == "" { + return "", nil + } + server, ok := file.find(file.Default) + if !ok { + return "", nil + } + return codexBaseURLForServer(server), nil +} diff --git a/cmd/subrouter/lifecycle_test.go b/cmd/subrouter/lifecycle_test.go new file mode 100644 index 000000000..9c94a4538 --- /dev/null +++ b/cmd/subrouter/lifecycle_test.go @@ -0,0 +1,42 @@ +package main + +import ( + "bytes" + "testing" +) + +type lifecycleController struct { + restarted bool +} + +func (c *lifecycleController) start() error { return nil } +func (c *lifecycleController) stop() error { return nil } +func (c *lifecycleController) restart() error { c.restarted = true; return nil } +func (c *lifecycleController) installed() bool { return true } +func (c *lifecycleController) remove() error { return nil } +func (c *lifecycleController) describe() string { + return "fake.daemon" +} + +func TestRestartWaitsForDaemonHealthBeforeReportingSuccess(t *testing.T) { + controller := &lifecycleController{} + healthChecks := 0 + var out bytes.Buffer + waitForReady := func() bool { + if out.Len() != 0 { + t.Fatal("success reported before readiness check") + } + healthChecks++ + return controller.restarted + } + + if err := runServerLifecycleWith(controller, "restart", waitForReady, &out); err != nil { + t.Fatal(err) + } + if healthChecks != 1 { + t.Fatalf("health checks = %d, want 1", healthChecks) + } + if got := out.String(); got != "restarted fake.daemon\n" { + t.Fatalf("output = %q", got) + } +} diff --git a/cmd/subrouter/main.go b/cmd/subrouter/main.go index 7318c831f..ee4837f02 100644 --- a/cmd/subrouter/main.go +++ b/cmd/subrouter/main.go @@ -25,11 +25,12 @@ import ( awsconfig "github.com/aws/aws-sdk-go-v2/config" "github.com/manaflow-ai/subrouter/internal/accounts" agentclaude "github.com/manaflow-ai/subrouter/internal/agents/claude" + "github.com/manaflow-ai/subrouter/internal/broker" "github.com/manaflow-ai/subrouter/internal/proxy" - "github.com/manaflow-ai/subrouter/selectacct" - "github.com/manaflow-ai/subrouter/session" "github.com/manaflow-ai/subrouter/internal/storepath" "github.com/manaflow-ai/subrouter/internal/transcript" + "github.com/manaflow-ai/subrouter/selectacct" + "github.com/manaflow-ai/subrouter/session" ) func main() { @@ -96,6 +97,10 @@ func runForProgram(program string, args []string) error { usage(program) return nil } + if program == "sr" && + (isDirectSRCommand(args[0]) || strings.Contains(args[0], "@")) { + return srForProgram(program, args) + } switch args[0] { case "serve": @@ -129,12 +134,17 @@ var directSRCommands = map[string]struct{}{ "add-api-key": {}, "add-key": {}, "admin-keys": {}, + "account": {}, + "accounts": {}, "attach-project": {}, "breadcrumbs": {}, "claude": {}, "claude-aws": {}, "claude-direct": {}, + "cleanup": {}, "cost": {}, + "daemon": {}, + "doctor": {}, "g": {}, "gemini": {}, "gui": {}, @@ -145,6 +155,7 @@ var directSRCommands = map[string]struct{}{ "list-admin-keys": {}, "login": {}, "ls": {}, + "logout": {}, "pick": {}, "remove": {}, "remove-admin-key": {}, @@ -152,9 +163,12 @@ var directSRCommands = map[string]struct{}{ "rm": {}, "server": {}, "servers": {}, + "setup": {}, "spend": {}, "status": {}, + "storage": {}, "switch": {}, + "team": {}, "trace": {}, "usage": {}, "use": {}, @@ -196,6 +210,7 @@ func serve(args []string) error { bedrockProfiles := flags.String("bedrock-profiles", "", "comma-separated AWS profiles for the Bedrock gateway; defaults to SUBROUTER_BEDROCK_PROFILES or discovered awN profiles") bedrockAutoBump := flags.Bool("bedrock-autobump", false, "request a Service Quotas increase (2x, deduped) when Bedrock throttles Fable/Opus") fableBedrockPrimary := flags.Bool("fable-bedrock-primary", false, "route Claude Fable to Bedrock first (before the subscription pool); defaults to SUBROUTER_FABLE_BEDROCK_PRIMARY") + cloudConfigPath := flags.String("cloud-config", "", "cmux.com team credential config; defaults to ~/.config/subrouter/cloud.json") if err := flags.Parse(args); err != nil { return err } @@ -239,21 +254,54 @@ func serve(args []string) error { return err } + cloudConfig, err := broker.LoadConfig(*cloudConfigPath) + if err != nil { + return fmt.Errorf("load cmux.com config: %w", err) + } + if cloudConfig.EffectiveCredentialSource() == broker.CredentialSourceTeam && + cloudConfig.LoggedIn() && + cloudConfig.TeamID == "" { + return errors.New("cmux.com login has no selected team; run 'sr team use '") + } + if cloudConfig.EffectiveCredentialSource() == broker.CredentialSourceTeam && + !cloudConfig.Ready() { + return errors.New("team credential storage requires login and a selected team; run 'sr login'") + } + if cloudConfig.TeamModeReady() && + strings.TrimSpace(cloudConfig.LocalProxyToken) == "" { + return errors.New("team credential storage has no local proxy secret; run 'sr setup' to repair it") + } + fableAPIKey := strings.TrimSpace( + os.Getenv("SUBROUTER_CLAUDE_FABLE_API_KEY"), + ) + fableBedrockEnabled := *fableBedrockPrimary || + envTrue("SUBROUTER_FABLE_BEDROCK_PRIMARY") + if cloudConfig.TeamModeReady() && + (*bedrockEnable || fableAPIKey != "" || fableBedrockEnabled) { + return errors.New( + "team credential storage cannot use local Bedrock or personal Fable credential fallback; remove the Bedrock/Fable options or run 'sr storage local'", + ) + } + var credentialBroker *broker.Client + if cloudConfig.TeamModeReady() { + credentialBroker = broker.NewClient(cloudConfig) + } + store, err := session.NewStore(*sessionPath) if err != nil { return err } codexStore := accounts.DefaultCodexStore() - codexAccounts, err := codexStore.List() + codexAccounts, claudeAccounts, err := loadProxyAccounts( + context.Background(), + credentialBroker != nil, + codexStore, + agentclaude.DefaultStore(), + ) if err != nil { return err } - claudeAccounts, err := agentclaude.DefaultStore().ListAccounts(context.Background()) - if err != nil { - slog.Warn("Claude accounts skipped", "error", err) - claudeAccounts = nil - } // Start with optimistic fallback scores so the proxy begins accepting // connections immediately. Blocking startup on a synchronous usage fetch // (an OAuth refresh per account) stalls socket-activated connections during @@ -261,7 +309,7 @@ func serve(args []string) error { // swapped in once ready. Per-request 401/429 failover covers the brief // window before fresh scores land. schedulerRef := selectacct.NewSchedulerRef(selectacct.NewScheduler(fallbackScores(codexAccounts))) - if *fetchUsage { + if *fetchUsage && credentialBroker == nil { go func() { fetchedScores, successful := fetchCodexScoresWithStore(context.Background(), codexStore, codexAccounts) if successful > 0 { @@ -306,10 +354,13 @@ func serve(args []string) error { initialAccounts := append([]accounts.Account(nil), codexAccounts...) initialAccounts = append(initialAccounts, claudeAccounts...) - accountRef := proxy.NewAccountRef(codexStore, initialAccounts, &http.Client{ - Timeout: 15 * time.Second, - Transport: outboundTransport, - }) + var accountRef *proxy.AccountRef + if credentialBroker == nil { + accountRef = proxy.NewAccountRef(codexStore, initialAccounts, &http.Client{ + Timeout: 15 * time.Second, + Transport: outboundTransport, + }) + } server := proxy.Server{ StreamDrops: &proxy.StreamDropStats{}, @@ -321,6 +372,7 @@ func serve(args []string) error { ZAIUpstream: zaiUpstream, Accounts: nil, AccountRef: accountRef, + CredentialBroker: credentialBroker, Sessions: store, SchedulerRef: schedulerRef, UsageScoreTTL: usageScoreTTLForServe(*fetchUsage, *usageScoreTTL), @@ -328,10 +380,11 @@ func serve(args []string) error { Logger: slog.Default(), Lifecycle: proxy.NewLifecycle(), AdminToken: *adminToken, + LocalProxyToken: cloudServerProxyToken(cloudConfig), MaxBodyBytes: *maxBodyBytes, Bedrock: bedrockConfig, - ClaudeFableAPIKey: strings.TrimSpace(os.Getenv("SUBROUTER_CLAUDE_FABLE_API_KEY")), - FableBedrockPrimary: *fableBedrockPrimary || envTrue("SUBROUTER_FABLE_BEDROCK_PRIMARY"), + ClaudeFableAPIKey: fableAPIKey, + FableBedrockPrimary: fableBedrockEnabled, Transcripts: transcript.NewRecorder(*transcriptDir), } transcriptGCSSyncer := transcript.NewGCSSyncer(transcript.GCSSyncerConfig{ @@ -346,7 +399,7 @@ func serve(args []string) error { if transcriptGCSSyncer.Enabled() { go transcriptGCSSyncer.Run(context.Background()) } - if srSwitchInterval > 0 && *fetchUsage { + if srSwitchInterval > 0 && *fetchUsage && credentialBroker == nil { go runSRAutoSwitch(context.Background(), srAutoSwitchConfig{ Interval: srSwitchInterval, AccountsFunc: accountRef.All, @@ -355,7 +408,7 @@ func serve(args []string) error { Logger: slog.Default(), Lease: newSRAutoSwitchLease(storepath.StateDir()), }) - } else if srSwitchInterval > 0 { + } else if srSwitchInterval > 0 && credentialBroker == nil { slog.Info("sr auto-switch disabled because usage fetching is disabled", "interval", srSwitchInterval.String()) } @@ -377,13 +430,37 @@ func serve(args []string) error { } if upstream != nil { - slog.Info("subrouter listening", "addr", *addr, "upstream", upstream.String(), "codex_accounts", len(codexAccounts), "claude_accounts", len(claudeAccounts), "transcripts", *transcriptDir, "transcript_gcs_uri", *transcriptGCSURI) + slog.Info("subrouter listening", "addr", *addr, "upstream", upstream.String(), "codex_accounts", len(codexAccounts), "claude_accounts", len(claudeAccounts), "cloud_team", cloudConfig.TeamID, "transcripts", *transcriptDir, "transcript_gcs_uri", *transcriptGCSURI) } else { - slog.Info("subrouter listening", "addr", *addr, "codex_upstream", codexUpstream.String(), "api_upstream", apiUpstream.String(), "claude_upstream", claudeUpstream.String(), "codex_accounts", len(codexAccounts), "claude_accounts", len(claudeAccounts), "transcripts", *transcriptDir, "transcript_gcs_uri", *transcriptGCSURI) + slog.Info("subrouter listening", "addr", *addr, "codex_upstream", codexUpstream.String(), "api_upstream", apiUpstream.String(), "claude_upstream", claudeUpstream.String(), "codex_accounts", len(codexAccounts), "claude_accounts", len(claudeAccounts), "cloud_team", cloudConfig.TeamID, "transcripts", *transcriptDir, "transcript_gcs_uri", *transcriptGCSURI) } return listenAndServeWithSignals(httpServer, server.Lifecycle, *shutdownTimeout, slog.Default()) } +func loadProxyAccounts( + ctx context.Context, + teamMode bool, + codexStore accounts.CodexStore, + claudeStore agentclaude.Store, +) ([]accounts.Account, []accounts.Account, error) { + if teamMode { + // Team mode never reads local provider credentials. Besides enforcing + // central refresh custody, this keeps a corrupt legacy file from taking + // down an otherwise healthy team daemon. + return nil, nil, nil + } + codexAccounts, err := codexStore.List() + if err != nil { + return nil, nil, err + } + claudeAccounts, err := claudeStore.ListAccounts(ctx) + if err != nil { + slog.Warn("Claude accounts skipped", "error", err) + claudeAccounts = nil + } + return codexAccounts, claudeAccounts, nil +} + func loadBedrockAWSSources(ctx context.Context, region string, profiles []string, autobump bool) (aws.Config, []proxy.BedrockCredentialSource, error) { if len(profiles) == 0 { cfg, err := awsconfig.LoadDefaultConfig(ctx, awsconfig.WithRegion(region)) @@ -883,6 +960,38 @@ func usageText(program string) string { } return fmt.Sprintf(`%[1]s routes AI coding-agent traffic across subscription accounts. +Getting started: + %[1]s login Sign in to cmux.com with Stack Auth and choose a team + %[1]s setup Install and start the local proxy daemon, then verify it + %[1]s setup --storage local + Set up this machine without shared credentials + %[1]s doctor Diagnose login, team vault, daemon, and local egress + %[1]s cleanup Remove the local daemon (--yes to apply, --purge for local credentials) + +Credential storage: + %[1]s storage Show the active credential source + %[1]s storage team Use credentials shared with the selected Stack team + %[1]s storage local Keep and use credentials only on this machine + %[1]s storage legacy Use the selected legacy remote Subrouter server + +Team vault management: + %[1]s team list List Stack Auth teams + %[1]s team current Show the selected team + %[1]s team use Select the team whose credentials this machine leases + %[1]s account list List credentials shared with the selected team + %[1]s account add + Add one credential to the selected team vault + %[1]s account import --only