Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
misc: addressed feedback
Sheen Capadngan16bfbd70b3dd
diff --git a/backend/e2e-test/routes/v1/agent-vault-session-logs.spec.ts b/backend/e2e-test/routes/v1/agent-vault-session-logs.spec.tsindex e8e4784ed2..523cf392e8 100644--- a/backend/e2e-test/routes/v1/agent-vault-session-logs.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault-session-logs.spec.ts@@ -619,6 +619,7 @@ describe("Agent Vault session logs", async () => {await configure();const bundle = await createAccessBundle(`session-logs-resolve-badkey-${Date.now()}`);const created = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: "datadog",hostPattern: "api.datadoghq.com",credential: { type: "bearer", headerName: "DD-API-KEY", headerPrefix: "", value: "abc123" }diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.tsindex a103113078..571b4f26c5 100644--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@ -397,6 +397,7 @@ describe("Agent Vault V1 Router", async () => {const attempts = await Promise.all([1, 2].map((n) =>inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: `race-${n}`,hostPattern: "api.raced.example.com",credential: { type: "passthrough" }@@ -418,6 +419,7 @@ describe("Agent Vault V1 Router", async () => {const bundle = await createAccessBundle("overlap-check");const first = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: "datadog-us5",hostPattern: "api.us5.datadoghq.com, api.datadoghq.eu",credential: { type: "bearer", headerName: "DD-API-KEY", headerPrefix: "", value: "abc123" }@@ -425,6 +427,7 @@ describe("Agent Vault V1 Router", async () => {expect(first.statusCode).toBe(200);const overlapping = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: "datadog-eu",hostPattern: "api.datadoghq.eu, api.datadoghq.com",credential: { type: "bearer", value: "def456" }@@ -433,6 +436,7 @@ describe("Agent Vault V1 Router", async () => {expect(JSON.parse(overlapping.payload).message).toContain("api.datadoghq.eu:443");const contained = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: "datadog-wildcard",hostPattern: "*.datadoghq.com",credential: { type: "passthrough" }@@ -444,6 +448,7 @@ describe("Agent Vault V1 Router", async () => {const bundle = await createAccessBundle("secret-handling");const res = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: "github",hostPattern: " API.GitHub.com ",credential: { type: "bearer", value: "ghp_secret_value" }@@ -470,6 +475,7 @@ describe("Agent Vault V1 Router", async () => {const bundle = await createAccessBundle("credential-patch");const created = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: "datadog",hostPattern: "api.datadoghq.com",credential: { type: "bearer", headerName: "DD-API-KEY", headerPrefix: "", value: "abc123" }@@ -501,6 +507,7 @@ describe("Agent Vault V1 Router", async () => {const bundle = await createAccessBundle("basic-halves");const created = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: "stripe",hostPattern: "api.stripe.com",credential: { type: "basic", username: "sk_live_key", password: "" }@@ -545,6 +552,7 @@ describe("Agent Vault V1 Router", async () => {const bundle = await createAccessBundle("type-change");const created = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: "github",hostPattern: "api.github.com",credential: { type: "bearer", value: "ghp_one" }@@ -565,6 +573,7 @@ describe("Agent Vault V1 Router", async () => {test("a path in a host pattern is rejected", async () => {const bundle = await createAccessBundle("no-paths");const res = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: "with-path",hostPattern: "gitlab.com/api/v4",credential: { type: "passthrough" }@@ -576,6 +585,7 @@ describe("Agent Vault V1 Router", async () => {const bundle = await createAccessBundle("service-policy");const created = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: "github",hostPattern: "api.github.com",allowedMethods: ["GET", "HEAD"],@@ -608,6 +618,7 @@ describe("Agent Vault V1 Router", async () => {const reject = async (prefix: string) =>(await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: `svc-${Math.random().toString(36).slice(2, 8)}`,hostPattern: `h${Math.random().toString(36).slice(2, 8)}.example.com`,allowedPathPrefixes: [prefix],@@ -633,6 +644,7 @@ describe("Agent Vault V1 Router", async () => {const bundle = await createAccessBundle("transformations");const created = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: "github",hostPattern: "api.github.com",credential: { type: "passthrough" },@@ -674,6 +686,7 @@ describe("Agent Vault V1 Router", async () => {const bundle = await createAccessBundle("keep-stored-value");const created = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: "github",hostPattern: "api.github.com",credential: { type: "passthrough" },@@ -726,6 +739,7 @@ describe("Agent Vault V1 Router", async () => {const bundle = await createAccessBundle("header-shadowing");const clash = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: "clash",hostPattern: "api.clash.example.com",credential: { type: "bearer", headerName: "X-Api-Key", headerPrefix: "", value: "k" },@@ -735,6 +749,7 @@ describe("Agent Vault V1 Router", async () => {expect(JSON.parse(clash.payload).message).toContain("X-Api-Key");const created = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: "github",hostPattern: "api.github.com",credential: { type: "bearer", headerName: "X-Api-Key", headerPrefix: "", value: "k" },@@ -763,6 +778,7 @@ describe("Agent Vault V1 Router", async () => {test("a header the proxy controls is refused, from either side", async () => {const bundle = await createAccessBundle("reserved-headers");const res = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: "reserved",hostPattern: "api.reserved.example.com",credential: { type: "passthrough" },@@ -771,6 +787,7 @@ describe("Agent Vault V1 Router", async () => {expect(res.statusCode).toBe(422);const asCredential = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: "reserved-credential",hostPattern: "api.reserved-credential.example.com",credential: { type: "bearer", headerName: "Content-Length", value: "t" }@@ -993,6 +1010,7 @@ describe("Agent Vault V1 Router", async () => {const org = await createVariable({ key: "ORG_ID", value: "org-42" });const created = await inject("POST", servicesUrl(bundle.id), {+ type: "http",name: "github",hostPattern: "api.github.com",credential: { type: "bearer", value: "{{GITHUB_TOKEN}}" },@@ -1047,6 +1065,7 @@ describe("Agent Vault V1 Router", async () => {const long = await createVariable({ key: "LONG", value: "x" });const created = await inject("POST", servicesUrl(bundle.id), {+ type: "http",name: "longest",hostPattern: "longest.example.com",credential: { type: "bearer", value: "{{LONG}}".repeat(3) }@@ -1065,6 +1084,7 @@ describe("Agent Vault V1 Router", async () => {const bundle = await createAccessBundle("variables-username-trim");await createVariable({ key: "PADDED", value: " padded " });const created = await inject("POST", servicesUrl(bundle.id), {+ type: "http",name: "padded",hostPattern: "padded.example.com",credential: { type: "basic", username: "{{PADDED}}", password: "{{PADDED}}" }@@ -1083,6 +1103,7 @@ describe("Agent Vault V1 Router", async () => {const bundle = await createAccessBundle("variables-missing");const gone = await createVariable({ key: "GONE", value: "x" });const created = await inject("POST", servicesUrl(bundle.id), {+ type: "http",name: "missing",hostPattern: "api.example.com",allowedMethods: ["GET"],@@ -1106,6 +1127,7 @@ describe("Agent Vault V1 Router", async () => {const bundle = await createAccessBundle("variables-rename");const variable = await createVariable({ key: "OLD_NAME", value: "first" });const created = await inject("POST", servicesUrl(bundle.id), {+ type: "http",name: "echo",hostPattern: "echo.example.com",credential: { type: "bearer", value: "{{OLD_NAME}}" }@@ -1134,6 +1156,7 @@ describe("Agent Vault V1 Router", async () => {expect((await resolve()).services[0].credential).toMatchObject({ value: "second" });const stale = await inject("POST", servicesUrl(bundle.id), {+ type: "http",name: "stale",hostPattern: "stale.example.com",credential: { type: "bearer", value: "{{OLD_NAME}}" }@@ -1146,6 +1169,7 @@ describe("Agent Vault V1 Router", async () => {const bundle = await createAccessBundle("variables-in-use");const variable = await createVariable({ key: "API_KEY", value: "key_value" });const created = await inject("POST", servicesUrl(bundle.id), {+ type: "http",name: "datadog",hostPattern: "api.datadoghq.com",credential: { type: "bearer", headerName: "DD-API-KEY", value: "{{API_KEY}}" }@@ -1173,6 +1197,7 @@ describe("Agent Vault V1 Router", async () => {const bundle = await createAccessBundle("variables-validation");const unknown = await inject("POST", servicesUrl(bundle.id), {+ type: "http",name: "unknown",hostPattern: "unknown.example.com",credential: { type: "bearer", value: "{{NOT_DEFINED}}" }@@ -1181,6 +1206,7 @@ describe("Agent Vault V1 Router", async () => {expect(JSON.parse(unknown.payload).message).toContain("NOT_DEFINED");const malformed = await inject("POST", servicesUrl(bundle.id), {+ type: "http",name: "malformed",hostPattern: "malformed.example.com",credential: { type: "passthrough" },@@ -1190,6 +1216,7 @@ describe("Agent Vault V1 Router", async () => {expect(malformed.payload).not.toContain("lower_case_secret");const bracedPlaceholder = await inject("POST", servicesUrl(bundle.id), {+ type: "http",name: "braced",hostPattern: "braced.example.com",credential: { type: "passthrough" },@@ -1199,12 +1226,14 @@ describe("Agent Vault V1 Router", async () => {// A prefix is sent as typed, so braces in one would reach the host as a reference nobody fills in.const bracedBearerPrefix = await inject("POST", servicesUrl(bundle.id), {+ type: "http",name: "braced-bearer",hostPattern: "braced-bearer.example.com",credential: { type: "bearer", headerPrefix: "{{ORG}}", value: "x" }});expect(bracedBearerPrefix.statusCode).toBe(422);const bracedHeaderPrefix = await inject("POST", servicesUrl(bundle.id), {+ type: "http",name: "braced-header",hostPattern: "braced-header.example.com",credential: { type: "passthrough" },@@ -1220,6 +1249,7 @@ describe("Agent Vault V1 Router", async () => {await createVariable({ key: "TOKEN", value: "t" });const atLimit = await inject("POST", servicesUrl(bundle.id), {+ type: "http",name: "at-limit",hostPattern: "at-limit.example.com",credential: { type: "bearer", value: "{{TOKEN}}".repeat(3) }@@ -1227,6 +1257,7 @@ describe("Agent Vault V1 Router", async () => {expect(atLimit.statusCode).toBe(200);const overLimit = await inject("POST", servicesUrl(bundle.id), {+ type: "http",name: "over-limit",hostPattern: "over-limit.example.com",credential: { type: "bearer", value: "{{TOKEN}}".repeat(4) }@@ -1311,7 +1342,7 @@ describe("Agent Vault V1 Router", async () => {await createVariable({ key: "BETA_TOKEN", value: "b" });await createVariable({ key: "GAMMA_KEY", value: "g" });const createService = async (body: Record<string, unknown>) =>- expect((await inject("POST", servicesUrl(bundle.id), body)).statusCode).toBe(200);+ expect((await inject("POST", servicesUrl(bundle.id), { type: "http", ...body })).statusCode).toBe(200);// Two fields of one service count as one service.await createService({name: "both-fields",@@ -1379,6 +1410,7 @@ describe("Agent Vault V1 Router", async () => {const createdIn = async (bundle: { id: string }, name: string) => {const res = await inject("POST", servicesUrl(bundle.id), {+ type: "http",name,hostPattern: `${name}.example.com`,credential: { type: "bearer", value: "{{SHARED_TOKEN}}" }@@ -1427,6 +1459,7 @@ describe("Agent Vault V1 Router", async () => {const bundle = await createAccessBundle("variables-delete-race");const variable = await createVariable({ key: "RACED", value: "raced_value" });const created = await inject("POST", servicesUrl(bundle.id), {+ type: "http",name: "raced",hostPattern: "raced.example.com",credential: { type: "passthrough" }@@ -1472,6 +1505,7 @@ describe("Agent Vault V1 Router", async () => {await trx("agent_vault_variables").where({ id: variable.id }).forUpdate().first();const pending = inject("POST", servicesUrl(bundle.id), {+ type: "http",name: "doomed",hostPattern: "doomed.example.com",credential: { type: "bearer", value: "{{DOOMED}}" }@@ -1500,6 +1534,7 @@ describe("Agent Vault V1 Router", async () => {await createVariable({ key: "HEADER", value: "the-header" });const created = await inject("POST", servicesUrl(bundle.id), {+ type: "http",name: "basic",hostPattern: "basic.example.com",credential: { type: "basic", username: "{{USER}}", password: "{{PASS}}" },@@ -1545,6 +1580,7 @@ describe("Agent Vault V1 Router", async () => {await createVariable({ key: "USER", value: "the-user" });const created = await inject("POST", servicesUrl(bundle.id), {+ type: "http",name: "legacy",hostPattern: "legacy.example.com",credential: { type: "basic", username: "u", password: "p" }@@ -1588,6 +1624,7 @@ describe("Agent Vault V1 Router", async () => {await createVariable({ key: "PASS", value: "the-pass" });const created = await inject("POST", servicesUrl(bundle.id), {+ type: "http",name: "stale",hostPattern: "stale.example.com",credential: { type: "basic", username: "{{FIRST_USER}}", password: "plain-pass" }@@ -1598,6 +1635,7 @@ describe("Agent Vault V1 Router", async () => {// What the other save commits, sealed by the API itself on a second service: a new username.const other = await inject("POST", servicesUrl(bundle.id), {+ type: "http",name: "other",hostPattern: "other.example.com",credential: { type: "basic", username: "{{SECOND_USER}}", password: "plain-pass" }@@ -1654,6 +1692,7 @@ describe("Agent Vault V1 Router", async () => {test("an update whose service is deleted while it waits is a 404, not a deleted variable", async () => {const bundle = await createAccessBundle("variables-deleted-service");const created = await inject("POST", servicesUrl(bundle.id), {+ type: "http",name: "doomed",hostPattern: "doomed.example.com",credential: { type: "passthrough" }@@ -1689,6 +1728,7 @@ describe("Agent Vault V1 Router", async () => {const bundle = await createAccessBundle("variables-bundle-delete");const variable = await createVariable({ key: "TOKEN", value: "t" });const created = await inject("POST", servicesUrl(bundle.id), {+ type: "http",name: "one",hostPattern: "one.example.com",credential: { type: "bearer", value: "{{TOKEN}}" },@@ -1715,6 +1755,7 @@ describe("Agent Vault V1 Router", async () => {const bundle = await createAccessBundle("variables-admin-only");const variable = await createVariable({ key: "TOKEN", value: "admin_only_value" });const created = await inject("POST", servicesUrl(bundle.id), {+ type: "http",name: "uses-token",hostPattern: "api.example.com",credential: { type: "bearer", value: "{{TOKEN}}" }@@ -2371,7 +2412,7 @@ describe("Agent Vault V1 Router", async () => {["POST",`/api/v1/agent-vault/access-bundles/${unknown}/services`,- { name: "c", hostPattern: "api.foo.com", credential: { type: "passthrough" } }+ { type: "http", name: "c", hostPattern: "api.foo.com", credential: { type: "passthrough" } }],// The bundle is the path resource, so a missing one is still 404 even though a missing actor in// the body is reported as skipped.@@ -3010,6 +3051,7 @@ describe("Agent Vault V1 Router", async () => {test("resolve carries the policy and the decrypted transformations", async () => {const bundle = await createAccessBundle("resolve-transformations");const created = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: "github",hostPattern: "api.github.com",allowedMethods: ["GET"],@@ -3073,6 +3115,7 @@ describe("Agent Vault V1 Router", async () => {test("a deactivated actor stops resolving, and resolves again once reactivated", async () => {const bundle = await createAccessBundle("resolve-deactivation");const service = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: "echo",hostPattern: "echo.example.com",credential: { type: "passthrough" }@@ -3120,6 +3163,7 @@ describe("Agent Vault V1 Router", async () => {test("a session whose user was deleted is refused before any lookup", async () => {const bundle = await createAccessBundle("resolve-deleted-user");await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: "echo",hostPattern: "echo.example.com",credential: { type: "passthrough" }@@ -3151,6 +3195,7 @@ describe("Agent Vault V1 Router", async () => {test("a session whose machine identity was deleted is refused before any lookup", async () => {const bundle = await createAccessBundle("resolve-deleted-identity");await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: "echo",hostPattern: "echo.example.com",credential: { type: "passthrough" }@@ -3192,6 +3237,7 @@ describe("Agent Vault V1 Router", async () => {};const bundle = await createAccessBundle("resolve-temporary-role");await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: "echo",hostPattern: "echo.example.com",credential: { type: "passthrough" }@@ -3910,6 +3956,7 @@ describe("Agent Vault V1 Router", async () => {expect((await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: "echo",hostPattern: "echo.example.com",credential: { type: "passthrough" }@@ -4005,6 +4052,7 @@ describe("Agent Vault V1 Router", async () => {expect((await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {+ type: "http",name: "echo",hostPattern: "echo.example.com",credential: { type: "passthrough" }diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.tsindex e885472e2b..ce4d2dd32f 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts@@ -320,8 +320,8 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProserviceId: service.id,name: service.name,serviceType: service.type,- serverUrl: service.config.serverUrl,- transport: service.config.transport,+ serverUrl: service.serverUrl ?? undefined,+ transport: service.transport ?? undefined,hostPattern: service.hostPattern,credentialType: service.credential.type,headerName:@@ -341,27 +341,6 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro}});- if (service.credential.type === AgentVaultCredentialType.OAuth) {- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- orgId: req.permission.orgId,- projectId: req.internalAgentVaultProjectId,- event: {- type: EventType.AGENT_VAULT_SERVICE_CREDENTIAL_AUTHORIZE,- metadata: {- accessBundleId: req.params.accessBundleId,- accessBundleName,- serviceId: service.id,- name: service.name,- serverUrl: service.config.serverUrl,- oauthIssuer: service.credential.issuer,- oauthScopes: service.credential.grantedScopes,- reauthorization: false- }- }- });- }-emitAgentVaultTelemetry(server.services.telemetry, req, {event: PostHogEventTypes.AgentVaultServiceCreated,properties: {@@ -483,27 +462,6 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro}});- if (isOauthAuthorized && service.credential.type === AgentVaultCredentialType.OAuth) {- await server.services.auditLog.createAuditLog({- ...req.auditLogInfo,- orgId: req.permission.orgId,- projectId: req.internalAgentVaultProjectId,- event: {- type: EventType.AGENT_VAULT_SERVICE_CREDENTIAL_AUTHORIZE,- metadata: {- accessBundleId: req.params.accessBundleId,- accessBundleName,- serviceId: service.id,- name: service.name,- serverUrl: service.config.serverUrl,- oauthIssuer: service.credential.issuer,- oauthScopes: service.credential.grantedScopes,- reauthorization: true- }- }- });- }-emitAgentVaultTelemetry(server.services.telemetry, req, {event: PostHogEventTypes.AgentVaultServiceUpdated,properties: {diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-oauth-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-oauth-router.tsindex cd26810e36..dee823b132 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-oauth-router.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-oauth-router.ts@@ -1,7 +1,11 @@import { z } from "zod";import { AgentVaultOauthAuthorizationStatus } from "@app/ee/services/agent-vault/agent-vault-enums";-import { OAUTH_CLIENT_CREDENTIAL_PATTERN } from "@app/ee/services/agent-vault-oauth/agent-vault-oauth-client-fns";+import {+ MAX_CLIENT_ID_LENGTH,+ MAX_CLIENT_SECRET_LENGTH,+ OAUTH_CLIENT_CREDENTIAL_PATTERN+} from "@app/ee/services/agent-vault-oauth/agent-vault-oauth-client-fns";import { AGENT_VAULT } from "@app/lib/api-docs";import { ApiDocsTags } from "@app/lib/api-docs/constants";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";@@ -44,15 +48,15 @@ export const registerAgentVaultOauthRouter = async (server: FastifyZodProvider).string().trim().min(1)- .max(512)- .pipe(printable(512))+ .max(MAX_CLIENT_ID_LENGTH)+ .pipe(printable(MAX_CLIENT_ID_LENGTH)).optional().describe(AGENT_VAULT.OAUTH.clientId),clientSecret: z.string().min(1)- .max(1024)- .pipe(printable(1024))+ .max(MAX_CLIENT_SECRET_LENGTH)+ .pipe(printable(MAX_CLIENT_SECRET_LENGTH)).optional().describe(AGENT_VAULT.OAUTH.clientSecret)}),diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.tsindex 9207b803bb..0ca6f4a377 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts@@ -2,6 +2,7 @@ import RE2 from "re2";import { z } from "zod";import {+ AgentVaultCredentialType,AgentVaultOauthStatus,AgentVaultServiceType,AgentVaultTrafficPolicy@@ -56,15 +57,20 @@ const SessionHeaderSchema = z// `source` and `expiresAt` are only on an OAuth credential. A proxy that predates them injects it as any bearer.const ResolvedBearerCredentialSchema = z.object({- type: z.literal("bearer").describe(AGENT_VAULT.CREDENTIAL_REFRESH.credentialType),+ type: z.literal(AgentVaultCredentialType.Bearer).describe(AGENT_VAULT.CREDENTIAL_REFRESH.credentialType),headerName: z.string().describe(AGENT_VAULT.SERVICE.headerName),headerPrefix: z.string().describe(AGENT_VAULT.SERVICE.headerPrefix),value: z.string().describe(AGENT_VAULT.CREDENTIAL_REFRESH.value),- source: z.literal("oauth").optional().describe(AGENT_VAULT.CREDENTIAL_REFRESH.source),+ source: z.literal(AgentVaultCredentialType.OAuth).optional().describe(AGENT_VAULT.CREDENTIAL_REFRESH.source),expiresAt: z.string().nullable().optional().describe(AGENT_VAULT.SERVICE.oauthExpiresAt)}).describe(JSON.stringify({ title: "Bearer" }));+const RejectedTokenHashSchema = z+ .string()+ .length(64)+ .regex(new RE2(/^[0-9a-fA-F]{64}$/), "Must be the hex sha256 of the rejected access token");+export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProvider) => {server.route({method: "POST",@@ -195,9 +201,15 @@ export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProvicredential: z.discriminatedUnion("type", [ResolvedBearerCredentialSchema,z- .object({ type: z.literal("basic"), username: z.string(), password: z.string() })+ .object({+ type: z.literal(AgentVaultCredentialType.Basic),+ username: z.string(),+ password: z.string()+ }).describe(JSON.stringify({ title: "Basic Auth" })),- z.object({ type: z.literal("passthrough") }).describe(JSON.stringify({ title: "Pass-through" }))+ z+ .object({ type: z.literal(AgentVaultCredentialType.Passthrough) })+ .describe(JSON.stringify({ title: "Pass-through" }))]),customHeaders: z.object({ name: z.string(), prefix: z.string(), value: z.string() }).array(),substitutions: z@@ -239,11 +251,42 @@ export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProviparams: z.object({ serviceId: z.string().uuid().describe(AGENT_VAULT.SERVICE.serviceId) }),body: z.object({hostPattern: AgentVaultHostPatternSchema.describe(AGENT_VAULT.CREDENTIAL_REFRESH.hostPattern),- rejectedTokenHash: z- .string()- .length(64)- .regex(new RE2(/^[0-9a-fA-F]{64}$/), "Must be the hex sha256 of the rejected access token")- .describe(AGENT_VAULT.CREDENTIAL_REFRESH.rejectedTokenHash),+ rejectedTokenHash: RejectedTokenHashSchema.describe(AGENT_VAULT.CREDENTIAL_REFRESH.rejectedTokenHash)+ }),+ response: {+ 200: z.object({+ credential: ResolvedBearerCredentialSchema.describe(AGENT_VAULT.CREDENTIAL_REFRESH.credential),+ status: z.nativeEnum(AgentVaultOauthStatus).describe(AGENT_VAULT.SERVICE.oauthStatus)+ })+ }+ },+ onRequest: verifyAuth([AuthMode.AGENT_VAULT_PROXY_ACCESS_TOKEN]),+ handler: async (req) =>+ server.services.agentVaultProxy.refreshCredential({+ proxyId: req.permission.id,+ orgId: req.permission.orgId,+ sessionToken: req.headers[SESSION_HEADER],+ serviceId: req.params.serviceId,+ hostPattern: req.body.hostPattern,+ rejectedTokenHash: req.body.rejectedTokenHash+ })+ });++ server.route({+ method: "POST",+ url: "/services/:serviceId/missing-scopes",+ config: { rateLimit: agentVaultCredentialRefreshLimit },+ schema: {+ hide: true,+ operationId: "reportAgentVaultServiceMissingScopes",+ description:+ "Record the scopes an MCP server asked for in an insufficient_scope challenge, so the service shows it needs reauthorizing with them. The token is not refreshed. A report for a token that is no longer current changes nothing. A 409 means the service's host pattern no longer matches `hostPattern`.",+ tags: [ApiDocsTags.AgentVaultProxies],+ headers: SessionHeaderSchema,+ params: z.object({ serviceId: z.string().uuid().describe(AGENT_VAULT.SERVICE.serviceId) }),+ body: z.object({+ hostPattern: AgentVaultHostPatternSchema.describe(AGENT_VAULT.CREDENTIAL_REFRESH.hostPattern),+ rejectedTokenHash: RejectedTokenHashSchema.describe(AGENT_VAULT.CREDENTIAL_REFRESH.rejectedTokenHash),requiredScopes: z.string().min(1)@@ -253,20 +296,17 @@ export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProvi"Each scope must be an OAuth scope token: printable ASCII with no spaces, quotes or backslashes").array()+ .min(1).max(50)- .optional().describe(AGENT_VAULT.CREDENTIAL_REFRESH.requiredScopes)}),response: {- 200: z.object({- credential: ResolvedBearerCredentialSchema.describe(AGENT_VAULT.CREDENTIAL_REFRESH.credential),- status: z.nativeEnum(AgentVaultOauthStatus).describe(AGENT_VAULT.SERVICE.oauthStatus)- })+ 204: z.string().length(0)}},onRequest: verifyAuth([AuthMode.AGENT_VAULT_PROXY_ACCESS_TOKEN]),- handler: async (req) =>- server.services.agentVaultProxy.refreshCredential({+ handler: async (req, res) => {+ await server.services.agentVaultProxy.reportMissingScopes({proxyId: req.permission.id,orgId: req.permission.orgId,sessionToken: req.headers[SESSION_HEADER],@@ -274,7 +314,9 @@ export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProvihostPattern: req.body.hostPattern,rejectedTokenHash: req.body.rejectedTokenHash,requiredScopes: req.body.requiredScopes- })+ });+ return res.status(204).send("");+ }});server.route({diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.tsindex a4ecf10e6d..4790eeab83 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts@@ -210,53 +210,38 @@ export const AgentVaultSubstitutionsUpdateSchema = AgentVaultSubstitutionUpdateS.superRefine(addDuplicatePlaceholderIssues).describe(AGENT_VAULT.SERVICE.substitutions);-// `type` is optional and means http, so clients written before MCP services keep working unchanged. Each-// option also takes the other type's fields, hidden from the docs, so the service can refuse them with a+// Each option also takes the other type's fields, hidden from the docs, so the service can refuse them with a// message naming the field rather than zod dropping them silently.-export const AgentVaultCreateServiceBodySchema = z.discriminatedUnion(- "type",- [- z- .object({- type: z- .literal(AgentVaultServiceType.Http)- .optional()- .transform(() => AgentVaultServiceType.Http as const)- .describe(AGENT_VAULT.SERVICE.type),- name: AgentVaultNameSchema.describe(AGENT_VAULT.SERVICE.name),- hostPattern: AgentVaultHostPatternSchema,- allowedMethods: AgentVaultAllowedMethodsSchema.optional(),- allowedPathPrefixes: AgentVaultAllowedPathPrefixesSchema.optional(),- credential: AgentVaultCredentialInputSchema,- customHeaders: AgentVaultCustomHeadersInputSchema.optional(),- substitutions: AgentVaultSubstitutionsInputSchema.optional(),- serverUrl: AgentVaultServerUrlSchema.optional().describe(openApiHidden()),- transport: AgentVaultMcpTransportSchema.optional().describe(openApiHidden())- })- .describe(JSON.stringify({ title: "HTTP service" })),- z- .object({- type: z.literal(AgentVaultServiceType.Mcp).describe(AGENT_VAULT.SERVICE.type),- name: AgentVaultNameSchema.describe(AGENT_VAULT.SERVICE.name),- serverUrl: AgentVaultServerUrlSchema,- transport: AgentVaultMcpTransportSchema,- credential: AgentVaultCredentialInputSchema.describe(AGENT_VAULT.SERVICE.mcpCredential),- customHeaders: AgentVaultCustomHeadersInputSchema.optional(),- hostPattern: AgentVaultHostPatternSchema.optional().describe(openApiHidden()),- allowedMethods: AgentVaultAllowedMethodsSchema.optional().describe(openApiHidden()),- allowedPathPrefixes: AgentVaultAllowedPathPrefixesSchema.optional().describe(openApiHidden()),- substitutions: AgentVaultSubstitutionsInputSchema.optional().describe(openApiHidden())- })- .describe(JSON.stringify({ title: "MCP service" }))- ],- {- // The default message lists the optional discriminator's `undefined` as an empty option.- errorMap: (issue, ctx) =>- issue.code === z.ZodIssueCode.invalid_union_discriminator- ? { message: `'type' must be '${AgentVaultServiceType.Http}' or '${AgentVaultServiceType.Mcp}'.` }- : { message: ctx.defaultError }- }-);+export const AgentVaultCreateServiceBodySchema = z.discriminatedUnion("type", [+ z+ .object({+ type: z.literal(AgentVaultServiceType.Http).describe(AGENT_VAULT.SERVICE.type),+ name: AgentVaultNameSchema.describe(AGENT_VAULT.SERVICE.name),+ hostPattern: AgentVaultHostPatternSchema,+ allowedMethods: AgentVaultAllowedMethodsSchema.optional(),+ allowedPathPrefixes: AgentVaultAllowedPathPrefixesSchema.optional(),+ credential: AgentVaultCredentialInputSchema,+ customHeaders: AgentVaultCustomHeadersInputSchema.optional(),+ substitutions: AgentVaultSubstitutionsInputSchema.optional(),+ serverUrl: AgentVaultServerUrlSchema.optional().describe(openApiHidden()),+ transport: AgentVaultMcpTransportSchema.optional().describe(openApiHidden())+ })+ .describe(JSON.stringify({ title: "HTTP service" })),+ z+ .object({+ type: z.literal(AgentVaultServiceType.Mcp).describe(AGENT_VAULT.SERVICE.type),+ name: AgentVaultNameSchema.describe(AGENT_VAULT.SERVICE.name),+ serverUrl: AgentVaultServerUrlSchema,+ transport: AgentVaultMcpTransportSchema,+ credential: AgentVaultCredentialInputSchema.describe(AGENT_VAULT.SERVICE.mcpCredential),+ customHeaders: AgentVaultCustomHeadersInputSchema.optional(),+ hostPattern: AgentVaultHostPatternSchema.optional().describe(openApiHidden()),+ allowedMethods: AgentVaultAllowedMethodsSchema.optional().describe(openApiHidden()),+ allowedPathPrefixes: AgentVaultAllowedPathPrefixesSchema.optional().describe(openApiHidden()),+ substitutions: AgentVaultSubstitutionsInputSchema.optional().describe(openApiHidden())+ })+ .describe(JSON.stringify({ title: "MCP service" }))+]);const variableReferenceBase = {variableId: z.string().uuid().describe(AGENT_VAULT.VARIABLE.variableId),@@ -296,18 +281,8 @@ export const AgentVaultServiceSchema = z.object({accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId),name: z.string().describe(AGENT_VAULT.SERVICE.name),type: z.nativeEnum(AgentVaultServiceType).describe(AGENT_VAULT.SERVICE.type),- // MCP first: the empty object matches anything, so it has to be the fallback.- config: z- .union([- z- .object({- serverUrl: z.string().describe(AGENT_VAULT.SERVICE.serverUrl),- transport: z.nativeEnum(AgentVaultMcpTransport).describe(AGENT_VAULT.SERVICE.transport)- })- .describe(JSON.stringify({ title: "MCP" })),- z.object({}).describe(JSON.stringify({ title: "HTTP" }))- ])- .describe(AGENT_VAULT.SERVICE.config),+ serverUrl: z.string().nullable().describe(AGENT_VAULT.SERVICE.serverUrlRead),+ transport: z.nativeEnum(AgentVaultMcpTransport).nullable().describe(AGENT_VAULT.SERVICE.transportRead),hostPattern: z.string().describe(AGENT_VAULT.SERVICE.hostPattern),allowedMethods: z.nativeEnum(AgentVaultHttpMethod).array().nullable().describe(AGENT_VAULT.SERVICE.allowedMethods),allowedPathPrefixes: z.string().array().nullable().describe(AGENT_VAULT.SERVICE.allowedPathPrefixes),diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.tsindex 9edb70f160..cc17eb1f19 100644--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts@@ -461,27 +461,31 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundcustomHeaders: TAgentVaultServiceCustomHeaders[],substitutions: TAgentVaultServiceSubstitutions[],variableReferences: TAgentVaultVariableReferenceWithKey[]- ) => ({- id: service.id,- accessBundleId: service.accessBundleId,- name: service.name,- type: service.type as AgentVaultServiceType,- // Plaintext and secret-free by construction (`{}` for http), so it is returned as stored.- config: (service.config ?? {}) as TAgentVaultServiceConfig,- hostPattern: service.hostPattern,- allowedMethods: (service.allowedMethods ?? null) as AgentVaultHttpMethod[] | null,- allowedPathPrefixes: service.allowedPathPrefixes ?? null,- credential: summarizeCredential(service),- customHeaders: customHeaders.map((header) => ({ id: header.id, name: header.name, prefix: header.prefix })),- substitutions: substitutions.map((substitution) => ({- id: substitution.id,- placeholder: substitution.placeholder,- surfaces: substitution.surfaces as AgentVaultSubstitutionSurface[]- })),- variableReferences: variableReferences.map(summarizeVariableReference),- createdAt: service.createdAt,- updatedAt: service.updatedAt- });+ ) => {+ const config = (service.config ?? {}) as TAgentVaultServiceConfig;+ return {+ id: service.id,+ accessBundleId: service.accessBundleId,+ name: service.name,+ type: service.type as AgentVaultServiceType,+ // Flat, like the create and update bodies, so a client can send back what it read. Null for an http service.+ serverUrl: config.serverUrl ?? null,+ transport: config.transport ?? null,+ hostPattern: service.hostPattern,+ allowedMethods: (service.allowedMethods ?? null) as AgentVaultHttpMethod[] | null,+ allowedPathPrefixes: service.allowedPathPrefixes ?? null,+ credential: summarizeCredential(service),+ customHeaders: customHeaders.map((header) => ({ id: header.id, name: header.name, prefix: header.prefix })),+ substitutions: substitutions.map((substitution) => ({+ id: substitution.id,+ placeholder: substitution.placeholder,+ surfaces: substitution.surfaces as AgentVaultSubstitutionSurface[]+ })),+ variableReferences: variableReferences.map(summarizeVariableReference),+ createdAt: service.createdAt,+ updatedAt: service.updatedAt+ };+ };const loadTransformations = async (serviceIds: string[],diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-dal.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-dal.tsindex 617ecde739..fb7c22a2ca 100644--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-dal.ts+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-service-dal.ts@@ -44,31 +44,30 @@ export const agentVaultServiceDALFactory = (db: TDbClient) => {// A refresh writes only if the sealed credential is still the one it read, so an admin reauthorizing in// between keeps the newer tokens. The config is a jsonb merge, so it only touches the keys it names.- // `keepStatus` is decided against the row being written, not the one the caller read: a status write that- // leaves the sealed credential alone (a scope report) passes the compare, and must not be overwritten.+ // `keepAdditionalScopesStatus` is decided against the row being written, not the one the caller read: a scope report+ // leaves the sealed credential alone, so it passes the compare, and its status must not be overwritten.const compareAndSwapCredential = async ({id,expectedEncryptedCredential,encryptedCredential,credentialConfigPatch,- keepStatus+ keepAdditionalScopesStatus}: {id: string;expectedEncryptedCredential: Buffer;encryptedCredential?: Buffer;credentialConfigPatch: Record<string, unknown>;- keepStatus?: { status: string; keys: string[] };+ keepAdditionalScopesStatus?: boolean;},tx?: Knex): Promise<Pick<TAgentVaultServices, "id" | "hostPattern" | "config" | "credentialConfig"> | undefined> => {try {const patch = JSON.stringify(credentialConfigPatch);- const keptKeys = ["status", ...(keepStatus?.keys ?? [])];- const credentialConfig = keepStatus+ const credentialConfig = keepAdditionalScopesStatus? db.raw(- `CASE WHEN "credentialConfig"->>'status' = ? THEN COALESCE("credentialConfig", '{}'::jsonb) || (?::jsonb${keptKeys.map(() => " - ?::text").join("")}) ELSE COALESCE("credentialConfig", '{}'::jsonb) || ?::jsonb END`,- [keepStatus.status, patch, ...keptKeys, patch]+ `CASE WHEN "credentialConfig"->>'status' = ? THEN COALESCE("credentialConfig", '{}'::jsonb) || (?::jsonb - 'status') ELSE COALESCE("credentialConfig", '{}'::jsonb) || ?::jsonb END`,+ [AgentVaultOauthStatus.NeedsAdditionalScopes, patch, patch]): db.raw(`COALESCE("credentialConfig", '{}'::jsonb) || ?::jsonb`, [patch]);const [row] = await (tx || db)(TableName.AgentVaultService)diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-client-fns.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-client-fns.tsindex 65268639f1..23de4e2f40 100644--- a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-client-fns.ts+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-client-fns.ts@@ -9,7 +9,11 @@ import {MAX_ERROR_DESCRIPTION_LENGTH,normalizeProviderText} from "./agent-vault-oauth-token-fns";-import { AgentVaultOauthClientAuthMethod, AgentVaultOauthCompatibility } from "./agent-vault-oauth-types";+import {+ AGENT_VAULT_OAUTH_GRANT_TYPE,+ AgentVaultOauthClientAuthMethod,+ AgentVaultOauthCompatibility+} from "./agent-vault-oauth-types";export const AGENT_VAULT_OAUTH_CLIENT_NAME = "Infisical Agent Vault";@@ -34,8 +38,8 @@ const SUPPORTED_AUTH_METHODS = Object.values(AgentVaultOauthClientAuthMethod) as// RFC 6749 appendix A.1 and A.2: both are VSCHAR. The ID is stored in jsonb and sent in the authorize URL, and the// secret is form-encoded into the token request, which throws on a lone surrogate.export const OAUTH_CLIENT_CREDENTIAL_PATTERN = new RE2(/^[\x20-\x7e]+$/);-const MAX_CLIENT_ID_LENGTH = 512;-const MAX_CLIENT_SECRET_LENGTH = 4096;+export const MAX_CLIENT_ID_LENGTH = 512;+export const MAX_CLIENT_SECRET_LENGTH = 4096;const parseRegistration = (body: string): TOauthClient | null => {let parsed: Record<string, unknown>;@@ -95,7 +99,7 @@ export const registerOauthClient = async ({const full = {...minimal,application_type: "web",- grant_types: ["authorization_code", "refresh_token"],+ grant_types: [AGENT_VAULT_OAUTH_GRANT_TYPE, "refresh_token"],response_types: ["code"]};diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-service.test.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-service.test.tsindex cadefb26a9..7f8fd583e0 100644--- a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-service.test.ts+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-service.test.ts@@ -18,6 +18,7 @@ import {} from "../agent-vault/agent-vault-enums";import { TOauthHttpClient, TOauthHttpResponse } from "./agent-vault-oauth-http-fns";import {+ AGENT_VAULT_SERVICE_MOVED_MESSAGE,agentVaultOauthServiceFactory,checkOauthClaimUnderLock,checkOauthServerUnderLock@@ -161,32 +162,28 @@ const setup = ({ metadata = LINEAR_JSON }: { metadata?: Record<string, unknown>const row = rows.get(id);return (row ? { ...row, credentialConfig: structuredClone(row.credentialConfig) } : undefined) as never;},- // Mirrors the SQL: the compare is on the sealed credential only, and `keepStatus` is decided on the row- // being written.+ // Mirrors the SQL: the compare is on the sealed credential only, and `keepAdditionalScopesStatus` is decided on+ // the row being written.compareAndSwapCredential: async ({id,expectedEncryptedCredential,encryptedCredential,credentialConfigPatch,- keepStatus+ keepAdditionalScopesStatus}: {id: string;expectedEncryptedCredential: Buffer;encryptedCredential?: Buffer;credentialConfigPatch: Record<string, unknown>;- keepStatus?: { status: string; keys: string[] };+ keepAdditionalScopesStatus?: boolean;}) => {const row = rows.get(id);if (!row?.encryptedCredential?.equals(expectedEncryptedCredential)) return undefined;if (encryptedCredential) row.encryptedCredential = encryptedCredential;const stored = row.credentialConfig as Record<string, unknown>;const patch =- keepStatus && stored.status === keepStatus.status- ? Object.fromEntries(- Object.entries(credentialConfigPatch).filter(- ([key]) => key !== "status" && !keepStatus.keys.includes(key)- )- )+ keepAdditionalScopesStatus && stored.status === AgentVaultOauthStatus.NeedsAdditionalScopes+ ? Object.fromEntries(Object.entries(credentialConfigPatch).filter(([key]) => key !== "status")): credentialConfigPatch;row.credentialConfig = { ...stored, ...patch };return {@@ -920,28 +917,25 @@ describe("refreshing a service's token", () => {});test("required scopes from a 403 mark it as needing them, with no refresh", async () => {- const result = await env.service.refreshServiceToken({+ await env.service.reportMissingScopes({serviceId: SERVICE_ID,- projectId: PROJECT_ID,- destination: DESTINATION,+ hostPattern: DESTINATION.hostPattern,rejectedTokenHash: hashAccessToken("old-access"),requiredScopes: ["admin"]});- expect(result.status).toBe(AgentVaultOauthStatus.NeedsAdditionalScopes);+ expect(config().status).toBe(AgentVaultOauthStatus.NeedsAdditionalScopes);expect(config().requiredScopes).toEqual(["admin"]);+ expect(openBytes<TAgentVaultOauthSecret>(row().encryptedCredential!).accessToken).toBe("old-access");expect(env.tokenRequests).toHaveLength(0);});test("required scopes for a token that was already replaced change nothing", async () => {- const result = await env.service.refreshServiceToken({+ await env.service.reportMissingScopes({serviceId: SERVICE_ID,- projectId: PROJECT_ID,- destination: DESTINATION,+ hostPattern: DESTINATION.hostPattern,rejectedTokenHash: hashAccessToken("older-access"),requiredScopes: ["admin"]});- expect(result.status).toBe(AgentVaultOauthStatus.Connected);- expect(result.credential.value).toBe("old-access");expect(config().status).toBe(AgentVaultOauthStatus.Connected);expect(config().requiredScopes).toEqual([]);expect(env.tokenRequests).toHaveLength(0);@@ -952,14 +946,12 @@ describe("refreshing a service's token", () => {status: AgentVaultOauthStatus.NeedsReauthorization,lastError: "revoked"});- const result = await env.service.refreshServiceToken({+ await env.service.reportMissingScopes({serviceId: SERVICE_ID,- projectId: PROJECT_ID,- destination: DESTINATION,+ hostPattern: DESTINATION.hostPattern,rejectedTokenHash: hashAccessToken("old-access"),requiredScopes: ["admin"]});- expect(result.status).toBe(AgentVaultOauthStatus.NeedsReauthorization);expect(config().status).toBe(AgentVaultOauthStatus.NeedsReauthorization);expect(config().requiredScopes).toEqual([]);});@@ -1087,10 +1079,9 @@ describe("refreshing a service's token", () => {test("two scope reports for the same token at once both end up required", async () => {const report = (scopes: string[]) =>- env.service.refreshServiceToken({+ env.service.reportMissingScopes({serviceId: SERVICE_ID,- projectId: PROJECT_ID,- destination: DESTINATION,+ hostPattern: DESTINATION.hostPattern,rejectedTokenHash: hashAccessToken("old-access"),requiredScopes: scopes});@@ -1105,22 +1096,32 @@ describe("refreshing a service's token", () => {status: AgentVaultOauthStatus.NeedsAdditionalScopes,requiredScopes: ["admin"]});- await env.service.refreshServiceToken({+ await env.service.reportMissingScopes({serviceId: SERVICE_ID,- projectId: PROJECT_ID,- destination: DESTINATION,+ hostPattern: DESTINATION.hostPattern,rejectedTokenHash: hashAccessToken("old-access"),requiredScopes: ["write", "admin", "write"]});expect(config().requiredScopes).toEqual(["admin", "write"]);});+ test("a scope report for a service that moved is a 409 and changes nothing", async () => {+ await expect(+ env.service.reportMissingScopes({+ serviceId: SERVICE_ID,+ hostPattern: "old.example.com",+ rejectedTokenHash: hashAccessToken("old-access"),+ requiredScopes: ["admin"]+ })+ ).rejects.toThrow(AGENT_VAULT_SERVICE_MOVED_MESSAGE);+ expect(config().requiredScopes).toEqual([]);+ });+test("a reauthorization needed after the report's read still isn't overridden by it", async () => {const liveRow = env.rows.get(SERVICE_ID)!;- const result = env.service.refreshServiceToken({+ const result = env.service.reportMissingScopes({serviceId: SERVICE_ID,- projectId: PROJECT_ID,- destination: DESTINATION,+ hostPattern: DESTINATION.hostPattern,rejectedTokenHash: hashAccessToken("old-access"),requiredScopes: ["admin"]});@@ -1128,7 +1129,8 @@ describe("refreshing a service's token", () => {status: AgentVaultOauthStatus.NeedsReauthorization,lastError: "revoked"});- expect((await result).status).toBe(AgentVaultOauthStatus.NeedsReauthorization);+ await result;+ expect(config().status).toBe(AgentVaultOauthStatus.NeedsReauthorization);expect(config().requiredScopes).toEqual([]);});});diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-service.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-service.tsindex ec5bb89b37..4b8e4fdb8f 100644--- a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-service.ts+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-service.ts@@ -67,6 +67,7 @@ import {TCreateAuthorizationDTO,TGetAuthorizationDTO,TRefreshServiceTokenDTO,+ TReportMissingScopesDTO,TResolvedOauthCredential} from "./agent-vault-oauth-types";@@ -647,11 +648,11 @@ export const agentVaultOauthServiceFactory = ({};const toResolvedCredential = (config: TAgentVaultOauthConfig, accessToken: string): TResolvedOauthCredential => ({- type: "bearer",+ type: AgentVaultCredentialType.Bearer,headerName: AGENT_VAULT_OAUTH_HEADER_NAME,headerPrefix: AGENT_VAULT_OAUTH_HEADER_PREFIX,value: accessToken,- source: "oauth",+ source: AgentVaultCredentialType.OAuth,expiresAt: config.expiresAt});@@ -707,7 +708,6 @@ export const agentVaultOauthServiceFactory = ({serviceId,projectId,rejectedTokenHash,- requiredScopes,expiresWithinSeconds,destination}: TRefreshServiceTokenDTO): Promise<{ credential: TResolvedOauthCredential; status: AgentVaultOauthStatus }> => {@@ -759,31 +759,6 @@ export const agentVaultOauthServiceFactory = ({current = updated ? fromWrittenRow(updated, current.secret, current.encryptedCredential) : await load(current);};- if (requiredScopes?.length) {- // Only the refused token is known to lack the scopes: a replacement may carry them. And a service that needs- // reauthorizing keeps saying so, since reauthorizing is what fixes both.- // Both conditions are checked again in the UPDATE, against the row it writes.- if (- rejectedTokenHash === current.config.accessTokenHash &&- current.config.status !== AgentVaultOauthStatus.NeedsReauthorization- ) {- const previousStatus = current.config.status;- const updated = await agentVaultServiceDAL.addRequiredScopes({- id: serviceId,- expectedEncryptedCredential: current.encryptedCredential,- rejectedTokenHash,- requiredScopes- });- current = updated ? fromWrittenRow(updated, current.secret, current.encryptedCredential) : await load(current);- if (updated && previousStatus !== AgentVaultOauthStatus.NeedsAdditionalScopes) {- logger.warn(- `agentVaultOauth: service status changed [serviceId=${serviceId}] [from=${previousStatus}] [to=${AgentVaultOauthStatus.NeedsAdditionalScopes}] [reason=insufficient_scope]`- );- }- }- return answer();- }-const decide = () =>decideRefresh({status: current.config.status,@@ -866,8 +841,8 @@ export const agentVaultOauthServiceFactory = ({scopesCommaSeparated: result.tokens.scopesCommaSeparated});const patch: Partial<TAgentVaultOauthConfig> = {- // Missing scopes stay missing after a refresh; only reauthorizing can add them. `keepStatus` below covers a- // scope report that lands after this read.+ // Missing scopes stay missing after a refresh; only reauthorizing can add them.+ // `keepAdditionalScopesStatus` below covers a scope report that lands after this read.status:config.status === AgentVaultOauthStatus.NeedsAdditionalScopes? AgentVaultOauthStatus.NeedsAdditionalScopes@@ -886,7 +861,7 @@ export const agentVaultOauthServiceFactory = ({expectedEncryptedCredential: current.encryptedCredential,encryptedCredential,credentialConfigPatch: patch,- keepStatus: { status: AgentVaultOauthStatus.NeedsAdditionalScopes, keys: ["requiredScopes"] }+ keepAdditionalScopesStatus: true});if (!swapped) {@@ -901,12 +876,42 @@ export const agentVaultOauthServiceFactory = ({}};+ // From a `403 insufficient_scope` challenge. Nothing is refreshed, since only reauthorizing can add scopes. Only+ // the refused token is known to lack them (a replacement may carry them), and a service that needs reauthorizing+ // keeps saying so; the UPDATE checks both against the row it writes, so a report that matches neither is a no-op.+ const reportMissingScopes = async ({+ serviceId,+ rejectedTokenHash,+ requiredScopes,+ hostPattern+ }: TReportMissingScopesDTO) => {+ const service = await agentVaultServiceDAL.findByIdPrimary(serviceId);+ if (!service || service.credentialType !== AgentVaultCredentialType.OAuth || !service.encryptedCredential) {+ throw new NotFoundError({ message: `OAuth service with ID '${serviceId}' not found` });+ }+ if (service.hostPattern !== hostPattern) throw new ConflictError({ message: AGENT_VAULT_SERVICE_MOVED_MESSAGE });++ const previousStatus = (service.credentialConfig as TAgentVaultOauthConfig).status;+ const updated = await agentVaultServiceDAL.addRequiredScopes({+ id: serviceId,+ expectedEncryptedCredential: service.encryptedCredential,+ rejectedTokenHash,+ requiredScopes+ });+ if (updated && previousStatus !== AgentVaultOauthStatus.NeedsAdditionalScopes) {+ logger.warn(+ `agentVaultOauth: service status changed [serviceId=${serviceId}] [from=${previousStatus}] [to=${AgentVaultOauthStatus.NeedsAdditionalScopes}] [reason=insufficient_scope]`+ );+ }+ };+return {createAuthorization,completeAuthorization,getAuthorization,claimAuthorization,buildCredentialFromAuthorization,- refreshServiceToken+ refreshServiceToken,+ reportMissingScopes};};diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.tsindex 4e8fa35621..fe9fbe2593 100644--- a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.ts+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.ts@@ -8,7 +8,11 @@ import { sanitizeUrlForLog } from "@app/lib/logger";import { AgentVaultOauthStatus } from "../agent-vault/agent-vault-enums";import { describeServer, splitScopes, stripTrailingSlash } from "./agent-vault-oauth-discovery-fns";import { TOauthHttpClient } from "./agent-vault-oauth-http-fns";-import { AgentVaultOauthClientAuthMethod, AgentVaultOauthCompatibility } from "./agent-vault-oauth-types";+import {+ AGENT_VAULT_OAUTH_GRANT_TYPE,+ AgentVaultOauthClientAuthMethod,+ AgentVaultOauthCompatibility+} from "./agent-vault-oauth-types";const base64Url = (buffer: Buffer) => buffer.toString("base64url");@@ -351,7 +355,7 @@ export const exchangeAuthorizationCode = (requestToken({...args,params: {- grant_type: "authorization_code",+ grant_type: AGENT_VAULT_OAUTH_GRANT_TYPE,code: args.code,code_verifier: args.codeVerifier,redirect_uri: args.redirectUridiff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-types.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-types.tsindex bb20fc2624..7b78dc5ce5 100644--- a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-types.ts+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-types.ts@@ -146,21 +146,28 @@ export type TClaimAuthorizationDTO = {};export type TResolvedOauthCredential = {- type: "bearer";+ type: AgentVaultCredentialType.Bearer;headerName: string;headerPrefix: string;value: string;- source: "oauth";+ source: AgentVaultCredentialType.OAuth;expiresAt: string | null;};+export type TReportMissingScopesDTO = {+ serviceId: string;+ // The sha256 of the token the upstream refused with `insufficient_scope`.+ rejectedTokenHash: string;+ requiredScopes: string[];+ // The host pattern the proxy sent the refused token to. A service that moved since is a 409.+ hostPattern: string;+};+export type TRefreshServiceTokenDTO = {serviceId: string;projectId: string;// On demand: the sha256 of the token the upstream rejected.rejectedTokenHash?: string;- // From a `403 insufficient_scope` challenge.- requiredScopes?: string[];// Lazy, from resolve: refresh when the token expires within this many seconds.expiresWithinSeconds?: number;// Where the caller will send the token. A service that moved since is a 409, never a token for the new server.diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.tsindex 297ac11ef0..e308df86c7 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.ts@@ -47,6 +47,7 @@ const serviceRow = (overrides: Partial<TResolveServiceRow> = {}): TResolveServicconst setup = (refresh: (dto: TRefreshServiceTokenDTO) => Promise<unknown>, rows = [serviceRow()]) => {const refreshServiceToken = vi.fn(refresh);+ const reportMissingScopes = vi.fn(async () => {});const service = agentVaultProxyServiceFactory({agentVaultProxyDAL: {findByIdWithOrg: async () => ({ projectId: PROJECT_ID, orgId: "org-1", pollInterval: 60 })@@ -89,9 +90,12 @@ const setup = (refresh: (dto: TRefreshServiceTokenDTO) => Promise<unknown>, rows},licenseService: {} as never,resourceAuthMethodService: {} as never,- agentVaultOauthService: { refreshServiceToken: refreshServiceToken as never }+ agentVaultOauthService: {+ refreshServiceToken: refreshServiceToken as never,+ reportMissingScopes: reportMissingScopes as never+ }});- return { service, refreshServiceToken };+ return { service, refreshServiceToken, reportMissingScopes };};const refreshed = {@@ -132,6 +136,36 @@ describe("credential refresh", () => {});});+describe("missing scopes report", () => {+ test("a host pattern that no longer matches the service is a 409, before anything is recorded", async () => {+ const { service, reportMissingScopes } = setup(async () => refreshed);+ const result = service.reportMissingScopes({+ ...refreshArgs,+ hostPattern: "old.example.com",+ requiredScopes: ["admin"]+ });+ await expect(result).rejects.toThrow(AGENT_VAULT_SERVICE_MOVED_MESSAGE);+ expect(reportMissingScopes).not.toHaveBeenCalled();+ });++ test("records the scopes against the rejected token without refreshing", async () => {+ const { service, refreshServiceToken, reportMissingScopes } = setup(async () => refreshed);+ await service.reportMissingScopes({+ ...refreshArgs,+ rejectedTokenHash: "A".repeat(64),+ hostPattern: "mcp.linear.app",+ requiredScopes: ["admin"]+ });+ expect(reportMissingScopes).toHaveBeenCalledWith({+ serviceId: SERVICE_ID,+ rejectedTokenHash: "a".repeat(64),+ requiredScopes: ["admin"],+ hostPattern: "mcp.linear.app"+ });+ expect(refreshServiceToken).not.toHaveBeenCalled();+ });+});+describe("resolve's lazy refresh", () => {const resolve = (service: ReturnType<typeof setup>["service"]) =>service.resolveSession({ proxyId: "proxy-1", orgId: "org-1", sessionToken: "token", hasSessionLogKey: false });diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.tsindex 648f90fcc2..b424e05517 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts@@ -67,6 +67,7 @@ import {TListProxiesDTO,TProxyByIdDTO,TRefreshCredentialDTO,+ TReportMissingScopesDTO,TResolvedService,TResolveSessionDTO,TUpdateProxyDTO@@ -97,7 +98,7 @@ type TAgentVaultProxyServiceFactoryDep = {TResourceAuthMethodServiceFactory,"initAtCreate" | "mintToken" | "loginWithToken" | "revokeAccess">;- agentVaultOauthService: Pick<TAgentVaultOauthServiceFactory, "refreshServiceToken">;+ agentVaultOauthService: Pick<TAgentVaultOauthServiceFactory, "refreshServiceToken" | "reportMissingScopes">;};export type TAgentVaultProxyServiceFactory = ReturnType<typeof agentVaultProxyServiceFactory>;@@ -341,7 +342,7 @@ export const agentVaultProxyServiceFactory = ({): TResolvedService["credential"] => {const config = (row.credentialConfig ?? {}) as Record<string, string>;if (row.credentialType === AgentVaultCredentialType.Passthrough || !row.encryptedCredential) {- return { type: "passthrough" };+ return { type: AgentVaultCredentialType.Passthrough };}if (!decryptor) throw new InternalServerError({ message: "Failed to resolve the session's credentials" });@@ -352,7 +353,7 @@ export const agentVaultProxyServiceFactory = ({if (row.credentialType === AgentVaultCredentialType.Bearer) {return {- type: "bearer",+ type: AgentVaultCredentialType.Bearer,headerName: config.headerName,headerPrefix: config.headerPrefix,value: secret.value@@ -363,15 +364,15 @@ export const agentVaultProxyServiceFactory = ({if (row.credentialType === AgentVaultCredentialType.OAuth) {const oauth = row.credentialConfig as TAgentVaultOauthConfig;return {- type: "bearer",+ type: AgentVaultCredentialType.Bearer,headerName: AGENT_VAULT_OAUTH_HEADER_NAME,headerPrefix: AGENT_VAULT_OAUTH_HEADER_PREFIX,value: secret.accessToken,- source: "oauth",+ source: AgentVaultCredentialType.OAuth,expiresAt: oauth.expiresAt ?? null};}- return { type: "basic", username: secret.username ?? "", password: secret.password ?? "" };+ return { type: AgentVaultCredentialType.Basic, username: secret.username ?? "", password: secret.password ?? "" };};// The ids come out of the decrypted fields rather than the reference rows, so a service saved mid-poll can@@ -716,16 +717,13 @@ export const agentVaultProxyServiceFactory = ({};};- // After the upstream rejected a token. Never audited, like resolve: it is proxy-driven and per request.- const refreshCredential = async ({+ const $findSessionOauthService = async ({proxyId,orgId,sessionToken,serviceId,- hostPattern,- rejectedTokenHash,- requiredScopes- }: TRefreshCredentialDTO) => {+ hostPattern+ }: Pick<TRefreshCredentialDTO, "proxyId" | "orgId" | "sessionToken" | "serviceId" | "hostPattern">) => {const { session, accessBundleIds } = await $authorizeSession({ proxyId, orgId, sessionToken });const [row] = await agentVaultResolveDAL.findResolvableServices({sessionId: session.id,@@ -743,20 +741,38 @@ export const agentVaultProxyServiceFactory = ({// not hand it the new server's token. The refresh re-checks against the primary, which this replica read may// trail.if (row.hostPattern !== hostPattern) throw new ConflictError({ message: AGENT_VAULT_SERVICE_MOVED_MESSAGE });+ return { session, row };+ };+ // After the upstream rejected a token. Never audited, like resolve: it is proxy-driven and per request.+ const refreshCredential = async ({ rejectedTokenHash, ...dto }: TRefreshCredentialDTO) => {+ const { session, row } = await $findSessionOauthService(dto);const result = await agentVaultOauthService.refreshServiceToken({serviceId: row.id,projectId: session.projectId,rejectedTokenHash: rejectedTokenHash.toLowerCase(),- requiredScopes,- destination: { hostPattern }+ destination: { hostPattern: dto.hostPattern }});logger.info(- `agentVaultCredentialRefresh: answered [sessionId=${session.id}] [proxyId=${proxyId}] [serviceId=${row.id}] [status=${result.status}]`+ `agentVaultCredentialRefresh: answered [sessionId=${session.id}] [proxyId=${dto.proxyId}] [serviceId=${row.id}] [status=${result.status}]`);return result;};+ // After the upstream refused a token with `insufficient_scope`. Not audited, for the same reason as a refresh.+ const reportMissingScopes = async ({ rejectedTokenHash, requiredScopes, ...dto }: TReportMissingScopesDTO) => {+ const { session, row } = await $findSessionOauthService(dto);+ await agentVaultOauthService.reportMissingScopes({+ serviceId: row.id,+ rejectedTokenHash: rejectedTokenHash.toLowerCase(),+ requiredScopes,+ hostPattern: dto.hostPattern+ });+ logger.info(+ `agentVaultMissingScopes: recorded [sessionId=${session.id}] [proxyId=${dto.proxyId}] [serviceId=${row.id}] [scopes=${requiredScopes.length}]`+ );+ };+return {getProxyForAuth,listProxies,@@ -768,6 +784,7 @@ export const agentVaultProxyServiceFactory = ({enroll,heartbeat,resolveSession,- refreshCredential+ refreshCredential,+ reportMissingScopes};};diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.tsindex 5f5954ec89..dc906f8629 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts@@ -1,6 +1,10 @@import { TGenericPermission } from "@app/lib/types";-import { AgentVaultServiceType, AgentVaultTrafficPolicy } from "../agent-vault/agent-vault-enums";+import {+ AgentVaultCredentialType,+ AgentVaultServiceType,+ AgentVaultTrafficPolicy+} from "../agent-vault/agent-vault-enums";export type TAgentVaultProxyScoped = { projectId: string; ctx: TGenericPermission };@@ -59,7 +63,10 @@ export type TRefreshCredentialDTO = {// The host pattern of the cached service the proxy injected the rejected token into.hostPattern: string;rejectedTokenHash: string;- requiredScopes?: string[];+};++export type TReportMissingScopesDTO = TRefreshCredentialDTO & {+ requiredScopes: string[];};export type TResolvedService = {@@ -72,16 +79,16 @@ export type TResolvedService = {allowedPathPrefixes: string[] | null;credential:| {- type: "bearer";+ type: AgentVaultCredentialType.Bearer;headerName: string;headerPrefix: string;value: string;// Set only for an OAuth credential, which the proxy may ask to refresh.- source?: "oauth";+ source?: AgentVaultCredentialType.OAuth;expiresAt?: string | null;}- | { type: "basic"; username: string; password: string }- | { type: "passthrough" };+ | { type: AgentVaultCredentialType.Basic; username: string; password: string }+ | { type: AgentVaultCredentialType.Passthrough };customHeaders: { name: string; prefix: string; value: string }[];substitutions: { placeholder: string; surfaces: string[]; value: string }[];};diff --git a/backend/src/ee/services/agent-vault/CLAUDE.md b/backend/src/ee/services/agent-vault/CLAUDE.mdindex 89ff1fef1d..ca30f07355 100644--- a/backend/src/ee/services/agent-vault/CLAUDE.md+++ b/backend/src/ee/services/agent-vault/CLAUDE.md@@ -260,12 +260,12 @@ code exchange and refresh; the proxy only ever receives the access token.- **Refresh writes the row, which no other credential does, so it races admin edits.** A refresh is acompare-and-swap on `encryptedCredential` and a jsonb merge of only the token keys, so an admin who reauthorizedmeanwhile keeps the newer tokens. An admin edit that keeps the tokens never writes `credentialConfig`, so it- can't write back token fields a refresh changed. A scope report changes only the config, so it- passes that compare; the refresh's UPDATE keeps `needs-additional-scopes` in SQL rather than in the WHERE, since+ can't write back token fields a refresh changed. A scope report (`missing-scopes`, its own route because it never+ refreshes) changes only the config, so it passes that compare; the refresh's UPDATE keeps `needs-additional-scopes` in SQL rather than in the WHERE, sincelosing the write would drop a rotated refresh token. For the same reason two scope reports can't be told apart bythe compare, so the report unions `requiredScopes` in its UPDATE (`addRequiredScopes`), never from what it read.-- **A token only goes where the service still points.** `credential-refresh` takes the host pattern the proxy- cached and answers 409 once the service has moved; resolve's lazy refresh is pinned to the host and server URL of+- **A token only goes where the service still points.** `credential-refresh` and `missing-scopes` take the host+ pattern the proxy cached and answer 409 once the service has moved; resolve's lazy refresh is pinned to the host and server URL ofthe snapshot it answers with, and falls back to that snapshot's own token. Both are checked on every row a tokencomes from, since a move can land mid-refresh. A reauthorizing save re-checks the authorization's server URLunder the bundle lock, and a reauthorization committed since its first read wins with a 409 (a refresh doesn't@@ -290,7 +290,8 @@ code exchange and refresh; the proxy only ever receives the access token.refreshes and sends the stored token for any still running, which finish in the background. A refresh waitsabout 3 seconds for another's lock, then answers with what is stored, and its token requests (the`invalid_target` retry included) share one 7 second budget. Keep that sum under the proxy's timeout.-- **Neither refreshes nor resolve are audited.** Connect and reauthorize are (`AGENT_VAULT_SERVICE_CREDENTIAL_AUTHORIZE`).+- **Neither refreshes nor resolve are audited.** Connect and reauthorize are recorded by the service create and+ update events, which carry `oauthIssuer` and `oauthScopes`.- **Non-conforming servers are supported through fallbacks**, each recorded in `compatibility`. A fallback mayrelax what a server must advertise, never a check that stops mix-up or token theft: the issuer must match (atrailing slash aside), the protected resource must be the server's own origin, and `iss` is checked whenever itdiff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex d15a949696..cde772d865 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -817,7 +817,6 @@ export enum EventType {AGENT_VAULT_SERVICE_CREATE = "agent-vault-service-create",AGENT_VAULT_SERVICE_UPDATE = "agent-vault-service-update",AGENT_VAULT_SERVICE_DELETE = "agent-vault-service-delete",- AGENT_VAULT_SERVICE_CREDENTIAL_AUTHORIZE = "agent-vault-service-credential-authorize",AGENT_VAULT_VARIABLE_CREATE = "agent-vault-variable-create",AGENT_VAULT_VARIABLE_UPDATE = "agent-vault-variable-update",AGENT_VAULT_VARIABLE_DELETE = "agent-vault-variable-delete",@@ -6554,21 +6553,6 @@ interface AgentVaultServiceUpdateEvent {};}-// On connect (create) and reauthorize (update). Refreshes are proxy-driven and not audited, like resolve.-interface AgentVaultServiceCredentialAuthorizeEvent {- type: EventType.AGENT_VAULT_SERVICE_CREDENTIAL_AUTHORIZE;- metadata: {- accessBundleId: string;- accessBundleName: string;- serviceId: string;- name: string;- serverUrl?: string;- oauthIssuer: string;- oauthScopes: string[];- reauthorization: boolean;- };-}-interface AgentVaultServiceDeleteEvent {type: EventType.AGENT_VAULT_SERVICE_DELETE;metadata: {@@ -8613,7 +8597,6 @@ export type Event =| AgentVaultServiceCreateEvent| AgentVaultServiceUpdateEvent| AgentVaultServiceDeleteEvent- | AgentVaultServiceCredentialAuthorizeEvent| AgentVaultVariableCreateEvent| AgentVaultVariableUpdateEvent| AgentVaultVariableDeleteEventdiff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 69f7b30852..729387b406 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -4487,9 +4487,10 @@ export const AGENT_VAULT = {SERVICE: {serviceId: "The ID of the service.",name: "The name of the service.",- type: "The kind of service. `http`, the default, brokers an HTTP API matched by host pattern. `mcp` brokers a remote MCP server, matched by the host of its server URL. Can't be changed after the service is created.",- config:- "Settings specific to the service's type. Empty for an `http` service. For an `mcp` service, its `serverUrl` and `transport`.",+ type: "The kind of service. `http` brokers an HTTP API matched by host pattern. `mcp` brokers a remote MCP server, matched by the host of its server URL. Can't be changed after the service is created.",+ serverUrlRead: "The MCP server's full URL. Null for an `http` service.",+ transportRead:+ "How the agent talks to the MCP server: `streamable-http`, or `sse` for the legacy HTTP+SSE transport. Null for an `http` service.",serverUrl:"The MCP server's full URL, as in `https://mcp.example.com/mcp`. Must use `https`, with no username, password, query string or fragment. The service covers this URL's host, plus its port when that is not 443, which is returned as `hostPattern`.",transport: "How the agent talks to the MCP server: `streamable-http`, or `sse` for the legacy HTTP+SSE transport.",diff --git a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsxindex 254d08ddf9..278542a5df 100644--- a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx+++ b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx@@ -359,8 +359,8 @@ export const ServiceSheet = ({reset({...BLANK_MCP_SERVICE_FORM,name: service.name,- serverUrl: service.config.serverUrl,- transport: service.config.transport,+ serverUrl: service.serverUrl,+ transport: service.transport,credentialType: isBearer ? AgentVaultCredentialType.Bearer : AgentVaultCredentialType.OAuth,headerName: isBearer ? credential.headerName : "Authorization",headerPrefix: isBearer ? credential.headerPrefix : "Bearer",diff --git a/frontend/src/components/agent-vault/service-sheet/serviceRequest.test.ts b/frontend/src/components/agent-vault/service-sheet/serviceRequest.test.tsindex 709a33b6f1..71012bd120 100644--- a/frontend/src/components/agent-vault/service-sheet/serviceRequest.test.ts+++ b/frontend/src/components/agent-vault/service-sheet/serviceRequest.test.ts@@ -69,6 +69,7 @@ describe("buildCreateServiceRequest", () => {)).toEqual({accessBundleId: "bundle-1",+ type: AgentVaultServiceType.Http,name: "stripe",hostPattern: "api.stripe.com,files.stripe.com",allowedMethods: [AgentVaultHttpMethod.Get],diff --git a/frontend/src/components/agent-vault/service-sheet/serviceRequest.ts b/frontend/src/components/agent-vault/service-sheet/serviceRequest.tsindex f5e40f3a44..9dfff31e9c 100644--- a/frontend/src/components/agent-vault/service-sheet/serviceRequest.ts+++ b/frontend/src/components/agent-vault/service-sheet/serviceRequest.ts@@ -119,7 +119,12 @@ export const buildCreateServiceRequest = (...buildMcpFields(data),credential: buildMcpCredential(data)}- : { accessBundleId, ...buildHttpFields(data), credential: buildHttpCredential(data) };+ : {+ accessBundleId,+ type: AgentVaultServiceType.Http,+ ...buildHttpFields(data),+ credential: buildHttpCredential(data)+ };export const buildUpdateServiceRequest = (accessBundleId: string,diff --git a/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts b/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.tsindex 87933e1089..e9133fd9d4 100644--- a/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts+++ b/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts@@ -50,7 +50,8 @@ const storedOAuthService = (serverUrl = SERVER_URL) =>name: "linear-mcp",hostPattern: "mcp.linear.app",type: AgentVaultServiceType.Mcp,- config: { serverUrl, transport: AgentVaultMcpTransport.StreamableHttp },+ serverUrl,+ transport: AgentVaultMcpTransport.StreamableHttp,allowedMethods: null,allowedPathPrefixes: null,credential: {diff --git a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts b/frontend/src/components/agent-vault/service-sheet/serviceSchema.tsindex 1c38349e98..904cc6feab 100644--- a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts+++ b/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts@@ -197,7 +197,7 @@ export const storedOAuthCredential = (): TAgentVaultOAuthCredentialSummary | null =>service?.type === AgentVaultServiceType.Mcp &&service.credential.type === AgentVaultCredentialType.OAuth &&- service.config.serverUrl === serverUrl.trim()+ service.serverUrl === serverUrl.trim()? service.credential: null;diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.tsindex b85024b481..62510c7b87 100644--- a/frontend/src/hooks/api/agentVault/types.ts+++ b/frontend/src/hooks/api/agentVault/types.ts@@ -95,14 +95,9 @@ export type TAgentVaultVariableReference = {| { field: AgentVaultVariableReferenceField.Substitution; substitutionId: string });-export type TAgentVaultMcpServiceConfig = {- serverUrl: string;- transport: AgentVaultMcpTransport;-};-export type TAgentVaultServiceConfig =- | { type: AgentVaultServiceType.Http; config: Record<string, never> }- | { type: AgentVaultServiceType.Mcp; config: TAgentVaultMcpServiceConfig };+ | { type: AgentVaultServiceType.Http; serverUrl: null; transport: null }+ | { type: AgentVaultServiceType.Mcp; serverUrl: string; transport: AgentVaultMcpTransport };export type TAgentVaultService = TAgentVaultServiceConfig & {id: string;@@ -299,7 +294,7 @@ export type TUpdateAgentVaultAccessBundleDTO = {export type TCreateAgentVaultServiceDTO =| {accessBundleId: string;- type?: AgentVaultServiceType.Http;+ type: AgentVaultServiceType.Http;name: string;hostPattern: string;allowedMethods?: AgentVaultHttpMethod[] | null;diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsxindex ce48bb6015..55ef8a81e8 100644--- a/frontend/src/hooks/api/auditLogs/constants.tsx+++ b/frontend/src/hooks/api/auditLogs/constants.tsx@@ -480,7 +480,6 @@ export const eventToNameMap: { [K in EventType]: string } = {[EventType.AGENT_VAULT_SERVICE_CREATE]: "Create service",[EventType.AGENT_VAULT_SERVICE_UPDATE]: "Update service",[EventType.AGENT_VAULT_SERVICE_DELETE]: "Delete service",- [EventType.AGENT_VAULT_SERVICE_CREDENTIAL_AUTHORIZE]: "Authorize service credential",[EventType.AGENT_VAULT_VARIABLE_CREATE]: "Create variable",[EventType.AGENT_VAULT_VARIABLE_UPDATE]: "Update variable",[EventType.AGENT_VAULT_VARIABLE_DELETE]: "Delete variable",@@ -562,7 +561,6 @@ export const projectToEventsMap: Partial<Record<ProjectType, EventType[]>> = {EventType.AGENT_VAULT_SERVICE_CREATE,EventType.AGENT_VAULT_SERVICE_UPDATE,EventType.AGENT_VAULT_SERVICE_DELETE,- EventType.AGENT_VAULT_SERVICE_CREDENTIAL_AUTHORIZE,EventType.AGENT_VAULT_VARIABLE_CREATE,EventType.AGENT_VAULT_VARIABLE_UPDATE,EventType.AGENT_VAULT_VARIABLE_DELETE,diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsxindex afb2ae4082..14486c3bd5 100644--- a/frontend/src/hooks/api/auditLogs/enums.tsx+++ b/frontend/src/hooks/api/auditLogs/enums.tsx@@ -478,7 +478,6 @@ export enum EventType {AGENT_VAULT_SERVICE_CREATE = "agent-vault-service-create",AGENT_VAULT_SERVICE_UPDATE = "agent-vault-service-update",AGENT_VAULT_SERVICE_DELETE = "agent-vault-service-delete",- AGENT_VAULT_SERVICE_CREDENTIAL_AUTHORIZE = "agent-vault-service-credential-authorize",AGENT_VAULT_VARIABLE_CREATE = "agent-vault-variable-create",AGENT_VAULT_VARIABLE_UPDATE = "agent-vault-variable-update",AGENT_VAULT_VARIABLE_DELETE = "agent-vault-variable-delete",diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsxindex e4af334260..b58bc7a7e1 100644--- a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx@@ -80,7 +80,7 @@ const ALL_TYPES = "all";const serviceTypeOf = (service: TAgentVaultService) => service.type ?? AgentVaultServiceType.Http;const targetOf = (service: TAgentVaultService) =>- service.type === AgentVaultServiceType.Mcp ? service.config.serverUrl : service.hostPattern;+ service.type === AgentVaultServiceType.Mcp ? service.serverUrl : service.hostPattern;const SORT_COMPARATORS: Record<SortColumn,@@ -131,8 +131,8 @@ const TypeBadge = ({ type }: { type: AgentVaultServiceType }) => (const TargetCell = ({ service }: { service: TAgentVaultService }) =>service.type === AgentVaultServiceType.Mcp ? (- <span className="block max-w-72 truncate font-mono text-sm" title={service.config.serverUrl}>- {service.config.serverUrl}+ <span className="block max-w-72 truncate font-mono text-sm" title={service.serverUrl}>+ {service.serverUrl}</span>) : (<HostsCell hostPattern={service.hostPattern} />