Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

misc: more feedback

Sheen Capadngan82741873a869
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.ts
index 571b4f26c5..da99620867 100644
--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts
+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts
@@ -7,7 +7,10 @@ import { pollUntil } from "e2e-test/testUtils/poll";
import { AccessScope, ActionProjectType, OrgMembershipRole, ProjectMembershipRole, ProjectType } from "@app/db/schemas";
import { seedData1 } from "@app/db/seed-data";
import { agentVaultServiceCustomHeaderDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-custom-header-dal";
+import { agentVaultServiceDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-dal";
import { agentVaultServiceSubstitutionDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-substitution-dal";
+import { MAX_OAUTH_SCOPES } from "@app/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns";
+import { AGENT_VAULT_SERVICE_MOVED_MESSAGE } from "@app/ee/services/agent-vault-oauth/agent-vault-oauth-service";
import { agentVaultProxyDALFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-dal";
import {
AGENT_VAULT_MAX_PROXIES_PER_ORG,
@@ -246,6 +249,26 @@ const createAccessBundle = async (name: string) => {
return (JSON.parse(res.payload) as { accessBundle: { id: string; name: string } }).accessBundle;
};
+// Enrollment only checks that it is a live CA. ECDSA P-256, because the FIPS image refuses Ed25519.
+const createProxyCaPem = async () => {
+ const algorithm = { name: "ECDSA", namedCurve: "P-256", hash: "SHA-256" };
+ const keys = await globalThis.crypto.subtle.generateKey(algorithm, true, ["sign", "verify"]);
+ const certificate = await x509.X509CertificateGenerator.createSelfSigned({
+ name: "CN=Agent Vault Proxy Test CA",
+ serialNumber: "01",
+ notBefore: new Date(Date.now() - 60_000),
+ notAfter: new Date(Date.now() + 24 * 60 * 60 * 1000),
+ signingAlgorithm: algorithm,
+ keys,
+ extensions: [
+ new x509.BasicConstraintsExtension(true, undefined, true),
+ // eslint-disable-next-line no-bitwise
+ new x509.KeyUsagesExtension(x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign, true)
+ ]
+ });
+ return certificate.toString("pem");
+};
+
describe("Agent Vault V1 Router", async () => {
// Tests create their own proxies, and an org can hold only AGENT_VAULT_MAX_PROXIES_PER_ORG.
beforeEach(async () => {
@@ -796,6 +819,303 @@ describe("Agent Vault V1 Router", async () => {
});
});
+ describe("MCP services", async () => {
+ const servicesUrl = (bundleId: string) => `/api/v1/agent-vault/access-bundles/${bundleId}/services`;
+
+ const createMcpService = async (bundleId: string, name: string, serverUrl: string) => {
+ const res = await inject("POST", servicesUrl(bundleId), {
+ type: "mcp",
+ name,
+ serverUrl,
+ transport: "streamable-http",
+ credential: { type: "bearer", value: "mcp-token" }
+ });
+ expect(res.statusCode).toBe(200);
+ return (JSON.parse(res.payload) as { service: { id: string; hostPattern: string } }).service;
+ };
+
+ const messageOf = (res: { payload: string }) => (JSON.parse(res.payload) as { message: string }).message;
+
+ test("an MCP service takes its host from the server URL, and moves with it", async () => {
+ const bundle = await createAccessBundle("mcp-host-pattern");
+
+ const res = await inject("POST", servicesUrl(bundle.id), {
+ type: "mcp",
+ name: "linear",
+ serverUrl: "https://mcp.linear.app/mcp",
+ transport: "sse",
+ credential: { type: "bearer", value: "lin_api_secret" }
+ });
+ expect(res.statusCode).toBe(200);
+ const { service } = JSON.parse(res.payload) as {
+ service: { id: string; type: string; hostPattern: string; serverUrl: string; transport: string };
+ };
+ expect(service).toMatchObject({
+ type: "mcp",
+ hostPattern: "mcp.linear.app",
+ serverUrl: "https://mcp.linear.app/mcp",
+ transport: "sse"
+ });
+ expect(res.payload).not.toContain("lin_api_secret");
+
+ const withPort = await createMcpService(bundle.id, "internal", "https://mcp.example.com:8443/mcp");
+ expect(withPort.hostPattern).toBe("mcp.example.com:8443");
+
+ const moved = await inject("PATCH", `${servicesUrl(bundle.id)}/${service.id}`, {
+ serverUrl: "https://mcp.linear.dev/mcp"
+ });
+ expect(moved.statusCode).toBe(200);
+ expect(JSON.parse(moved.payload).service.hostPattern).toBe("mcp.linear.dev");
+ });
+
+ test("a field that belongs to the other type is refused by name, on create and update", async () => {
+ const bundle = await createAccessBundle("mcp-wrong-fields");
+ const mcp = {
+ type: "mcp",
+ name: "linear",
+ serverUrl: "https://mcp.linear.app/mcp",
+ transport: "streamable-http",
+ credential: { type: "bearer", value: "token" }
+ };
+
+ const withHttpFields = await inject("POST", servicesUrl(bundle.id), {
+ ...mcp,
+ hostPattern: "mcp.linear.app",
+ allowedMethods: ["GET"]
+ });
+ expect(withHttpFields.statusCode).toBe(400);
+ expect(messageOf(withHttpFields)).toContain("An MCP service doesn't take 'hostPattern' or 'allowedMethods'.");
+
+ const withBasic = await inject("POST", servicesUrl(bundle.id), {
+ ...mcp,
+ credential: { type: "basic", username: "user", password: "pass" }
+ });
+ expect(withBasic.statusCode).toBe(400);
+ expect(messageOf(withBasic)).toContain("An MCP service can't use basic auth as its credential.");
+
+ const httpWithServerUrl = await inject("POST", servicesUrl(bundle.id), {
+ type: "http",
+ name: "github",
+ hostPattern: "api.github.com",
+ serverUrl: "https://api.github.com/mcp",
+ credential: { type: "bearer", value: "token" }
+ });
+ expect(httpWithServerUrl.statusCode).toBe(400);
+ expect(messageOf(httpWithServerUrl)).toContain("An HTTP service doesn't take 'serverUrl'.");
+
+ const service = await createMcpService(bundle.id, "linear", "https://mcp.linear.app/mcp");
+ const patchedHostPattern = await inject("PATCH", `${servicesUrl(bundle.id)}/${service.id}`, {
+ hostPattern: "other.example.com"
+ });
+ expect(patchedHostPattern.statusCode).toBe(400);
+ expect(messageOf(patchedHostPattern)).toContain("An MCP service doesn't take 'hostPattern'.");
+ });
+
+ test("a service's type can't be changed", async () => {
+ const bundle = await createAccessBundle("mcp-type-change");
+ const service = await createMcpService(bundle.id, "linear", "https://mcp.linear.app/mcp");
+
+ const res = await inject("PATCH", `${servicesUrl(bundle.id)}/${service.id}`, { type: "http" });
+ expect(res.statusCode).toBe(400);
+ expect(messageOf(res)).toContain("A service's type can't be changed.");
+
+ const stored = await inject("GET", `/api/v1/agent-vault/access-bundles/${bundle.id}`);
+ expect(stored.payload).toContain('"type":"mcp"');
+ });
+
+ describe("credential refresh", async () => {
+ // A real enrolled proxy on the real route, so the session and proxy checks run as they do in production.
+ const proxyFor = async (bundle: { name: string }, proxyName: string) => {
+ const mint = await inject("POST", "/api/v1/agent-vault/sessions", { accessBundles: [bundle.name], ttl: "1h" });
+ expect(mint.statusCode).toBe(200);
+ const { session } = JSON.parse(mint.payload) as { session: { token: string } };
+
+ const created = await inject("POST", "/api/v1/agent-vault/proxies", { name: proxyName });
+ expect(created.statusCode).toBe(200);
+ const { token } = JSON.parse(created.payload) as { token: string };
+ const login = await testServer.inject({
+ method: "POST",
+ url: "/api/v1/agent-vault/proxy/login",
+ body: { method: ResourceAuthMethodType.Token, token, rootCaCertificate: await createProxyCaPem() }
+ });
+ expect(login.statusCode).toBe(200);
+ const { accessToken } = JSON.parse(login.payload) as { accessToken: string };
+
+ return (serviceId: string, hostPattern: string) =>
+ testServer.inject({
+ method: "POST",
+ url: `/api/v1/agent-vault/proxy/services/${serviceId}/credential-refresh`,
+ headers: { authorization: `Bearer ${accessToken}`, "x-infisical-agent-session": session.token },
+ body: { hostPattern, rejectedTokenHash: "a".repeat(64) }
+ });
+ };
+
+ test("a service outside the session is a 404, and one without OAuth is a 400", async () => {
+ const bundle = await createAccessBundle("refresh-not-found");
+ const service = await createMcpService(bundle.id, "linear", "https://mcp.linear.app/mcp");
+ const otherBundle = await createAccessBundle("refresh-other-bundle");
+ const outside = await createMcpService(otherBundle.id, "linear", "https://mcp.linear.app/mcp");
+ const refresh = await proxyFor(bundle, "refresh-not-found");
+
+ const unknown = await refresh(crypto.randomUUID(), "mcp.linear.app");
+ expect(unknown.statusCode).toBe(404);
+ const otherSession = await refresh(outside.id, "mcp.linear.app");
+ expect(otherSession.statusCode).toBe(404);
+
+ const bearer = await refresh(service.id, "mcp.linear.app");
+ expect(bearer.statusCode).toBe(400);
+ expect(messageOf(bearer)).toBe(
+ "The service 'linear' doesn't use OAuth, so Infisical can't refresh its credential."
+ );
+ });
+
+ test("a host pattern the service no longer has is a 409, so no token goes to the old host", async () => {
+ const bundle = await createAccessBundle("refresh-moved");
+ const service = await createMcpService(bundle.id, "linear", "https://mcp.linear.app/mcp");
+ // Connecting OAuth needs a browser sign-in, so the row is switched to OAuth directly.
+ await testDb("agent_vault_services")
+ .where({ id: service.id })
+ .update({
+ credentialType: "oauth",
+ credentialConfig: { status: "connected", accessTokenHash: "a".repeat(64) }
+ });
+ const refresh = await proxyFor(bundle, "refresh-moved");
+
+ const res = await refresh(service.id, "mcp.old-linear.app");
+ expect(res.statusCode).toBe(409);
+ expect(messageOf(res)).toBe(AGENT_VAULT_SERVICE_MOVED_MESSAGE);
+ });
+ });
+ });
+
+ // The unit tests run these against a JS copy of the SQL. Only Postgres can show the compare, the jsonb merge and
+ // the union happen in one UPDATE, against the row being written.
+ describe("OAuth credential writes (postgres)", async () => {
+ const serviceDAL = agentVaultServiceDALFactory(testDb as never);
+ const SEALED = Buffer.from("sealed-credential-1");
+ const TOKEN_HASH = "b".repeat(64);
+
+ const oauthService = async (name: string, config: Record<string, unknown> = {}) => {
+ const bundle = await createAccessBundle(name);
+ const res = await inject("POST", `/api/v1/agent-vault/access-bundles/${bundle.id}/services`, {
+ type: "mcp",
+ name,
+ serverUrl: "https://mcp.linear.app/mcp",
+ transport: "streamable-http",
+ credential: { type: "bearer", value: "token" }
+ });
+ expect(res.statusCode).toBe(200);
+ const { service } = JSON.parse(res.payload) as { service: { id: string } };
+ // Connecting OAuth needs a browser sign-in, so the row is switched to OAuth directly.
+ await testDb("agent_vault_services")
+ .where({ id: service.id })
+ .update({
+ credentialType: "oauth",
+ encryptedCredential: SEALED,
+ credentialConfig: {
+ status: "connected",
+ accessTokenHash: TOKEN_HASH,
+ grantedScopes: ["read"],
+ requiredScopes: [],
+ ...config
+ }
+ });
+ return service.id;
+ };
+
+ const storedConfig = async (id: string) =>
+ (await testDb("agent_vault_services").where({ id }).first()).credentialConfig as Record<string, unknown>;
+
+ test("compareAndSwapCredential writes only over the sealed credential it read, and merges just its keys", async () => {
+ const id = await oauthService("cas-write");
+ const swapped = await serviceDAL.compareAndSwapCredential({
+ id,
+ expectedEncryptedCredential: SEALED,
+ encryptedCredential: Buffer.from("sealed-credential-2"),
+ credentialConfigPatch: { accessTokenHash: "c".repeat(64), lastError: null }
+ });
+ expect(swapped?.credentialConfig).toMatchObject({ accessTokenHash: "c".repeat(64), grantedScopes: ["read"] });
+
+ const stale = await serviceDAL.compareAndSwapCredential({
+ id,
+ expectedEncryptedCredential: SEALED,
+ encryptedCredential: Buffer.from("sealed-credential-3"),
+ credentialConfigPatch: { accessTokenHash: "d".repeat(64) }
+ });
+ expect(stale).toBeUndefined();
+ const row = await testDb("agent_vault_services").where({ id }).first();
+ expect(row.encryptedCredential.toString()).toBe("sealed-credential-2");
+ expect(row.credentialConfig.accessTokenHash).toBe("c".repeat(64));
+ });
+
+ test("compareAndSwapCredential keeps needs-additional-scopes only when asked, judged on the stored row", async () => {
+ const patch = { status: "connected", lastError: null };
+ const kept = await oauthService("cas-keep-scopes", { status: "needs-additional-scopes", lastError: "old" });
+ await serviceDAL.compareAndSwapCredential({
+ id: kept,
+ expectedEncryptedCredential: SEALED,
+ credentialConfigPatch: patch,
+ keepAdditionalScopesStatus: true
+ });
+ expect(await storedConfig(kept)).toMatchObject({ status: "needs-additional-scopes", lastError: null });
+
+ const replaced = await oauthService("cas-replace-scopes", { status: "needs-additional-scopes" });
+ await serviceDAL.compareAndSwapCredential({
+ id: replaced,
+ expectedEncryptedCredential: SEALED,
+ credentialConfigPatch: patch
+ });
+ expect((await storedConfig(replaced)).status).toBe("connected");
+ });
+
+ test("addRequiredScopes unions in the UPDATE, so two reports at once both land", async () => {
+ const id = await oauthService("scopes-concurrent");
+ const report = (requiredScopes: string[]) =>
+ serviceDAL.addRequiredScopes({
+ id,
+ expectedEncryptedCredential: SEALED,
+ rejectedTokenHash: TOKEN_HASH,
+ requiredScopes
+ });
+
+ await Promise.all([report(["admin"]), report(["write", "admin"])]);
+ const config = await storedConfig(id);
+ expect(config.status).toBe("needs-additional-scopes");
+ expect([...(config.requiredScopes as string[])].sort()).toEqual(["admin", "write"]);
+ });
+
+ test("addRequiredScopes writes nothing for granted scopes, a replaced token, or a dead login", async () => {
+ const id = await oauthService("scopes-refused");
+ const report = (requiredScopes: string[], rejectedTokenHash = TOKEN_HASH) =>
+ serviceDAL.addRequiredScopes({ id, expectedEncryptedCredential: SEALED, rejectedTokenHash, requiredScopes });
+
+ expect(await report(["read"])).toBeUndefined();
+ expect(await report(["admin"], "e".repeat(64))).toBeUndefined();
+
+ const dead = await oauthService("scopes-dead-login", { status: "needs-reauthorization" });
+ expect(
+ await serviceDAL.addRequiredScopes({
+ id: dead,
+ expectedEncryptedCredential: SEALED,
+ rejectedTokenHash: TOKEN_HASH,
+ requiredScopes: ["admin"]
+ })
+ ).toBeUndefined();
+ expect(await storedConfig(id)).toMatchObject({ status: "connected", requiredScopes: [] });
+ });
+
+ test("addRequiredScopes stops growing the list at the scope limit", async () => {
+ const id = await oauthService("scopes-cap");
+ await serviceDAL.addRequiredScopes({
+ id,
+ expectedEncryptedCredential: SEALED,
+ rejectedTokenHash: TOKEN_HASH,
+ requiredScopes: Array.from({ length: MAX_OAUTH_SCOPES + 5 }, (_, index) => `scope-${index}`)
+ });
+ expect((await storedConfig(id)).requiredScopes).toHaveLength(MAX_OAUTH_SCOPES);
+ });
+ });
+
describe("variables", async () => {
const variablesUrl = "/api/v1/agent-vault/variables";
const servicesUrl = (accessBundleId: string) => `/api/v1/agent-vault/access-bundles/${accessBundleId}/services`;
@@ -829,26 +1149,6 @@ describe("Agent Vault V1 Router", async () => {
const referencesByField = (references: TReference[]) =>
references.map((reference) => `${reference.field}:${reference.key}`).sort();
- // Enrollment only checks that it is a live CA. ECDSA P-256, because the FIPS image refuses Ed25519.
- const createProxyCaPem = async () => {
- const algorithm = { name: "ECDSA", namedCurve: "P-256", hash: "SHA-256" };
- const keys = await globalThis.crypto.subtle.generateKey(algorithm, true, ["sign", "verify"]);
- const certificate = await x509.X509CertificateGenerator.createSelfSigned({
- name: "CN=Agent Vault Variables Test CA",
- serialNumber: "01",
- notBefore: new Date(Date.now() - 60_000),
- notAfter: new Date(Date.now() + 24 * 60 * 60 * 1000),
- signingAlgorithm: algorithm,
- keys,
- extensions: [
- new x509.BasicConstraintsExtension(true, undefined, true),
- // eslint-disable-next-line no-bitwise
- new x509.KeyUsagesExtension(x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign, true)
- ]
- });
- return certificate.toString("pem");
- };
-
type TResolved = {
services: {
name: string;
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.ts
index d99653b35f..9934fc6baf 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
@@ -25,6 +25,11 @@ const AuthorizationViewSchema = z.object({
const printable = (max: number) =>
z.string().max(max).regex(OAUTH_VSCHAR_PATTERN, "Use printable ASCII characters without line breaks or accents");
+// Sent to the provider as typed, unlike the credential fields that take `{{KEY}}`, so a reference would only come
+// back as an invalid_client nobody can explain.
+const noVariableReference = (value: string) => !value.includes("{{");
+const VARIABLES_NOT_SUPPORTED_MESSAGE = "Variables aren't supported here. Paste the value.";
+
// JWT only: an authorization ends in a browser redirect, so only a signed-in user can start or finish one.
export const registerAgentVaultOauthRouter = async (server: FastifyZodProvider) => {
server.route({
@@ -46,12 +51,14 @@ export const registerAgentVaultOauthRouter = async (server: FastifyZodProvider)
.trim()
.min(1)
.pipe(printable(MAX_CLIENT_ID_LENGTH))
+ .refine(noVariableReference, VARIABLES_NOT_SUPPORTED_MESSAGE)
.optional()
.describe(AGENT_VAULT.OAUTH.clientId),
clientSecret: z
.string()
.min(1)
.pipe(printable(MAX_CLIENT_SECRET_LENGTH))
+ .refine(noVariableReference, VARIABLES_NOT_SUPPORTED_MESSAGE)
.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.ts
index 0ca6f4a377..c04b510a7b 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
@@ -245,7 +245,7 @@ export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProvi
hide: true,
operationId: "refreshAgentVaultServiceCredential",
description:
- "After the upstream rejected an OAuth token, return a fresh one. If the rejected token is no longer the current one, the current one is returned without calling the provider. A 409 means the service's host pattern no longer matches `hostPattern`, and no token is returned.",
+ "Get a new access token after the MCP server rejected the current one. Returns 409 if the service now points at a different server.",
tags: [ApiDocsTags.AgentVaultProxies],
headers: SessionHeaderSchema,
params: z.object({ serviceId: z.string().uuid().describe(AGENT_VAULT.SERVICE.serviceId) }),
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.ts
index a90f0d6397..e1c26a9a5c 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
@@ -62,40 +62,45 @@ const basicHalvesAreNotBothEmpty = (
});
};
-export const AgentVaultCredentialInputSchema = z
- .discriminatedUnion("type", [
- z
- .object({
- type: z.literal(AgentVaultCredentialType.Bearer),
- headerName: agentVaultHeaderNameSchema.optional().describe(AGENT_VAULT.SERVICE.headerName),
- headerPrefix: agentVaultHeaderPrefixSchema.optional().describe(AGENT_VAULT.SERVICE.headerPrefix),
- value: acceptsVariableReferences(
- z.string().min(1).max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
- ).describe(AGENT_VAULT.SERVICE.value)
- })
- .describe(JSON.stringify({ title: "Bearer" })),
- z
- .object({
- type: z.literal(AgentVaultCredentialType.Basic),
- username: acceptsVariableReferences(
- z.string().trim().max(256).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
- ).describe(AGENT_VAULT.SERVICE.username),
- password: acceptsVariableReferences(
- z.string().max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
- ).describe(AGENT_VAULT.SERVICE.password)
- })
- .describe(JSON.stringify({ title: "Basic Auth" })),
- z
- .object({ type: z.literal(AgentVaultCredentialType.Passthrough) })
- .describe(JSON.stringify({ title: "Pass-through" })),
- z
- .object({
- type: z.literal(AgentVaultCredentialType.OAuth),
- authorizationId: z.string().uuid().describe(AGENT_VAULT.SERVICE.authorizationId)
- })
- .describe(JSON.stringify({ title: "OAuth" }))
- ])
- .superRefine(basicHalvesAreNotBothEmpty);
+const bearerCredentialInput = z.object({
+ type: z.literal(AgentVaultCredentialType.Bearer),
+ headerName: agentVaultHeaderNameSchema.optional().describe(AGENT_VAULT.SERVICE.headerName),
+ headerPrefix: agentVaultHeaderPrefixSchema.optional().describe(AGENT_VAULT.SERVICE.headerPrefix),
+ value: acceptsVariableReferences(
+ z.string().min(1).max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
+ ).describe(AGENT_VAULT.SERVICE.value)
+});
+const basicCredentialInput = z.object({
+ type: z.literal(AgentVaultCredentialType.Basic),
+ username: acceptsVariableReferences(
+ z.string().trim().max(256).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
+ ).describe(AGENT_VAULT.SERVICE.username),
+ password: acceptsVariableReferences(
+ z.string().max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
+ ).describe(AGENT_VAULT.SERVICE.password)
+});
+const passthroughCredentialInput = z.object({ type: z.literal(AgentVaultCredentialType.Passthrough) });
+const oauthCredentialInput = z.object({
+ type: z.literal(AgentVaultCredentialType.OAuth),
+ authorizationId: z.string().uuid().describe(AGENT_VAULT.SERVICE.authorizationId)
+});
+
+const docsTitle = (title: string, hidden = false) => JSON.stringify({ title, ...(hidden ? { "x-hidden": true } : {}) });
+
+// Only a user in the UI can complete an authorization, so the API docs never offer OAuth. The MCP schema also
+// hides the types an MCP service can't use, but still accepts them so the service refuses them by name.
+const credentialInputSchema = ({ mcp }: { mcp: boolean }) =>
+ z
+ .discriminatedUnion("type", [
+ bearerCredentialInput.describe(docsTitle("Bearer")),
+ basicCredentialInput.describe(docsTitle("Basic Auth", mcp)),
+ passthroughCredentialInput.describe(docsTitle("Pass-through", mcp)),
+ oauthCredentialInput.describe(docsTitle("OAuth", true))
+ ])
+ .superRefine(basicHalvesAreNotBothEmpty);
+
+export const AgentVaultCredentialInputSchema = credentialInputSchema({ mcp: false });
+export const AgentVaultMcpCredentialInputSchema = credentialInputSchema({ mcp: true });
// Not derived from the create schema: its `.default()`s would turn an omitted field into a reset on a PATCH.
export const AgentVaultCredentialUpdateSchema = z
@@ -135,7 +140,8 @@ export const AgentVaultCredentialUpdateSchema = z
type: z.literal(AgentVaultCredentialType.OAuth),
authorizationId: z.string().uuid().describe(AGENT_VAULT.SERVICE.updateAuthorizationId)
})
- .describe(JSON.stringify({ title: "OAuth" }))
+ // Only a user in the UI can complete an authorization, so the API docs don't offer it.
+ .describe(JSON.stringify({ title: "OAuth", "x-hidden": true }))
])
.superRefine(basicHalvesAreNotBothEmpty);
@@ -159,13 +165,6 @@ export const AgentVaultCredentialSummarySchema = z.discriminatedUnion("type", [
grantedScopes: z.string().array().describe(AGENT_VAULT.SERVICE.oauthGrantedScopes),
requiredScopes: z.string().array().describe(AGENT_VAULT.SERVICE.oauthRequiredScopes),
expiresAt: z.string().nullable().describe(AGENT_VAULT.SERVICE.oauthExpiresAt),
- authorizedBy: z
- .object({
- userId: z.string().uuid().describe(AGENT_VAULT.SERVICE.oauthAuthorizedByUserId),
- username: z.string().describe(AGENT_VAULT.SERVICE.oauthAuthorizedByUsername)
- })
- .nullable()
- .describe(AGENT_VAULT.SERVICE.oauthAuthorizedBy),
authorizedAt: z.string().nullable().describe(AGENT_VAULT.SERVICE.oauthAuthorizedAt),
lastError: z.string().nullable().describe(AGENT_VAULT.SERVICE.oauthLastError)
})
@@ -233,7 +232,7 @@ export const AgentVaultCreateServiceBodySchema = z.discriminatedUnion("type", [
name: AgentVaultNameSchema.describe(AGENT_VAULT.SERVICE.name),
serverUrl: AgentVaultServerUrlSchema,
transport: AgentVaultMcpTransportSchema,
- credential: AgentVaultCredentialInputSchema.describe(AGENT_VAULT.SERVICE.mcpCredential),
+ credential: AgentVaultMcpCredentialInputSchema.describe(AGENT_VAULT.SERVICE.mcpCredential),
customHeaders: AgentVaultCustomHeadersInputSchema.optional(),
hostPattern: AgentVaultHostPatternSchema.optional().describe(openApiHidden()),
allowedMethods: AgentVaultAllowedMethodsSchema.optional().describe(openApiHidden()),
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.ts
index 04551c6372..69194ebe7b 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
@@ -412,7 +412,6 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
grantedScopes: oauth.grantedScopes ?? [],
requiredScopes: oauth.requiredScopes ?? [],
expiresAt: oauth.expiresAt ?? null,
- authorizedBy: oauth.authorizedBy ?? null,
authorizedAt: oauth.authorizedAt ?? null,
lastError: oauth.lastError ?? null
};
@@ -668,6 +667,16 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
}
};
+ // An authorization only comes from a browser sign-in in the UI, so a machine identity could never hold one.
+ const assertOauthConnectedByUser = (
+ ctx: TGetAccessBundleDTO["ctx"],
+ credential?: TAgentVaultCredentialInput | TAgentVaultCredentialUpdate
+ ) => {
+ if (credential?.type === AgentVaultCredentialType.OAuth && ctx.actor !== ActorType.USER) {
+ throw new BadRequestError({ message: "OAuth services can only be connected by a user in the Infisical UI." });
+ }
+ };
+
// The tokens come from an authorization the same user completed. Claiming it deletes it right before the write,
// and a save that then fails puts it back, so it can be retried without authorizing again.
const claimOauthCredential = async ({
@@ -687,7 +696,6 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
authorizationId: string;
previousRequiredScopes?: string[];
}) => {
- const [user] = ctx.actor === ActorType.USER ? await userDAL.find({ id: ctx.actorId }) : [];
const claim = await agentVaultOauthService.claimAuthorization({
authorizationId,
projectId,
@@ -697,10 +705,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
serverUrl
});
const build = (requiredScopes?: string[]) =>
- agentVaultOauthService.buildCredentialFromAuthorization(claim.record, {
- authorizedBy: user ? { userId: user.id, username: user.username } : null,
- previousRequiredScopes: requiredScopes
- });
+ agentVaultOauthService.buildCredentialFromAuthorization(claim.record, { previousRequiredScopes: requiredScopes });
try {
return { claim, ...build(previousRequiredScopes), rebuild: build };
} catch (err) {
@@ -905,6 +910,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
ProjectPermissionAgentVaultAccessBundleActions.Edit,
ProjectPermissionSub.AgentVaultAccessBundles
);
+ assertOauthConnectedByUser(rest.ctx, credential);
const serviceType = getAgentVaultServiceType(type);
assertServiceFieldsSupported(serviceType, {
@@ -1097,6 +1103,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
ProjectPermissionAgentVaultAccessBundleActions.Edit,
ProjectPermissionSub.AgentVaultAccessBundles
);
+ assertOauthConnectedByUser(rest.ctx, credential);
const service = await agentVaultServiceDAL.findByIdInAccessBundle({ id: serviceId, accessBundleId: bundle.id });
if (!service) throw new NotFoundError({ message: `Service with ID '${serviceId}' not found` });
@@ -1312,6 +1319,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
// The claim checked the server URL of the first read; these tokens must never reach another host.
const requiredScopes = checkOauthClaimUnderLock({
authorizedServerUrl: oauth.claim.record.serverUrl,
+ authorizedIssuer: oauth.claim.record.issuer,
lockedServerUrl: getServiceServerUrl(lockedServiceConfig ?? locked.config),
readOauth: storedOauth,
lockedOauth
@@ -1343,7 +1351,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
);
if (!lockedBundle) throw new NotFoundError({ message: `Access bundle with ID '${accessBundleId}' not found` });
- const locked = await agentVaultServiceDAL.findByIdInAccessBundle(
+ const locked = await agentVaultServiceDAL.lockByIdInAccessBundle(
{ id: service.id, accessBundleId: bundle.id },
tx
);
diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts
index 3eaa669e6e..2bcfdbd7d8 100644
--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts
+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts
@@ -30,7 +30,6 @@ export type TAgentVaultOauthCredentialSummary = {
grantedScopes: string[];
requiredScopes: string[];
expiresAt: string | null;
- authorizedBy: { userId: string; username: string } | null;
authorizedAt: string | null;
lastError: string | null;
};
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.ts
index e954a1247c..c3e1043bed 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
@@ -35,6 +35,19 @@ export const agentVaultServiceDALFactory = (db: TDbClient) => {
}
};
+ // A scope report or token refresh is a single UPDATE that only checks the sealed credential, so a save that read
+ // the row without this lock could write over one that committed in between.
+ const lockByIdInAccessBundle = async (
+ { id, accessBundleId }: { id: string; accessBundleId: string },
+ tx: Knex
+ ): Promise<TAgentVaultServices | undefined> => {
+ try {
+ return await tx(TableName.AgentVaultService).where({ id, accessBundleId }).forUpdate().first();
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Lock agent vault service" });
+ }
+ };
+
const findByIdPrimary = async (id: string, tx?: Knex): Promise<TAgentVaultServices | undefined> => {
try {
return await (tx || db)(TableName.AgentVaultService).where({ id }).first();
@@ -126,6 +139,7 @@ export const agentVaultServiceDALFactory = (db: TDbClient) => {
...orm,
findByAccessBundleId,
findByIdInAccessBundle,
+ lockByIdInAccessBundle,
findByIdPrimary,
compareAndSwapCredential,
addRequiredScopes
diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-client-fns.test.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-client-fns.test.ts
index d0fe846f0f..e64f8cdebb 100644
--- a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-client-fns.test.ts
+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-client-fns.test.ts
@@ -46,7 +46,8 @@ describe("client registration", () => {
const args = {
serverUrl: "https://mcp.example.com/mcp",
registrationEndpoint: "https://mcp.example.com/register",
- redirectUri: "https://app.infisical.com/agent-vault/oauth/callback"
+ redirectUri: "https://app.infisical.com/agent-vault/oauth/callback",
+ grantTypesSupported: null
};
test("sends the full metadata and keeps the method the server assigned", async () => {
@@ -71,6 +72,12 @@ describe("client registration", () => {
});
});
+ test("asks for refresh_token only when the server doesn't list grants without it", async () => {
+ const { http, calls } = stubPosts([json(201, { client_id: "c-1" })]);
+ await registerOauthClient({ http, ...args, grantTypesSupported: ["authorization_code"] });
+ expect(calls[0].json).toMatchObject({ grant_types: ["authorization_code"] });
+ });
+
test("a rejected registration is retried once without application_type, keeping the grant types", async () => {
const { http, calls } = stubPosts([
json(400, { error: "invalid_client_metadata" }),
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.ts
index 1491b4ea8f..49955468b2 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
@@ -73,23 +73,27 @@ const parseRegistration = (body: string): TOauthClient | null => {
// RFC 7591. Servers must ignore metadata fields they don't understand, so the only one a strict server can refuse
// is `application_type` (an OIDC registration value); a refusal is retried once without it. `grant_types` stays,
-// or a strict server registers authorization_code only and every refresh fails with unauthorized_client.
+// or a strict server registers authorization_code only and every refresh fails with unauthorized_client. It drops
+// refresh_token only when the server's metadata lists its grants without it, since a strict one refuses the request.
export const registerOauthClient = async ({
http,
serverUrl,
registrationEndpoint,
- redirectUri
+ redirectUri,
+ grantTypesSupported
}: {
http: TOauthHttpClient;
serverUrl: string;
registrationEndpoint: string;
redirectUri: string;
+ grantTypesSupported: string[] | null;
}): Promise<{ client: TOauthClient; compatibility: AgentVaultOauthCompatibility[] }> => {
+ const refreshSupported = !grantTypesSupported || grantTypesSupported.includes("refresh_token");
const minimal = {
client_name: AGENT_VAULT_OAUTH_CLIENT_NAME,
redirect_uris: [redirectUri],
token_endpoint_auth_method: AgentVaultOauthClientAuthMethod.None,
- grant_types: [AGENT_VAULT_OAUTH_GRANT_TYPE, "refresh_token"],
+ grant_types: refreshSupported ? [AGENT_VAULT_OAUTH_GRANT_TYPE, "refresh_token"] : [AGENT_VAULT_OAUTH_GRANT_TYPE],
response_types: ["code"]
};
const full = { ...minimal, application_type: "web" };
diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns.test.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns.test.ts
index 3c312e314b..53ee435e0d 100644
--- a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns.test.ts
+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns.test.ts
@@ -27,10 +27,18 @@ type TStubServer = {
getThrows?: boolean;
// Requests that never answer, as a hung server's would.
hang?: boolean;
+ hangUrls?: string[];
json: Record<string, unknown>;
};
-const stubHttp = ({ challenge = null, probeThrows = false, getThrows = false, hang = false, json }: TStubServer) => {
+const stubHttp = ({
+ challenge = null,
+ probeThrows = false,
+ getThrows = false,
+ hang = false,
+ hangUrls = [],
+ json
+}: TStubServer) => {
const fetched: string[] = [];
const never = () =>
new Promise<never>(() => {
@@ -44,7 +52,7 @@ const stubHttp = ({ challenge = null, probeThrows = false, getThrows = false, ha
},
get: async (url) => {
fetched.push(url);
- if (hang) return never();
+ if (hang || hangUrls.includes(url)) return never();
if (getThrows) throw new Error("getaddrinfo ENOTFOUND");
return url in json
? { status: 200, contentType: "application/json", body: JSON.stringify(json[url]) }
@@ -67,6 +75,7 @@ const LINEAR_AS = {
registration_endpoint: "https://mcp.linear.app/register",
scopes_supported: ["read", "write", "openid", "email"],
token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post", "none"],
+ grant_types_supported: ["authorization_code", "refresh_token"],
code_challenge_methods_supported: ["S256"],
authorization_response_iss_parameter_supported: true
};
@@ -270,6 +279,7 @@ describe("discovering an MCP server's authorization server", () => {
scopes: ["read", "write"],
issParameterSupported: true,
tokenEndpointAuthMethodsSupported: ["client_secret_basic", "client_secret_post", "none"],
+ grantTypesSupported: ["authorization_code", "refresh_token"],
compatibility: [],
oauthAdvertised: true
});
@@ -282,6 +292,26 @@ describe("discovering an MCP server's authorization server", () => {
]);
});
+ test("lower-priority URLs that never answer don't hold up the preferred ones", async () => {
+ const { http } = stubHttp({
+ challenge: 'Bearer resource_metadata="https://mcp.linear.app/.well-known/oauth-protected-resource/mcp"',
+ hangUrls: [
+ "https://mcp.linear.app/.well-known/oauth-protected-resource",
+ "https://mcp.linear.app/.well-known/openid-configuration"
+ ],
+ json: {
+ "https://mcp.linear.app/.well-known/oauth-protected-resource/mcp": {
+ resource: "https://mcp.linear.app/mcp",
+ authorization_servers: ["https://mcp.linear.app"]
+ },
+ "https://mcp.linear.app/.well-known/oauth-authorization-server": LINEAR_AS
+ }
+ });
+ await expect(discoverOauthServer(http, "https://mcp.linear.app/mcp", 1000)).resolves.toMatchObject({
+ tokenEndpoint: "https://mcp.linear.app/token"
+ });
+ });
+
test("an issuer with a path and no registration endpoint (GitHub)", async () => {
const { http, fetched } = stubHttp({
challenge:
diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns.ts
index c25bae0678..c3a865afb7 100644
--- a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns.ts
+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns.ts
@@ -26,6 +26,7 @@ export type TOauthDiscovery = {
scopes: string[];
issParameterSupported: boolean;
tokenEndpointAuthMethodsSupported: string[] | null;
+ grantTypesSupported: string[] | null;
compatibility: AgentVaultOauthCompatibility[];
// False when the server answered but sent no Bearer challenge and serves no OAuth metadata, which usually
// means the URL is wrong. Old servers can still work with an admin-entered client, so it only warns.
@@ -123,6 +124,18 @@ const fetchJson = async (http: TOauthHttpClient, url: string): Promise<TFetchedJ
}
};
+// The requests are already running together; this takes the first usable answer in priority order as soon as every
+// URL ahead of it has answered, so a slow URL lower down never holds up a preferred one that already did.
+const firstUsableInOrder = async <T>(pending: Promise<T>[], usable: (value: T) => boolean): Promise<T | null> => {
+ // eslint-disable-next-line no-restricted-syntax
+ for (const promise of pending) {
+ // eslint-disable-next-line no-await-in-loop
+ const value = await promise;
+ if (usable(value)) return value;
+ }
+ return null;
+};
+
// RFC 9728 section 3.1: the well-known segment goes between the host and the path.
export const protectedResourceMetadataUrls = (serverUrl: string, challengeUrl?: string): string[] => {
const url = new URL(serverUrl);
@@ -223,26 +236,36 @@ const discover = async (http: TOauthHttpClient, serverUrl: string): Promise<TOau
const compatibility = new Set<AgentVaultOauthCompatibility>();
let answered = false;
- // The probe and the well-known locations are asked at once; the challenge only says where to look first.
- const wellKnownUrls = protectedResourceMetadataUrls(serverUrl);
- const [challenge, wellKnown] = await Promise.all([
- http.probe(serverUrl).then(
- (response) => {
- answered = true;
- return parseBearerChallenge(response.wwwAuthenticate);
- },
- () => {
- logger.info(`agentVaultOauth: MCP server probe failed [server=${describeServer(serverUrl)}]`);
- return null;
- }
- ),
- Promise.all(wellKnownUrls.map(async (url) => [url, await fetchJson(http, url)] as const))
- ]);
- const fetched = new Map<string, TFetchedJson>(wellKnown);
+ // The probe and the well-known locations are asked at once; the challenge only says where to look first, and its
+ // URL is asked as soon as the probe answers rather than after the well-known ones.
+ const fetches = new Map<string, Promise<TFetchedJson>>(
+ protectedResourceMetadataUrls(serverUrl).map((url) => [url, fetchJson(http, url)])
+ );
+ const challenge = await http.probe(serverUrl).then(
+ (response) => {
+ answered = true;
+ return parseBearerChallenge(response.wwwAuthenticate);
+ },
+ () => {
+ logger.info(`agentVaultOauth: MCP server probe failed [server=${describeServer(serverUrl)}]`);
+ return null;
+ }
+ );
const orderedUrls = protectedResourceMetadataUrls(serverUrl, challenge?.resource_metadata);
- const challengeUrl = orderedUrls.find((url) => !fetched.has(url));
- if (challengeUrl) fetched.set(challengeUrl, await fetchJson(http, challengeUrl));
- if ([...fetched.values()].some((result) => result.answered)) answered = true;
+ orderedUrls.forEach((url) => {
+ if (!fetches.has(url)) fetches.set(url, fetchJson(http, url));
+ });
+
+ const protectedResource =
+ (
+ await firstUsableInOrder(
+ orderedUrls.map((url) => fetches.get(url)!),
+ (result) => Boolean(result.json && Array.isArray(result.json.authorization_servers))
+ )
+ )?.json ?? null;
+ // Waits on every URL only when none had usable metadata, and by then they have all settled anyway.
+ if (protectedResource) answered = true;
+ else if (!answered) answered = (await Promise.all(fetches.values())).some((result) => result.answered);
if (!answered) {
throw new BadRequestError({
@@ -250,11 +273,6 @@ const discover = async (http: TOauthHttpClient, serverUrl: string): Promise<TOau
});
}
- const protectedResource =
- orderedUrls
- .map((url) => fetched.get(url)?.json)
- .find((candidate) => candidate && Array.isArray(candidate.authorization_servers)) ?? null;
-
let resource = serverUrl;
let issuer = new URL(serverUrl).origin;
if (protectedResource) {
@@ -272,8 +290,13 @@ const discover = async (http: TOauthHttpClient, serverUrl: string): Promise<TOau
compatibility.add(AgentVaultOauthCompatibility.NoProtectedResourceMetadata);
}
- const metadataResults = await Promise.all(authorizationServerMetadataUrls(issuer).map((url) => fetchJson(http, url)));
- const metadata = metadataResults.map((result) => result.json).find(Boolean) ?? null;
+ const metadata =
+ (
+ await firstUsableInOrder(
+ authorizationServerMetadataUrls(issuer).map((url) => fetchJson(http, url)),
+ (result) => Boolean(result.json)
+ )
+ )?.json ?? null;
const scopes = selectScopes({
challengeScope: challenge?.scope,
@@ -302,6 +325,7 @@ const discover = async (http: TOauthHttpClient, serverUrl: string): Promise<TOau
scopes,
issParameterSupported: false,
tokenEndpointAuthMethodsSupported: null,
+ grantTypesSupported: null,
compatibility: [...compatibility],
oauthAdvertised
};
@@ -333,6 +357,7 @@ const discover = async (http: TOauthHttpClient, serverUrl: string): Promise<TOau
}
const authMethods = metadata.token_endpoint_auth_methods_supported;
+ const grantTypes = metadata.grant_types_supported;
return {
issuer,
authorizationEndpoint,
@@ -345,6 +370,9 @@ const discover = async (http: TOauthHttpClient, serverUrl: string): Promise<TOau
tokenEndpointAuthMethodsSupported: Array.isArray(authMethods)
? authMethods.filter((method): method is string => typeof method === "string")
: null,
+ grantTypesSupported: Array.isArray(grantTypes)
+ ? grantTypes.filter((grantType): grantType is string => typeof grantType === "string")
+ : null,
compatibility: [...compatibility],
oauthAdvertised
};
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.ts
index f70e9ef4b9..b11a3e7e7a 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
@@ -1,6 +1,6 @@
import crypto from "node:crypto";
-import { createMongoAbility } from "@casl/ability";
+import { createMongoAbility, ForbiddenError } from "@casl/ability";
import { beforeEach, describe, expect, test, vi } from "vitest";
import {
@@ -98,7 +98,10 @@ const LINEAR_JSON: Record<string, unknown> = {
}
};
-const setup = ({ metadata = LINEAR_JSON }: { metadata?: Record<string, unknown> } = {}) => {
+const setup = ({
+ metadata = LINEAR_JSON,
+ canEditBundles = true
+}: { metadata?: Record<string, unknown>; canEditBundles?: boolean } = {}) => {
const store = new Map<string, string>();
const ttls = new Map<string, number>();
const rows = new Map<string, TRow>();
@@ -106,6 +109,7 @@ const setup = ({ metadata = LINEAR_JSON }: { metadata?: Record<string, unknown>
const registrations: unknown[] = [];
let registerHandler: () => TOauthHttpResponse = () => json(201, { client_id: "registered-client" });
let lockHandler: (settings: unknown) => Promise<void> = async () => {};
+ let lockTail = Promise.resolve();
let tokenHandler: (form: URLSearchParams) => TOauthHttpResponse = () =>
json(200, { access_token: "at-1", token_type: "Bearer", refresh_token: "rt-1", expires_in: 3600, scope: "read" });
@@ -155,9 +159,21 @@ const setup = ({ metadata = LINEAR_JSON }: { metadata?: Record<string, unknown>
},
deleteItem: async (key: string) => (store.delete(key) ? 1 : 0),
ttl: async (key: string) => (store.has(key) ? (ttls.get(key) ?? -1) : -2),
+ // A real mutex, so a second caller waits until the first one releases.
acquireLock: async (_keys: string[], _duration: number, settings?: unknown) => {
await lockHandler(settings);
- return { release: async () => ({}) as never };
+ const previous = lockTail;
+ let unlock = () => {};
+ lockTail = new Promise((resolve) => {
+ unlock = resolve;
+ });
+ await previous;
+ return {
+ release: async () => {
+ unlock();
+ return {} as never;
+ }
+ };
}
},
kmsService: kms as never,
@@ -248,12 +264,16 @@ const setup = ({ metadata = LINEAR_JSON }: { metadata?: Record<string, unknown>
permissionService: {
getProjectPermission: async () =>
({
- permission: createMongoAbility([
- {
- action: ProjectPermissionAgentVaultAccessBundleActions.Edit,
- subject: ProjectPermissionSub.AgentVaultAccessBundles
- }
- ]),
+ permission: createMongoAbility(
+ canEditBundles
+ ? [
+ {
+ action: ProjectPermissionAgentVaultAccessBundleActions.Edit,
+ subject: ProjectPermissionSub.AgentVaultAccessBundles
+ }
+ ]
+ : []
+ ),
hasRole: () => true,
memberships: []
}) as never
@@ -323,7 +343,6 @@ const oauthConfig = (overrides: Partial<TAgentVaultOauthConfig> = {}): TAgentVau
status: AgentVaultOauthStatus.Connected,
expiresAt: new Date(Date.now() + 3600_000).toISOString(),
accessTokenHash: hashAccessToken("old-access"),
- authorizedBy: { userId: USER_ID, username: "[email protected]" },
authorizedAt: new Date().toISOString(),
lastRefreshedAt: null,
lastError: null,
@@ -484,6 +503,42 @@ describe("starting an authorization", () => {
await expect(createAuthorization(setup(), { clientSecret: "shh" })).rejects.toThrow(/client ID/);
});
+ test("a caller who can't edit access bundles is refused before any request to the server", async () => {
+ const env = setup({ canEditBundles: false });
+ await expect(createAuthorization(env)).rejects.toThrow(ForbiddenError);
+ expect(env.registrations).toHaveLength(0);
+ });
+
+ test("a machine identity is refused, since signing in to the provider needs a browser", async () => {
+ const env = setup();
+ await expect(
+ env.service.createAuthorization({
+ projectId: PROJECT_ID,
+ ctx: { ...ctxOf(USER_ID), actor: ActorType.IDENTITY },
+ accessBundleId: BUNDLE_ID,
+ serverUrl: SERVER_URL
+ })
+ ).rejects.toThrow("Only a user can authorize an OAuth connection");
+ });
+
+ test("an HTTP service can't be authorized, since only MCP services use OAuth", async () => {
+ const env = setup();
+ env.rows.set(SERVICE_ID, {
+ id: SERVICE_ID,
+ name: "stripe",
+ type: AgentVaultServiceType.Http,
+ accessBundleId: BUNDLE_ID,
+ credentialType: AgentVaultCredentialType.Bearer,
+ credentialConfig: {},
+ encryptedCredential: null,
+ hostPattern: "api.stripe.com",
+ config: null
+ });
+ await expect(createAuthorization(env, { serviceId: SERVICE_ID })).rejects.toThrow(
+ "The service 'stripe' is an HTTP service. Only MCP services use OAuth."
+ );
+ });
+
test("an unknown bundle is a 404", async () => {
const env = setup();
await expect(
@@ -694,7 +749,7 @@ describe("completing an authorization", () => {
});
expect(refusedView.authorization).toMatchObject({
status: AgentVaultOauthAuthorizationStatus.Failed,
- error: "'mcp.linear.app' refused the token request: Code expired"
+ error: "The login server 'mcp.linear.app' refused the token request: Code expired"
});
});
@@ -710,7 +765,7 @@ describe("completing an authorization", () => {
code: "test-authorization-code",
iss: "https://mcp.linear.app"
});
- expect(view.authorization.error).toBe("'mcp.linear.app' refused the token request: bad code");
+ expect(view.authorization.error).toBe("The login server 'mcp.linear.app' refused the token request: bad code");
});
test("comma-joined scopes from the exchange are granted as the scopes asked for, and recorded", async () => {
@@ -770,9 +825,7 @@ describe("using an authorization", () => {
env.service.claimAuthorization({ ...claimArgs, authorizationId: id, ctx: ctxOf(OTHER_USER_ID) })
).rejects.toThrow(NotFoundError);
const { record } = await env.service.claimAuthorization({ ...claimArgs, authorizationId: id });
- const { config, encryptedCredential } = env.service.buildCredentialFromAuthorization(record, {
- authorizedBy: { userId: USER_ID, username: "[email protected]" }
- });
+ const { config, encryptedCredential } = env.service.buildCredentialFromAuthorization(record);
expect(openBytes<TAgentVaultOauthSecret>(encryptedCredential)).toEqual({
accessToken: "at-1",
@@ -959,6 +1012,20 @@ describe("refreshing a service's token", () => {
expect(openBytes<TAgentVaultOauthSecret>(row().encryptedCredential!).accessToken).toBe("reauthorized-access");
});
+ test("two refreshes of the same rejected token reach the provider once, and both get the new token", async () => {
+ env.onToken(() => json(200, { access_token: "new-access", token_type: "Bearer", expires_in: 600 }));
+ const refresh = () =>
+ env.service.refreshServiceToken({
+ serviceId: SERVICE_ID,
+ projectId: PROJECT_ID,
+ destination: DESTINATION,
+ rejectedTokenHash: hashAccessToken("old-access")
+ });
+ const results = await Promise.all([refresh(), refresh()]);
+ expect(env.tokenRequests).toHaveLength(1);
+ expect(results.map((result) => result.credential.value)).toEqual(["new-access", "new-access"]);
+ });
+
test("invalid_grant marks the service as needing reauthorization", async () => {
env.onToken(() => json(400, { error: "invalid_grant" }));
const result = await env.service.refreshServiceToken({
@@ -990,7 +1057,7 @@ describe("refreshing a service's token", () => {
});
expect(result.status).toBe(AgentVaultOauthStatus.NeedsReauthorization);
expect(config().lastError).toBe(
- `The MCP server no longer accepts this service's login ('mcp.linear.app' refused the token request: ${error}). Reauthorize this service.`
+ `This service's login is no longer accepted (The login server 'mcp.linear.app' refused the token request: ${error}). Reauthorize this service.`
);
// A dead login isn't retried on the next poll.
@@ -1061,7 +1128,9 @@ describe("refreshing a service's token", () => {
rejectedTokenHash: hashAccessToken("old-access")
});
expect(result.status).toBe(AgentVaultOauthStatus.Connected);
- expect(config().lastError).toBe("'mcp.linear.app' refused the token request: temporarily_unavailable");
+ expect(config().lastError).toBe(
+ "The login server 'mcp.linear.app' refused the token request: temporarily_unavailable"
+ );
expect(config().lastError).not.toContain("old-");
});
@@ -1073,7 +1142,7 @@ describe("refreshing a service's token", () => {
destination: DESTINATION,
rejectedTokenHash: hashAccessToken("old-access")
});
- expect(config().lastError).toBe("'mcp.linear.app' refused the token request: server _error");
+ expect(config().lastError).toBe("The login server 'mcp.linear.app' refused the token request: server _error");
});
test("an expires_in too large for a date is stored as no expiry instead of throwing", async () => {
@@ -1372,10 +1441,7 @@ describe("building a credential from an authorization", () => {
sealedCredential: sealBytes({ accessToken: "at-1" }).toString("base64")
}) as unknown as TAgentVaultOauthAuthorization;
const build = (grantedScopes: string[], previousRequiredScopes?: string[]) =>
- setup().service.buildCredentialFromAuthorization(record(grantedScopes), {
- authorizedBy: null,
- previousRequiredScopes
- }).config;
+ setup().service.buildCredentialFromAuthorization(record(grantedScopes), { previousRequiredScopes }).config;
test("a required scope the provider didn't grant keeps the service needing it", () => {
expect(build(["read", "write"], ["admin", "write"])).toMatchObject({
@@ -1385,10 +1451,10 @@ describe("building a credential from an authorization", () => {
});
test("records the server URL the tokens were authorized for", () => {
- const { config } = setup().service.buildCredentialFromAuthorization(
- { ...record(["read"]), serverUrl: SERVER_URL } as TAgentVaultOauthAuthorization,
- { authorizedBy: null }
- );
+ const { config } = setup().service.buildCredentialFromAuthorization({
+ ...record(["read"]),
+ serverUrl: SERVER_URL
+ } as TAgentVaultOauthAuthorization);
expect(config.serverUrl).toBe(SERVER_URL);
});
@@ -1403,14 +1469,16 @@ describe("building a credential from an authorization", () => {
describe("a reauthorization checked under the bundle lock", () => {
const authorizedAt = "2026-10-15T10:00:00.000Z";
+ const ISSUER = "https://mcp.linear.app";
test("a service moved to another server since the claim refuses the save, naming hosts only", () => {
const check = () =>
checkOauthClaimUnderLock({
authorizedServerUrl: "https://mcp.linear.app/mcp?k=secret",
+ authorizedIssuer: ISSUER,
lockedServerUrl: "https://mcp.other.example/path/key",
readOauth: { authorizedAt },
- lockedOauth: { authorizedAt, requiredScopes: [] }
+ lockedOauth: { authorizedAt, issuer: ISSUER, requiredScopes: [] }
});
expect(check).toThrow(BadRequestError);
expect(check).toThrow(
@@ -1422,9 +1490,10 @@ describe("a reauthorization checked under the bundle lock", () => {
expect(() =>
checkOauthClaimUnderLock({
authorizedServerUrl: SERVER_URL,
+ authorizedIssuer: ISSUER,
lockedServerUrl: SERVER_URL,
readOauth: { authorizedAt },
- lockedOauth: { authorizedAt: "2026-10-15T10:05:00.000Z", requiredScopes: [] }
+ lockedOauth: { authorizedAt: "2026-10-15T10:05:00.000Z", issuer: ISSUER, requiredScopes: [] }
})
).toThrow(ConflictError);
});
@@ -1433,20 +1502,34 @@ describe("a reauthorization checked under the bundle lock", () => {
expect(
checkOauthClaimUnderLock({
authorizedServerUrl: SERVER_URL,
+ authorizedIssuer: ISSUER,
lockedServerUrl: SERVER_URL,
readOauth: { authorizedAt },
- lockedOauth: { authorizedAt, requiredScopes: ["admin"] }
+ lockedOauth: { authorizedAt, issuer: ISSUER, requiredScopes: ["admin"] }
})
).toEqual(["admin"]);
expect(
checkOauthClaimUnderLock({
authorizedServerUrl: SERVER_URL,
+ authorizedIssuer: ISSUER,
lockedServerUrl: SERVER_URL,
readOauth: undefined,
lockedOauth: undefined
})
).toEqual([]);
});
+
+ test("scopes reported against another issuer are not carried over", () => {
+ expect(
+ checkOauthClaimUnderLock({
+ authorizedServerUrl: SERVER_URL,
+ authorizedIssuer: "https://auth.other.example",
+ lockedServerUrl: SERVER_URL,
+ readOauth: { authorizedAt },
+ lockedOauth: { authorizedAt, issuer: ISSUER, requiredScopes: ["admin"] }
+ })
+ ).toEqual([]);
+ });
});
describe("an edit that keeps a service's OAuth tokens, checked under the bundle lock", () => {
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.ts
index 679b58119c..43e64ac78d 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
@@ -52,13 +52,12 @@ import {
normalizeProviderText,
refreshAccessToken,
TOKEN_REQUEST_BUDGET_MS,
+ toResolvedOauthCredential,
validateCallbackIssuer,
withTokenCompatibility
} from "./agent-vault-oauth-token-fns";
import {
AGENT_VAULT_OAUTH_GRANT_TYPE,
- AGENT_VAULT_OAUTH_HEADER_NAME,
- AGENT_VAULT_OAUTH_HEADER_PREFIX,
AgentVaultOauthRegistration,
TAgentVaultOauthAuthorization,
TAgentVaultOauthAuthorizationView,
@@ -146,23 +145,26 @@ const AGENT_VAULT_REAUTHORIZED_DURING_SAVE_MESSAGE =
// Run under the bundle lock against the row read there, since a save that landed after the first read may have
// moved the service or reauthorized it. A newer reauthorization wins over a stale one, so an older authorization
// can't swap the account the service acts as back. A refresh doesn't count: it keeps `authorizedAt`, and its
-// rotated tokens are what this save replaces anyway. Returns the required scopes still to carry over.
+// rotated tokens are what this save replaces anyway. Returns the required scopes still to carry over, which are none
+// when the new authorization is from another issuer: the sign-in didn't ask for them either.
export const checkOauthClaimUnderLock = ({
authorizedServerUrl,
+ authorizedIssuer,
lockedServerUrl,
readOauth,
lockedOauth
}: {
authorizedServerUrl: string;
+ authorizedIssuer: string;
lockedServerUrl: string | null;
readOauth: Pick<TAgentVaultOauthConfig, "authorizedAt"> | undefined;
- lockedOauth: Pick<TAgentVaultOauthConfig, "authorizedAt" | "requiredScopes"> | undefined;
+ lockedOauth: Pick<TAgentVaultOauthConfig, "authorizedAt" | "issuer" | "requiredScopes"> | undefined;
}) => {
assertAuthorizationServerUrl(authorizedServerUrl, lockedServerUrl);
if ((readOauth?.authorizedAt ?? null) !== (lockedOauth?.authorizedAt ?? null)) {
throw new ConflictError({ message: AGENT_VAULT_REAUTHORIZED_DURING_SAVE_MESSAGE });
}
- return lockedOauth?.requiredScopes ?? [];
+ return lockedOauth?.issuer === authorizedIssuer ? lockedOauth.requiredScopes : [];
};
// For an edit that keeps the service's tokens, under the bundle lock: the server URL the save writes must still be
@@ -347,7 +349,8 @@ export const agentVaultOauthServiceFactory = ({
http,
serverUrl,
registrationEndpoint: discovery.registrationEndpoint,
- redirectUri: callbackUri
+ redirectUri: callbackUri,
+ grantTypesSupported: discovery.grantTypesSupported
});
client = registered.client;
compatibility.push(...registered.compatibility);
@@ -519,7 +522,6 @@ export const agentVaultOauthServiceFactory = ({
// Outside any transaction: this is a network call to the provider.
const result = await exchangeAuthorizationCode({
http,
- serverUrl: record.serverUrl,
issuer: record.issuer,
tokenEndpoint: record.tokenEndpoint,
clientId: record.clientId,
@@ -627,13 +629,7 @@ export const agentVaultOauthServiceFactory = ({
// both are the project cipher over the same JSON shape, so nothing is opened to move it.
const buildCredentialFromAuthorization = (
record: TAgentVaultOauthAuthorization,
- {
- authorizedBy,
- previousRequiredScopes = []
- }: {
- authorizedBy: { userId: string; username: string } | null;
- previousRequiredScopes?: string[];
- }
+ { previousRequiredScopes = [] }: { previousRequiredScopes?: string[] } = {}
): { config: TAgentVaultOauthConfig; encryptedCredential: Buffer } => {
const now = new Date().toISOString();
// A provider may grant less than was asked, so a scope the upstream demanded stays missing until it's granted.
@@ -659,7 +655,6 @@ export const agentVaultOauthServiceFactory = ({
status: requiredScopes.length ? AgentVaultOauthStatus.NeedsAdditionalScopes : AgentVaultOauthStatus.Connected,
expiresAt: record.expiresAt,
accessTokenHash: record.accessTokenHash ?? "",
- authorizedBy,
authorizedAt: now,
lastRefreshedAt: null,
lastError: null
@@ -668,15 +663,6 @@ export const agentVaultOauthServiceFactory = ({
};
};
- const toResolvedCredential = (config: TAgentVaultOauthConfig, accessToken: string): TResolvedOauthCredential => ({
- type: AgentVaultCredentialType.Bearer,
- headerName: AGENT_VAULT_OAUTH_HEADER_NAME,
- headerPrefix: AGENT_VAULT_OAUTH_HEADER_PREFIX,
- value: accessToken,
- source: AgentVaultCredentialType.OAuth,
- expiresAt: config.expiresAt
- });
-
// An unchanged blob holds the same tokens, so a re-read only opens the blob when it changed.
const loadOauthService = async (
serviceId: string,
@@ -757,7 +743,7 @@ export const agentVaultOauthServiceFactory = ({
const answer = () => {
assertSameDestination(current);
return {
- credential: toResolvedCredential(current.config, current.secret.accessToken),
+ credential: toResolvedOauthCredential(current.config, current.secret.accessToken),
status: current.config.status
};
};
@@ -830,7 +816,6 @@ export const agentVaultOauthServiceFactory = ({
const { config, secret } = current;
const result = await refreshAccessToken({
http,
- serverUrl: config.resource ?? config.issuer,
issuer: config.issuer,
tokenEndpoint: config.tokenEndpoint,
clientId: config.clientId,
@@ -846,7 +831,7 @@ export const agentVaultOauthServiceFactory = ({
if (!result.ok) {
if (isDeadLoginError(result.errorCode)) {
await markNeedsReauthorization(
- `The MCP server no longer accepts this service's login (${result.message}). Reauthorize this service.`
+ `This service's login is no longer accepted (${result.message}). Reauthorize this service.`
);
} else {
await applyStatus({ lastError: result.message });
diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.socket.test.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.socket.test.ts
index 2df7d75aad..c53769cab1 100644
--- a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.socket.test.ts
+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.socket.test.ts
@@ -119,7 +119,6 @@ describe("OAuth token requests over HTTPS", () => {
const args = () => ({
http: agentVaultOauthHttpClient,
issuer,
- serverUrl: `${issuer}/mcp`,
tokenEndpoint: `${issuer}/token`,
clientId: "id: one",
resource: `${issuer}/mcp`,
@@ -186,6 +185,7 @@ describe("OAuth token requests over HTTPS", () => {
transportTrust.allowInternalIps = false;
const result = await refreshAccessToken({ ...args(), refreshToken: "rt-one" });
expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.message).toContain("because it's on a private network");
expect(requests).toHaveLength(0);
});
diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.test.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.test.ts
index e3f0d260ad..260d919f65 100644
--- a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.test.ts
+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.test.ts
@@ -2,13 +2,18 @@ import crypto from "node:crypto";
import { describe, expect, test, vi } from "vitest";
-import { AgentVaultOauthStatus } from "../agent-vault/agent-vault-enums";
+import { BadRequestError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+import { PRIVATE_ADDRESS_REFUSED_MESSAGE } from "@app/lib/validator";
+
+import { AgentVaultCredentialType, AgentVaultOauthStatus } from "../agent-vault/agent-vault-enums";
import { TOauthHttpClient, TOauthHttpResponse } from "./agent-vault-oauth-http-fns";
import {
buildAuthorizeUrl,
decideRefresh,
exchangeAuthorizationCode,
expiresAtFrom,
+ formUrlEncode,
generatePkce,
generateState,
hashAccessToken,
@@ -19,6 +24,7 @@ import {
parseGrantedScopes,
parseTokenResponse,
requestToken,
+ toResolvedOauthCredential,
validateCallbackIssuer,
withTokenCompatibility
} from "./agent-vault-oauth-token-fns";
@@ -62,9 +68,8 @@ const json = (status: number, body: unknown): TOauthHttpResponse => ({
});
const tokenArgs = {
- serverUrl: "https://mcp.example.com/mcp",
- issuer: "https://mcp.example.com",
- tokenEndpoint: "https://mcp.example.com/token",
+ issuer: "https://auth.example.com",
+ tokenEndpoint: "https://auth.example.com/token",
params: { grant_type: "refresh_token", refresh_token: "rt-1" },
clientId: "client-1",
tokenEndpointAuthMethod: AgentVaultOauthClientAuthMethod.None,
@@ -213,7 +218,7 @@ describe("token requests", () => {
expect(result).toMatchObject({
ok: false,
errorCode: "invalid_grant",
- message: "'mcp.example.com' refused the token request: invalid_grant"
+ message: "The login server 'auth.example.com' refused the token request: invalid_grant"
});
});
@@ -222,7 +227,7 @@ describe("token requests", () => {
expect(await requestToken({ http, ...tokenArgs })).toMatchObject({
ok: false,
errorCode: null,
- message: "'mcp.example.com' refused the token request: HTTP 400"
+ message: "The login server 'auth.example.com' refused the token request: HTTP 400"
});
});
@@ -241,9 +246,10 @@ describe("token requests", () => {
});
test("provider refusals cannot expose request secrets or their Basic authorization header", async () => {
- const clientSecret = "client +/secret";
+ const clientSecret = "client +/secret-with_.*";
const encoded = new URLSearchParams({ value: clientSecret }).toString().slice("value=".length);
- const basic = Buffer.from(`${tokenArgs.clientId}:${encoded}`).toString("base64");
+ // oauth4webapi escapes - _ . * in the Basic header, which URLSearchParams leaves alone.
+ const basic = Buffer.from("client%2D1:client+%2B%2Fsecret%2Dwith%5F%2E%2A").toString("base64");
const { http } = stubPosts([
json(400, {
error: "invalid_grant",
@@ -278,13 +284,14 @@ describe("token requests", () => {
await requestToken({
http,
...tokenArgs,
- clientId: "id:1",
- clientSecret: "s&2",
+ clientId: "id:1-a",
+ clientSecret: "s&2_b.c*",
tokenEndpointAuthMethod: AgentVaultOauthClientAuthMethod.ClientSecretBasic
});
expect(new Headers(calls[0].headers).get("authorization")).toBe(
- `Basic ${Buffer.from("id%3A1:s%262").toString("base64")}`
+ `Basic ${Buffer.from(`${formUrlEncode("id:1-a")}:${formUrlEncode("s&2_b.c*")}`).toString("base64")}`
);
+ expect(formUrlEncode("id:1-a s&2_b.c*!~'()")).toBe("id%3A1%2Da+s%262%5Fb%2Ec%2A%21%7E%27%28%29");
expect(calls[0].form!.has("client_secret")).toBe(false);
});
@@ -353,7 +360,8 @@ describe("token requests", () => {
expect(await requestToken({ http, ...tokenArgs })).toEqual({
ok: false,
errorCode: "bad_verification_code",
- message: "'mcp.example.com' refused the token request: The code passed is incorrect or expired.",
+ message:
+ "The login server 'auth.example.com' refused the token request: The code passed is incorrect or expired.",
resourceDropped: false
});
});
@@ -379,11 +387,41 @@ describe("token requests", () => {
}
};
const result = await requestToken({ http, ...tokenArgs });
+ expect(!result.ok && result.message).toBe("Couldn't reach the login server 'auth.example.com'.");
+ });
+
+ test("a private login server is named as the reason, since retrying can't help", async () => {
+ const http: TOauthHttpClient = {
+ ...stubPosts([]).http,
+ postForm: async () => {
+ throw new BadRequestError({ message: PRIVATE_ADDRESS_REFUSED_MESSAGE });
+ }
+ };
+ const result = await requestToken({ http, ...tokenArgs });
expect(!result.ok && result.message).toBe(
- "Couldn't reach the token endpoint of 'mcp.example.com'. Try again in a moment."
+ "Infisical can't reach the login server 'auth.example.com' because it's on a private network. Use a bearer token for this service instead."
);
});
+ test("the reason a request never got an answer is logged, without the URL path or request secrets", async () => {
+ const http: TOauthHttpClient = {
+ ...stubPosts([]).http,
+ postForm: async () => {
+ throw new Error("certificate has expired while sending rt-1");
+ }
+ };
+ vi.mocked(logger.info).mockClear();
+ await requestToken({ http, ...tokenArgs, tokenEndpoint: "https://auth.example.com/tenant-secret/token" });
+ const line = vi
+ .mocked(logger.info)
+ .mock.calls.map(([message]) => String(message))
+ .join("\n");
+ expect(line).toContain("certificate has expired");
+ expect(line).toContain("https://auth.example.com");
+ expect(line).not.toContain("tenant-secret");
+ expect(line).not.toContain("rt-1");
+ });
+
test("a server that never answers fails inside the budget, and each request gets only what is left of it", async () => {
const timeouts: number[] = [];
const http: TOauthHttpClient = {
@@ -396,9 +434,7 @@ describe("token requests", () => {
const startedAt = Date.now();
const result = await requestToken({ http, ...tokenArgs, budgetMs: 50 });
expect(Date.now() - startedAt).toBeLessThan(1000);
- expect(!result.ok && result.message).toBe(
- "Couldn't reach the token endpoint of 'mcp.example.com'. Try again in a moment."
- );
+ expect(!result.ok && result.message).toBe("Couldn't reach the login server 'auth.example.com'.");
expect(timeouts).toHaveLength(1);
expect(timeouts[0]).toBeLessThanOrEqual(50);
});
@@ -550,6 +586,25 @@ describe("granted scopes", () => {
});
});
+describe("the resolved credential", () => {
+ test("is a bearer credential a proxy without OAuth support injects as is", () => {
+ expect(toResolvedOauthCredential({ expiresAt: "2026-10-21T00:00:00.000Z" }, "access-token")).toEqual({
+ type: AgentVaultCredentialType.Bearer,
+ headerName: "Authorization",
+ headerPrefix: "Bearer",
+ value: "access-token",
+ source: AgentVaultCredentialType.OAuth,
+ expiresAt: "2026-10-21T00:00:00.000Z"
+ });
+ });
+
+ test("reports no expiry when the stored config has none", () => {
+ expect(
+ toResolvedOauthCredential({} as Parameters<typeof toResolvedOauthCredential>[0], "access-token").expiresAt
+ ).toBeNull();
+ });
+});
+
describe("refresh decisions", () => {
const now = new Date("2026-10-15T12:00:00Z");
const base = {
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.ts
index 1a9b5f3dfc..06e355b474 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
@@ -3,9 +3,11 @@ import crypto from "node:crypto";
import * as oauth from "oauth4webapi";
import RE2 from "re2";
-import { sanitizeUrlForLog } from "@app/lib/logger";
+import { BadRequestError } from "@app/lib/errors";
+import { logger, sanitizeUrlForLog } from "@app/lib/logger";
+import { PRIVATE_ADDRESS_REFUSED_MESSAGE } from "@app/lib/validator";
-import { AgentVaultOauthStatus } from "../agent-vault/agent-vault-enums";
+import { AgentVaultCredentialType, AgentVaultOauthStatus } from "../agent-vault/agent-vault-enums";
import {
describeServer,
OFFLINE_ACCESS_SCOPE,
@@ -15,8 +17,12 @@ import {
import { TOauthHttpClient } from "./agent-vault-oauth-http-fns";
import {
AGENT_VAULT_OAUTH_GRANT_TYPE,
+ AGENT_VAULT_OAUTH_HEADER_NAME,
+ AGENT_VAULT_OAUTH_HEADER_PREFIX,
AgentVaultOauthClientAuthMethod,
- AgentVaultOauthCompatibility
+ AgentVaultOauthCompatibility,
+ TAgentVaultOauthConfig,
+ TResolvedOauthCredential
} from "./agent-vault-oauth-types";
const base64Url = (buffer: Buffer) => buffer.toString("base64url");
@@ -194,6 +200,14 @@ const PROVIDER_WHITESPACE_RE = new RE2(/[\s\p{Z}\ufeff\x00-\x1f\x7f]+/gu);
const PROVIDER_FORMATTING_RE = new RE2(/[\p{Cc}\p{Cf}\p{Co}]/gu);
const REPEATED_SPACES_RE = new RE2(/ {2,}/g);
const PROVIDER_URL_RE = new RE2(/https?:\/\/[^\s\v\p{Z}\ufeff<>"']+/giu);
+const FORM_URL_ESCAPED_RE = new RE2(/[-_.!~*'()]|%20/g);
+
+// The encoding oauth4webapi applies to the client ID and secret in a client_secret_basic header, which escapes
+// more characters than URLSearchParams does.
+export const formUrlEncode = (value: string) =>
+ encodeURIComponent(value).replace(FORM_URL_ESCAPED_RE, (match) =>
+ match === "%20" ? "+" : `%${match.charCodeAt(0).toString(16).toUpperCase()}`
+ );
// Anything a provider sends that can end up in a message, a log line, `lastError` or an authorization's `error`
// goes through here: line breaks and tabs become spaces, other control and formatting characters (NUL, lone
@@ -206,13 +220,15 @@ export const normalizeProviderText = (
) => {
if (typeof text !== "string" || !text) return "";
// Providers can echo request credentials in their descriptions. Redact literal and form-encoded values before
- // truncating, so a partial secret is never left at the cut.
+ // truncating, so a partial secret is never left at the cut. The request body is encoded by URLSearchParams and
+ // the Basic header by `formUrlEncode`, so both forms are redacted.
let redacted = text;
sensitiveValues
.filter((value): value is string => Boolean(value))
.forEach((value) => {
- const encoded = new URLSearchParams({ value }).toString().slice("value=".length);
- [...new Set([value, encoded, encoded.replaceAll("+", "%20")])].forEach((secret) => {
+ const encodings = [new URLSearchParams({ value }).toString().slice("value=".length), formUrlEncode(value)];
+ const secrets = new Set([value, ...encodings.flatMap((encoded) => [encoded, encoded.replaceAll("+", "%20")])]);
+ secrets.forEach((secret) => {
redacted = redacted.split(secret).join("[redacted]");
});
});
@@ -250,7 +266,6 @@ const withTimeout = <T>(promise: Promise<T>, ms: number) => {
export const requestToken = async ({
http,
- serverUrl,
issuer,
tokenEndpoint,
params,
@@ -263,7 +278,6 @@ export const requestToken = async ({
budgetMs = TOKEN_REQUEST_BUDGET_MS
}: {
http: TOauthHttpClient;
- serverUrl: string;
issuer: string;
tokenEndpoint: string;
params: Record<string, string>;
@@ -276,7 +290,9 @@ export const requestToken = async ({
sensitiveValues?: string[];
budgetMs?: number;
}): Promise<TTokenRequestResult> => {
- const host = describeServer(serverUrl);
+ // The login server can live elsewhere than the MCP server (Supabase, Stripe, GitHub), so name the host the admin
+ // needs to check.
+ const host = describeServer(tokenEndpoint);
const deadline = Date.now() + budgetMs;
const authorizationServer = { issuer, token_endpoint: tokenEndpoint };
const client = { client_id: clientId };
@@ -287,15 +303,15 @@ export const requestToken = async ({
if (clientSecret && tokenEndpointAuthMethod === AgentVaultOauthClientAuthMethod.ClientSecretPost) {
clientAuthentication = oauth.ClientSecretPost(clientSecret);
}
- const encodedClientId = new URLSearchParams({ value: clientId }).toString().slice("value=".length);
- const encodedClientSecret = new URLSearchParams({ value: clientSecret ?? "" }).toString().slice("value=".length);
const requestSecrets = [
...sensitiveValues,
clientSecret,
params.code,
params.code_verifier,
params.refresh_token,
- ...(clientSecret ? [Buffer.from(`${encodedClientId}:${encodedClientSecret}`).toString("base64")] : [])
+ ...(clientSecret
+ ? [Buffer.from(`${formUrlEncode(clientId)}:${formUrlEncode(clientSecret)}`).toString("base64")]
+ : [])
];
const send = async (withResource: boolean): Promise<TTokenRequestResult> => {
@@ -320,11 +336,23 @@ export const requestToken = async ({
}),
remainingMs
);
- } catch {
+ } catch (err) {
+ // Only the message: the error itself carries the request config, client secret and Basic header included.
+ const reason = normalizeProviderText(
+ err instanceof Error ? err.message : String(err),
+ MAX_ERROR_DESCRIPTION_LENGTH,
+ requestSecrets
+ );
+ logger.info(
+ `agentVaultOauth: token request failed [tokenEndpoint=${sanitizeUrlForLog(tokenEndpoint)}] [reason=${reason}]`
+ );
+ const isPrivateAddress = err instanceof BadRequestError && err.message === PRIVATE_ADDRESS_REFUSED_MESSAGE;
return {
ok: false,
errorCode: null,
- message: `Couldn't reach the token endpoint of '${host}'. Try again in a moment.`,
+ message: isPrivateAddress
+ ? `Infisical can't reach the login server '${host}' because it's on a private network. Use a bearer token for this service instead.`
+ : `Couldn't reach the login server '${host}'.`,
resourceDropped: !withResource
};
}
@@ -337,7 +365,7 @@ export const requestToken = async ({
return {
ok: false,
errorCode: null,
- message: `'${host}' returned a token Infisical can't use (it must be printable text that works as a bearer token).`,
+ message: `The login server '${host}' returned a token Infisical can't use (it must be printable text that works as a bearer token).`,
resourceDropped: !withResource
};
}
@@ -351,7 +379,7 @@ export const requestToken = async ({
return {
ok: false,
errorCode,
- message: `'${host}' refused the token request: ${detail}`,
+ message: `The login server '${host}' refused the token request: ${detail}`,
resourceDropped: !withResource
};
};
@@ -407,6 +435,20 @@ export const withTokenCompatibility = (
return used.length ? [...compatibility, ...used] : compatibility;
};
+// Sent in the bearer shape so a proxy that predates OAuth injects it unchanged; `source` is what tells a newer one
+// it may ask for a refresh. Both the session poll and the refresh endpoint build it here, so the two can't drift.
+export const toResolvedOauthCredential = (
+ config: Pick<TAgentVaultOauthConfig, "expiresAt">,
+ accessToken: string
+): TResolvedOauthCredential => ({
+ type: AgentVaultCredentialType.Bearer,
+ headerName: AGENT_VAULT_OAUTH_HEADER_NAME,
+ headerPrefix: AGENT_VAULT_OAUTH_HEADER_PREFIX,
+ value: accessToken,
+ source: AgentVaultCredentialType.OAuth,
+ expiresAt: config.expiresAt ?? null
+});
+
// Never throws: `parseExpiresIn` bounds what a provider sends, and anything that still isn't a date is no expiry.
export const expiresAtFrom = (expiresIn: number | undefined, now: Date) => {
if (expiresIn === undefined) return null;
diff --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.ts
index 7b78dc5ce5..2527d92622 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
@@ -57,7 +57,6 @@ export type TAgentVaultOauthConfig = {
status: AgentVaultOauthStatus;
expiresAt: string | null;
accessTokenHash: string;
- authorizedBy: { userId: string; username: string } | null;
authorizedAt: string | null;
lastRefreshedAt: string | null;
lastError: string | null;
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.ts
index e308df86c7..e15095d33e 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
@@ -45,7 +45,11 @@ const serviceRow = (overrides: Partial<TResolveServiceRow> = {}): TResolveServic
...overrides
});
-const setup = (refresh: (dto: TRefreshServiceTokenDTO) => Promise<unknown>, rows = [serviceRow()]) => {
+const setup = (
+ refresh: (dto: TRefreshServiceTokenDTO) => Promise<unknown>,
+ rows = [serviceRow()],
+ variables: { id: string; encryptedValue: Buffer }[] = []
+) => {
const refreshServiceToken = vi.fn(refresh);
const reportMissingScopes = vi.fn(async () => {});
const service = agentVaultProxyServiceFactory({
@@ -55,7 +59,7 @@ const setup = (refresh: (dto: TRefreshServiceTokenDTO) => Promise<unknown>, rows
agentVaultResolveDAL: { findResolvableServices: async () => rows },
agentVaultServiceCustomHeaderDAL: { findByServiceIds: async () => [] },
agentVaultServiceSubstitutionDAL: { findByServiceIds: async () => [] },
- agentVaultVariableDAL: { findValuesForResolve: async () => [] },
+ agentVaultVariableDAL: { findValuesForResolve: async () => variables },
agentVaultSessionDAL: {
findByTokenHash: async () =>
({ id: "session-1", projectId: PROJECT_ID, userId: "user-1", revokedAt: null, expiresAt: null }) as never
@@ -191,6 +195,68 @@ describe("resolve's lazy refresh", () => {
});
});
+ test("waits at most 4 seconds for a refresh, then sends the stored token", async () => {
+ vi.useFakeTimers();
+ try {
+ const { service } = setup(() => new Promise(() => {}));
+ let settled = false;
+ const result = resolve(service).finally(() => {
+ settled = true;
+ });
+ await vi.advanceTimersByTimeAsync(3_999);
+ expect(settled).toBe(false);
+ await vi.advanceTimersByTimeAsync(1);
+ const { services } = await result;
+ expect(services[0].credential).toMatchObject({ value: "snapshot-access" });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ test("a service that needs reauthorization isn't refreshed, even when its token is about to expire", async () => {
+ const { service, refreshServiceToken } = setup(
+ async () => refreshed,
+ [
+ serviceRow({
+ credentialConfig: {
+ status: AgentVaultOauthStatus.NeedsReauthorization,
+ expiresAt: new Date(Date.now() + 10_000).toISOString()
+ }
+ })
+ ]
+ );
+ const { services } = await resolve(service);
+ expect(refreshServiceToken).not.toHaveBeenCalled();
+ expect(services[0].credential).toMatchObject({ value: "snapshot-access" });
+ });
+
+ test("a variable reference inside an OAuth token is sent as is, while a Bearer token's is expanded", async () => {
+ const variableId = "44444444-4444-4444-8444-444444444444";
+ const reference = `{{${variableId}}}`;
+ const { service } = setup(
+ async () => refreshed,
+ [
+ serviceRow({
+ credentialConfig: { status: AgentVaultOauthStatus.Connected, expiresAt: null },
+ encryptedCredential: Buffer.from(JSON.stringify({ accessToken: `oauth-${reference}` }))
+ }),
+ serviceRow({
+ id: "55555555-5555-4555-8555-555555555555",
+ type: AgentVaultServiceType.Http,
+ hostPattern: "api.example.com",
+ config: null,
+ credentialType: AgentVaultCredentialType.Bearer,
+ credentialConfig: { headerName: "Authorization", headerPrefix: "Bearer" },
+ encryptedCredential: Buffer.from(JSON.stringify({ value: `bearer-${reference}` }))
+ })
+ ],
+ [{ id: variableId, encryptedValue: Buffer.from(JSON.stringify({ value: "expanded" })) }]
+ );
+ const { services } = await resolve(service);
+ expect(services[0].credential).toMatchObject({ value: `oauth-${reference}` });
+ expect(services[1].credential).toMatchObject({ value: "bearer-expanded" });
+ });
+
test("an OAuth token is always sent as Authorization: Bearer, whatever its config holds", async () => {
const { service } = setup(
async () => refreshed,
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.ts
index 874ee5e61c..65fffe9fa7 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
@@ -39,11 +39,8 @@ import {
AGENT_VAULT_SERVICE_MOVED_MESSAGE,
TAgentVaultOauthServiceFactory
} from "../agent-vault-oauth/agent-vault-oauth-service";
-import {
- AGENT_VAULT_OAUTH_HEADER_NAME,
- AGENT_VAULT_OAUTH_HEADER_PREFIX,
- TAgentVaultOauthConfig
-} from "../agent-vault-oauth/agent-vault-oauth-types";
+import { toResolvedOauthCredential } from "../agent-vault-oauth/agent-vault-oauth-token-fns";
+import { TAgentVaultOauthConfig } from "../agent-vault-oauth/agent-vault-oauth-types";
import { TAgentVaultSessionDALFactory } from "../agent-vault-session/agent-vault-session-dal";
import { hashSessionToken } from "../agent-vault-session/agent-vault-session-fns";
import { TAgentVaultSessionLogConfigDALFactory } from "../agent-vault-session-log/agent-vault-session-log-config-dal";
@@ -359,18 +356,8 @@ export const agentVaultProxyServiceFactory = ({
value: secret.value
};
}
- // Sent in the bearer shape so a proxy that predates OAuth injects it unchanged; `source` is what tells a
- // newer one it may ask for a refresh.
if (row.credentialType === AgentVaultCredentialType.OAuth) {
- const oauth = row.credentialConfig as TAgentVaultOauthConfig;
- return {
- type: AgentVaultCredentialType.Bearer,
- headerName: AGENT_VAULT_OAUTH_HEADER_NAME,
- headerPrefix: AGENT_VAULT_OAUTH_HEADER_PREFIX,
- value: secret.accessToken,
- source: AgentVaultCredentialType.OAuth,
- expiresAt: oauth.expiresAt ?? null
- };
+ return toResolvedOauthCredential(row.credentialConfig as TAgentVaultOauthConfig, secret.accessToken);
}
return { type: AgentVaultCredentialType.Basic, username: secret.username ?? "", password: secret.password ?? "" };
};
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 03c1326743..80a2ca7cf0 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -4487,15 +4487,15 @@ export const AGENT_VAULT = {
SERVICE: {
serviceId: "The ID of the service.",
name: "The name of the service.",
- 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.",
+ type: "The service type: `http` for an HTTP API, or `mcp` for a remote MCP server. 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`.",
+ "The MCP server's URL, such as `https://mcp.example.com/mcp`. Must use `https`, with no username, password, query string or fragment.",
transport: "How the agent talks to the MCP server: `streamable-http`, or `sse` for the legacy HTTP+SSE transport.",
mcpCredential:
- "The credential the proxy attaches to requests to the MCP server. An MCP service takes a bearer token, or `oauth` with the `authorizationId` of a completed OAuth authorization. An OAuth token is always sent as `Authorization: Bearer <token>`.",
+ "The credential the proxy attaches to requests to the MCP server, a bearer token. To use OAuth instead, connect the service in the Infisical UI.",
authorizationId:
"The ID of a completed OAuth authorization for this service's server URL, started by the same user. Each authorization can be used once.",
updateAuthorizationId:
@@ -4505,11 +4505,7 @@ export const AGENT_VAULT = {
oauthIssuer: "The OAuth authorization server that issued the tokens.",
oauthGrantedScopes: "The scopes the authorization server granted.",
oauthRequiredScopes: "Scopes the MCP server asked for that the connection lacks. Reauthorize to request them.",
- oauthExpiresAt:
- "When the current access token expires, or null if the server didn't say. Infisical refreshes it before then.",
- oauthAuthorizedBy: "The user who authorized the connection.",
- oauthAuthorizedByUserId: "The ID of the user who authorized the connection.",
- oauthAuthorizedByUsername: "The username of the user who authorized the connection.",
+ oauthExpiresAt: "When the current access token expires, or null if the server didn't say.",
oauthAuthorizedAt: "When the connection was last authorized.",
oauthLastError: "The last refresh failure, if any. Never contains a token.",
hostPattern:
diff --git a/backend/src/lib/validator/index.ts b/backend/src/lib/validator/index.ts
index db8b80f9d7..a0fbed28b6 100644
--- a/backend/src/lib/validator/index.ts
+++ b/backend/src/lib/validator/index.ts
@@ -4,7 +4,7 @@ export {
normalizeAllowedEmailDomains
} from "./email-domain-matcher";
export type { TValidatedHost } from "./safe-request";
-export { buildSsrfSafeAgent, safeRequest } from "./safe-request";
+export { buildSsrfSafeAgent, PRIVATE_ADDRESS_REFUSED_MESSAGE, safeRequest } from "./safe-request";
export {
isAliasedEmail,
isDisposableEmail,
diff --git a/backend/src/lib/validator/safe-request.ts b/backend/src/lib/validator/safe-request.ts
index 640a26874e..55e6ba3ce8 100644
--- a/backend/src/lib/validator/safe-request.ts
+++ b/backend/src/lib/validator/safe-request.ts
@@ -19,6 +19,9 @@ import { BadRequestError } from "../errors";
import { isPrivateIp } from "../ip/ipRange";
import { AGENT_CACHE_MAX, agentCache } from "./agent-pool";
+// Exported so a caller can tell this refusal, which retrying never fixes, from a failure that might pass.
+export const PRIVATE_ADDRESS_REFUSED_MESSAGE = "Local IPs not allowed as URL";
+
const formatEntries = (entries: LookupAddress[]) => entries.map((e) => `${e.family}:${e.address}`).join(",");
export type TValidatedHost = {
@@ -66,7 +69,7 @@ export const validateAndPinUrl = async (
} else {
if (!appCfg.ALLOW_INTERNAL_IP_CONNECTIONS && (rawHost === "localhost" || rawHost === "host.docker.internal")) {
logger.warn(`safeRequest: rejecting literal local hostname [hostname=${rawHost}]`);
- throw new BadRequestError({ message: "Local IPs not allowed as URL" });
+ throw new BadRequestError({ message: PRIVATE_ADDRESS_REFUSED_MESSAGE });
}
const lookups = await dns.lookup(rawHost, { all: true });
@@ -80,7 +83,7 @@ export const validateAndPinUrl = async (
const isInternalIp = entries.some((e) => isPrivateIp(e.address));
if (isInternalIp && !appCfg.ALLOW_INTERNAL_IP_CONNECTIONS) {
logger.warn(`safeRequest: rejecting private/internal IP [hostname=${rawHost}] [entries=${formatEntries(entries)}]`);
- throw new BadRequestError({ message: "Local IPs not allowed as URL" });
+ throw new BadRequestError({ message: PRIVATE_ADDRESS_REFUSED_MESSAGE });
}
// Block Infisical's own infrastructure (DB, Redis, etc.).
diff --git a/backend/src/server/plugins/fastify-zod.ts b/backend/src/server/plugins/fastify-zod.ts
index c2c25bbc1f..e3c799dc2f 100644
--- a/backend/src/server/plugins/fastify-zod.ts
+++ b/backend/src/server/plugins/fastify-zod.ts
@@ -53,8 +53,8 @@ const zodToJsonSchemaOptions = {
/**
* Normalizes a JSON schema for OpenAPI output.
*
- * Two jobs. It removes properties marked with "x-hidden": true, so a field can be
- * hidden from the docs while still being validated
+ * Two jobs. It removes properties and union variants marked with "x-hidden": true, so a
+ * field or variant can be hidden from the docs while still being validated
* (usage: .describe(JSON.stringify({ "x-hidden": true }))). And it flattens JSON
* Schema tuple form, which zod-to-json-schema emits for z.tuple() even under its
* openApi3 target: OpenAPI 3.0 has no tuple type and requires `items` to be a single
@@ -110,12 +110,17 @@ const removeHiddenProperties = (schema: FreeformRecord, keepHidden = false): Fre
result.allOf = result.allOf.map((v: FreeformRecord) => removeHiddenProperties(v, keepHidden));
}
+ const visibleVariants = (variants: FreeformRecord[]) =>
+ variants
+ .filter((v) => keepHidden || !v?.["x-hidden"])
+ .map((v: FreeformRecord) => removeHiddenProperties(v, keepHidden));
+
if (result.oneOf && Array.isArray(result.oneOf)) {
- result.oneOf = result.oneOf.map((v: FreeformRecord) => removeHiddenProperties(v, keepHidden));
+ result.oneOf = visibleVariants(result.oneOf);
}
if (result.anyOf && Array.isArray(result.anyOf)) {
- result.anyOf = result.anyOf.map((v: FreeformRecord) => removeHiddenProperties(v, keepHidden));
+ result.anyOf = visibleVariants(result.anyOf);
}
return result;
diff --git a/docs/documentation/platform/agent-vault/access-bundles.mdx b/docs/documentation/platform/agent-vault/access-bundles.mdx
index 66a3acbbf0..b80f222b62 100644
--- a/docs/documentation/platform/agent-vault/access-bundles.mdx
+++ b/docs/documentation/platform/agent-vault/access-bundles.mdx
@@ -3,7 +3,7 @@ title: "Access bundles"
description: "Lists of services that AI agents can access during a session."
---
-An access bundle defines the list of [services](/documentation/platform/agent-vault/services) (external systems) that an AI agent can access during a [session](/documentation/platform/agent-vault/sessions).
+An access bundle defines the list of [services](/documentation/platform/agent-vault/services) (external APIs or MCP servers) that an AI agent can access during a [session](/documentation/platform/agent-vault/sessions).
You can reuse access bundles across as many sessions as you like. This makes them useful for scoping what services an agent can access depending on its task. For example, you might have:
diff --git a/docs/documentation/platform/agent-vault/how-it-works.mdx b/docs/documentation/platform/agent-vault/how-it-works.mdx
index ffcdedf2b2..dad2716fe8 100644
--- a/docs/documentation/platform/agent-vault/how-it-works.mdx
+++ b/docs/documentation/platform/agent-vault/how-it-works.mdx
@@ -33,7 +33,7 @@ Here's how the four concepts connect:
<Steps>
<Step>
- The access bundle groups the services (external systems) you want your agent to reach.
+ The access bundle groups the services (external APIs or MCP servers) you want your agent to reach.
```mermaid
flowchart LR
diff --git a/docs/documentation/platform/agent-vault/mcp-servers.mdx b/docs/documentation/platform/agent-vault/mcp-servers.mdx
index 0d241acdab..50223622f6 100644
--- a/docs/documentation/platform/agent-vault/mcp-servers.mdx
+++ b/docs/documentation/platform/agent-vault/mcp-servers.mdx
@@ -27,7 +27,7 @@ You add the MCP server to your agent with its real URL and no credentials. When
On the **Details** step, enter a **Name**, and check the [**Transport** and **Server URL**](#server-url-and-transport). A template fills in the transport and server URL for you. Select **Continue**.
</Step>
<Step>
- On the **Credential** step, pick an **Auth Method** and set up the [credential](#credential-types). Select **Continue**.
+ On the **Credential** step, pick a **Credential Type** and set up the [credential](#credential-types). Select **Continue**.
</Step>
<Step>
On the **Review** step, select **Add Service**. The service appears in the bundle's list with the type **MCP Server**.
@@ -51,7 +51,7 @@ With OAuth, you sign in to the provider once from Infisical. Infisical stores th
<Steps>
<Step>
- Under **Auth Method**, select **OAuth**, then select the button that names your server, such as **Authorize with mcp.linear.app**.
+ Under **Credential Type**, select **OAuth**, then select the button that names your server, such as **Authorize with mcp.linear.app**.
<Note>
Some servers, such as GitHub's, don't let Infisical register itself as an OAuth client. For these servers, the card asks for an OAuth app of your own instead. Create an OAuth app with the provider, and set its redirect URI to the **Redirect URI** the card shows. Then enter the app's **Client ID** and **Client Secret** (leave **Client Secret** empty for a public client), and authorize again.
@@ -147,6 +147,7 @@ Infisical won't save a custom header with the same name as the credential's head
## Limitations
- **Remote servers only:** An MCP service covers MCP servers that the agent reaches over HTTPS. A local MCP server that the agent starts as a process isn't an MCP service, but you can add [HTTP services](/documentation/platform/agent-vault/http-apis) for the APIs that the local server calls
+- **No OAuth on private networks:** Infisical connects to the MCP server and to the provider to set up OAuth and refresh the access token, so if either one is on a private network, use a [Bearer token](#bearer-token) instead, or set [`ALLOW_INTERNAL_IP_CONNECTIONS`](/self-hosting/configuration/envars#param-allow-internal-ip-connections) to `true` if you self-host Infisical on that network
- **No tool filtering:** The agent can call every tool the server offers to the credential, so limit what the agent can do through the credential's own permissions
- **No connectors that run in a vendor's cloud:** Custom connectors in claude.ai or ChatGPT connect from the vendor's servers, so their traffic never reaches your proxy
- **No WebSocket transports:** The proxy doesn't support [WebSocket connections](/documentation/platform/agent-vault/proxies#supported-connections)
@@ -161,7 +162,9 @@ Infisical won't save a custom header with the same name as the credential's head
{"error":"upstream_auth_failed","message":"The MCP server rejected the credential Infisical provided. Reauthorize this service in Infisical Agent Vault."}
```
- In the access bundle's **Services** table, the service shows **Needs Reauthorization** or **Needs Additional Scopes**. Open the service's menu, select **Reauthorize**, and sign in to the provider again. Then try the tool call again.
+ In the access bundle's **Services** table, the service shows **Needs Additional Scopes** if the server asked for scopes the authorization lacks, and **Needs Reauthorization** if the provider no longer accepts the service's login. If the server rejected the fresh token, the service shows no warning.
+
+ In each case, reauthorize the service. Open the service's menu, select **Edit**, and continue to the **Credential** step. Select **Reauthorize**, sign in to the provider again, then continue and select **Save**. Then try the tool call again.
</Accordion>
<Accordion title="Authorize fails on a self-hosted instance">
The redirect URI that Infisical gives the provider is your instance's `SITE_URL` followed by `/agent-vault/oauth/callback`. Check that:
diff --git a/docs/documentation/platform/agent-vault/plan-your-setup.mdx b/docs/documentation/platform/agent-vault/plan-your-setup.mdx
index a2b8605790..9739327d9a 100644
--- a/docs/documentation/platform/agent-vault/plan-your-setup.mdx
+++ b/docs/documentation/platform/agent-vault/plan-your-setup.mdx
@@ -41,7 +41,7 @@ Configure the following options to get custom guidance and best practices tailor
Before running an agent, you set up two things:
<ul>
- <li>An [access bundle](/documentation/platform/agent-vault/access-bundles) in Infisical: a list of the [services](/documentation/platform/agent-vault/services) (the external systems) that the agent can use, each with its real credential</li>
+ <li>An [access bundle](/documentation/platform/agent-vault/access-bundles) in Infisical: a list of the [services](/documentation/platform/agent-vault/services) (the external APIs or MCP servers) that the agent can use, each with its real credential</li>
<li>A running [proxy](/documentation/platform/agent-vault/proxies): a program on its own machine that every request from the agent goes through</li>
</ul>
diff --git a/docs/documentation/platform/agent-vault/session-logs.mdx b/docs/documentation/platform/agent-vault/session-logs.mdx
index 96d7d9ebac..c1139a0485 100644
--- a/docs/documentation/platform/agent-vault/session-logs.mdx
+++ b/docs/documentation/platform/agent-vault/session-logs.mdx
@@ -127,7 +127,7 @@ You can view a session's logs if you created the session or you're an Agent Vaul
<Tabs>
<Tab title="In Infisical">
- Go to **Sessions** and select **View Session Logs** on the session's row. You can filter the requests by type (**HTTP APIs** or **MCP Servers**) and outcome, and search them by host, path, method, tool, or service. While the session is active, new requests appear as the proxy uploads them.
+ Go to **Sessions** and select **View Session Logs** on the session's row. You can filter the requests by outcome and search them by host, path, method, tool, or service. While the session is active, new requests appear as the proxy uploads them.
<Frame>
<img src="/images/platform/agent-vault/session-logs-view.png" alt="The Session Logs sheet for an active session, listing each request's time, method, host, path, upstream status, and outcome" />
diff --git a/frontend/src/components/agent-vault/ServiceTemplateSelect.tsx b/frontend/src/components/agent-vault/ServiceTemplateSelect.tsx
index bd8fb5c925..a8ac277d5d 100644
--- a/frontend/src/components/agent-vault/ServiceTemplateSelect.tsx
+++ b/frontend/src/components/agent-vault/ServiceTemplateSelect.tsx
@@ -1,19 +1,13 @@
import { ReactNode, useMemo, useState } from "react";
import { GlobeIcon, PlusIcon, SearchIcon } from "lucide-react";
+import { twMerge } from "tailwind-merge";
import {
- Badge,
Button,
CardTitle,
InputGroup,
InputGroupAddon,
- InputGroupInput,
- Item,
- ItemContent,
- ItemDescription,
- ItemHeader,
- ItemMedia,
- ItemTitle
+ InputGroupInput
} from "@app/components/v3";
import { ProviderIcon } from "@app/components/v3/platform/ProviderIcon";
import {
@@ -32,7 +26,7 @@ enum TypeFilter {
}
const MCP_SECTION_DESCRIPTION =
- "Remote MCP servers. The proxy attaches the credential and logs each tool call.";
+ "Remote MCP servers. The proxy attaches the credential to requests for them.";
const HTTP_SECTION_DESCRIPTION =
"Web APIs your agent calls directly. The proxy attaches the credential to requests for their hosts.";
@@ -55,26 +49,37 @@ const SelectableCard = ({
tag,
name,
description,
+ isCustom,
onSelect
}: {
media: ReactNode;
tag?: string;
name: string;
description: string;
+ isCustom?: boolean;
onSelect: () => void;
}) => (
- <Item asChild variant="outline" className="cursor-pointer hover:bg-container-hover">
- <button type="button" onClick={onSelect}>
- <ItemHeader>
- <ItemMedia variant="image">{media}</ItemMedia>
- {tag && <Badge variant="outline">{tag}</Badge>}
- </ItemHeader>
- <ItemContent>
- <ItemTitle>{name}</ItemTitle>
- <ItemDescription>{description}</ItemDescription>
- </ItemContent>
- </button>
- </Item>
+ <button
+ type="button"
+ onClick={onSelect}
+ className={twMerge(
+ "group flex cursor-pointer flex-col gap-3 rounded-md border border-border bg-card p-4 text-left transition-colors hover:border-border-strong hover:bg-surface-hover/50",
+ isCustom && "border-dashed border-border-strong hover:border-border-emphasis"
+ )}
+ >
+ <div className="flex items-start justify-between gap-2">
+ <div className="flex h-9 w-9 items-center justify-center rounded-md bg-surface-hover">
+ {media}
+ </div>
+ {tag && (
+ <span className="text-[10px] font-medium tracking-wider text-muted uppercase">{tag}</span>
+ )}
+ </div>
+ <div className="flex flex-col gap-1">
+ <p className="text-sm font-semibold text-foreground">{name}</p>
+ <p className="text-xs leading-relaxed text-muted">{description}</p>
+ </div>
+ </button>
);
const TemplateCard = ({
@@ -90,11 +95,12 @@ const TemplateCard = ({
<SelectableCard
media={
hasImageError ? (
- <GlobeIcon />
+ <GlobeIcon className="h-5 w-5 text-label-secondary" />
) : (
<ProviderIcon
icon={template.image}
alt={`${template.name} logo`}
+ className="h-6 w-6 object-contain"
onError={() => setHasImageError(true)}
/>
)
@@ -116,7 +122,13 @@ const CustomCard = ({
description: string;
onSelect: () => void;
}) => (
- <SelectableCard media={<PlusIcon />} name={name} description={description} onSelect={onSelect} />
+ <SelectableCard
+ media={<PlusIcon className="h-5 w-5 text-label-secondary" />}
+ name={name}
+ description={description}
+ isCustom
+ onSelect={onSelect}
+ />
);
const Grid = ({ children }: { children: ReactNode }) => (
@@ -127,21 +139,10 @@ const SectionLabel = ({ children }: { children: ReactNode }) => (
<p className="mb-3 text-[11px] font-medium tracking-wider text-muted uppercase">{children}</p>
);
-const SectionHeader = ({
- title,
- description,
- action
-}: {
- title: string;
- description: string;
- action?: ReactNode;
-}) => (
- <div className="mb-4 flex items-end justify-between gap-4">
- <div>
- <CardTitle className="text-sm leading-snug">{title}</CardTitle>
- <p className="mt-0.5 text-xs text-muted">{description}</p>
- </div>
- {action}
+const SectionHeader = ({ title, description }: { title: string; description: string }) => (
+ <div className="mb-4">
+ <CardTitle className="text-sm leading-snug">{title}</CardTitle>
+ <p className="mt-0.5 text-xs text-muted">{description}</p>
</div>
);
@@ -207,17 +208,7 @@ export const ServiceTemplateSelect = ({ onSelect }: Props) => {
)}
{showsHttp && (
<div>
- <SectionHeader
- title="HTTP APIs"
- description={HTTP_SECTION_DESCRIPTION}
- action={
- typeFilter === TypeFilter.All && (
- <Button variant="ghost" size="xs" onClick={() => setTypeFilter(TypeFilter.Http)}>
- View All
- </Button>
- )
- }
- />
+ <SectionHeader title="HTTP APIs" description={HTTP_SECTION_DESCRIPTION} />
<SectionLabel>Popular</SectionLabel>
<Grid>
{customHttpCard}
@@ -227,7 +218,7 @@ export const ServiceTemplateSelect = ({ onSelect }: Props) => {
</Grid>
</div>
)}
- {typeFilter === TypeFilter.Http &&
+ {showsHttp &&
Object.values(AgentVaultTemplateCategory).map((category) => {
const templates = AGENT_VAULT_TEMPLATES.filter(
(template) => template.category === category
diff --git a/frontend/src/components/agent-vault/service-sheet/McpCredentialFields.tsx b/frontend/src/components/agent-vault/service-sheet/McpCredentialFields.tsx
index e68ef66821..d7402d7bec 100644
--- a/frontend/src/components/agent-vault/service-sheet/McpCredentialFields.tsx
+++ b/frontend/src/components/agent-vault/service-sheet/McpCredentialFields.tsx
@@ -36,9 +36,16 @@ type Props = {
service?: TAgentVaultService | null;
openItem: string;
onOpenChange: (item: string) => void;
+ onSignInChange?: (isSigningIn: boolean) => void;
};
-export const McpCredentialFields = ({ accessBundleId, service, openItem, onOpenChange }: Props) => {
+export const McpCredentialFields = ({
+ accessBundleId,
+ service,
+ openItem,
+ onOpenChange,
+ onSignInChange
+}: Props) => {
const { control, watch, setValue, clearErrors } = useFormContext<TServiceForm>();
const { storedKeys } = useServiceVariables();
const secret = watch("secret");
@@ -70,7 +77,7 @@ export const McpCredentialFields = ({ accessBundleId, service, openItem, onOpenC
return (
<div className="flex flex-col gap-5">
<Field>
- <FieldLabel id={authMethodLabelId}>Auth Method</FieldLabel>
+ <FieldLabel id={authMethodLabelId}>Credential Type</FieldLabel>
<FieldContent>
<Select
value={isOAuth ? AgentVaultCredentialType.OAuth : AgentVaultCredentialType.Bearer}
@@ -91,7 +98,11 @@ export const McpCredentialFields = ({ accessBundleId, service, openItem, onOpenC
</Field>
{isOAuth ? (
- <OAuthAuthorizeCard accessBundleId={accessBundleId} service={service} />
+ <OAuthAuthorizeCard
+ accessBundleId={accessBundleId}
+ service={service}
+ onSignInChange={onSignInChange}
+ />
) : (
<Controller
control={control}
diff --git a/frontend/src/components/agent-vault/service-sheet/McpDetailsFields.tsx b/frontend/src/components/agent-vault/service-sheet/McpDetailsFields.tsx
index 0844669eaa..f1bc45dc63 100644
--- a/frontend/src/components/agent-vault/service-sheet/McpDetailsFields.tsx
+++ b/frontend/src/components/agent-vault/service-sheet/McpDetailsFields.tsx
@@ -2,14 +2,17 @@ import { useId } from "react";
import { Controller, useFormContext } from "react-hook-form";
import {
- Button,
- ButtonGroup,
Field,
FieldContent,
FieldDescription,
FieldError,
FieldLabel,
- Input
+ Input,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
} from "@app/components/v3";
import { AgentVaultMcpTransport } from "@app/hooks/api/agentVault";
@@ -21,6 +24,7 @@ export const McpDetailsFields = () => {
const { control } = useFormContext<TServiceForm>();
const nameInputId = useId();
const serverUrlInputId = useId();
+ const transportLabelId = useId();
return (
<div className="flex flex-col gap-5">
@@ -49,25 +53,20 @@ export const McpDetailsFields = () => {
name="transport"
render={({ field }) => (
<Field>
- <FieldLabel>Transport</FieldLabel>
+ <FieldLabel id={transportLabelId}>Transport</FieldLabel>
<FieldContent>
- <ButtonGroup aria-label="Transport">
- {TRANSPORTS.map((transport) => {
- const isSelected = field.value === transport;
- return (
- <Button
- key={transport}
- type="button"
- size="sm"
- variant={isSelected ? "av" : "outline"}
- aria-pressed={isSelected}
- onClick={() => field.onChange(transport)}
- >
+ <Select value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger aria-labelledby={transportLabelId} className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {TRANSPORTS.map((transport) => (
+ <SelectItem key={transport} value={transport}>
{TRANSPORT_LABELS[transport]}
- </Button>
- );
- })}
- </ButtonGroup>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
<FieldDescription>
Most servers use Streamable HTTP. Pick SSE only for a server on the older HTTP+SSE
transport.
@@ -92,9 +91,6 @@ export const McpDetailsFields = () => {
spellCheck={false}
isError={Boolean(fieldState.error)}
/>
- <FieldDescription>
- The URL your agent connects to. The credential is only sent to this host.
- </FieldDescription>
<FieldError>{fieldState.error?.message}</FieldError>
</FieldContent>
</Field>
diff --git a/frontend/src/components/agent-vault/service-sheet/OAuthAuthorizeCard.tsx b/frontend/src/components/agent-vault/service-sheet/OAuthAuthorizeCard.tsx
index bb07a5c294..6135dee9fa 100644
--- a/frontend/src/components/agent-vault/service-sheet/OAuthAuthorizeCard.tsx
+++ b/frontend/src/components/agent-vault/service-sheet/OAuthAuthorizeCard.tsx
@@ -1,4 +1,4 @@
-import { Fragment, ReactNode, useId, useState } from "react";
+import { Fragment, ReactNode, useEffect, useId, useState } from "react";
import { useFormContext, useWatch } from "react-hook-form";
import { format } from "date-fns";
import { CheckIcon, CircleAlertIcon, CircleXIcon, InfoIcon, TriangleAlertIcon } from "lucide-react";
@@ -31,6 +31,8 @@ import { TAgentVaultService } from "@app/hooks/api/agentVault/types";
import {
newOAuthAuthorizationId,
OAUTH_STATUS_LABELS,
+ oauthClientIdSchema,
+ oauthClientSecretSchema,
storedOAuthCredential,
TServiceForm
} from "./serviceSchema";
@@ -131,13 +133,16 @@ const Scopes = ({ granted, requested }: { granted: string[]; requested: string[]
type Props = {
accessBundleId: string;
service?: TAgentVaultService | null;
+ onSignInChange?: (isSigningIn: boolean) => void;
};
-export const OAuthAuthorizeCard = ({ accessBundleId, service }: Props) => {
+export const OAuthAuthorizeCard = ({ accessBundleId, service, onSignInChange }: Props) => {
const {
control,
register,
setValue,
+ setError,
+ clearErrors,
formState: { errors }
} = useFormContext<TServiceForm>();
const [serverUrl, authorizationId, authorizedUrl, scopes, clientId = "", clientSecret = ""] =
@@ -168,26 +173,26 @@ export const OAuthAuthorizeCard = ({ accessBundleId, service }: Props) => {
);
const stored = storedOAuthCredential(service, serverUrl);
- const {
- state,
- isClientRequired,
- isOAuthAdvertised,
- redirectUri,
- registrationError,
- authorize,
- cancel
- } = useOAuthAuthorize({
- onAuthorized: (authorization) => {
- setValue("oauthAuthorizedUrl", trimmedUrl, { shouldDirty: true });
- setValue("oauthScopes", authorization.scopes, { shouldDirty: true });
- setValue("oauthAuthorizationId", authorization.id, {
- shouldDirty: true,
- shouldValidate: true
- });
- }
- });
+ const { state, isClientRequired, isOAuthAdvertised, redirectUri, authorize, cancel } =
+ useOAuthAuthorize({
+ onAuthorized: (authorization) => {
+ setValue("oauthAuthorizedUrl", trimmedUrl, { shouldDirty: true });
+ setValue("oauthScopes", authorization.scopes, { shouldDirty: true });
+ setValue("oauthAuthorizationId", authorization.id, {
+ shouldDirty: true,
+ shouldValidate: true
+ });
+ }
+ });
const isWaiting = state.status === "starting" || state.status === "pending";
+
+ // Leaving the step unmounts this card, which stops the poll and drops a sign-in still in progress, so the sheet
+ // holds navigation until it finishes or is cancelled.
+ useEffect(() => {
+ onSignInChange?.(isWaiting);
+ }, [isWaiting, onSignInChange]);
+ useEffect(() => () => onSignInChange?.(false), [onSignInChange]);
const wantsOwnApp = isClientRequired || isUsingOwnApp;
const isOwnApp = wantsOwnApp && !isNewlyAuthorized;
const hasAuthorization = isNewlyAuthorized || Boolean(stored);
@@ -198,13 +203,33 @@ export const OAuthAuthorizeCard = ({ accessBundleId, service }: Props) => {
setValue("oauthClientSecret", "");
};
- const handleAuthorize = () =>
+ // Checked here rather than left to the form: the form validates on save, and the popup has to open
+ // synchronously in this click.
+ const handleAuthorize = () => {
+ if (wantsOwnApp) {
+ const problems = (
+ [
+ ["oauthClientId", oauthClientIdSchema.safeParse(clientId)],
+ ["oauthClientSecret", oauthClientSecretSchema.safeParse(clientSecret)]
+ ] as const
+ ).flatMap(([name, result]) =>
+ result.success ? [] : [[name, result.error.issues[0].message] as const]
+ );
+ clearErrors(["oauthClientId", "oauthClientSecret"]);
+ if (problems.length) {
+ problems.forEach(([name, message]) => setError(name, { message }));
+ return;
+ }
+ }
+ // A failed or cancelled replacement must not leave the previous sign-in in the form to be saved.
+ setValue("oauthAuthorizationId", "");
authorize({
accessBundleId,
serverUrl: trimmedUrl,
...(stored && service ? { serviceId: service.id } : {}),
...(wantsOwnApp ? { clientId: clientId.trim(), clientSecret: clientSecret || undefined } : {})
});
+ };
const requested = stored
? stored.requiredScopes.filter((scope) => !stored.grantedScopes.includes(scope))
@@ -370,13 +395,6 @@ export const OAuthAuthorizeCard = ({ accessBundleId, service }: Props) => {
</AlertDescription>
</Alert>
)}
- {isClientRequired && isOAuthAdvertised && (
- <p className="text-xs text-muted">
- {registrationError
- ? `${host} didn't accept automatic setup, so use your own OAuth app.`
- : `${host} needs your own OAuth app.`}
- </p>
- )}
<Field>
<FieldLabel htmlFor={redirectUriInputId}>Redirect URI</FieldLabel>
<FieldContent>
@@ -394,8 +412,7 @@ export const OAuthAuthorizeCard = ({ accessBundleId, service }: Props) => {
</InputGroupAddon>
</InputGroup>
<FieldDescription>
- Add this as a redirect URI in your OAuth app on {host}, then enter the
- app&apos;s client ID and secret.
+ Add this as a redirect URI in your OAuth app on {host}.
</FieldDescription>
</FieldContent>
</Field>
diff --git a/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx b/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx
index cdd28466fe..cb2c926dc2 100644
--- a/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx
+++ b/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx
@@ -92,11 +92,11 @@ export const ReviewFields = ({ isUpdate, service }: Props) => {
<div className="flex flex-wrap gap-x-8 gap-y-4">
<Detail>
<DetailLabel>Name</DetailLabel>
- <DetailValue className="font-mono">{form.name}</DetailValue>
+ <DetailValue>{form.name}</DetailValue>
</Detail>
<Detail>
<DetailLabel>Server URL</DetailLabel>
- <DetailValue className="font-mono break-all">{form.serverUrl.trim()}</DetailValue>
+ <DetailValue className="break-all">{form.serverUrl.trim()}</DetailValue>
</Detail>
<Detail>
<DetailLabel>Transport</DetailLabel>
@@ -132,12 +132,6 @@ export const ReviewFields = ({ isUpdate, service }: Props) => {
<DetailGroup>
<DetailGroupHeader className="border-b border-border pb-2">Credential</DetailGroupHeader>
<div className="flex flex-wrap gap-x-8 gap-y-4">
- {isMcp && (
- <Detail>
- <DetailLabel>Owner</DetailLabel>
- <DetailValue>Shared</DetailValue>
- </Detail>
- )}
<Detail>
<DetailLabel>Type</DetailLabel>
<DetailValue>
diff --git a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx
index 278542a5df..da71d70881 100644
--- a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx
+++ b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
import { FormProvider, useForm, useWatch } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import slugify from "@sindresorhus/slugify";
@@ -9,6 +9,14 @@ import {
Button,
DiscardChangesAlertDialog,
DocumentationLinkBadge,
+ Field,
+ FieldContent,
+ FieldLabel,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
Sheet,
SheetContent,
SheetDescription,
@@ -25,7 +33,10 @@ import {
AgentVaultHttpTemplate,
AgentVaultMcpTemplate,
AgentVaultTemplate,
- findTemplateForHostPattern
+ findMcpTemplateForHostPattern,
+ findTemplateForHostPattern,
+ guessServiceTypeForRequest,
+ lastPathSegment
} from "@app/helpers/agentVaultTemplates";
import { findVariableReferences, VARIABLE_KEY_RE } from "@app/helpers/agentVaultVariables";
import { useDebounce, useDiscardChangesGuard, useWizardSteps } from "@app/hooks";
@@ -34,6 +45,7 @@ import {
AgentVaultMcpTransport,
AgentVaultServiceType,
AgentVaultVariableReferenceField,
+ SERVICE_SAVE_HANDLED_ERROR_CODES,
useAgentVaultVariableKeyStatus,
useCreateAgentVaultService,
useUpdateAgentVaultService
@@ -61,6 +73,7 @@ import {
isOAuthAuthorizationMissing,
MCP_SERVICE_STEP_FIELDS,
SERVICE_STEP_FIELDS,
+ SERVICE_TYPE_LABELS,
ServiceStep,
TServiceForm,
UNCHANGED_SECRET
@@ -142,14 +155,73 @@ const formFromTemplate = (picked: AgentVaultHttpTemplate | null, hosts: string[]
};
};
+const prefillName = (hostPattern: string) =>
+ slugify(hostPattern.replace(/:\d+$/, ""), { lowercase: true }).slice(0, 64).replace(/-+$/, "");
+
+// A service added from a session log row starts from the request the proxy saw.
+const prefillFor = (
+ serviceType: AgentVaultServiceType,
+ hostPattern: string,
+ path = ""
+): { template: AgentVaultTemplate | null; form: TServiceForm } => {
+ if (serviceType === AgentVaultServiceType.Mcp) {
+ const picked = findMcpTemplateForHostPattern(hostPattern) ?? null;
+ if (picked) return { template: picked, form: mcpFormFromTemplate(picked) };
+ return {
+ template: null,
+ form: {
+ ...BLANK_MCP_SERVICE_FORM,
+ name: prefillName(hostPattern),
+ serverUrl: `https://${hostPattern}${path.split("?")[0]}`,
+ transport:
+ lastPathSegment(path) === "sse"
+ ? AgentVaultMcpTransport.Sse
+ : AgentVaultMcpTransport.StreamableHttp
+ }
+ };
+ }
+ const picked = findTemplateForHostPattern(hostPattern) ?? null;
+ const form = formFromTemplate(picked, [hostPattern]);
+ return { template: picked, form: picked ? form : { ...form, name: prefillName(hostPattern) } };
+};
+
+const PrefillTypeField = ({
+ value,
+ onChange
+}: {
+ value: AgentVaultServiceType;
+ onChange: (serviceType: AgentVaultServiceType) => void;
+}) => {
+ const labelId = useId();
+ return (
+ <Field>
+ <FieldLabel id={labelId}>Service Type</FieldLabel>
+ <FieldContent>
+ <Select value={value} onValueChange={(next) => onChange(next as AgentVaultServiceType)}>
+ <SelectTrigger aria-labelledby={labelId} className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {Object.values(AgentVaultServiceType).map((type) => (
+ <SelectItem key={type} value={type}>
+ {SERVICE_TYPE_LABELS[type]}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </FieldContent>
+ </Field>
+ );
+};
+
type Props = {
isOpen: boolean;
onOpenChange: (isOpen: boolean) => void;
accessBundleId: string;
service?: TAgentVaultService | null;
prefillHost?: string;
- // Only for an existing service, whose steps start at Details.
- initialStep?: ServiceStep;
+ // The path of the logged request, which helps tell an MCP server from an HTTP API.
+ prefillPath?: string;
onSaved?: () => void;
};
@@ -192,13 +264,33 @@ const storedVariableKeys = (service?: TAgentVaultService | null) => {
// until after it mounts and takes its height.
const SECTION_OPEN_MS = 250;
+// The server keeps a completed authorization for 10 minutes. Expiring it here a little early covers the poll
+// that delivered it, so the sheet never shows one the server has already dropped.
+const OAUTH_AUTHORIZATION_LIFETIME_MS = (10 * 60 - 30) * 1000;
+const OAUTH_AUTHORIZATION_EXPIRED_MESSAGE =
+ "This authorization expired before the service was saved. Authorize again.";
+
+// A successful save consumes the authorization and a failed one restores it, so these refusals mean it expired,
+// another save used it, or it can't be used for this service. Only authorizing again gets past any of them.
+const rejectedAuthorizationMessage = (error: unknown) => {
+ if (!axios.isAxiosError<{ message?: unknown }>(error)) return null;
+ const status = error.response?.status;
+ const message = error.response?.data?.message;
+ if (typeof message !== "string") return null;
+ const isRejected =
+ (status === 400 && /authoriz/i.test(message)) ||
+ (status === 404 && message.startsWith("Authorization with ID")) ||
+ (status === 409 && message.includes("already used by another save"));
+ return isRejected ? message : null;
+};
+
export const ServiceSheet = ({
isOpen,
onOpenChange,
accessBundleId,
service,
prefillHost,
- initialStep,
+ prefillPath,
onSaved
}: Props) => {
const isUpdate = Boolean(service);
@@ -240,6 +332,7 @@ export const ServiceSheet = ({
control,
handleSubmit,
reset,
+ getValues,
setError,
trigger,
watch,
@@ -299,6 +392,7 @@ export const ServiceSheet = ({
const panelRef = useRef<HTMLDivElement>(null);
const [openItem, setOpenItem] = useState(ADVANCED_ITEM);
+ const [isSigningIn, setIsSigningIn] = useState(false);
// The stand-in for formState.submitCount, which only counts handleSubmit and so never moves for a
// wizard that gates its steps with trigger. Without it a second Continue reveals nothing, because
// the errors it finds are the ones already there.
@@ -340,16 +434,7 @@ export const ServiceSheet = ({
useEffect(() => {
if (!isOpen) return;
- setStep(
- service && initialStep
- ? Math.max(
- SERVICE_STEPS.filter((meta) => meta.step !== ServiceStep.Template).findIndex(
- (meta) => meta.step === initialStep
- ),
- 0
- )
- : 0
- );
+ setStep(0);
setTemplate(null);
setOpenItem(service?.type === AgentVaultServiceType.Mcp ? "" : ADVANCED_ITEM);
@@ -407,23 +492,27 @@ export const ServiceSheet = ({
}))
});
} else if (prefillHost) {
- const picked = findTemplateForHostPattern(prefillHost) ?? null;
- const form = formFromTemplate(picked, [prefillHost]);
- setTemplate(picked);
- reset(
- picked
- ? form
- : {
- ...form,
- name: slugify(prefillHost.replace(/:\d+$/, ""), { lowercase: true })
- .slice(0, 64)
- .replace(/-+$/, "")
- }
+ const { template: picked, form } = prefillFor(
+ guessServiceTypeForRequest(prefillHost, prefillPath),
+ prefillHost,
+ prefillPath
);
+ setTemplate(picked);
+ setOpenItem(form.serviceType === AgentVaultServiceType.Mcp ? "" : ADVANCED_ITEM);
+ reset(form);
} else {
reset(BLANK_SERVICE_FORM);
}
- }, [isOpen, service, isUpdate, prefillHost, initialStep, reset, setStep]);
+ }, [isOpen, service, isUpdate, prefillHost, prefillPath, reset, setStep]);
+
+ // The template step is skipped for a prefilled sheet, so this is where a wrong guess of the type is corrected.
+ const switchPrefillType = (serviceType: AgentVaultServiceType) => {
+ if (!prefillHost) return;
+ const { template: picked, form } = prefillFor(serviceType, prefillHost, prefillPath);
+ setTemplate(picked);
+ setOpenItem(serviceType === AgentVaultServiceType.Mcp ? "" : ADVANCED_ITEM);
+ reset(form);
+ };
const handleTemplatePicked = (
picked: AgentVaultTemplate | null,
@@ -488,14 +577,13 @@ export const ServiceSheet = ({
return;
}
- // An authorization is consumed by the first save that uses it, and is tied to one server URL.
- if (
- serverResponse?.error === ApiErrorTypes.BadRequestError &&
- data.credentialType === AgentVaultCredentialType.OAuth &&
- /authoriz/i.test(serverResponse.message)
- ) {
+ const rejectedAuthorization =
+ data.credentialType === AgentVaultCredentialType.OAuth
+ ? rejectedAuthorizationMessage(error)
+ : null;
+ if (rejectedAuthorization) {
setValue("oauthAuthorizationId", "");
- setError("oauthAuthorizationId", { type: "server", message: serverResponse.message });
+ setError("oauthAuthorizationId", { type: "server", message: rejectedAuthorization });
setStep(stepKeys.indexOf(ServiceStep.Credential));
return;
}
@@ -560,12 +648,14 @@ export const ServiceSheet = ({
return;
}
- if (serverResponse?.error === ApiErrorTypes.BadRequestError) onRequestError(error);
+ if (serverResponse && SERVICE_SAVE_HANDLED_ERROR_CODES.includes(serverResponse.error)) {
+ onRequestError(error);
+ }
}
};
const handleStepChange = async (target: number) => {
- if (target === step) return;
+ if (target === step || isSigningIn) return;
if (target < step) {
if (stepKeys[target] === ServiceStep.Template) returnToTemplates();
else setStep(target);
@@ -574,6 +664,8 @@ export const ServiceSheet = ({
for (let i = step; i < target; i += 1) {
// eslint-disable-next-line no-await-in-loop
if (!(await trigger(stepFields[stepKeys[i]] as (keyof TServiceForm)[]))) {
+ // Show the step that failed, or its error sits on a step nobody can see.
+ setStep(i);
return;
}
}
@@ -603,6 +695,22 @@ export const ServiceSheet = ({
"oauthAuthorizationId",
"oauthAuthorizedUrl"
]);
+
+ useEffect(() => {
+ if (!oauthAuthorizationId) return undefined;
+ const timeout = window.setTimeout(() => {
+ if (getValues("oauthAuthorizationId") !== oauthAuthorizationId) return;
+ setValue("oauthAuthorizationId", "");
+ if (getValues("credentialType") === AgentVaultCredentialType.OAuth) {
+ setError("oauthAuthorizationId", {
+ type: "server",
+ message: OAUTH_AUTHORIZATION_EXPIRED_MESSAGE
+ });
+ }
+ }, OAUTH_AUTHORIZATION_LIFETIME_MS);
+ return () => window.clearTimeout(timeout);
+ }, [oauthAuthorizationId, getValues, setValue, setError]);
+
const isAwaitingAuthorization =
current.step === ServiceStep.Credential &&
isOAuthAuthorizationMissing(
@@ -633,7 +741,7 @@ export const ServiceSheet = ({
<SheetHeader>
{isTemplateStep ? (
<>
- <SheetTitle>Choose a Template</SheetTitle>
+ <SheetTitle>Choose a template</SheetTitle>
<SheetDescription>
Start from a template, or configure the service yourself.
</SheetDescription>
@@ -664,7 +772,7 @@ export const ServiceSheet = ({
<div className="flex min-h-0 flex-1 overflow-hidden">
<aside className="flex w-60 shrink-0 flex-col border-r border-border px-5 py-6">
<p className="mb-5 text-[11px] font-medium tracking-wider text-muted uppercase">
- Setup Steps
+ Setup steps
</p>
<Stepper
activeStep={step}
@@ -694,8 +802,17 @@ export const ServiceSheet = ({
<p className="mt-1 text-sm text-muted">{current.subtitle}</p>
</div>
- {current.step === ServiceStep.Details &&
- (isMcp ? <McpDetailsFields /> : <DetailsFields />)}
+ {current.step === ServiceStep.Details && (
+ <div className="flex flex-col gap-5">
+ {prefillHost && !isUpdate && (
+ <PrefillTypeField
+ value={isMcp ? AgentVaultServiceType.Mcp : AgentVaultServiceType.Http}
+ onChange={switchPrefillType}
+ />
+ )}
+ {isMcp ? <McpDetailsFields /> : <DetailsFields />}
+ </div>
+ )}
{current.step === ServiceStep.Credential && isMcp && (
<ServiceVariablesContext.Provider value={serviceVariables}>
<McpCredentialFields
@@ -703,6 +820,7 @@ export const ServiceSheet = ({
service={service}
openItem={openItem}
onOpenChange={setOpenItem}
+ onSignInChange={setIsSigningIn}
/>
</ServiceVariablesContext.Provider>
)}
@@ -726,7 +844,7 @@ export const ServiceSheet = ({
</p>
<DocumentationLinkBadge href={SERVICE_DOCS_URL} />
</div>
- <h3 className="text-sm font-normal text-foreground">What This Step Does</h3>
+ <p className="text-sm font-semibold text-foreground">What this step does</p>
<p className="text-sm leading-relaxed text-muted">{current.rightDescription}</p>
{current.rightTip && (
<p className="text-sm leading-relaxed text-muted">{current.rightTip}</p>
@@ -735,7 +853,10 @@ export const ServiceSheet = ({
</div>
<SheetFooter className="items-center justify-between border-t">
- <span className="text-xs text-muted">{isDirty ? "Unsaved changes" : ""}</span>
+ <span className="text-xs text-muted">
+ {isSigningIn && "Finish or cancel signing in first."}
+ {!isSigningIn && isDirty && "Unsaved changes"}
+ </span>
<div className="flex items-center gap-3">
<span className="text-xs text-muted">
Step {step + 1} of {steps.length}
@@ -744,6 +865,7 @@ export const ServiceSheet = ({
<Button
type="button"
variant="outline"
+ isDisabled={isSigningIn}
onClick={
stepKeys[step - 1] === ServiceStep.Template ? returnToTemplates : goBack
}
@@ -755,7 +877,7 @@ export const ServiceSheet = ({
type="button"
variant="av"
onClick={handleNext}
- isDisabled={isAwaitingAuthorization}
+ isDisabled={isAwaitingAuthorization || isSigningIn}
isPending={isLastStep && isSubmitting}
>
{isLastStep ? saveLabel : "Continue"}
diff --git a/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts b/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts
index c290015c0d..cc3995bce2 100644
--- a/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts
+++ b/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts
@@ -12,6 +12,7 @@ import {
buildServiceSchema,
isOAuthAuthorizationMissing,
newOAuthAuthorizationId,
+ OAUTH_CLIENT_VARIABLES_MESSAGE,
oauthStatusLabel,
serverUrlError,
storedOAuthCredential,
@@ -61,7 +62,6 @@ const storedOAuthService = (serverUrl = SERVER_URL) =>
grantedScopes: ["read"],
requiredScopes: [],
expiresAt: null,
- authorizedBy: null,
authorizedAt: null,
lastError: null
},
@@ -74,6 +74,7 @@ const storedOAuthService = (serverUrl = SERVER_URL) =>
describe("serverUrlError", () => {
it("rejects a query string", () => {
expect(serverUrlError("https://mcp.example.com/mcp?token=abc")).toMatch(/query string/);
+ expect(serverUrlError("https://*.example.com/mcp")).toMatch(/not a wildcard/);
});
it("accepts a plain server URL", () => {
@@ -189,6 +190,15 @@ describe("oauthStatusLabel", () => {
expect(oauthStatusLabel(mcpForm(), storedOAuthService())).toBe("Needs Reauthorization");
expect(oauthStatusLabel(mcpForm())).toBe("Not authorized");
});
+
+ it("calls a working stored authorization Authorized, the word the card uses", () => {
+ const service = storedOAuthService();
+ const working = {
+ ...service,
+ credential: { ...service.credential, status: AgentVaultOauthStatus.Connected }
+ } as TAgentVaultService;
+ expect(oauthStatusLabel(mcpForm(), working)).toBe("Authorized");
+ });
});
describe("buildServiceSchema with OAuth", () => {
@@ -216,6 +226,29 @@ describe("buildServiceSchema with OAuth", () => {
]);
});
+ it("refuses a variable reference in the client ID or secret, which are sent as typed", () => {
+ const result = buildServiceSchema(storedOAuthService()).safeParse(
+ mcpForm({
+ oauthClientId: "{{GITHUB_CLIENT_ID}}",
+ oauthClientSecret: "{{GITHUB_CLIENT_SECRET}}"
+ })
+ );
+ expect(result.error?.issues.map(({ path, message }) => [path.join("."), message])).toEqual([
+ ["oauthClientId", OAUTH_CLIENT_VARIABLES_MESSAGE],
+ ["oauthClientSecret", OAUTH_CLIENT_VARIABLES_MESSAGE]
+ ]);
+ });
+
+ it("refuses a client ID or secret the API would refuse, such as one with a pasted smart quote", () => {
+ const result = buildServiceSchema(storedOAuthService()).safeParse(
+ mcpForm({ oauthClientId: "\u201cclient-1\u201d", oauthClientSecret: "line\nbreak" })
+ );
+ expect(result.error?.issues.map((issue) => issue.path.join("."))).toEqual([
+ "oauthClientId",
+ "oauthClientSecret"
+ ]);
+ });
+
it("ignores the bearer header fields and reserves Authorization for the token", () => {
const authorized = { oauthAuthorizationId: "auth-1", oauthAuthorizedUrl: SERVER_URL };
expect(
diff --git a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts b/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts
index b02ceeb4b8..ffba4e898e 100644
--- a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts
+++ b/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts
@@ -44,7 +44,7 @@ export const HTTP_CREDENTIAL_TYPES = [
];
export const OAUTH_STATUS_LABELS: Record<AgentVaultOauthStatus, string> = {
- [AgentVaultOauthStatus.Connected]: "Connected",
+ [AgentVaultOauthStatus.Connected]: "Authorized",
[AgentVaultOauthStatus.NeedsReauthorization]: "Needs Reauthorization",
[AgentVaultOauthStatus.NeedsAdditionalScopes]: "Needs Additional Scopes"
};
@@ -101,6 +101,9 @@ export const serverUrlError = (value: string): string | null => {
if (trimmed.includes("?")) {
return "Server URLs can't include a query string, since it is stored and shown in plaintext. Put a token in the Bearer token or a custom header instead.";
}
+ // The URL parser percent-encodes the *, so the hostname carries %2A.
+ if (/\*|%2a/i.test(url.hostname))
+ return "The server URL must name a specific host, not a wildcard.";
return null;
};
@@ -120,6 +123,27 @@ const CONTROL_CHARS_MESSAGE =
"This can't contain line breaks or other control characters. Check for a stray newline if you pasted it.";
// Double braces wrap a variable reference, and neither a prefix nor a placeholder takes one.
+// The client ID and secret go to the provider as typed, unlike the credential fields that take `{{KEY}}`.
+export const OAUTH_CLIENT_VARIABLES_MESSAGE = "Variables aren't supported here. Paste the value.";
+
+// RFC 6749's VSCHAR, which the API requires, so a pasted smart quote is caught here rather than as a 422.
+const OAUTH_CLIENT_CHARS_RE = /^[\x20-\x7e]*$/;
+const OAUTH_CLIENT_CHARS_MESSAGE = "Use printable ASCII characters without line breaks or accents.";
+
+// Shared with the Authorize card, which checks them before it opens the sign-in window.
+export const oauthClientIdSchema = z
+ .string()
+ .trim()
+ .max(2048, "A client ID can be at most 2048 characters.")
+ .regex(OAUTH_CLIENT_CHARS_RE, OAUTH_CLIENT_CHARS_MESSAGE)
+ .refine((value) => !value.includes("{{"), OAUTH_CLIENT_VARIABLES_MESSAGE);
+
+export const oauthClientSecretSchema = z
+ .string()
+ .max(4096, "A client secret can be at most 4096 characters.")
+ .regex(OAUTH_CLIENT_CHARS_RE, OAUTH_CLIENT_CHARS_MESSAGE)
+ .refine((value) => !value.includes("{{"), OAUTH_CLIENT_VARIABLES_MESSAGE);
+
const hasDoubleBraces = (text: string) => text.includes("{{") || text.includes("}}");
const PREFIX_BRACES_MESSAGE =
@@ -259,15 +283,8 @@ export const buildServiceSchema = (
// The server URL the authorization was made for, so editing the URL afterwards asks for a new one.
oauthAuthorizedUrl: z.string(),
oauthScopes: z.array(z.string()),
- oauthClientId: z
- .string()
- .trim()
- .max(2048, "A client ID can be at most 2048 characters.")
- .optional(),
- oauthClientSecret: z
- .string()
- .max(4096, "A client secret can be at most 4096 characters.")
- .optional(),
+ oauthClientId: oauthClientIdSchema.optional(),
+ oauthClientSecret: oauthClientSecretSchema.optional(),
methods: z.array(z.nativeEnum(AgentVaultHttpMethod)),
pathPrefixes: z
.array(z.string())
diff --git a/frontend/src/components/agent-vault/service-sheet/stepMeta.ts b/frontend/src/components/agent-vault/service-sheet/stepMeta.ts
index a883763971..1c30930786 100644
--- a/frontend/src/components/agent-vault/service-sheet/stepMeta.ts
+++ b/frontend/src/components/agent-vault/service-sheet/stepMeta.ts
@@ -18,11 +18,20 @@ type StepMeta = {
const VARIABLE_TIP =
"To use a variable, type {{ in any value and pick it from the list. The proxy puts the variable's value in its place.";
+const TEMPLATE_STEP: StepMeta = { step: ServiceStep.Template, name: "Template" };
+
+const REVIEW_STEP: StepMeta = {
+ step: ServiceStep.Review,
+ name: "Review",
+ shortDescription: "Confirm and add",
+ title: "Review",
+ subtitle: "Check everything before you save. You can change it later.",
+ rightLabel: "REVIEW",
+ rightDescription: "Review your settings before saving."
+};
+
export const SERVICE_STEPS: StepMeta[] = [
- {
- step: ServiceStep.Template,
- name: "Template"
- },
+ TEMPLATE_STEP,
{
step: ServiceStep.Details,
name: "Details",
@@ -44,22 +53,11 @@ export const SERVICE_STEPS: StepMeta[] = [
"Agents reach this service without ever holding the credential themselves. Custom headers go out on top of it, and a substitution swaps a placeholder your agent already sends for the real value.",
rightTip: VARIABLE_TIP
},
- {
- step: ServiceStep.Review,
- name: "Review",
- shortDescription: "Confirm and add",
- title: "Review",
- subtitle: "Check everything before you save. You can change it later.",
- rightLabel: "REVIEW",
- rightDescription: "Review your settings before saving."
- }
+ REVIEW_STEP
];
export const MCP_SERVICE_STEPS: StepMeta[] = [
- {
- step: ServiceStep.Template,
- name: "Template"
- },
+ TEMPLATE_STEP,
{
step: ServiceStep.Details,
name: "Details",
@@ -68,7 +66,7 @@ export const MCP_SERVICE_STEPS: StepMeta[] = [
subtitle: "What this service is called and the MCP server it connects to.",
rightLabel: "DETAILS",
rightDescription:
- "The agent connects to this server through the proxy, which adds the credential. Tools come later: most servers only list them to an authenticated session."
+ "The agent connects to this server through the proxy, which adds the credential."
},
{
step: ServiceStep.Credential,
@@ -78,16 +76,8 @@ export const MCP_SERVICE_STEPS: StepMeta[] = [
subtitle: "How the proxy authenticates to this MCP server.",
rightLabel: "CREDENTIAL",
rightDescription:
- "The proxy authenticates to the MCP server for the agent. Infisical refreshes OAuth tokens automatically, and the agent never sees them. The agent can call any tool the server exposes to this credential.",
+ "The proxy authenticates to the MCP server for the agent. The agent can call any tool the server exposes to this credential.",
rightTip: VARIABLE_TIP
},
- {
- step: ServiceStep.Review,
- name: "Review",
- shortDescription: "Confirm and add",
- title: "Review",
- subtitle: "Check everything before you save. You can change it later.",
- rightLabel: "REVIEW",
- rightDescription: "Review your settings before saving."
- }
+ REVIEW_STEP
];
diff --git a/frontend/src/components/agent-vault/service-sheet/useOAuthAuthorize.ts b/frontend/src/components/agent-vault/service-sheet/useOAuthAuthorize.ts
index f2fe1ecced..80ac6ecd72 100644
--- a/frontend/src/components/agent-vault/service-sheet/useOAuthAuthorize.ts
+++ b/frontend/src/components/agent-vault/service-sheet/useOAuthAuthorize.ts
@@ -3,6 +3,7 @@ import axios from "axios";
import {
AgentVaultOauthAuthorizationStatus,
+ isTerminalOauthAuthorizationError,
useCreateAgentVaultOauthAuthorization,
useGetAgentVaultOauthAuthorization
} from "@app/hooks/api/agentVault";
@@ -15,11 +16,11 @@ const POLL_TIMEOUT_MS = 5 * 60 * 1000;
const POPUP_NAME = "infisical-agent-vault-oauth";
const POPUP_FEATURES = "popup,width=600,height=720";
-export type TOAuthAuthorizeState =
+type TOAuthAuthorizeState =
| { status: "idle" }
| { status: "starting" }
| { status: "pending" }
- | { status: "authorized"; authorization: TAgentVaultOauthAuthorization }
+ | { status: "authorized" }
| { status: "failed"; message: string };
const serverMessage = (error: unknown) => {
@@ -37,7 +38,6 @@ export const useOAuthAuthorize = ({
const [state, setState] = useState<TOAuthAuthorizeState>({ status: "idle" });
const [isClientRequired, setIsClientRequired] = useState(false);
const [redirectUri, setRedirectUri] = useState<string | null>(null);
- const [registrationError, setRegistrationError] = useState<string | null>(null);
const [isOAuthAdvertised, setIsOAuthAdvertised] = useState(true);
const [pendingAuthorization, setPendingAuthorization] = useState<{
id: string;
@@ -56,7 +56,9 @@ export const useOAuthAuthorize = ({
const stop = useCallback(() => {
attemptRef.current += 1;
setPendingAuthorization(null);
- if (popupRef.current && !popupRef.current.closed) popupRef.current.close();
+ // Best effort: once the popup reaches a provider, Cross-Origin-Opener-Policy can sever this handle, which then
+ // reads as closed and ignores close(). Checking `closed` first would skip the close every time.
+ popupRef.current?.close();
popupRef.current = null;
}, []);
@@ -72,14 +74,15 @@ export const useOAuthAuthorize = ({
useEffect(() => {
if (!pendingAuthorization || attemptRef.current !== pendingAuthorization.attempt) return;
- if (authorizationError) {
+ // The poll keeps going through a transient error, and the sign-in timeout still bounds it.
+ if (authorizationError && isTerminalOauthAuthorizationError(authorizationError)) {
fail(serverMessage(authorizationError) ?? "Couldn't check the authorization status.");
return;
}
if (!authorization) return;
if (authorization.status === AgentVaultOauthAuthorizationStatus.Authorized) {
stop();
- setState({ status: "authorized", authorization });
+ setState({ status: "authorized" });
onAuthorizedRef.current(authorization);
return;
}
@@ -125,7 +128,6 @@ export const useOAuthAuthorize = ({
registrationRequired,
oauthAdvertised,
redirectUri: uri,
- registrationError: reason,
authorization: createdAuthorization
}) => {
if (attemptRef.current !== attempt) return;
@@ -133,7 +135,6 @@ export const useOAuthAuthorize = ({
stop();
setIsClientRequired(true);
setRedirectUri(uri);
- setRegistrationError(reason);
setIsOAuthAdvertised(oauthAdvertised);
setState({ status: "idle" });
return;
@@ -161,7 +162,6 @@ export const useOAuthAuthorize = ({
isClientRequired,
isOAuthAdvertised,
redirectUri,
- registrationError,
authorize,
cancel
};
diff --git a/frontend/src/helpers/agentVaultTemplates.ts b/frontend/src/helpers/agentVaultTemplates.ts
index a32ade7c5a..9ced40b47b 100644
--- a/frontend/src/helpers/agentVaultTemplates.ts
+++ b/frontend/src/helpers/agentVaultTemplates.ts
@@ -505,15 +505,38 @@ export const findTemplateForHostPattern = (
);
};
-/** For icons: an MCP service's host pattern is derived from its server URL, so the MCP templates match it too. */
-export const findAnyTemplateForHostPattern = (
+export const findMcpTemplateForHostPattern = (
hostPattern: string
-): AgentVaultTemplate | undefined => {
+): AgentVaultMcpTemplate | undefined => {
const hosts = hostsOfPattern(hostPattern);
- return (
- findTemplateForHostPattern(hostPattern) ??
- AGENT_VAULT_MCP_TEMPLATES.find((template) =>
- templateHosts(template).some((templateHost) => hosts.includes(templateHost))
- )
+ return AGENT_VAULT_MCP_TEMPLATES.find((template) =>
+ templateHosts(template).some((templateHost) => hosts.includes(templateHost))
);
};
+
+/** For icons: an MCP service's host pattern is derived from its server URL, so the MCP templates match it too. */
+export const findAnyTemplateForHostPattern = (
+ hostPattern: string
+): AgentVaultTemplate | undefined =>
+ findTemplateForHostPattern(hostPattern) ?? findMcpTemplateForHostPattern(hostPattern);
+
+const MCP_PATH_SEGMENTS = new Set(["mcp", "sse"]);
+
+export const lastPathSegment = (path: string) =>
+ path.split("?")[0].split("/").filter(Boolean).at(-1)?.toLowerCase() ?? "";
+
+/**
+ * Which kind of service a request from a session log most likely went to, for prefilling the service sheet: a known
+ * MCP server, else a host whose first label is `mcp` or a path ending in `/mcp` or `/sse`, else an HTTP API.
+ */
+export const guessServiceTypeForRequest = (
+ hostPattern: string,
+ path = ""
+): AgentVaultServiceType => {
+ const [firstLabel] = stripPort(hostPattern).split(".");
+ const isMcp =
+ Boolean(findMcpTemplateForHostPattern(hostPattern)) ||
+ firstLabel.toLowerCase() === "mcp" ||
+ MCP_PATH_SEGMENTS.has(lastPathSegment(path));
+ return isMcp ? AgentVaultServiceType.Mcp : AgentVaultServiceType.Http;
+};
diff --git a/frontend/src/hooks/api/agentVault/mutations.tsx b/frontend/src/hooks/api/agentVault/mutations.tsx
index ddcd99d6b2..b5a6ff2051 100644
--- a/frontend/src/hooks/api/agentVault/mutations.tsx
+++ b/frontend/src/hooks/api/agentVault/mutations.tsx
@@ -93,13 +93,19 @@ export const useDeleteAgentVaultAccessBundle = () => {
});
};
+// The service sheet renders these inline when it recognizes them (a host-pattern conflict, an authorization that
+// expired or was already used) and hands the rest back to onRequestError, so the global toast must not also fire.
+export const SERVICE_SAVE_HANDLED_ERROR_CODES: string[] = [
+ ApiErrorTypes.BadRequestError,
+ ApiErrorTypes.ConflictError,
+ "NotFound"
+];
+
export const useCreateAgentVaultService = () => {
const { currentOrg } = useOrganization();
const queryClient = useQueryClient();
return useMutation({
- // The sheet renders a host-pattern conflict inline and hands anything else back to onRequestError,
- // so the global toast must not also fire for it.
- meta: { skipValidationToast: true, handledErrorCodes: [ApiErrorTypes.BadRequestError] },
+ meta: { skipValidationToast: true, handledErrorCodes: SERVICE_SAVE_HANDLED_ERROR_CODES },
mutationFn: async ({ accessBundleId, ...params }: TCreateAgentVaultServiceDTO) => {
const { data } = await apiRequest.post<{ service: TAgentVaultService }>(
`/api/v1/agent-vault/access-bundles/${accessBundleId}/services`,
@@ -121,9 +127,7 @@ export const useUpdateAgentVaultService = () => {
const { currentOrg } = useOrganization();
const queryClient = useQueryClient();
return useMutation({
- // The sheet renders a host-pattern conflict inline and hands anything else back to onRequestError,
- // so the global toast must not also fire for it.
- meta: { skipValidationToast: true, handledErrorCodes: [ApiErrorTypes.BadRequestError] },
+ meta: { skipValidationToast: true, handledErrorCodes: SERVICE_SAVE_HANDLED_ERROR_CODES },
mutationFn: async ({ accessBundleId, serviceId, ...params }: TUpdateAgentVaultServiceDTO) => {
const { data } = await apiRequest.patch<{ service: TAgentVaultService }>(
`/api/v1/agent-vault/access-bundles/${accessBundleId}/services/${serviceId}`,
@@ -461,9 +465,8 @@ export const useRevealAgentVaultVariableValue = () =>
export const useCreateAgentVaultOauthAuthorization = () =>
useMutation({
- // Discovery and registration failures name the server and what failed, and the Authorize card
- // shows them in place.
- meta: { handledErrorCodes: [ApiErrorTypes.BadRequestError] },
+ // The Authorize card shows every failure in place, discovery and registration ones naming the server.
+ meta: { skipErrorToast: true },
mutationFn: async (params: TCreateAgentVaultOauthAuthorizationDTO) => {
const { data } = await apiRequest.post<TCreateAgentVaultOauthAuthorizationResponse>(
"/api/v1/agent-vault/oauth/authorizations",
diff --git a/frontend/src/hooks/api/agentVault/queries.tsx b/frontend/src/hooks/api/agentVault/queries.tsx
index d7974cd1d1..f3bea5018c 100644
--- a/frontend/src/hooks/api/agentVault/queries.tsx
+++ b/frontend/src/hooks/api/agentVault/queries.tsx
@@ -128,6 +128,14 @@ export const agentVaultKeys = {
[...agentVaultKeys.sessions(orgId), sessionId, "logs-live", range ?? {}] as const
};
+// A dropped connection, a deploy, a 5xx or a rate limit can clear on the next poll; any other client error,
+// such as the 404 of an expired authorization, never will.
+export const isTerminalOauthAuthorizationError = (error: unknown) => {
+ if (!axios.isAxiosError(error)) return true;
+ const status = error.response?.status;
+ return status !== undefined && status >= 400 && status < 500 && status !== 408 && status !== 429;
+};
+
export const useGetAgentVaultOauthAuthorization = (authorizationId: string) => {
const { currentOrg } = useOrganization();
@@ -138,11 +146,12 @@ export const useGetAgentVaultOauthAuthorization = (authorizationId: string) => {
staleTime: 0,
gcTime: 0,
retry: false,
- refetchInterval: (query) =>
- query.state.error ||
- (query.state.data && query.state.data.status !== AgentVaultOauthAuthorizationStatus.Pending)
- ? false
- : 2000,
+ refetchInterval: (query) => {
+ const { data, error } = query.state;
+ if (error && isTerminalOauthAuthorizationError(error)) return false;
+ if (data && data.status !== AgentVaultOauthAuthorizationStatus.Pending) return false;
+ return error ? 5000 : 2000;
+ },
// The provider popup can leave the Infisical tab in the background until authorization finishes.
refetchIntervalInBackground: true
});
diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.ts
index 6539c15395..50662374a9 100644
--- a/frontend/src/hooks/api/agentVault/types.ts
+++ b/frontend/src/hooks/api/agentVault/types.ts
@@ -21,7 +21,6 @@ export type TAgentVaultOauthCredentialSummary = {
grantedScopes: string[];
requiredScopes: string[];
expiresAt: string | null;
- authorizedBy: { userId: string; username: string } | null;
authorizedAt: string | null;
lastError: string | null;
};
diff --git a/frontend/src/hooks/api/reactQuery.tsx b/frontend/src/hooks/api/reactQuery.tsx
index d100866a28..7fd6bd8079 100644
--- a/frontend/src/hooks/api/reactQuery.tsx
+++ b/frontend/src/hooks/api/reactQuery.tsx
@@ -140,6 +140,8 @@ export const onRequestError = (
_context?: unknown,
mutation?: { meta?: Record<string, unknown> }
) => {
+ // For a mutation whose caller shows every failure in place, where a toast would repeat it.
+ if (mutation?.meta?.skipErrorToast) return;
if (axios.isAxiosError(error)) {
const serverResponse = error.response?.data as TApiErrors;
const handledErrorCodes = mutation?.meta?.handledErrorCodes;
diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx
index f94c68e89b..9fe5248afe 100644
--- a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx
@@ -14,7 +14,6 @@ import {
import { AccessBundleFormDialog } from "@app/components/agent-vault/AccessBundleFormDialog";
import { ManageAccessSheet } from "@app/components/agent-vault/ManageAccessSheet";
import { ServiceSheet } from "@app/components/agent-vault/service-sheet";
-import { ServiceStep } from "@app/components/agent-vault/service-sheet/serviceSchema";
import {
Button,
DropdownMenu,
@@ -56,7 +55,6 @@ export const AgentVaultAccessBundleDetailPage = () => {
const [isDeleteOpen, setIsDeleteOpen] = useState(false);
const [isServiceSheetOpen, setIsServiceSheetOpen] = useState(false);
const [serviceToEdit, setServiceToEdit] = useState<TAgentVaultService | null>(null);
- const [serviceSheetStep, setServiceSheetStep] = useState<ServiceStep | undefined>();
if (isPending) return <PageLoader />;
if (!accessBundle) {
@@ -133,17 +131,10 @@ export const AgentVaultAccessBundleDetailPage = () => {
canManage={isAdmin}
onAdd={() => {
setServiceToEdit(null);
- setServiceSheetStep(undefined);
setIsServiceSheetOpen(true);
}}
onEdit={(service) => {
setServiceToEdit(service);
- setServiceSheetStep(undefined);
- setIsServiceSheetOpen(true);
- }}
- onReauthorize={(service) => {
- setServiceToEdit(service);
- setServiceSheetStep(ServiceStep.Credential);
setIsServiceSheetOpen(true);
}}
/>
@@ -158,7 +149,6 @@ export const AgentVaultAccessBundleDetailPage = () => {
onOpenChange={setIsServiceSheetOpen}
accessBundleId={accessBundle.id}
service={serviceToEdit}
- initialStep={serviceSheetStep}
/>
<AccessBundleFormDialog
diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx
index 6f8e664c2b..80da49cf8e 100644
--- a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx
@@ -2,13 +2,10 @@ import { useMemo, useState } from "react";
import { format } from "date-fns";
import {
ChevronDownIcon,
- GlobeIcon,
- KeyRoundIcon,
MoreHorizontalIcon,
PencilIcon,
PlusIcon,
SearchIcon,
- ServerIcon,
TrashIcon
} from "lucide-react";
import { twMerge } from "tailwind-merge";
@@ -21,7 +18,6 @@ import {
import { ServiceIcon } from "@app/components/agent-vault/ServiceIconStack";
import { createNotification } from "@app/components/notifications";
import {
- Badge,
Button,
Card,
CardAction,
@@ -43,11 +39,6 @@ import {
InputGroup,
InputGroupAddon,
InputGroupInput,
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
Table,
TableBody,
TableCell,
@@ -75,10 +66,6 @@ enum SortColumn {
Created = "created"
}
-const ALL_TYPES = "all";
-
-const serviceTypeOf = (service: TAgentVaultService) => service.type ?? AgentVaultServiceType.Http;
-
const targetOf = (service: TAgentVaultService) =>
service.type === AgentVaultServiceType.Mcp ? service.serverUrl : service.hostPattern;
@@ -87,8 +74,9 @@ const SORT_COMPARATORS: Record<
(a: TAgentVaultService, b: TAgentVaultService) => number
> = {
[SortColumn.Name]: (a, b) => a.name.localeCompare(b.name),
- [SortColumn.Type]: (a, b) => serviceTypeOf(a).localeCompare(serviceTypeOf(b)),
- [SortColumn.Target]: (a, b) => targetOf(a).localeCompare(targetOf(b)),
+ [SortColumn.Type]: (a, b) => a.type.localeCompare(b.type),
+ // The host, not the shown URL, so MCP servers sort among the HTTP hosts instead of together under "https".
+ [SortColumn.Target]: (a, b) => a.hostPattern.localeCompare(b.hostPattern),
[SortColumn.Created]: (a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
};
@@ -98,7 +86,6 @@ type Props = {
canManage: boolean;
onAdd: () => void;
onEdit: (service: TAgentVaultService) => void;
- onReauthorize: (service: TAgentVaultService) => void;
};
// Two hosts is what the column fits comfortably; the rest go behind the count so the table keeps its
@@ -122,32 +109,17 @@ const HostsCell = ({ hostPattern }: { hostPattern: string }) => {
);
};
-const TypeBadge = ({ type }: { type: AgentVaultServiceType }) => (
- <Badge variant="outline">
- {type === AgentVaultServiceType.Mcp ? <ServerIcon /> : <GlobeIcon />}
- {SERVICE_TYPE_LABELS[type]}
- </Badge>
-);
-
const TargetCell = ({ service }: { service: TAgentVaultService }) =>
service.type === AgentVaultServiceType.Mcp ? (
- <span className="block max-w-72 truncate font-mono text-sm" title={service.serverUrl}>
+ <span className="block max-w-72 truncate text-sm" title={service.serverUrl}>
{service.serverUrl}
</span>
) : (
<HostsCell hostPattern={service.hostPattern} />
);
-export const ServicesCard = ({
- accessBundleId,
- services,
- canManage,
- onAdd,
- onEdit,
- onReauthorize
-}: Props) => {
+export const ServicesCard = ({ accessBundleId, services, canManage, onAdd, onEdit }: Props) => {
const [search, setSearch] = useState("");
- const [typeFilter, setTypeFilter] = useState<AgentVaultServiceType | typeof ALL_TYPES>(ALL_TYPES);
const [serviceToDelete, setServiceToDelete] = useState<TAgentVaultService | null>(null);
const deleteService = useDeleteAgentVaultService();
@@ -156,17 +128,20 @@ export const ServicesCard = ({
const displayed = useMemo(() => {
const term = search.trim().toLowerCase();
- const filtered = services.filter(
- (service) =>
- (typeFilter === ALL_TYPES || serviceTypeOf(service) === typeFilter) &&
- (service.name.toLowerCase().includes(term) ||
- service.hostPattern.toLowerCase().includes(term) ||
- targetOf(service).toLowerCase().includes(term))
+ // A bundle holds few services, so the type is matched by search ("mcp", "http") rather than a filter.
+ const filtered = services.filter((service) =>
+ [
+ service.name,
+ service.hostPattern,
+ targetOf(service),
+ service.type,
+ SERVICE_TYPE_LABELS[service.type]
+ ].some((text) => text.toLowerCase().includes(term))
);
const ordered = [...filtered].sort(SORT_COMPARATORS[sortColumn]);
return sortDirection === "ascending" ? ordered : ordered.reverse();
- }, [services, search, typeFilter, sortColumn, sortDirection]);
+ }, [services, search, sortColumn, sortDirection]);
const handleSort = (column: SortColumn, direction: "ascending" | "descending" | "none") => {
if (direction === "none") {
@@ -222,36 +197,24 @@ export const ServicesCard = ({
</Button>
</CardAction>
)}
- {services.length > 0 && (
- <div className="flex items-center gap-3 @xs:col-span-2">
- <InputGroup className="flex-1">
- <InputGroupAddon>
- <SearchIcon />
- </InputGroupAddon>
- <InputGroupInput
- aria-label="Search services"
- value={search}
- onChange={(e) => setSearch(e.target.value)}
- placeholder="Search services..."
- />
- </InputGroup>
- <Select
- value={typeFilter}
- onValueChange={(value) => setTypeFilter(value as typeof typeFilter)}
- >
- <SelectTrigger className="w-44" aria-label="Filter by type">
- <SelectValue />
- </SelectTrigger>
- <SelectContent position="popper" align="end">
- <SelectItem value={ALL_TYPES}>All Types</SelectItem>
- <SelectItem value={AgentVaultServiceType.Http}>HTTP APIs</SelectItem>
- <SelectItem value={AgentVaultServiceType.Mcp}>MCP Servers</SelectItem>
- </SelectContent>
- </Select>
- </div>
- )}
</CardHeader>
+ {services.length > 0 && (
+ <CardContent>
+ <InputGroup>
+ <InputGroupAddon>
+ <SearchIcon />
+ </InputGroupAddon>
+ <InputGroupInput
+ aria-label="Search services"
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search services..."
+ />
+ </InputGroup>
+ </CardContent>
+ )}
+
{displayed.length === 0 ? (
<CardContent>
<Empty className="border">
@@ -262,7 +225,7 @@ export const ServicesCard = ({
<EmptyDescription>
{services.length === 0
? "Add services to give this bundle access to external hosts."
- : "Try a different search term or type."}
+ : "Try a different search term."}
</EmptyDescription>
</EmptyHeader>
</Empty>
@@ -316,7 +279,7 @@ export const ServicesCard = ({
</div>
</TableCell>
<TableCell>
- <TypeBadge type={serviceTypeOf(service)} />
+ <span className="text-sm">{SERVICE_TYPE_LABELS[service.type]}</span>
</TableCell>
<TableCell>
<TargetCell service={service} />
@@ -346,12 +309,6 @@ export const ServicesCard = ({
<PencilIcon />
Edit
</DropdownMenuItem>
- {service.credential.type === AgentVaultCredentialType.OAuth && (
- <DropdownMenuItem onClick={() => onReauthorize(service)}>
- <KeyRoundIcon />
- Reauthorize
- </DropdownMenuItem>
- )}
<DropdownMenuItem
variant="danger"
onClick={() => setServiceToDelete(service)}
diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsx
index c7741aa08f..5489535256 100644
--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsx
@@ -111,14 +111,19 @@ const PathDetail = ({ record }: { record: TAgentVaultSessionLogRecord }) => (
</span>
);
-const McpCallText = ({ call }: { call: TAgentVaultSessionLogMcpCall }) =>
+// The proxy records a tool only for tools/call, so the method beside it would say nothing new.
+const McpCallText = ({ call, path }: { call: TAgentVaultSessionLogMcpCall; path: string }) =>
call.tool ? (
- <>
- <span className="truncate font-mono text-foreground">{call.tool}</span>
- <span className="shrink-0 font-mono text-xs text-muted">{call.method}</span>
- </>
+ <Tooltip>
+ <TooltipTrigger className="min-w-0 truncate text-left font-mono text-foreground">
+ {call.tool}
+ </TooltipTrigger>
+ <TooltipContent className="max-w-sm font-mono text-xs break-all">{call.tool}</TooltipContent>
+ </Tooltip>
) : (
- <span className="truncate font-mono text-xs text-muted">{call.method}</span>
+ <span className="min-w-0 truncate font-mono text-xs text-muted" title={path}>
+ {call.method}
+ </span>
);
const McpDetail = ({ record }: { record: TAgentVaultSessionLogRecord }) => {
@@ -132,9 +137,7 @@ const McpDetail = ({ record }: { record: TAgentVaultSessionLogRecord }) => {
MCP
</Badge>
{first ? (
- <span className="flex min-w-0 items-baseline gap-1.5" title={record.path}>
- <McpCallText call={first} />
- </span>
+ <McpCallText call={first} path={record.path} />
) : (
<span className="min-w-0 truncate text-muted" title={record.path}>
{record.path}
@@ -159,7 +162,7 @@ const McpDetail = ({ record }: { record: TAgentVaultSessionLogRecord }) => {
)}
{truncated && (
<p className={twMerge("text-xs text-muted", rest.length > 0 && "mt-1.5")}>
- More calls in this batch weren&apos;t recorded.
+ More calls in this request weren&apos;t recorded.
</p>
)}
</TooltipContent>
diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.tsx
index 213c4fffb3..a995cce4eb 100644
--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.tsx
@@ -36,7 +36,6 @@ import {
import { useOrganization, useProjectPermission, useSubscription } from "@app/context";
import {
AGENT_VAULT_SESSION_LOG_LIVE_POLL_MS,
- AgentVaultServiceType,
AgentVaultSessionLogDecision,
getSessionLogStorageError,
sessionLogRecordKey,
@@ -56,9 +55,7 @@ import {
chunkIdTime,
groupSessionLogGaps,
matchesSessionLogSearch,
- matchesSessionLogType,
- sessionLogSearchTerm,
- SessionLogTypeFilter
+ sessionLogSearchTerm
} from "./SessionLogsPanel.utils";
import { useNewRequestsCounter } from "./useNewRequestsCounter";
import { useSessionLogsLiveTail } from "./useSessionLogsLiveTail";
@@ -113,12 +110,12 @@ export const SessionLogsPanel = ({ session }: Props) => {
// Not cleared on close: a prefilled host drops the sheet's template step, so clearing the host
// while the sheet animates out would change the step on screen.
const [serviceHost, setServiceHost] = useState<string | null>(null);
+ const [servicePath, setServicePath] = useState<string | undefined>();
const [isServiceSheetOpen, setIsServiceSheetOpen] = useState(false);
const [addedHosts, setAddedHosts] = useState<Set<string>>(() => new Set());
const [search, setSearch] = useState("");
const [decisionFilter, setDecisionFilter] = useState<DecisionFilter>("all");
- const [typeFilter, setTypeFilter] = useState<SessionLogTypeFilter>("all");
const { range, applyRange, isActive, canTail, isLive, isPausedForBudget, pauseForBudget } =
useSessionLogsLiveTail(session);
const { history, live, arrived, isLiveGapUnfilled } = useGetAgentVaultSessionLogs(session.id, {
@@ -193,14 +190,12 @@ export const SessionLogsPanel = ({ session }: Props) => {
() =>
records.filter((record) => {
if (decisionFilter !== "all" && record.decision !== decisionFilter) return false;
- if (!matchesSessionLogType(record, typeFilter)) return false;
return matchesSessionLogSearch(record, search);
}),
- [records, search, decisionFilter, typeFilter]
+ [records, search, decisionFilter]
);
- const hasBrowserFilter =
- Boolean(sessionLogSearchTerm(search)) || decisionFilter !== "all" || typeFilter !== "all";
+ const hasBrowserFilter = Boolean(sessionLogSearchTerm(search)) || decisionFilter !== "all";
const isFiltered = hasBrowserFilter || Boolean(range);
// Counted once opened: a chunk's request count isn't known until it is decrypted.
@@ -230,7 +225,6 @@ export const SessionLogsPanel = ({ session }: Props) => {
const filterKey = [
sessionLogSearchTerm(search),
decisionFilter,
- typeFilter,
range?.startDate.getTime(),
range?.endDate.getTime()
].join("|");
@@ -518,19 +512,6 @@ export const SessionLogsPanel = ({ session }: Props) => {
)}
</InputGroup>
</div>
- <Select
- value={typeFilter}
- onValueChange={(value) => setTypeFilter(value as SessionLogTypeFilter)}
- >
- <SelectTrigger aria-label="Filter by type">
- <SelectValue />
- </SelectTrigger>
- <SelectContent position="popper">
- <SelectItem value="all">All Types</SelectItem>
- <SelectItem value={AgentVaultServiceType.Http}>HTTP APIs</SelectItem>
- <SelectItem value={AgentVaultServiceType.Mcp}>MCP Servers</SelectItem>
- </SelectContent>
- </Select>
<Select
value={decisionFilter}
onValueChange={(value) => setDecisionFilter(value as DecisionFilter)}
@@ -715,6 +696,7 @@ export const SessionLogsPanel = ({ session }: Props) => {
isAddable
? () => {
setServiceHost(hostPatternFor(record));
+ setServicePath(record.path);
setIsServiceSheetOpen(true);
}
: undefined
@@ -783,6 +765,7 @@ export const SessionLogsPanel = ({ session }: Props) => {
onOpenChange={setIsServiceSheetOpen}
accessBundleId={accessBundle.id}
prefillHost={serviceHost ?? undefined}
+ prefillPath={servicePath}
onSaved={() => {
if (serviceHost) setAddedHosts((prev) => new Set(prev).add(serviceHost));
}}
diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.test.ts b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.test.ts
index 5bf1f90b1f..97cf7ab326 100644
--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.test.ts
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.test.ts
@@ -13,7 +13,6 @@ import {
groupRepeatedMcpCalls,
groupSessionLogGaps,
matchesSessionLogSearch,
- matchesSessionLogType,
mcpCallLabel,
mcpMoreCallsLabel,
sessionLogMcpCalls,
@@ -138,34 +137,6 @@ describe("matchesSessionLogSearch", () => {
});
});
-describe("matchesSessionLogType", () => {
- const http = { ...record(1), serviceType: AgentVaultServiceType.Http };
- const mcp = { ...record(2), serviceType: AgentVaultServiceType.Mcp };
- const untyped = { ...record(3), serviceType: null };
- const legacy = record(4);
-
- it("keeps every record for all types", () => {
- [http, mcp, untyped, legacy].forEach((entry) =>
- assert.equal(matchesSessionLogType(entry, "all"), true)
- );
- });
-
- it("keeps only records of the chosen type", () => {
- assert.deepEqual(
- [http, mcp, untyped, legacy].map((entry) =>
- matchesSessionLogType(entry, AgentVaultServiceType.Http)
- ),
- [true, false, false, false]
- );
- assert.deepEqual(
- [http, mcp, untyped, legacy].map((entry) =>
- matchesSessionLogType(entry, AgentVaultServiceType.Mcp)
- ),
- [false, true, false, false]
- );
- });
-});
-
describe("sessionLogMcpCalls", () => {
const calls = [{ method: "tools/call", tool: "search" }, { method: "initialize" }];
diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.ts b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.ts
index baa42b5216..4cca7aeba3 100644
--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.ts
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.utils.ts
@@ -123,14 +123,6 @@ export const matchesSessionLogSearch = (record: TAgentVaultSessionLogRecord, sea
].some((field) => field.includes(term));
};
-export type SessionLogTypeFilter = "all" | AgentVaultServiceType;
-
-// Passthrough and blocked requests matched no service, so they have no type to filter on.
-export const matchesSessionLogType = (
- record: TAgentVaultSessionLogRecord,
- filter: SessionLogTypeFilter
-) => filter === "all" || record.serviceType === filter;
-
export const sessionLogMcpCalls = (
record: TAgentVaultSessionLogRecord
): TAgentVaultSessionLogMcpCall[] => {