Skip to content

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

misc: address feedback

Sheen Capadngan246ecd167e76
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.ts
index da99620867..5b3edbbe46 100644
--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts
+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts
@@ -510,7 +510,7 @@ describe("Agent Vault V1 Router", async () => {
(await testDb("agent_vault_services").where({ id: service.id }).first()).encryptedCredential;
const before = await sealed();
- const rotated = await inject("PATCH", url, { credential: { type: "bearer", value: "rotated456" } });
+ const rotated = await inject("PATCH", url, { type: "http", credential: { type: "bearer", value: "rotated456" } });
expect(rotated.statusCode).toBe(200);
expect(JSON.parse(rotated.payload).service.credential).toEqual({
type: "bearer",
@@ -520,7 +520,10 @@ describe("Agent Vault V1 Router", async () => {
expect((await sealed()).equals(before)).toBe(false);
const afterRotate = await sealed();
- const renamed = await inject("PATCH", url, { credential: { type: "bearer", headerName: "X-Api-Key" } });
+ const renamed = await inject("PATCH", url, {
+ type: "http",
+ credential: { type: "bearer", headerName: "X-Api-Key" }
+ });
expect(renamed.statusCode).toBe(200);
expect(JSON.parse(renamed.payload).service.credential.headerName).toBe("X-Api-Key");
expect((await sealed()).equals(afterRotate)).toBe(true);
@@ -550,23 +553,29 @@ describe("Agent Vault V1 Router", async () => {
};
const before = await sealedPair();
- const emptied = await inject("PATCH", url, { credential: { type: "basic", username: "" } });
+ const emptied = await inject("PATCH", url, { type: "http", credential: { type: "basic", username: "" } });
expect(emptied.statusCode).toBe(400);
expect((await sealedPair()).equals(before)).toBe(true);
- const flipped = await inject("PATCH", url, { credential: { type: "basic", username: "", password: "hunter2" } });
+ const flipped = await inject("PATCH", url, {
+ type: "http",
+ credential: { type: "basic", username: "", password: "hunter2" }
+ });
expect(flipped.statusCode).toBe(200);
expect((await sealedPair()).equals(before)).toBe(false);
- const named = await inject("PATCH", url, { credential: { type: "basic", username: "sk_live_key" } });
+ const named = await inject("PATCH", url, {
+ type: "http",
+ credential: { type: "basic", username: "sk_live_key" }
+ });
expect(named.statusCode).toBe(200);
- const cleared = await inject("PATCH", url, { credential: { type: "basic", password: "" } });
+ const cleared = await inject("PATCH", url, { type: "http", credential: { type: "basic", password: "" } });
expect(cleared.statusCode).toBe(200);
- const emptiedAgain = await inject("PATCH", url, { credential: { type: "basic", username: "" } });
+ const emptiedAgain = await inject("PATCH", url, { type: "http", credential: { type: "basic", username: "" } });
expect(emptiedAgain.statusCode).toBe(400);
const afterClear = await sealedPair();
- const renamed = await inject("PATCH", url, { name: "stripe-live" });
+ const renamed = await inject("PATCH", url, { type: "http", name: "stripe-live" });
expect(renamed.statusCode).toBe(200);
expect((await sealedPair()).equals(afterClear)).toBe(true);
});
@@ -583,13 +592,13 @@ describe("Agent Vault V1 Router", async () => {
const { service } = JSON.parse(created.payload) as { service: { id: string } };
const url = `/api/v1/agent-vault/access-bundles/${bundle.id}/services/${service.id}`;
- const emptyBasic = await inject("PATCH", url, { credential: { type: "basic" } });
+ const emptyBasic = await inject("PATCH", url, { type: "http", credential: { type: "basic" } });
expect(emptyBasic.statusCode).toBe(400);
- const noSecret = await inject("PATCH", url, { credential: { type: "basic", username: "bot" } });
+ const noSecret = await inject("PATCH", url, { type: "http", credential: { type: "basic", username: "bot" } });
expect(noSecret.statusCode).toBe(200);
- const bearerNoValue = await inject("PATCH", url, { credential: { type: "bearer" } });
+ const bearerNoValue = await inject("PATCH", url, { type: "http", credential: { type: "bearer" } });
expect(bearerNoValue.statusCode).toBe(400);
});
@@ -624,16 +633,16 @@ describe("Agent Vault V1 Router", async () => {
const url = `/api/v1/agent-vault/access-bundles/${bundle.id}/services/${service.id}`;
- const renamed = await inject("PATCH", url, { name: "github-read" });
+ const renamed = await inject("PATCH", url, { type: "http", name: "github-read" });
expect(JSON.parse(renamed.payload).service.allowedMethods).toEqual(["GET", "HEAD"]);
- const cleared = await inject("PATCH", url, { allowedMethods: null, allowedPathPrefixes: null });
+ const cleared = await inject("PATCH", url, { type: "http", allowedMethods: null, allowedPathPrefixes: null });
expect(cleared.statusCode).toBe(200);
expect(JSON.parse(cleared.payload).service.allowedMethods).toBeNull();
expect(JSON.parse(cleared.payload).service.allowedPathPrefixes).toBeNull();
- expect((await inject("PATCH", url, { allowedMethods: [] })).statusCode).toBe(422);
- expect((await inject("PATCH", url, { allowedPathPrefixes: [] })).statusCode).toBe(422);
+ expect((await inject("PATCH", url, { type: "http", allowedMethods: [] })).statusCode).toBe(422);
+ expect((await inject("PATCH", url, { type: "http", allowedPathPrefixes: [] })).statusCode).toBe(422);
});
test("a path prefix that would need normalising to judge is rejected", async () => {
@@ -726,6 +735,7 @@ describe("Agent Vault V1 Router", async () => {
const before = await sealed();
const renamed = await inject("PATCH", url, {
+ type: "http",
customHeaders: [{ id: customHeaderId, name: "X-Organization-Id" }]
});
expect(renamed.statusCode).toBe(200);
@@ -733,18 +743,23 @@ describe("Agent Vault V1 Router", async () => {
expect(JSON.parse(renamed.payload).service.customHeaders[0].name).toBe("X-Organization-Id");
expect((await sealed()).equals(before)).toBe(true);
- const byName = await inject("PATCH", url, { customHeaders: [{ name: "X-Organization-Id", prefix: "Token" }] });
+ const byName = await inject("PATCH", url, {
+ type: "http",
+ customHeaders: [{ name: "X-Organization-Id", prefix: "Token" }]
+ });
expect(byName.statusCode).toBe(200);
expect(JSON.parse(byName.payload).service.customHeaders[0].id).toBe(customHeaderId);
expect(JSON.parse(byName.payload).service.customHeaders[0].prefix).toBe("Token");
expect((await sealed()).equals(before)).toBe(true);
const newRowNoValue = await inject("PATCH", url, {
+ type: "http",
customHeaders: [{ name: "X-Organization-Id" }, { name: "X-New" }]
});
expect(newRowNoValue.statusCode).toBe(400);
const duplicateId = await inject("PATCH", url, {
+ type: "http",
customHeaders: [
{ id: customHeaderId, name: "X-A", value: "a" },
{ id: customHeaderId, name: "X-B", value: "b" }
@@ -752,7 +767,7 @@ describe("Agent Vault V1 Router", async () => {
});
expect(duplicateId.statusCode).toBe(400);
- const emptied = await inject("PATCH", url, { customHeaders: [] });
+ const emptied = await inject("PATCH", url, { type: "http", customHeaders: [] });
expect(emptied.statusCode).toBe(200);
expect(JSON.parse(emptied.payload).service.customHeaders).toHaveLength(0);
expect(await testDb("agent_vault_service_custom_headers").where({ serviceId: service.id })).toHaveLength(0);
@@ -782,16 +797,21 @@ describe("Agent Vault V1 Router", async () => {
const { service } = JSON.parse(created.payload) as { service: { id: string } };
const url = `/api/v1/agent-vault/access-bundles/${bundle.id}/services/${service.id}`;
- const headersOnly = await inject("PATCH", url, { customHeaders: [{ name: "X-Api-Key", value: "shadow" }] });
+ const headersOnly = await inject("PATCH", url, {
+ type: "http",
+ customHeaders: [{ name: "X-Api-Key", value: "shadow" }]
+ });
expect(headersOnly.statusCode).toBe(400);
const credentialOnly = await inject("PATCH", url, {
+ type: "http",
credential: { type: "bearer", headerName: "X-Org-Id" }
});
expect(credentialOnly.statusCode).toBe(400);
expect(JSON.parse(credentialOnly.payload).message).toContain("X-Org-Id");
const basicClash = await inject("PATCH", url, {
+ type: "http",
credential: { type: "basic", username: "u", password: "p" },
customHeaders: [{ name: "Authorization", value: "shadow" }]
});
@@ -862,6 +882,7 @@ describe("Agent Vault V1 Router", async () => {
expect(withPort.hostPattern).toBe("mcp.example.com:8443");
const moved = await inject("PATCH", `${servicesUrl(bundle.id)}/${service.id}`, {
+ type: "mcp",
serverUrl: "https://mcp.linear.dev/mcp"
});
expect(moved.statusCode).toBe(200);
@@ -905,6 +926,7 @@ describe("Agent Vault V1 Router", async () => {
const service = await createMcpService(bundle.id, "linear", "https://mcp.linear.app/mcp");
const patchedHostPattern = await inject("PATCH", `${servicesUrl(bundle.id)}/${service.id}`, {
+ type: "mcp",
hostPattern: "other.example.com"
});
expect(patchedHostPattern.statusCode).toBe(400);
@@ -915,12 +937,46 @@ describe("Agent Vault V1 Router", 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" });
+ const url = `${servicesUrl(bundle.id)}/${service.id}`;
+ const res = await inject("PATCH", url, { type: "http", name: "renamed" });
expect(res.statusCode).toBe(400);
- expect(messageOf(res)).toContain("A service's type can't be changed.");
+ expect(messageOf(res)).toContain("The service 'linear' is an MCP service, so send 'type': 'mcp'.");
+
+ expect((await inject("PATCH", url, { name: "renamed" })).statusCode).toBe(422);
+ expect((await inject("PATCH", url, { type: "mcp" })).statusCode).toBe(422);
const stored = await inject("GET", `/api/v1/agent-vault/access-bundles/${bundle.id}`);
expect(stored.payload).toContain('"type":"mcp"');
+ expect(stored.payload).not.toContain("renamed");
+ });
+
+ test("a service read back unchanged, minus its credential, is accepted as an update", async () => {
+ const bundle = await createAccessBundle("read-back");
+ const mcp = await createMcpService(bundle.id, "linear", "https://mcp.linear.app/mcp");
+ const http = await inject("POST", servicesUrl(bundle.id), {
+ type: "http",
+ name: "stripe",
+ hostPattern: "api.stripe.com",
+ credential: { type: "passthrough" }
+ });
+ expect(http.statusCode).toBe(200);
+
+ type TReadService = Record<string, unknown> & { id: string; credential: unknown };
+ const read = JSON.parse((await inject("GET", `/api/v1/agent-vault/access-bundles/${bundle.id}`)).payload) as {
+ accessBundle: { services: TReadService[] };
+ };
+ expect(read.accessBundle.services.map((service) => service.id).sort()).toEqual(
+ [mcp.id, (http.json().service as { id: string }).id].sort()
+ );
+
+ await Promise.all(
+ read.accessBundle.services.map(async ({ id, accessBundleId, credential, createdAt, updatedAt, ...fields }) => {
+ const res = await inject("PATCH", `${servicesUrl(bundle.id)}/${id}`, fields);
+ expect(res.statusCode).toBe(200);
+ const { service } = res.json() as { service: TReadService };
+ expect(service).toMatchObject(fields);
+ })
+ );
});
describe("credential refresh", async () => {
@@ -1026,6 +1082,55 @@ describe("Agent Vault V1 Router", async () => {
const storedConfig = async (id: string) =>
(await testDb("agent_vault_services").where({ id }).first()).credentialConfig as Record<string, unknown>;
+ test("a member reads a service's OAuth setup but not the admin's sign-in state", async () => {
+ const id = await oauthService("oauth-member-read", {
+ issuer: "https://mcp.linear.app",
+ expiresAt: "2030-01-01T00:00:00.000Z",
+ authorizedAt: "2026-01-01T00:00:00.000Z",
+ lastError: "Linear refused the refresh for [email protected]"
+ });
+ const { accessBundleId } = await testDb("agent_vault_services").where({ id }).first();
+ const member = await createUaIdentity(`av-oauth-member-${Date.now()}`);
+ type TBundleRead = { accessBundle: { services: { credential: Record<string, unknown> }[] } };
+
+ try {
+ expect(
+ (await inject("POST", "/api/v1/agent-vault/members", { machineIdentityIds: [member.id], role: "member" }))
+ .statusCode
+ ).toBe(200);
+ expect(
+ (
+ await inject("POST", `/api/v1/agent-vault/access-bundles/${accessBundleId}/members`, {
+ machineIdentityIds: [member.id]
+ })
+ ).statusCode
+ ).toBe(200);
+
+ const reached = await member.asIdentity("GET", `/api/v1/agent-vault/access-bundles/${accessBundleId}`);
+ expect(reached.statusCode).toBe(200);
+ const { credential } = (JSON.parse(reached.payload) as TBundleRead).accessBundle.services[0];
+ expect(credential).toEqual({
+ type: "oauth",
+ status: "connected",
+ issuer: "https://mcp.linear.app",
+ grantedScopes: ["read"],
+ requiredScopes: []
+ });
+ expect(reached.payload).not.toContain("[email protected]");
+
+ const asAdmin = JSON.parse(
+ (await inject("GET", `/api/v1/agent-vault/access-bundles/${accessBundleId}`)).payload
+ ) as TBundleRead;
+ expect(asAdmin.accessBundle.services[0].credential).toMatchObject({
+ expiresAt: "2030-01-01T00:00:00.000Z",
+ authorizedAt: "2026-01-01T00:00:00.000Z",
+ lastError: "Linear refused the refresh for [email protected]"
+ });
+ } finally {
+ await deleteUaIdentity(member.id);
+ }
+ });
+
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({
@@ -1482,6 +1587,7 @@ describe("Agent Vault V1 Router", async () => {
expect(JSON.parse(refused.payload).message).toContain(`'datadog' (access bundle '${bundle.name}')`);
const detached = await inject("PATCH", `${servicesUrl(bundle.id)}/${service.id}`, {
+ type: "http",
credential: { type: "bearer", value: "literal_value" }
});
expect(detached.statusCode).toBe(200);
@@ -1846,6 +1952,7 @@ describe("Agent Vault V1 Router", async () => {
// The password and the renamed header were not sent, so both keep what they had.
const patched = await inject("PATCH", url, {
+ type: "http",
credential: { type: "basic", username: "plain-user" },
customHeaders: [{ id: service.customHeaders[0].id, name: "X-Renamed" }]
});
@@ -1861,14 +1968,14 @@ describe("Agent Vault V1 Router", async () => {
expect(resolved.credential).toEqual({ type: "basic", username: "plain-user", password: "the-pass" });
expect(resolved.customHeaders).toEqual([{ name: "X-Renamed", prefix: "", value: "the-header" }]);
- const switched = await inject("PATCH", url, { credential: { type: "bearer", value: "literal" } });
+ const switched = await inject("PATCH", url, { type: "http", credential: { type: "bearer", value: "literal" } });
expect(switched.statusCode).toBe(200);
expect(referencesByField(JSON.parse(switched.payload).service.variableReferences)).toEqual([
"custom-header:HEADER"
]);
await expectReferencesMatchSealedText(bundle.id);
- const dropped = await inject("PATCH", url, { customHeaders: [] });
+ const dropped = await inject("PATCH", url, { type: "http", customHeaders: [] });
expect(dropped.statusCode).toBe(200);
expect(JSON.parse(dropped.payload).service.variableReferences).toEqual([]);
expect(await testDb("agent_vault_service_variable_references").where({ serviceId: service.id })).toHaveLength(0);
@@ -1901,6 +2008,7 @@ describe("Agent Vault V1 Router", async () => {
});
const patched = await inject("PATCH", `${servicesUrl(bundle.id)}/${service.id}`, {
+ type: "http",
credential: { type: "basic", username: "{{USER}}" }
});
expect(patched.statusCode).toBe(200);
@@ -1955,7 +2063,7 @@ describe("Agent Vault V1 Router", async () => {
const { rows } = await trx.raw("select pg_backend_pid() as pid");
await trx("agent_vault_access_bundles").where({ id: bundle.id }).forUpdate().first();
- const pending = inject("PATCH", url, { credential: { type: "basic", password: "{{PASS}}" } });
+ const pending = inject("PATCH", url, { type: "http", credential: { type: "basic", password: "{{PASS}}" } });
await waitUntilBlockedBy(rows[0].pid);
await trx("agent_vault_services")
@@ -1980,7 +2088,7 @@ describe("Agent Vault V1 Router", async () => {
expect(kept.encryptedCredential.equals(otherRow.encryptedCredential)).toBe(true);
await expectReferencesMatchSealedText(bundle.id);
- const retried = await inject("PATCH", url, { credential: { type: "basic", password: "{{PASS}}" } });
+ const retried = await inject("PATCH", url, { type: "http", credential: { type: "basic", password: "{{PASS}}" } });
expect(retried.statusCode).toBe(200);
await expectReferencesMatchSealedText(bundle.id);
@@ -2008,6 +2116,7 @@ describe("Agent Vault V1 Router", async () => {
await trx("agent_vault_access_bundles").where({ id: bundle.id }).forUpdate().first();
const pending = inject("PATCH", url, {
+ type: "http",
substitutions: [{ placeholder: "__ORG__", surfaces: ["header"], value: "org-42" }]
});
await waitUntilBlockedBy(rows[0].pid);
diff --git a/backend/src/db/sanitized-schema.yaml b/backend/src/db/sanitized-schema.yaml
index 93f7b7a0f2..b202d1f64a 100644
--- a/backend/src/db/sanitized-schema.yaml
+++ b/backend/src/db/sanitized-schema.yaml
@@ -78,6 +78,7 @@ tables:
- credentialType
- allowedMethods
- allowedPathPrefixes
+ - type
- createdAt
- updatedAt
diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts
index ce4d2dd32f..becaab43a7 100644
--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts
+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts
@@ -6,13 +6,12 @@ import {
AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE,
AGENT_VAULT_NO_CONTROL_CHARS_RE
} from "@app/ee/services/agent-vault/agent-vault-credential-schemas";
-import { AgentVaultCredentialType, AgentVaultServiceType } from "@app/ee/services/agent-vault/agent-vault-enums";
+import { AgentVaultCredentialType } from "@app/ee/services/agent-vault/agent-vault-enums";
import { parseHostPatterns } from "@app/ee/services/agent-vault/agent-vault-host-pattern-fns";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { AGENT_VAULT } from "@app/lib/api-docs";
import { ApiDocsTags } from "@app/lib/api-docs/constants";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
-import { openApiHidden } from "@app/server/lib/schemas";
import { emitAgentVaultTelemetry } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
@@ -21,23 +20,17 @@ import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
import { actorContext } from "./agent-vault-router-fns";
import {
AgentVaultActorRefSchema,
- AgentVaultAllowedMethodsSchema,
- AgentVaultAllowedPathPrefixesSchema,
AgentVaultCreatedMemberSchema,
AgentVaultCreateServiceBodySchema,
AgentVaultCredentialUpdateSchema,
- AgentVaultCustomHeadersUpdateSchema,
- AgentVaultHostPatternSchema,
agentVaultListQuery,
- AgentVaultMcpTransportSchema,
AgentVaultMemberIdsSchema,
AgentVaultMemberRevokeIdsSchema,
AgentVaultMemberSchema,
AgentVaultNameSchema,
AgentVaultProductMemberSchema,
- AgentVaultServerUrlSchema,
AgentVaultServiceSchema,
- AgentVaultSubstitutionsUpdateSchema
+ AgentVaultUpdateServiceBodySchema
} from "./agent-vault-schemas";
const AccessBundleDescriptionSchema = z
@@ -374,31 +367,14 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro
accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId),
serviceId: z.string().uuid().describe(AGENT_VAULT.SERVICE.serviceId)
}),
- body: z
- .object({
- // Accepted only so the refusal is a readable 400 rather than a silently dropped field.
- type: z.nativeEnum(AgentVaultServiceType).optional().describe(openApiHidden()),
- name: AgentVaultNameSchema.optional().describe(AGENT_VAULT.SERVICE.name),
- hostPattern: AgentVaultHostPatternSchema.optional(),
- serverUrl: AgentVaultServerUrlSchema.optional(),
- transport: AgentVaultMcpTransportSchema.optional(),
- allowedMethods: AgentVaultAllowedMethodsSchema.optional(),
- allowedPathPrefixes: AgentVaultAllowedPathPrefixesSchema.optional(),
- credential: AgentVaultCredentialUpdateSchema.optional(),
- customHeaders: AgentVaultCustomHeadersUpdateSchema.optional(),
- substitutions: AgentVaultSubstitutionsUpdateSchema.optional()
- })
- .refine(
- (body) => Object.values(body).some((value) => value !== undefined),
- "Provide at least one of 'name', 'hostPattern', 'serverUrl', 'transport', 'allowedMethods', 'allowedPathPrefixes', 'credential', 'customHeaders' or 'substitutions' to update"
- ),
+ body: AgentVaultUpdateServiceBodySchema,
response: {
200: z.object({ service: AgentVaultServiceSchema })
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
handler: async (req) => {
- const { service, accessBundleName } = await server.services.agentVaultAccessBundle.updateService({
+ const { service, accessBundleName, update } = await server.services.agentVaultAccessBundle.updateService({
projectId: req.internalAgentVaultProjectId,
ctx: actorContext(req),
accessBundleId: req.params.accessBundleId,
@@ -420,10 +396,10 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro
serviceId: service.id,
name: req.body.name,
serviceType: service.type,
- serverUrl: req.body.serverUrl,
- transport: req.body.transport,
+ serverUrl: update.serverUrl,
+ transport: update.transport,
// Derived from the server URL for an MCP service, so it is reported whenever that changed.
- hostPattern: req.body.hostPattern ?? (req.body.serverUrl ? service.hostPattern : undefined),
+ hostPattern: update.hostPattern ?? (update.serverUrl ? service.hostPattern : undefined),
credentialType: req.body.credential?.type,
headerName:
req.body.credential?.type === AgentVaultCredentialType.Bearer
@@ -441,21 +417,21 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro
isOauthAuthorized && service.credential.type === AgentVaultCredentialType.OAuth
? service.credential.grantedScopes
: undefined,
- allowedMethods: req.body.allowedMethods,
- allowedPathPrefixes: req.body.allowedPathPrefixes,
+ allowedMethods: update.allowedMethods,
+ allowedPathPrefixes: update.allowedPathPrefixes,
customHeaderNames: req.body.customHeaders?.map((header) => header.name),
// A row omitting a value keeps the stored secret, so sending one is what marks a rotation.
// Without this a rotation and a no-op save write the same row.
customHeadersReplaced: req.body.customHeaders
?.filter((header) => header.value !== undefined)
.map((header) => header.name),
- substitutionPlaceholders: req.body.substitutions?.map((substitution) => substitution.placeholder),
- substitutionsReplaced: req.body.substitutions
+ substitutionPlaceholders: update.substitutions?.map((substitution) => substitution.placeholder),
+ substitutionsReplaced: update.substitutions
?.filter((substitution) => substitution.value !== undefined)
.map((substitution) => substitution.placeholder),
credentialReplaced: isStoredSecretReplaced(req.body.credential),
variableKeys:
- req.body.credential || req.body.customHeaders || req.body.substitutions
+ req.body.credential || req.body.customHeaders || update.substitutions
? variableKeysOf(service)
: undefined
}
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 9934fc6baf..3bae277d1a 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
@@ -6,6 +6,7 @@ import {
MAX_CLIENT_SECRET_LENGTH
} from "@app/ee/services/agent-vault-oauth/agent-vault-oauth-client-fns";
import { OAUTH_VSCHAR_PATTERN } from "@app/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns";
+import { AgentVaultOauthRegistration } from "@app/ee/services/agent-vault-oauth/agent-vault-oauth-types";
import { AGENT_VAULT } from "@app/lib/api-docs";
import { ApiDocsTags } from "@app/lib/api-docs/constants";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
@@ -60,20 +61,18 @@ export const registerAgentVaultOauthRouter = async (server: FastifyZodProvider)
.pipe(printable(MAX_CLIENT_SECRET_LENGTH))
.refine(noVariableReference, VARIABLES_NOT_SUPPORTED_MESSAGE)
.optional()
- .describe(AGENT_VAULT.OAUTH.clientSecret)
+ .describe(AGENT_VAULT.OAUTH.clientSecret),
+ registration: z.literal(AgentVaultOauthRegistration.Dynamic).optional().describe(AGENT_VAULT.OAUTH.registration)
}),
response: {
200: z.object({
registrationRequired: z.boolean().describe(AGENT_VAULT.OAUTH.registrationRequired),
oauthAdvertised: z.boolean().describe(AGENT_VAULT.OAUTH.oauthAdvertised),
redirectUri: z.string().describe(AGENT_VAULT.OAUTH.redirectUri),
- registrationError: z.string().nullable().describe(AGENT_VAULT.OAUTH.registrationError),
authorization: z
.object({
id: z.string().uuid().describe(AGENT_VAULT.OAUTH.authorizationId),
- status: z.nativeEnum(AgentVaultOauthAuthorizationStatus).describe(AGENT_VAULT.OAUTH.status),
- authorizeUrl: z.string().describe(AGENT_VAULT.OAUTH.authorizeUrl),
- scopes: z.string().array().describe(AGENT_VAULT.OAUTH.scopes)
+ authorizeUrl: z.string().describe(AGENT_VAULT.OAUTH.authorizeUrl)
})
.nullable()
.describe(AGENT_VAULT.OAUTH.authorization)
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 e1c26a9a5c..c4c0e53735 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
@@ -103,47 +103,48 @@ export const AgentVaultCredentialInputSchema = credentialInputSchema({ mcp: fals
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
- .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)
- )
- .optional()
- .describe(AGENT_VAULT.SERVICE.updateValue)
- })
- .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)
- )
- .optional()
- .describe(AGENT_VAULT.SERVICE.updateUsername),
- password: acceptsVariableReferences(
- z.string().max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
- )
- .optional()
- .describe(AGENT_VAULT.SERVICE.updatePassword)
- })
- .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.updateAuthorizationId)
- })
- // 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);
+const credentialUpdateSchema = ({ mcp }: { mcp: boolean }) =>
+ 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)
+ )
+ .optional()
+ .describe(AGENT_VAULT.SERVICE.updateValue)
+ })
+ .describe(docsTitle("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)
+ )
+ .optional()
+ .describe(AGENT_VAULT.SERVICE.updateUsername),
+ password: acceptsVariableReferences(
+ z.string().max(8192).regex(AGENT_VAULT_NO_CONTROL_CHARS_RE, AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE)
+ )
+ .optional()
+ .describe(AGENT_VAULT.SERVICE.updatePassword)
+ })
+ .describe(docsTitle("Basic Auth", mcp)),
+ z.object({ type: z.literal(AgentVaultCredentialType.Passthrough) }).describe(docsTitle("Pass-through", mcp)),
+ z
+ .object({
+ type: z.literal(AgentVaultCredentialType.OAuth),
+ authorizationId: z.string().uuid().describe(AGENT_VAULT.SERVICE.updateAuthorizationId)
+ })
+ .describe(docsTitle("OAuth", true))
+ ])
+ .superRefine(basicHalvesAreNotBothEmpty);
+
+export const AgentVaultCredentialUpdateSchema = credentialUpdateSchema({ mcp: false });
+export const AgentVaultMcpCredentialUpdateSchema = credentialUpdateSchema({ mcp: true });
export const AgentVaultCredentialSummarySchema = z.discriminatedUnion("type", [
z
@@ -164,9 +165,9 @@ export const AgentVaultCredentialSummarySchema = z.discriminatedUnion("type", [
issuer: z.string().describe(AGENT_VAULT.SERVICE.oauthIssuer),
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),
- authorizedAt: z.string().nullable().describe(AGENT_VAULT.SERVICE.oauthAuthorizedAt),
- lastError: z.string().nullable().describe(AGENT_VAULT.SERVICE.oauthLastError)
+ expiresAt: z.string().nullable().optional().describe(AGENT_VAULT.SERVICE.oauthExpiresAt),
+ authorizedAt: z.string().nullable().optional().describe(AGENT_VAULT.SERVICE.oauthAuthorizedAt),
+ lastError: z.string().nullable().optional().describe(AGENT_VAULT.SERVICE.oauthLastError)
})
.describe(JSON.stringify({ title: "OAuth" }))
]);
@@ -242,6 +243,45 @@ export const AgentVaultCreateServiceBodySchema = z.discriminatedUnion("type", [
.describe(JSON.stringify({ title: "MCP service" }))
]);
+// Every field but `type` is optional, and `type` must match the stored one. Each option also takes the fields
+// GET returns for the other type (null, empty, or an MCP service's derived host pattern), so a client can send back
+// what it read; anything else in them is refused by name, as on create.
+export const AgentVaultUpdateServiceBodySchema = z
+ .discriminatedUnion("type", [
+ z
+ .object({
+ type: z.literal(AgentVaultServiceType.Http).describe(AGENT_VAULT.SERVICE.updateType),
+ name: AgentVaultNameSchema.optional().describe(AGENT_VAULT.SERVICE.name),
+ hostPattern: AgentVaultHostPatternSchema.optional(),
+ allowedMethods: AgentVaultAllowedMethodsSchema.optional(),
+ allowedPathPrefixes: AgentVaultAllowedPathPrefixesSchema.optional(),
+ credential: AgentVaultCredentialUpdateSchema.optional(),
+ customHeaders: AgentVaultCustomHeadersUpdateSchema.optional(),
+ substitutions: AgentVaultSubstitutionsUpdateSchema.optional(),
+ serverUrl: AgentVaultServerUrlSchema.nullable().optional().describe(openApiHidden()),
+ transport: AgentVaultMcpTransportSchema.nullable().optional().describe(openApiHidden())
+ })
+ .describe(JSON.stringify({ title: "HTTP service" })),
+ z
+ .object({
+ type: z.literal(AgentVaultServiceType.Mcp).describe(AGENT_VAULT.SERVICE.updateType),
+ name: AgentVaultNameSchema.optional().describe(AGENT_VAULT.SERVICE.name),
+ serverUrl: AgentVaultServerUrlSchema.optional(),
+ transport: AgentVaultMcpTransportSchema.optional(),
+ credential: AgentVaultMcpCredentialUpdateSchema.optional().describe(AGENT_VAULT.SERVICE.mcpCredential),
+ customHeaders: AgentVaultCustomHeadersUpdateSchema.optional(),
+ hostPattern: AgentVaultHostPatternSchema.optional().describe(openApiHidden()),
+ allowedMethods: AgentVaultAllowedMethodsSchema.optional().describe(openApiHidden()),
+ allowedPathPrefixes: AgentVaultAllowedPathPrefixesSchema.optional().describe(openApiHidden()),
+ substitutions: AgentVaultSubstitutionsUpdateSchema.optional().describe(openApiHidden())
+ })
+ .describe(JSON.stringify({ title: "MCP service" }))
+ ])
+ .refine(
+ ({ type, ...fields }) => Object.values(fields).some((value) => value !== undefined),
+ "Provide at least one field besides 'type' to update"
+ );
+
const variableReferenceBase = {
variableId: z.string().uuid().describe(AGENT_VAULT.VARIABLE.variableId),
key: z.string().describe(AGENT_VAULT.VARIABLE.key)
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 69194ebe7b..a47551ac65 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
@@ -53,6 +53,7 @@ import {
assertCredentialTypeSupported,
assertServiceFieldsSupported,
buildServiceConfig,
+ dropReadBackServiceFields,
getAgentVaultServiceType,
getServiceServerUrl,
resolveServiceHostPattern,
@@ -468,7 +469,8 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
accessBundleId: service.accessBundleId,
name: service.name,
type: service.type as AgentVaultServiceType,
- // Flat, like the create and update bodies, so a client can send back what it read. Null for an http service.
+ // Flat, like the create and update bodies, so a client can send back what it read (all but the credential, whose
+ // secret is never returned). Null for an http service.
serverUrl: config.serverUrl ?? null,
transport: config.transport ?? null,
hostPattern: service.hostPattern,
@@ -749,7 +751,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
ProjectPermissionSub.AgentVaultAccessBundles
);
// Variables are admin only, so a member's services leave variableReferences out. An empty list would claim
- // they use no variables.
+ // they use no variables. The OAuth sign-in state is the admin's account, so members don't get it either.
const canReadVariables = permission.can(
ProjectPermissionAgentVaultAccessBundleActions.Edit,
ProjectPermissionSub.AgentVaultAccessBundles
@@ -775,7 +777,16 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
substitutions.filter((substitution) => substitution.serviceId === service.id),
variableReferences.filter((reference) => reference.serviceId === service.id)
);
- return canReadVariables ? projected : { ...projected, variableReferences: undefined };
+ if (canReadVariables) return projected;
+ const { credential } = projected;
+ return {
+ ...projected,
+ variableReferences: undefined,
+ credential:
+ credential.type === AgentVaultCredentialType.OAuth
+ ? { ...credential, expiresAt: undefined, authorizedAt: undefined, lastError: undefined }
+ : credential
+ };
})
};
};
@@ -1088,14 +1099,14 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
serviceId,
type,
name,
- hostPattern: requestedHostPattern,
- serverUrl,
- transport,
credential,
- allowedMethods,
- allowedPathPrefixes,
customHeaders,
- substitutions,
+ hostPattern: sentHostPattern,
+ serverUrl: sentServerUrl,
+ transport: sentTransport,
+ allowedMethods: sentAllowedMethods,
+ allowedPathPrefixes: sentAllowedPathPrefixes,
+ substitutions: sentSubstitutions,
...rest
}: TUpdateServiceDTO) => {
const { bundle, permission } = await resolveReachableBundle({ ...rest, accessBundleId });
@@ -1108,12 +1119,27 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
const service = await agentVaultServiceDAL.findByIdInAccessBundle({ id: serviceId, accessBundleId: bundle.id });
if (!service) throw new NotFoundError({ message: `Service with ID '${serviceId}' not found` });
- if (type !== undefined) {
+ const serviceType = getAgentVaultServiceType(service.type);
+ if (type !== service.type) {
throw new BadRequestError({
- message: "A service's type can't be changed. Leave 'type' out, or create a new service of the other type."
+ message: `The service '${service.name}' is an ${serviceType.label} service, so send 'type': '${service.type}'. A service's type can't be changed; create a new service of the other type instead.`
});
}
- const serviceType = getAgentVaultServiceType(service.type);
+ const sentFields = dropReadBackServiceFields(
+ serviceType,
+ {
+ hostPattern: sentHostPattern,
+ serverUrl: sentServerUrl,
+ transport: sentTransport,
+ allowedMethods: sentAllowedMethods,
+ allowedPathPrefixes: sentAllowedPathPrefixes,
+ substitutions: sentSubstitutions
+ },
+ service.hostPattern
+ );
+ const { hostPattern: requestedHostPattern, allowedMethods, allowedPathPrefixes, substitutions } = sentFields;
+ const serverUrl = sentFields.serverUrl ?? undefined;
+ const transport = sentFields.transport ?? undefined;
assertServiceFieldsSupported(serviceType, {
hostPattern: requestedHostPattern,
allowedMethods,
@@ -1545,7 +1571,15 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
result.updatedSubstitutions,
result.variableReferences
),
- accessBundleName: bundle.name
+ accessBundleName: bundle.name,
+ update: {
+ hostPattern: requestedHostPattern,
+ serverUrl,
+ transport,
+ allowedMethods,
+ allowedPathPrefixes,
+ substitutions
+ }
};
};
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 2bcfdbd7d8..b2321acf0e 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
@@ -29,9 +29,10 @@ export type TAgentVaultOauthCredentialSummary = {
issuer: string;
grantedScopes: string[];
requiredScopes: string[];
- expiresAt: string | null;
- authorizedAt: string | null;
- lastError: string | null;
+ // Left out for members: they describe the admin's sign-in, not the service's setup.
+ expiresAt?: string | null;
+ authorizedAt?: string | null;
+ lastError?: string | null;
};
export type TAgentVaultCredentialSummary =
@@ -109,12 +110,13 @@ export type TCreateServiceDTO = TAgentVaultProjectScoped & {
export type TUpdateServiceDTO = TAgentVaultProjectScoped & {
accessBundleId: string;
serviceId: string;
- // Only so the refusal can be a readable 400: a service's type never changes.
- type?: AgentVaultServiceType;
+ // Must match the stored type, which never changes.
+ type: AgentVaultServiceType;
name?: string;
hostPattern?: string;
- serverUrl?: string;
- transport?: AgentVaultMcpTransport;
+ // Null only as an HTTP service's read-back value.
+ serverUrl?: string | null;
+ transport?: AgentVaultMcpTransport | null;
allowedMethods?: AgentVaultHttpMethod[] | null;
allowedPathPrefixes?: string[] | null;
credential?: TAgentVaultCredentialUpdate;
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 53ee435e0d..7a0139478c 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
@@ -1,5 +1,8 @@
import { describe, expect, test, vi } from "vitest";
+import { BadRequestError } from "@app/lib/errors";
+import { PRIVATE_ADDRESS_REFUSED_MESSAGE } from "@app/lib/validator";
+
import {
authorizationServerMetadataUrls,
checkIssuer,
@@ -508,6 +511,19 @@ describe("discovering an MCP server's authorization server", () => {
);
});
+ test("a server on a private network says so, since checking the URL or retrying won't help", async () => {
+ const { http } = stubHttp({ getThrows: true, json: {} });
+ const refused: TOauthHttpClient = {
+ ...http,
+ probe: async () => {
+ throw new BadRequestError({ message: PRIVATE_ADDRESS_REFUSED_MESSAGE });
+ }
+ };
+ await expect(discoverOauthServer(refused, "https://mcp.internal.example.com/mcp")).rejects.toThrow(
+ "Infisical can't reach 'mcp.internal.example.com' because it's on a private network. Use a bearer token for this service instead."
+ );
+ });
+
test("a server that answers without any OAuth signal is not advertised, but still gets guessed endpoints", async () => {
const { http } = stubHttp({ challenge: null, json: {} });
const discovery = await discoverOauthServer(http, "https://mcp.example.com/mcp");
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 c3a865afb7..f0b8597ea6 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
@@ -2,6 +2,7 @@ import RE2 from "re2";
import { BadRequestError } from "@app/lib/errors";
import { logger, sanitizeUrlForLog } from "@app/lib/logger";
+import { PRIVATE_ADDRESS_REFUSED_MESSAGE } from "@app/lib/validator";
import { TOauthHttpClient, TOauthHttpResponse } from "./agent-vault-oauth-http-fns";
import { AgentVaultOauthCompatibility } from "./agent-vault-oauth-types";
@@ -235,6 +236,7 @@ export const selectScopes = ({
const discover = async (http: TOauthHttpClient, serverUrl: string): Promise<TOauthDiscovery> => {
const compatibility = new Set<AgentVaultOauthCompatibility>();
let answered = false;
+ let isPrivateAddress = false;
// 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.
@@ -246,7 +248,8 @@ const discover = async (http: TOauthHttpClient, serverUrl: string): Promise<TOau
answered = true;
return parseBearerChallenge(response.wwwAuthenticate);
},
- () => {
+ (err: unknown) => {
+ isPrivateAddress = err instanceof BadRequestError && err.message === PRIVATE_ADDRESS_REFUSED_MESSAGE;
logger.info(`agentVaultOauth: MCP server probe failed [server=${describeServer(serverUrl)}]`);
return null;
}
@@ -269,7 +272,9 @@ const discover = async (http: TOauthHttpClient, serverUrl: string): Promise<TOau
if (!answered) {
throw new BadRequestError({
- message: `Couldn't reach '${describeServer(serverUrl)}'. Check the server URL and that the server is online.`
+ message: isPrivateAddress
+ ? `Infisical can't reach '${describeServer(serverUrl)}' because it's on a private network. Use a bearer token for this service instead.`
+ : `Couldn't reach '${describeServer(serverUrl)}'. Check the server URL and that the server is online.`
});
}
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 b11a3e7e7a..989e930c84 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
@@ -8,6 +8,7 @@ import {
ProjectPermissionSub
} from "@app/ee/services/permission/project-permission";
import { BadRequestError, ConflictError, NotFoundError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
import { ActorType } from "@app/services/auth/auth-type";
import {
@@ -349,6 +350,10 @@ const oauthConfig = (overrides: Partial<TAgentVaultOauthConfig> = {}): TAgentVau
...overrides
});
+// The start response carries only the authorize URL; what was asked for is on the stored record.
+const storedAuthorization = (env: ReturnType<typeof setup>, id: string) =>
+ JSON.parse(env.store.get(`agent-vault-oauth-authorization:${id}`)!) as TAgentVaultOauthAuthorization;
+
describe("starting an authorization", () => {
test("discovers, registers a client, and returns an authorize URL with PKCE S256, resource and state", async () => {
const env = setup();
@@ -363,8 +368,11 @@ describe("starting an authorization", () => {
expect(url.searchParams.get("resource")).toBe(SERVER_URL);
expect(url.searchParams.get("redirect_uri")).toBe(REDIRECT_URI);
expect(url.searchParams.get("state")!.startsWith(`${authorization!.id}.`)).toBe(true);
- expect(authorization!.scopes).toEqual(["read", "write"]);
- expect(authorization!.status).toBe(AgentVaultOauthAuthorizationStatus.Pending);
+ expect(url.searchParams.get("scope")).toBe("read write");
+ expect(storedAuthorization(env, authorization!.id)).toMatchObject({
+ requestedScopes: ["read", "write"],
+ status: AgentVaultOauthAuthorizationStatus.Pending
+ });
expect(env.registrations).toHaveLength(1);
// The PKCE verifier is sealed in Redis, never stored in plaintext.
@@ -373,6 +381,7 @@ describe("starting an authorization", () => {
});
test("a server without a registration endpoint asks for a client", async () => {
+ vi.mocked(logger.warn).mockClear();
const env = setup({
metadata: {
...LINEAR_JSON,
@@ -386,12 +395,13 @@ describe("starting an authorization", () => {
registrationRequired: true,
oauthAdvertised: true,
redirectUri: REDIRECT_URI,
- registrationError: null,
authorization: null
});
+ expect(logger.warn).not.toHaveBeenCalledWith(expect.stringContaining("client registration failed"));
});
- test("a registration endpoint that refuses asks for a client, with the reason naming the host only", async () => {
+ test("a registration endpoint that refuses asks for a client, and the reason is logged naming the host only", async () => {
+ vi.mocked(logger.warn).mockClear();
const env = setup();
env.onRegister(() => json(400, { error: "invalid_redirect_uri", error_description: "Redirect URI not allowed" }));
@@ -400,27 +410,25 @@ describe("starting an authorization", () => {
registrationRequired: true,
oauthAdvertised: true,
redirectUri: REDIRECT_URI,
- registrationError:
- "Couldn't set up OAuth for 'mcp.linear.app': its registration endpoint refused to register Infisical as a client (Redirect URI not allowed). Enter the client ID and secret of your own OAuth app instead.",
authorization: null
});
- expect(result.registrationError).not.toContain("/mcp");
+ expect(logger.warn).toHaveBeenCalledWith(
+ `agentVaultOauth: client registration failed [projectId=${PROJECT_ID}] [server=mcp.linear.app] [error=its registration endpoint refused to register Infisical as a client (Redirect URI not allowed).]`
+ );
});
- test("a registration endpoint that can't be reached says so without the error text", async () => {
+ test("a registration endpoint that can't be reached is logged without the error text", async () => {
+ vi.mocked(logger.warn).mockClear();
const env = setup();
env.onRegister(() => {
throw new Error("connect ECONNREFUSED https://mcp.linear.app/register?token=abc");
});
const result = await createAuthorization(env);
expect(result.registrationRequired).toBe(true);
- expect(result.registrationError).toBe(
- "Couldn't set up OAuth for 'mcp.linear.app': its registration endpoint couldn't be reached. Enter the client ID and secret of your own OAuth app instead."
+ expect(logger.warn).toHaveBeenCalledWith(
+ `agentVaultOauth: client registration failed [projectId=${PROJECT_ID}] [server=mcp.linear.app] [error=its registration endpoint couldn't be reached.]`
);
- });
-
- test("a successful start has no registration error", async () => {
- expect((await createAuthorization(setup())).registrationError).toBeNull();
+ expect(vi.mocked(logger.warn).mock.calls.flat().join()).not.toContain("ECONNREFUSED");
});
test("an admin-entered client is used as is, with no registration", async () => {
@@ -462,6 +470,36 @@ describe("starting an authorization", () => {
expect(clientIdOf(authorization!.authorizeUrl)).toBe("old-client");
});
+ test("switching back to automatic setup registers a fresh client instead of the one entered by hand", async () => {
+ const env = setup();
+ storeOauthService(env, { registration: AgentVaultOauthRegistration.Manual });
+ const { authorization } = await createAuthorization(env, {
+ serviceId: SERVICE_ID,
+ registration: AgentVaultOauthRegistration.Dynamic
+ });
+ expect(env.registrations).toHaveLength(1);
+ expect(clientIdOf(authorization!.authorizeUrl)).toBe("registered-client");
+ expect(storedAuthorization(env, authorization!.id).requestedScopes).toEqual(["admin"]);
+ });
+
+ test("switching back to automatic setup never falls back to the client entered by hand", async () => {
+ const env = setup();
+ env.onRegister(() => json(400, { error: "invalid_client_metadata" }));
+ storeOauthService(env, { registration: AgentVaultOauthRegistration.Manual });
+ const result = await createAuthorization(env, {
+ serviceId: SERVICE_ID,
+ registration: AgentVaultOauthRegistration.Dynamic
+ });
+ expect(result.registrationRequired).toBe(true);
+ expect(result.authorization).toBeNull();
+ });
+
+ test("a client ID together with registration 'dynamic' is refused", async () => {
+ await expect(
+ createAuthorization(setup(), { clientId: "my-app", registration: AgentVaultOauthRegistration.Dynamic })
+ ).rejects.toThrow(/not both/);
+ });
+
test("reauthorizing falls back to the stored client when a fresh one can't be registered", async () => {
const env = setup();
env.onRegister(() => json(400, { error: "invalid_client_metadata" }));
@@ -489,14 +527,14 @@ describe("starting an authorization", () => {
expect((await createAuthorization(env, { serviceId: SERVICE_ID })).registrationRequired).toBe(true);
const { authorization } = await createAuthorization(env, { serviceId: SERVICE_ID, clientId: "my-app" });
- expect(authorization!.scopes).toEqual(["read", "write"]);
+ expect(storedAuthorization(env, authorization!.id).requestedScopes).toEqual(["read", "write"]);
});
test("reauthorizing at the same issuer asks again for the scopes the service holds and still needs", async () => {
const env = setup();
storeOauthService(env, { requiredScopes: ["write"] });
const { authorization } = await createAuthorization(env, { serviceId: SERVICE_ID });
- expect(authorization!.scopes).toEqual(["admin", "write"]);
+ expect(storedAuthorization(env, authorization!.id).requestedScopes).toEqual(["admin", "write"]);
});
test("a client secret without a client ID is refused", async () => {
@@ -1044,6 +1082,7 @@ describe("refreshing a service's token", () => {
{ error: "invalid_client", status: 401, why: "the server dropped the registered client" },
{ error: "unauthorized_client", status: 400, why: "the client may no longer use this grant" },
{ error: "bad_refresh_token", status: 200, why: "GitHub, with a 200" },
+ { error: "incorrect_client_credentials", status: 200, why: "GitHub's invalid_client, with a 200" },
{ error: "invalid_refresh_token", status: 200, why: "Slack, with ok: false" },
{ error: "token_revoked", status: 200, why: "Slack" },
{ error: "token_expired", status: 200, why: "Slack" }
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 f363c98ede..821a9ef9b6 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
@@ -32,12 +32,7 @@ import {
registerOauthClient,
TOauthClient
} from "./agent-vault-oauth-client-fns";
-import {
- describeServer,
- discoverOauthServer,
- oauthSetupError,
- OFFLINE_ACCESS_SCOPE
-} from "./agent-vault-oauth-discovery-fns";
+import { describeServer, discoverOauthServer, OFFLINE_ACCESS_SCOPE } from "./agent-vault-oauth-discovery-fns";
import { agentVaultOauthHttpClient, TOauthHttpClient } from "./agent-vault-oauth-http-fns";
import {
buildAuthorizeUrl,
@@ -137,7 +132,7 @@ const assertAuthorizationServerUrl = (authorizedServerUrl: string, serviceServer
};
export const OAUTH_SERVER_URL_NEEDS_AUTHORIZATION_MESSAGE =
- "Changing an OAuth service's server URL needs a new authorization, since its tokens belong to the old server. Authorize the service for the new URL and send its 'authorizationId'.";
+ "This service uses OAuth, so its server URL can only be changed by reauthorizing it in the Infisical UI.";
const AGENT_VAULT_REAUTHORIZED_DURING_SAVE_MESSAGE =
"This service was reauthorized by another save while this one was in progress, and that newer connection was kept. Reload the service, then authorize again if you still want to replace it.";
@@ -281,7 +276,8 @@ export const agentVaultOauthServiceFactory = ({
serverUrl,
serviceId,
clientId,
- clientSecret
+ clientSecret,
+ registration: requestedRegistration
}: TCreateAuthorizationDTO) => {
const { permission, accessBundleIds } = await getAgentVaultReachability(
{ permissionService, membershipDAL },
@@ -304,6 +300,11 @@ export const agentVaultOauthServiceFactory = ({
if (clientSecret && !clientId) {
throw new BadRequestError({ message: "A client secret needs the client ID it belongs to." });
}
+ if (clientId && requestedRegistration === AgentVaultOauthRegistration.Dynamic) {
+ throw new BadRequestError({
+ message: "Send either the client ID of your own OAuth app or registration 'dynamic', not both."
+ });
+ }
let stored: { config: TAgentVaultOauthConfig; clientSecret?: string } | null = null;
if (serviceId) {
@@ -326,10 +327,15 @@ export const agentVaultOauthServiceFactory = ({
// A client is only ever used with the issuer it was registered at, and so are the scopes it was granted.
const sameIssuerStored = stored && stored.config.issuer === discovery.issuer ? stored : null;
+ // Switching a service from its own OAuth app back to automatic setup must not sign in with that app again.
+ const reusableStored =
+ requestedRegistration === AgentVaultOauthRegistration.Dynamic &&
+ sameIssuerStored?.config.registration === AgentVaultOauthRegistration.Manual
+ ? null
+ : sameIssuerStored;
let client: TOauthClient | null = null;
let registration: AgentVaultOauthRegistration | null = null;
- let registrationError: string | null = null;
if (clientId) {
client = manualOauthClient({
clientId,
@@ -338,7 +344,7 @@ export const agentVaultOauthServiceFactory = ({
});
registration = AgentVaultOauthRegistration.Manual;
} else if (
- sameIssuerStored?.config.registration !== AgentVaultOauthRegistration.Manual &&
+ reusableStored?.config.registration !== AgentVaultOauthRegistration.Manual &&
discovery.registrationEndpoint
) {
// Reauthorizing registers a fresh client rather than reusing the stored one, which the server may have dropped
@@ -360,27 +366,27 @@ export const agentVaultOauthServiceFactory = ({
if (!(error instanceof OauthRegistrationError)) throw error;
// A guessed /register that isn't there means the server has no registration, not that it is broken.
// Either way the fix is the same, an admin-entered client, so the caller is asked for one.
- registrationError = discovery.endpointsGuessed
- ? null
- : oauthSetupError(serverUrl, `${error.message} Enter the client ID and secret of your own OAuth app instead.`)
- .message;
+ if (!discovery.endpointsGuessed) {
+ logger.warn(
+ `agentVaultOauth: client registration failed [projectId=${projectId}] [server=${describeServer(serverUrl)}] [error=${error.message}]`
+ );
+ }
}
}
// The stored client is still worth trying when no fresh one could be registered.
- if (!client && sameIssuerStored) {
+ if (!client && reusableStored) {
client = {
- clientId: sameIssuerStored.config.clientId,
- clientSecret: sameIssuerStored.clientSecret,
- tokenEndpointAuthMethod: sameIssuerStored.config.tokenEndpointAuthMethod
+ clientId: reusableStored.config.clientId,
+ clientSecret: reusableStored.clientSecret,
+ tokenEndpointAuthMethod: reusableStored.config.tokenEndpointAuthMethod
};
- registration = sameIssuerStored.config.registration;
+ registration = reusableStored.config.registration;
}
if (!client || !registration) {
return {
registrationRequired: true,
oauthAdvertised: discovery.oauthAdvertised,
redirectUri: callbackUri,
- registrationError,
authorization: null
};
}
@@ -435,10 +441,8 @@ export const agentVaultOauthServiceFactory = ({
registrationRequired: false,
oauthAdvertised: discovery.oauthAdvertised,
redirectUri: callbackUri,
- registrationError: null,
authorization: {
id,
- status: record.status,
authorizeUrl: buildAuthorizeUrl({
authorizationEndpoint: record.authorizationEndpoint,
clientId: client.clientId,
@@ -447,8 +451,7 @@ export const agentVaultOauthServiceFactory = ({
state,
resource: record.resource,
scopes: requestedScopes
- }),
- scopes: requestedScopes
+ })
}
};
};
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 260d919f65..3fb9d72f29 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
@@ -19,6 +19,7 @@ import {
hashAccessToken,
isSameState,
MAX_EXPIRES_IN_SECONDS,
+ MAX_GRANTED_OAUTH_SCOPES,
normalizeProviderText,
parseExpiresIn,
parseGrantedScopes,
@@ -231,6 +232,23 @@ describe("token requests", () => {
});
});
+ test("a 5xx with no OAuth error reads as an outage, not a refusal", async () => {
+ const { http } = stubPosts([json(503, {})]);
+ expect(await requestToken({ http, ...tokenArgs })).toMatchObject({
+ ok: false,
+ errorCode: null,
+ message: "The login server 'auth.example.com' is having trouble right now (HTTP 503)."
+ });
+ });
+
+ test("a 5xx that names an OAuth error still quotes it", async () => {
+ const { http } = stubPosts([json(503, { error: "temporarily_unavailable" })]);
+ expect(await requestToken({ http, ...tokenArgs })).toMatchObject({
+ errorCode: "temporarily_unavailable",
+ message: "The login server 'auth.example.com' refused the token request: temporarily_unavailable"
+ });
+ });
+
test("an access token that can't go into a header is refused, and a bad refresh token is dropped", async () => {
const refused = stubPosts([json(200, { access_token: "a\r\nX-Evil: 1", token_type: "bearer" })]);
expect((await requestToken({ http: refused.http, ...tokenArgs })).ok).toBe(false);
@@ -366,6 +384,24 @@ describe("token requests", () => {
});
});
+ test("a grant of more scopes than a reauthorize can ask for is refused rather than stored", async () => {
+ const scopes = (count: number) => Array.from({ length: count }, (_, i) => `scope-${i}`).join(" ");
+ const { http } = stubPosts([
+ json(200, { access_token: "at-2", token_type: "Bearer", scope: scopes(MAX_GRANTED_OAUTH_SCOPES) }),
+ json(200, { access_token: "at-3", token_type: "Bearer", scope: scopes(MAX_GRANTED_OAUTH_SCOPES + 1) })
+ ]);
+
+ const atLimit = await requestToken({ http, ...tokenArgs });
+ expect(atLimit.ok && atLimit.tokens.scopes).toHaveLength(MAX_GRANTED_OAUTH_SCOPES);
+
+ const overLimit = await requestToken({ http, ...tokenArgs });
+ expect(overLimit).toMatchObject({
+ ok: false,
+ errorCode: null,
+ message: `The login server 'auth.example.com' granted ${MAX_GRANTED_OAUTH_SCOPES + 1} OAuth scopes, more than the ${MAX_GRANTED_OAUTH_SCOPES} Infisical supports.`
+ });
+ });
+
test("a non-bearer token is refused", async () => {
const { http } = stubPosts([json(200, { access_token: "a", token_type: "DPoP" })]);
const result = await requestToken({ http, ...tokenArgs });
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 06e355b474..a21543ebdc 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
@@ -10,6 +10,7 @@ import { PRIVATE_ADDRESS_REFUSED_MESSAGE } from "@app/lib/validator";
import { AgentVaultCredentialType, AgentVaultOauthStatus } from "../agent-vault/agent-vault-enums";
import {
describeServer,
+ MAX_OAUTH_SCOPES,
OFFLINE_ACCESS_SCOPE,
splitScopes,
stripTrailingSlash
@@ -166,6 +167,10 @@ export const parseGrantedScopes = (
return { scopes: splitScopes(scope), commaSeparated: false };
};
+// A reauthorize asks for at most the 100 discovered scopes plus 100 an agent reported, so no real server grants more.
+// Granted scopes go into the pending authorization in Redis and are asked for again on every reauthorize.
+export const MAX_GRANTED_OAUTH_SCOPES = 2 * MAX_OAUTH_SCOPES;
+
const PROOF_OF_POSSESSION_TOKEN_TYPES = new Set(["dpop", "mac", "pop"]);
export const parseTokenResponse = (
@@ -361,6 +366,15 @@ export const requestToken = async ({
// GitHub answers a failed exchange with a 200 and an `error` field.
if (response.status >= 200 && response.status < 300 && body && body.error === undefined) {
const tokens = parseTokenResponse(body, requestedScopes);
+ const grantedCount = tokens?.scopes?.length ?? 0;
+ if (grantedCount > MAX_GRANTED_OAUTH_SCOPES) {
+ return {
+ ok: false,
+ errorCode: null,
+ message: `The login server '${host}' granted ${grantedCount} OAuth scopes, more than the ${MAX_GRANTED_OAUTH_SCOPES} Infisical supports.`,
+ resourceDropped: !withResource
+ };
+ }
if (tokens) return { ok: true, tokens, resourceDropped: !withResource };
return {
ok: false,
@@ -372,16 +386,13 @@ export const requestToken = async ({
const errorCode = normalizeProviderText(body?.error, MAX_ERROR_CODE_LENGTH) || null;
const description = normalizeProviderText(body?.error_description, MAX_ERROR_DESCRIPTION_LENGTH, requestSecrets);
- const detail =
- description ||
- normalizeProviderText(errorCode, MAX_ERROR_CODE_LENGTH, requestSecrets) ||
- `HTTP ${response.status}`;
- return {
- ok: false,
- errorCode,
- message: `The login server '${host}' refused the token request: ${detail}`,
- resourceDropped: !withResource
- };
+ const detail = description || normalizeProviderText(errorCode, MAX_ERROR_CODE_LENGTH, requestSecrets);
+ // A bare 5xx is an outage, not a refusal, and the refresh keeps retrying it.
+ const message =
+ !detail && response.status >= 500
+ ? `The login server '${host}' is having trouble right now (HTTP ${response.status}).`
+ : `The login server '${host}' refused the token request: ${detail || `HTTP ${response.status}`}`;
+ return { ok: false, errorCode, message, resourceDropped: !withResource };
};
const result = await send(true);
@@ -392,12 +403,13 @@ export const requestToken = async ({
};
// Refresh errors that mean the login is gone for good, so retrying on every poll only repeats the refusal. The
-// client codes mean the server dropped the registered client (the MCP SDK starts over on invalid_client too); the
-// rest are providers' own names for a dead refresh token.
+// client codes mean the server dropped the registered client (the MCP SDK starts over on invalid_client too) or no
+// longer accepts its secret; the rest are providers' own names for a dead refresh token.
const DEAD_LOGIN_ERROR_CODES = new Set([
"invalid_grant",
"invalid_client",
"unauthorized_client",
+ "incorrect_client_credentials", // GitHub's invalid_client, sent with a 200
"bad_refresh_token", // GitHub
"invalid_refresh_token", // Slack
"token_revoked", // Slack
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 2527d92622..af10212ed9 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
@@ -115,6 +115,7 @@ export type TCreateAuthorizationDTO = {
serviceId?: string;
clientId?: string;
clientSecret?: string;
+ registration?: AgentVaultOauthRegistration.Dynamic;
};
export type TCompleteAuthorizationDTO = {
diff --git a/backend/src/ee/services/agent-vault/CLAUDE.md b/backend/src/ee/services/agent-vault/CLAUDE.md
index d374372847..56c94d93dc 100644
--- a/backend/src/ee/services/agent-vault/CLAUDE.md
+++ b/backend/src/ee/services/agent-vault/CLAUDE.md
@@ -315,10 +315,18 @@ code exchange and refresh; the proxy only ever receives the access token.
`expires_in` outside 1 second to 1 year counts as no expiry.
- **Token requests are never retried by the HTTP client.** Codes are one-use and refresh tokens can rotate. Only
the explicit `invalid_target` fallback retries them, inside the same request deadline.
+- **Known gap: scopes only grow.** Reauthorizing at the same issuer asks for every granted and required scope, so
+ a scope an agent's call reported (`missing-scopes`) sticks for good. There is no way to drop one requested scope
+ or reset to the server's defaults short of deleting the service; a follow-up should add both.
+- **Known gap: a Bearer token MCP service only gets the 401 rewrite.** The proxy turns its upstream 401 into a
+ 502 so the agent doesn't start its own sign-in, but a `403 insufficient_scope` reaches the agent unchanged, as
+ for HTTP services, and an MCP client may start its own OAuth on it (the TypeScript SDK's `onInsufficientScope`
+ defaults to `reauthorize`).
## Session logs
-Metadata only (method, host, path, status, decision), never bodies, headers or the query string. The agent is
+Metadata only (method, host, path, status, decision). Bodies, headers and the query string are never stored;
+for an MCP service the proxy reads only the JSON-RPC method and tool name of each call from the body. The agent is
hostile input: nothing it sends may erase or hide its own records, so the proxy logs every request it drops.
- **Bytes go proxy to the customer's bucket to the browser, and S3 is the index.** Infisical stores nothing per
@@ -393,3 +401,10 @@ hostile input: nothing it sends may erase or hide its own records, so the proxy
- The browser fetches session logs straight from S3, so `frontend/index.html`'s CSP `connect-src` must list
every host the SDK presigns: `*.s3.<region>`, the path-style `s3.<region>` used for dotted bucket names, and
both `s3-fips` forms. A region added to `AWSRegion` needs its hosts there too.
+
+## Follow-ups
+
+- **Docs screenshots predate the MCP UI.** Retake them once the Agent Vault UI redesign lands:
+ `access-bundle-services.png` (columns are now Type and Target, and it should show an MCP row),
+ `service-template-picker.png` (the service type sidebar, the MCP Servers section, **Custom HTTP API**), and
+ `session-logs-view.png` (the Request column, with a tool call and a `tools/list` row).
diff --git a/backend/src/ee/services/agent-vault/agent-vault-service-type-fns.test.ts b/backend/src/ee/services/agent-vault/agent-vault-service-type-fns.test.ts
index c0def8cf2c..2770ad3e99 100644
--- a/backend/src/ee/services/agent-vault/agent-vault-service-type-fns.test.ts
+++ b/backend/src/ee/services/agent-vault/agent-vault-service-type-fns.test.ts
@@ -8,6 +8,7 @@ import {
assertServiceFieldsSupported,
buildServiceConfig,
deriveMcpHostPattern,
+ dropReadBackServiceFields,
findUnsupportedServiceFields,
resolveServiceHostPattern
} from "./agent-vault-service-type-fns";
@@ -143,6 +144,40 @@ describe("fields a type does not take", () => {
});
});
+describe("fields read back unchanged on an update", () => {
+ test("the other type's empty values and an MCP service's derived host pattern count as not sent", () => {
+ expect(
+ dropReadBackServiceFields(
+ mcp,
+ { hostPattern: "mcp.linear.app", allowedMethods: null, allowedPathPrefixes: null, substitutions: [] },
+ "mcp.linear.app"
+ )
+ ).toEqual({
+ hostPattern: undefined,
+ allowedMethods: undefined,
+ allowedPathPrefixes: undefined,
+ substitutions: undefined
+ });
+ expect(dropReadBackServiceFields(http, { serverUrl: null, transport: null }, "api.example.com")).toEqual({
+ serverUrl: undefined,
+ transport: undefined
+ });
+ });
+
+ test("a real value for a field the type doesn't take is kept, so it is still refused", () => {
+ expect(
+ dropReadBackServiceFields(mcp, { hostPattern: "other.example.com", substitutions: [{}] }, "mcp.linear.app")
+ ).toEqual({ hostPattern: "other.example.com", substitutions: [{}] });
+ });
+
+ test("a field the type does take keeps its empty value, which clears it", () => {
+ expect(dropReadBackServiceFields(http, { allowedMethods: null, substitutions: [] }, "api.example.com")).toEqual({
+ allowedMethods: null,
+ substitutions: []
+ });
+ });
+});
+
describe("credential types", () => {
test("an MCP service takes a bearer token or OAuth", () => {
expect(() => assertCredentialTypeSupported(mcp, AgentVaultCredentialType.Bearer)).not.toThrow();
diff --git a/backend/src/ee/services/agent-vault/agent-vault-service-type-fns.ts b/backend/src/ee/services/agent-vault/agent-vault-service-type-fns.ts
index 5fed32657a..1d3f726e69 100644
--- a/backend/src/ee/services/agent-vault/agent-vault-service-type-fns.ts
+++ b/backend/src/ee/services/agent-vault/agent-vault-service-type-fns.ts
@@ -172,6 +172,26 @@ export const findUnsupportedServiceFields = (
return Object.keys(supported).filter((field) => !supported[field] && fields[field] !== undefined);
};
+// GET returns the fields a type doesn't use as null or empty, and an MCP service's host pattern derived from its
+// server URL. Sending those back unchanged is not an attempt to set them, so they are dropped before the
+// unsupported-field check refuses anything else.
+export const dropReadBackServiceFields = <T extends TAgentVaultServiceTypedFields>(
+ definition: TAgentVaultServiceTypeDefinition,
+ fields: T,
+ storedHostPattern: string
+): T => {
+ const isReadBack = (field: string) => {
+ const value = fields[field];
+ return (
+ value === null ||
+ (Array.isArray(value) && value.length === 0) ||
+ (field === "hostPattern" && value === storedHostPattern)
+ );
+ };
+ const dropped = findUnsupportedServiceFields(definition, fields).filter(isReadBack);
+ return { ...fields, ...Object.fromEntries(dropped.map((field) => [field, undefined])) };
+};
+
const quoteList = (fields: string[]) => {
const quoted = fields.map((field) => `'${field}'`);
return quoted.length > 1 ? `${quoted.slice(0, -1).join(", ")} or ${quoted[quoted.length - 1]}` : quoted[0];
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 80a2ca7cf0..6cc2c5cb98 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -4488,6 +4488,7 @@ export const AGENT_VAULT = {
serviceId: "The ID of the service.",
name: "The name of the service.",
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.",
+ updateType: "The service's type, `http` or `mcp`. Must match the type the service was created with.",
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.",
@@ -4505,9 +4506,10 @@ 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.",
- oauthAuthorizedAt: "When the connection was last authorized.",
- oauthLastError: "The last refresh failure, if any. Never contains a token.",
+ oauthExpiresAt:
+ "When the current access token expires, or null if the server didn't say. Not returned to Agent Vault members.",
+ oauthAuthorizedAt: "When the connection was last authorized. Not returned to Agent Vault members.",
+ oauthLastError: "The last refresh failure, if any. Never contains a token. Not returned to Agent Vault members.",
hostPattern:
"A comma-separated set of hosts this service covers, each optionally with a port (defaults to `443`). A leading `*.` wildcard matches exactly one label. Paths are not supported.",
headerName: "The header the credential is written to. Defaults to `Authorization`.",
@@ -4557,18 +4559,18 @@ export const AGENT_VAULT = {
accessBundleId: "The access bundle the service is in, or will be created in.",
serverUrl: "The MCP server's URL. Must match the server URL of the service the authorization is saved to.",
serviceId:
- "The MCP service being reauthorized. Its OAuth client is reused, and its granted and required scopes are requested.",
+ "The ID of the MCP service to reauthorize. Leave it out when connecting a new service. When set, the sign-in asks for the scopes the service already has, and can only be saved to that service.",
clientId:
"The client ID of your own OAuth app, for a server that doesn't support dynamic client registration. Register the app with the redirect URI `<your Infisical URL>/agent-vault/oauth/callback`.",
clientSecret: "The client secret of your own OAuth app, if it has one.",
+ registration:
+ "Send `dynamic` to register a new client with the server, even when the service being reauthorized uses your own OAuth app.",
registrationRequired:
- "True when the server can't register Infisical as a client by itself. Send `clientId` (and `clientSecret`) of your own OAuth app.",
+ "True when the server can't register Infisical as a client by itself, or refused to. Send `clientId` (and `clientSecret`) of your own OAuth app.",
redirectUri:
"The redirect URI Infisical sends to the authorization server. Register your own OAuth app with this exact value.",
oauthAdvertised:
"False when the MCP server answered but sent no OAuth challenge and serves no OAuth metadata. The server URL may be wrong; a server that does use OAuth can still be connected with your own client ID and secret.",
- registrationError:
- "Why the server's registration endpoint refused to register Infisical, when it did. Null when the server has no registration endpoint, or when registration wasn't needed.",
status: "`pending` until the authorization server redirects back, then `authorized` or `failed`.",
error: "Why the authorization failed, when it did.",
scopes: "The scopes requested, or once authorized, the scopes granted.",
diff --git a/docs/documentation/platform/agent-vault/guides/custom-agent.mdx b/docs/documentation/platform/agent-vault/guides/custom-agent.mdx
index f26d165d66..75882ac10e 100644
--- a/docs/documentation/platform/agent-vault/guides/custom-agent.mdx
+++ b/docs/documentation/platform/agent-vault/guides/custom-agent.mdx
@@ -33,7 +33,7 @@ First, create an [access bundle](/documentation/platform/agent-vault/access-bund
Select the access bundle you just created, then select **Add Service**.
</Step>
<Step>
- On the **Choose a template** panel, pick the template for the API, or select **Custom** and enter the API's host.
+ On the **Choose a template** panel, pick the template for the API, or select **Custom HTTP API** and enter the API's host.
</Step>
<Step>
On the **Credential** step, paste the real API key.
diff --git a/docs/documentation/platform/agent-vault/guides/hermes-gateway.mdx b/docs/documentation/platform/agent-vault/guides/hermes-gateway.mdx
index a5d16d57ea..c313e404ff 100644
--- a/docs/documentation/platform/agent-vault/guides/hermes-gateway.mdx
+++ b/docs/documentation/platform/agent-vault/guides/hermes-gateway.mdx
@@ -82,8 +82,8 @@ Most Hermes setups have three kinds of API keys:
| Kind | Example keys | Service to add in Step 2 |
| --- | --- | --- |
| Model provider (the LLM API Hermes sends its prompts to) | `OPENROUTER_API_KEY`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` | The provider's template, such as **OpenRouter**, **Anthropic**, or **OpenAI** |
-| Messaging platform (where you chat with Hermes) | `TELEGRAM_BOT_TOKEN` | A **Custom** service for `api.telegram.org` |
-| External APIs | `GITHUB_TOKEN` | The API's template, such as **GitHub** (or a **Custom** service if Infisical has no template for the API) |
+| Messaging platform (where you chat with Hermes) | `TELEGRAM_BOT_TOKEN` | A **Custom HTTP API** service for `api.telegram.org` |
+| External APIs | `GITHUB_TOKEN` | The API's template, such as **GitHub** (or a **Custom HTTP API** service if Infisical has no template for the API) |
<Note>
If your `~/.hermes/.env` contains any keys that hold non-sensitive information, those keys don't need services in Agent Vault. This includes settings like allowed user IDs and channel IDs.
@@ -107,7 +107,7 @@ First, create an [access bundle](/documentation/platform/agent-vault/access-bund
Select the access bundle you just created, then select **Add Service**.
</Step>
<Step>
- On the **Choose a template** panel, pick the template for the API, or select **Custom** and enter the API's host.
+ On the **Choose a template** panel, pick the template for the API, or select **Custom HTTP API** and enter the API's host.
</Step>
<Step>
On the **Credential** step, paste the real value of the API key from `~/.hermes/.env`.
diff --git a/docs/documentation/platform/agent-vault/guides/openclaw-gateway.mdx b/docs/documentation/platform/agent-vault/guides/openclaw-gateway.mdx
index 088fcb573f..c7c4af1620 100644
--- a/docs/documentation/platform/agent-vault/guides/openclaw-gateway.mdx
+++ b/docs/documentation/platform/agent-vault/guides/openclaw-gateway.mdx
@@ -76,8 +76,8 @@ Most OpenClaw setups have three kinds of API keys:
| Kind | Example keys | Service to add in Step 2 |
| --- | --- | --- |
| Model provider (the LLM API OpenClaw sends its prompts to) | `OPENROUTER_API_KEY`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` | The provider's template, such as **OpenRouter**, **Anthropic**, or **OpenAI** |
-| Messaging platform (where you chat with OpenClaw) | `channels.telegram.botToken` or `TELEGRAM_BOT_TOKEN` | A **Custom** service for `api.telegram.org` |
-| External APIs | `GITHUB_TOKEN` | The API's template, such as **GitHub** (or a **Custom** service if Infisical has no template for the API) |
+| Messaging platform (where you chat with OpenClaw) | `channels.telegram.botToken` or `TELEGRAM_BOT_TOKEN` | A **Custom HTTP API** service for `api.telegram.org` |
+| External APIs | `GITHUB_TOKEN` | The API's template, such as **GitHub** (or a **Custom HTTP API** service if Infisical has no template for the API) |
<Note>
Settings that hold non-sensitive information don't need services in Agent Vault. This includes settings like allowed user IDs and channel IDs.
@@ -101,7 +101,7 @@ First, create an [access bundle](/documentation/platform/agent-vault/access-bund
Select the access bundle you just created, then select **Add Service**.
</Step>
<Step>
- On the **Choose a template** panel, pick the template for the API, or select **Custom** and enter the API's host.
+ On the **Choose a template** panel, pick the template for the API, or select **Custom HTTP API** and enter the API's host.
</Step>
<Step>
On the **Credential** step, paste the real value of the API key.
diff --git a/docs/documentation/platform/agent-vault/how-it-works.mdx b/docs/documentation/platform/agent-vault/how-it-works.mdx
index f1b8cfc842..9d75ff06fd 100644
--- a/docs/documentation/platform/agent-vault/how-it-works.mdx
+++ b/docs/documentation/platform/agent-vault/how-it-works.mdx
@@ -117,8 +117,10 @@ Here's a breakdown of each primitive that Agent Vault relies on.
A service represents one external system that an agent can reach, such as GitHub's REST API or Linear's MCP server. Each service holds:
- **Target**: Where the system is, such as the host `api.github.com` or the server URL `https://mcp.linear.app/mcp`
-- **Credential**: The real token, username and password, or OAuth connection that the proxy attaches to the agent's requests, if the service uses one
-- **Options**: Settings that depend on the service's type, such as the HTTP methods and paths it allows, custom headers, and substitutions
+- **Credential**: The real token, username and password, or OAuth authorization that the proxy attaches to the agent's requests, if the service uses one
+- **Rules** (HTTP APIs): The HTTP methods and paths the service allows
+- **Custom headers**: Extra headers the proxy adds to each request
+- **Substitutions** (HTTP APIs): Placeholders the proxy replaces with real values
Agent Vault supports two types of service: [HTTP APIs](/documentation/platform/agent-vault/http-apis) and [MCP servers](/documentation/platform/agent-vault/mcp-servers).
diff --git a/docs/documentation/platform/agent-vault/http-apis.mdx b/docs/documentation/platform/agent-vault/http-apis.mdx
index 54f5d90737..0292f48bdc 100644
--- a/docs/documentation/platform/agent-vault/http-apis.mdx
+++ b/docs/documentation/platform/agent-vault/http-apis.mdx
@@ -18,7 +18,7 @@ To add an HTTP service to an access bundle:
In Agent Vault, go to **Access Bundles**. Select your access bundle, then select **Add Service**.
</Step>
<Step>
- On the **Choose a template** panel, pick the template for the API you want to reach, or select **Custom** to configure the host and header yourself.
+ On the **Choose a template** panel, pick the template for the API you want to reach, or select **Custom HTTP API** to configure the host and header yourself.
<Frame>
<img src="/images/platform/agent-vault/service-template-picker.png" alt="The Choose a template panel with Custom, OpenAI, Anthropic, Slack, GitHub, and Google Workspace" />
diff --git a/docs/documentation/platform/agent-vault/mcp-servers.mdx b/docs/documentation/platform/agent-vault/mcp-servers.mdx
index 4718e2c27c..e60ff8b2c1 100644
--- a/docs/documentation/platform/agent-vault/mcp-servers.mdx
+++ b/docs/documentation/platform/agent-vault/mcp-servers.mdx
@@ -21,7 +21,7 @@ You add the MCP server to your agent with its real URL and no credentials. When
In Agent Vault, go to **Access Bundles**. Select your access bundle, then select **Add Service**.
</Step>
<Step>
- On the **Choose a Template** panel, pick a template under **MCP Servers**, or select **Custom MCP Server** to connect any other remote MCP server.
+ On the **Choose a template** panel, pick a template under **MCP Servers**, or select **Custom MCP Server** to connect any other remote MCP server.
</Step>
<Step>
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**.
@@ -51,17 +51,17 @@ With OAuth, you sign in to the provider once from Infisical. Infisical stores th
<Steps>
<Step>
- Under **Credential Type**, select **OAuth**, then select the button that names your server, such as **Authorize with mcp.linear.app**.
+ Under **Credential Type**, select **OAuth**, then select **Authorize**.
<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.
+ Some servers, such as GitHub's, don't let Infisical register itself as an OAuth client. For these servers, Infisical 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** that Infisical shows. Then enter the app's **Client ID** and **Client Secret** (leave **Client Secret** empty for a public client), and authorize again.
</Note>
</Step>
<Step>
In the pop-up window, sign in to the provider and approve access.
</Step>
<Step>
- When the card shows **Authorized** and the scopes the provider granted, select **Continue**. **Continue** stays disabled until the authorization succeeds.
+ When Infisical shows **Authorized** and the scopes the provider granted, select **Continue**. **Continue** stays disabled until the authorization succeeds.
</Step>
</Steps>
@@ -108,11 +108,14 @@ Infisical won't save a custom header with the same name as the credential's head
If the service uses the SSE transport, use `--transport sse` instead.
</Tab>
<Tab title="Codex">
- ```bash
- codex mcp add linear --url https://mcp.linear.app/mcp
+ In `~/.codex/config.toml`, add the server by its URL:
+
+ ```toml
+ [mcp_servers.linear]
+ url = "https://mcp.linear.app/mcp"
```
- Don't run `codex mcp login` for the server.
+ Don't use `codex mcp add`, which starts the server's OAuth sign-in from the agent, and don't run `codex mcp login` for the server.
</Tab>
<Tab title="OpenCode">
In `opencode.json`, add the server as a remote MCP server with OAuth turned off:
@@ -156,15 +159,11 @@ Infisical won't save a custom header with the same name as the credential's head
<AccordionGroup>
<Accordion title="The agent gets a 502 response from the MCP server">
- If the server rejects an OAuth service's token, the proxy gets a fresh token from Infisical and sends the request again. If the server rejects the request again, or asks for scopes the authorization lacks, the proxy returns this `502` response to the agent:
-
- ```json
- {"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 **Missing 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.
+ If the server rejects an OAuth service's token, the proxy gets a fresh token from Infisical and sends the request again. If that doesn't work, or if the server rejects a Bearer token, the proxy returns a `502` response to the agent. Its message says what to do:
- 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.
+ - **The service needs to be reauthorized:** The provider no longer accepts the service's login, or the server asked for scopes the authorization lacks. The access bundle's **Services** table shows **Needs Reauthorization** or **Missing Scopes** for 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**.
+ - **Try again in a moment:** The proxy couldn't get a valid token from Infisical this time. Try the tool call again.
+ - **The service's credential was rejected:** The server rejected the service's Bearer token. Edit the service and paste a new token.
</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:
@@ -173,10 +172,9 @@ Infisical won't save a custom header with the same name as the credential's head
- `SITE_URL` uses `https://` (providers such as Linear refuse a redirect URI on plain `http://` unless the host is `localhost`)
</Accordion>
<Accordion title="The agent asks you to sign in to the MCP server">
- The request reached the server without a credential, or with a Bearer token the server rejected. Check that:
+ The request reached the server without a credential. Check that:
- The agent runs through `infisical agent-vault run` with a session for the access bundle
- The server URL in the agent has the same host as the service's **Server URL**
- - The service's Bearer token is still valid (if it isn't, edit the service and paste a new one)
</Accordion>
</AccordionGroup>
diff --git a/docs/documentation/platform/agent-vault/session-logs.mdx b/docs/documentation/platform/agent-vault/session-logs.mdx
index e998ed379e..9253aebafd 100644
--- a/docs/documentation/platform/agent-vault/session-logs.mdx
+++ b/docs/documentation/platform/agent-vault/session-logs.mdx
@@ -259,9 +259,7 @@ If a request matched an MCP service, its row shows an **MCP** badge and the call
The proxy never records a tool's arguments or results.
-If the agent sent several calls in one request, the row shows the first call followed by `+N more`, and the tooltip on `+N more` lists the other calls. The proxy records up to 32 calls per request. If a request held more, the row shows `N+ more` instead.
-
-If the proxy can't read the calls, the row shows the request path. This happens if the request body is larger than 1 MB, compressed, or not valid JSON.
+If the agent sent several calls in one request, the row shows the first one. If the proxy can't read the calls, such as from a compressed body, the row shows the request path.
## Managing session logs
diff --git a/docs/snippets/agent-vault/slots/ServiceTemplatePick.mdx b/docs/snippets/agent-vault/slots/ServiceTemplatePick.mdx
index c90f22488c..a53f81f030 100644
--- a/docs/snippets/agent-vault/slots/ServiceTemplatePick.mdx
+++ b/docs/snippets/agent-vault/slots/ServiceTemplatePick.mdx
@@ -21,7 +21,7 @@ import { AgentVaultBranch } from "/snippets/AgentVaultQuickstartConfigurator.jsx
</AgentVaultBranch>
<AgentVaultBranch service="custom">
- Select **Custom**. You'll set the host, header name, and prefix yourself on the next step.
+ Select **Custom HTTP API**. You'll set the host, header name, and prefix yourself on the next step.
</AgentVaultBranch>
<AgentVaultBranch service="gemini">
diff --git a/docs/snippets/agent-vault/slots/ServiceTemplatePickNote.mdx b/docs/snippets/agent-vault/slots/ServiceTemplatePickNote.mdx
index 0f07cff47c..dda2dbf392 100644
--- a/docs/snippets/agent-vault/slots/ServiceTemplatePickNote.mdx
+++ b/docs/snippets/agent-vault/slots/ServiceTemplatePickNote.mdx
@@ -2,6 +2,6 @@ import { AgentVaultBranch } from "/snippets/AgentVaultQuickstartConfigurator.jsx
<AgentVaultBranch service="none">
<Note>
- If the API you want to access isn't on the template list, pick **Custom** and set the host, header name, and prefix yourself. For more information, check out the [HTTP APIs](/documentation/platform/agent-vault/http-apis) documentation.
+ If the API you want to access isn't on the template list, pick **Custom HTTP API** and set the host, header name, and prefix yourself. For more information, check out the [HTTP APIs](/documentation/platform/agent-vault/http-apis) documentation.
</Note>
</AgentVaultBranch>
diff --git a/frontend/src/components/agent-vault/ServiceTemplateSelect.tsx b/frontend/src/components/agent-vault/ServiceTemplateSelect.tsx
index a8ac277d5d..c8081b2a81 100644
--- a/frontend/src/components/agent-vault/ServiceTemplateSelect.tsx
+++ b/frontend/src/components/agent-vault/ServiceTemplateSelect.tsx
@@ -3,11 +3,13 @@ import { GlobeIcon, PlusIcon, SearchIcon } from "lucide-react";
import { twMerge } from "tailwind-merge";
import {
- Button,
CardTitle,
InputGroup,
InputGroupAddon,
- InputGroupInput
+ InputGroupInput,
+ Tabs,
+ TabsList,
+ TabsTrigger
} from "@app/components/v3";
import { ProviderIcon } from "@app/components/v3/platform/ProviderIcon";
import {
@@ -30,19 +32,15 @@ const MCP_SECTION_DESCRIPTION =
const HTTP_SECTION_DESCRIPTION =
"Web APIs your agent calls directly. The proxy attaches the credential to requests for their hosts.";
-// Each count includes the type's Custom card, so it matches the cards the filter shows.
-const TYPE_FILTERS: { value: TypeFilter; label: string; count: number }[] = [
- {
- value: TypeFilter.All,
- label: "All Types",
- count: AGENT_VAULT_TEMPLATES.length + AGENT_VAULT_MCP_TEMPLATES.length + 2
- },
- { value: TypeFilter.Http, label: "HTTP APIs", count: AGENT_VAULT_TEMPLATES.length + 1 },
- { value: TypeFilter.Mcp, label: "MCP Servers", count: AGENT_VAULT_MCP_TEMPLATES.length + 1 }
+const TYPE_FILTERS: { value: TypeFilter; label: string }[] = [
+ { value: TypeFilter.All, label: "All Types" },
+ { value: TypeFilter.Mcp, label: "MCP Servers" },
+ { value: TypeFilter.Http, label: "HTTP APIs" }
];
+// MCP cards sit under the "MCP Servers" heading, so a tag would only repeat it.
const templateTag = (template: AgentVaultTemplate) =>
- template.serviceType === AgentVaultServiceType.Mcp ? "MCP Server" : template.category;
+ template.serviceType === AgentVaultServiceType.Mcp ? undefined : template.category;
const SelectableCard = ({
media,
@@ -161,16 +159,15 @@ export const ServiceTemplateSelect = ({ onSelect }: Props) => {
const term = search.trim().toLowerCase();
if (!term) return null;
- const candidates: AgentVaultTemplate[] = [
- ...(showsMcp ? AGENT_VAULT_MCP_TEMPLATES : []),
- ...(showsHttp ? AGENT_VAULT_TEMPLATES : [])
- ];
- return candidates.filter((template) =>
- [template.name, templateTag(template), template.key, ...(template.aliases ?? [])].some(
+ const matches = (template: AgentVaultTemplate) =>
+ [template.name, template.key, templateTag(template) ?? "", ...(template.aliases ?? [])].some(
(value) => value.toLowerCase().includes(term)
- )
- );
- }, [search, showsHttp, showsMcp]);
+ );
+ return {
+ mcp: AGENT_VAULT_MCP_TEMPLATES.filter(matches),
+ http: AGENT_VAULT_TEMPLATES.filter(matches)
+ };
+ }, [search]);
const popular = AGENT_VAULT_TEMPLATES.filter((template) =>
POPULAR_AGENT_VAULT_TEMPLATES.includes(template.key)
@@ -180,7 +177,7 @@ export const ServiceTemplateSelect = ({ onSelect }: Props) => {
const customHttpCard = (
<CustomCard
- name="Custom"
+ name="Custom HTTP API"
description="Configure the hosts yourself."
onSelect={() => onSelect(null, AgentVaultServiceType.Http)}
/>
@@ -193,6 +190,41 @@ export const ServiceTemplateSelect = ({ onSelect }: Props) => {
/>
);
+ // Each section keeps its custom card even when nothing of its type matches, so a custom service is always one
+ // click away.
+ const renderSearch = ({
+ mcp,
+ http
+ }: {
+ mcp: AgentVaultTemplate[];
+ http: AgentVaultTemplate[];
+ }) => (
+ <>
+ {showsMcp && (
+ <div>
+ <SectionHeader title="MCP Servers" description={MCP_SECTION_DESCRIPTION} />
+ <Grid>
+ {customMcpCard}
+ {mcp.map((template) => (
+ <TemplateCard key={template.key} template={template} onSelect={select} />
+ ))}
+ </Grid>
+ </div>
+ )}
+ {showsHttp && (
+ <div>
+ <SectionHeader title="HTTP APIs" description={HTTP_SECTION_DESCRIPTION} />
+ <Grid>
+ {customHttpCard}
+ {http.map((template) => (
+ <TemplateCard key={template.key} template={template} onSelect={select} />
+ ))}
+ </Grid>
+ </div>
+ )}
+ </>
+ );
+
const renderBrowse = () => (
<>
{showsMcp && (
@@ -241,29 +273,21 @@ export const ServiceTemplateSelect = ({ onSelect }: Props) => {
return (
<div className="flex min-h-0 flex-1">
- <aside className="flex w-60 shrink-0 flex-col border-r border-border px-5 py-6">
- <p className="mb-3 text-[11px] font-medium tracking-wider text-muted uppercase">
- Service Types
- </p>
- <div role="group" aria-label="Service types" className="flex flex-col gap-0.5">
- {TYPE_FILTERS.map((filter) => {
- const isActive = filter.value === typeFilter;
- return (
- <Button
- key={filter.value}
- type="button"
- variant={isActive ? "outline" : "ghost"}
- isFullWidth
- aria-pressed={isActive}
- onClick={() => setTypeFilter(filter.value)}
- className="justify-between"
- >
+ <aside className="flex w-54 shrink-0 flex-col border-r border-border px-5 py-6">
+ <SectionLabel>Service Types</SectionLabel>
+ <Tabs
+ orientation="vertical"
+ value={typeFilter}
+ onValueChange={(value) => setTypeFilter(value as TypeFilter)}
+ >
+ <TabsList variant="av" aria-label="Service types">
+ {TYPE_FILTERS.map((filter) => (
+ <TabsTrigger key={filter.value} value={filter.value}>
{filter.label}
- <span className="text-xs text-muted tabular-nums">{filter.count}</span>
- </Button>
- );
- })}
- </div>
+ </TabsTrigger>
+ ))}
+ </TabsList>
+ </Tabs>
</aside>
<div className="flex min-w-0 flex-1 flex-col gap-6 overflow-y-auto p-6">
@@ -279,17 +303,7 @@ export const ServiceTemplateSelect = ({ onSelect }: Props) => {
/>
</InputGroup>
- {filtered ? (
- <Grid>
- {showsMcp && customMcpCard}
- {showsHttp && customHttpCard}
- {filtered.map((template) => (
- <TemplateCard key={template.key} template={template} onSelect={select} />
- ))}
- </Grid>
- ) : (
- renderBrowse()
- )}
+ {filtered ? renderSearch(filtered) : renderBrowse()}
</div>
</div>
);
diff --git a/frontend/src/components/agent-vault/service-sheet/OAuthAuthorizeCard.tsx b/frontend/src/components/agent-vault/service-sheet/OAuthAuthorizeCard.tsx
index 9b38c3b447..7f8f959da5 100644
--- a/frontend/src/components/agent-vault/service-sheet/OAuthAuthorizeCard.tsx
+++ b/frontend/src/components/agent-vault/service-sheet/OAuthAuthorizeCard.tsx
@@ -106,7 +106,7 @@ const ScopeValues = ({ scopes, className }: { scopes: string[]; className?: stri
type="button"
variant="link"
size="sm"
- className="ml-1.5 align-baseline text-xs text-muted hover:text-foreground"
+ className="ml-1.5 align-baseline text-xs"
onClick={() => setIsExpanded(true)}
>
+{hidden} more
@@ -142,6 +142,7 @@ export const OAuthAuthorizeCard = ({ accessBundleId, service, onSignInChange }:
setValue,
setError,
clearErrors,
+ getValues,
formState: { errors }
} = useFormContext<TServiceForm>();
const [
@@ -167,7 +168,11 @@ export const OAuthAuthorizeCard = ({ accessBundleId, service, onSignInChange }:
const clientIdInputId = useId();
const clientSecretInputId = useId();
const redirectUriInputId = useId();
- const [isUsingOwnApp, setIsUsingOwnApp] = useState(false);
+ // The client fields keep their values across remounts (Back, or Bearer then OAuth), and the schema checks them.
+ const [isUsingOwnApp, setIsUsingOwnApp] = useState(() =>
+ Boolean(getValues("oauthClientId") || getValues("oauthClientSecret"))
+ );
+ const [isAutomaticSetupChosen, setIsAutomaticSetupChosen] = useState(false);
const trimmedUrl = serverUrl.trim();
const host = hostOf(trimmedUrl);
@@ -207,6 +212,7 @@ export const OAuthAuthorizeCard = ({ accessBundleId, service, onSignInChange }:
const switchToAutomaticSetup = () => {
setIsUsingOwnApp(false);
+ setIsAutomaticSetupChosen(true);
setValue("oauthClientId", "");
setValue("oauthClientSecret", "");
};
@@ -235,7 +241,11 @@ export const OAuthAuthorizeCard = ({ accessBundleId, service, onSignInChange }:
accessBundleId,
serverUrl: trimmedUrl,
...(stored && service ? { serviceId: service.id } : {}),
- ...(wantsOwnApp ? { clientId: clientId.trim(), clientSecret: clientSecret || undefined } : {})
+ ...(wantsOwnApp
+ ? { clientId: clientId.trim(), clientSecret: clientSecret || undefined }
+ : {}),
+ // Without it, reauthorizing a service that uses its own OAuth app signs in with that app again.
+ ...(!wantsOwnApp && isAutomaticSetupChosen ? { registration: "dynamic" as const } : {})
});
};
@@ -247,7 +257,7 @@ export const OAuthAuthorizeCard = ({ accessBundleId, service, onSignInChange }:
state.status === "failed" ||
(stored && stored.status !== AgentVaultOauthStatus.Connected && !isNewlyAuthorized);
- let authorizeLabel = `Authorize with ${host}`;
+ let authorizeLabel = "Authorize";
if (state.status === "failed") authorizeLabel = "Try Again";
else if (hasAuthorization) authorizeLabel = "Reauthorize";
@@ -404,9 +414,7 @@ export const OAuthAuthorizeCard = ({ accessBundleId, service, onSignInChange }:
/>
</InputGroupAddon>
</InputGroup>
- <FieldDescription>
- Add this as a redirect URI in your OAuth app on {host}.
- </FieldDescription>
+ <FieldDescription>Add this as a redirect URI in your OAuth app.</FieldDescription>
</FieldContent>
</Field>
<div className="flex flex-col gap-4 md:flex-row md:gap-3">
@@ -449,7 +457,6 @@ export const OAuthAuthorizeCard = ({ accessBundleId, service, onSignInChange }:
type="button"
variant="link"
size="sm"
- className="text-muted hover:text-foreground"
onClick={isUsingOwnApp ? switchToAutomaticSetup : () => setIsUsingOwnApp(true)}
>
{isUsingOwnApp ? "Use automatic setup" : "Use your own OAuth app"}
@@ -464,7 +471,6 @@ export const OAuthAuthorizeCard = ({ accessBundleId, service, onSignInChange }:
type="button"
variant="link"
size="sm"
- className="text-muted hover:text-foreground"
onClick={() => {
setValue("oauthAuthorizationRejection", "");
clearErrors("oauthAuthorizationId");
diff --git a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx
index 58a161e6d5..12dc1dc13e 100644
--- a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx
+++ b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx
@@ -686,7 +686,7 @@ export const ServiceSheet = ({
await goNext();
};
- const customName = isMcp ? "Custom MCP Server" : "Custom";
+ const customName = isMcp ? "Custom MCP Server" : "Custom HTTP API";
const stepDescription = (meta: (typeof SERVICE_STEPS)[number]) => {
if (meta.step === ServiceStep.Template) return template?.name ?? customName;
diff --git a/frontend/src/components/agent-vault/service-sheet/serviceRequest.test.ts b/frontend/src/components/agent-vault/service-sheet/serviceRequest.test.ts
index 71012bd120..2669c1fb05 100644
--- a/frontend/src/components/agent-vault/service-sheet/serviceRequest.test.ts
+++ b/frontend/src/components/agent-vault/service-sheet/serviceRequest.test.ts
@@ -174,6 +174,7 @@ describe("buildUpdateServiceRequest", () => {
).toEqual({
accessBundleId: "bundle-1",
serviceId: "service-1",
+ type: AgentVaultServiceType.Http,
name: "stripe",
hostPattern: "api.stripe.com",
allowedMethods: null,
@@ -218,6 +219,7 @@ describe("buildUpdateServiceRequest", () => {
expect(buildUpdateServiceRequest("bundle-1", "service-1", mcpForm())).toEqual({
accessBundleId: "bundle-1",
serviceId: "service-1",
+ type: AgentVaultServiceType.Mcp,
name: "linear-mcp",
serverUrl: SERVER_URL,
transport: AgentVaultMcpTransport.StreamableHttp,
diff --git a/frontend/src/components/agent-vault/service-sheet/serviceRequest.ts b/frontend/src/components/agent-vault/service-sheet/serviceRequest.ts
index 9dfff31e9c..95affd0c6c 100644
--- a/frontend/src/components/agent-vault/service-sheet/serviceRequest.ts
+++ b/frontend/src/components/agent-vault/service-sheet/serviceRequest.ts
@@ -135,12 +135,14 @@ export const buildUpdateServiceRequest = (
? {
accessBundleId,
serviceId,
+ type: AgentVaultServiceType.Mcp,
...buildMcpFields(data),
...withCredential(buildMcpCredentialPatch(data))
}
: {
accessBundleId,
serviceId,
+ type: AgentVaultServiceType.Http,
...buildHttpFields(data),
credential: buildHttpCredentialPatch(data)
};
diff --git a/frontend/src/hooks/api/agentVault/mutations.tsx b/frontend/src/hooks/api/agentVault/mutations.tsx
index b5a6ff2051..26e7545014 100644
--- a/frontend/src/hooks/api/agentVault/mutations.tsx
+++ b/frontend/src/hooks/api/agentVault/mutations.tsx
@@ -98,7 +98,7 @@ export const useDeleteAgentVaultAccessBundle = () => {
export const SERVICE_SAVE_HANDLED_ERROR_CODES: string[] = [
ApiErrorTypes.BadRequestError,
ApiErrorTypes.ConflictError,
- "NotFound"
+ ApiErrorTypes.NotFoundError
];
export const useCreateAgentVaultService = () => {
@@ -479,7 +479,7 @@ export const useCreateAgentVaultOauthAuthorization = () =>
export const useCompleteAgentVaultOauthAuthorization = () =>
useMutation({
// The callback page shows every outcome itself.
- meta: { handledErrorCodes: [ApiErrorTypes.BadRequestError, "NotFound"] },
+ meta: { handledErrorCodes: [ApiErrorTypes.BadRequestError, ApiErrorTypes.NotFoundError] },
mutationFn: async ({
authorizationId,
...params
diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.ts
index 50662374a9..62478978b5 100644
--- a/frontend/src/hooks/api/agentVault/types.ts
+++ b/frontend/src/hooks/api/agentVault/types.ts
@@ -20,9 +20,10 @@ export type TAgentVaultOauthCredentialSummary = {
issuer: string;
grantedScopes: string[];
requiredScopes: string[];
- expiresAt: string | null;
- authorizedAt: string | null;
- lastError: string | null;
+ // Left out for Agent Vault members.
+ expiresAt?: string | null;
+ authorizedAt?: string | null;
+ lastError?: string | null;
};
export type TAgentVaultCredentialSummary =
@@ -317,6 +318,8 @@ export type TCreateAgentVaultServiceDTO =
export type TUpdateAgentVaultServiceDTO = {
accessBundleId: string;
serviceId: string;
+ // Must match the service's type, which never changes.
+ type: AgentVaultServiceType;
name?: string;
hostPattern?: string;
allowedMethods?: AgentVaultHttpMethod[] | null;
@@ -341,6 +344,7 @@ export type TCreateAgentVaultOauthAuthorizationDTO = {
serviceId?: string;
clientId?: string;
clientSecret?: string;
+ registration?: "dynamic";
};
export type TCreateAgentVaultOauthAuthorizationResponse = {
@@ -348,13 +352,9 @@ export type TCreateAgentVaultOauthAuthorizationResponse = {
// False when the server answered but advertises no OAuth, which usually means a wrong URL.
oauthAdvertised: boolean;
redirectUri: string;
- // Why the server's registration endpoint refused Infisical; null when it simply has none.
- registrationError: string | null;
authorization: {
id: string;
- status: AgentVaultOauthAuthorizationStatus;
authorizeUrl: string;
- scopes: string[];
} | null;
};
diff --git a/frontend/src/hooks/api/types.ts b/frontend/src/hooks/api/types.ts
index f82520cb65..0a2185364b 100644
--- a/frontend/src/hooks/api/types.ts
+++ b/frontend/src/hooks/api/types.ts
@@ -44,7 +44,8 @@ export enum ApiErrorTypes {
UnauthorizedError = "UnauthorizedError",
ForbiddenError = "PermissionDenied",
CustomForbiddenError = "ForbiddenError",
- RateLimitError = "RateLimitExceeded"
+ RateLimitError = "RateLimitExceeded",
+ NotFoundError = "NotFound"
}
export type TApiErrors =
diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx
index 80da49cf8e..23d4fec525 100644
--- a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/ServicesCard.tsx
@@ -112,7 +112,7 @@ const HostsCell = ({ hostPattern }: { hostPattern: string }) => {
const TargetCell = ({ service }: { service: TAgentVaultService }) =>
service.type === AgentVaultServiceType.Mcp ? (
<span className="block max-w-72 truncate text-sm" title={service.serverUrl}>
- {service.serverUrl}
+ {service.serverUrl.replace(/^https:\/\//i, "")}
</span>
) : (
<HostsCell hostPattern={service.hostPattern} />
diff --git a/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/AgentVaultOAuthCallbackPage.tsx b/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/AgentVaultOAuthCallbackPage.tsx
index 684d6f27a4..3c92c72fa3 100644
--- a/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/AgentVaultOAuthCallbackPage.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultOAuthCallbackPage/AgentVaultOAuthCallbackPage.tsx
@@ -1,5 +1,6 @@
import { useEffect, useRef, useState } from "react";
import { Helmet } from "react-helmet";
+import { useTranslation } from "react-i18next";
import { useSearch } from "@tanstack/react-router";
import axios from "axios";
import { CircleAlertIcon } from "lucide-react";
@@ -39,6 +40,7 @@ const failureMessage = (error: unknown) => {
};
export const AgentVaultOAuthCallbackPage = () => {
+ const { t } = useTranslation();
const search = useSearch({ from: "/_authenticate/agent-vault/oauth/callback" });
const completeAuthorization = useCompleteAgentVaultOauthAuthorization();
const [outcome, setOutcome] = useState<TOutcome>({ status: "working" });
@@ -95,7 +97,7 @@ export const AgentVaultOAuthCallbackPage = () => {
return (
<AuthPageLayout variant="focused" showFooter={false}>
<Helmet>
- <title>Agent Vault Authorization</title>
+ <title>{t("common.head-title", { title: "Agent Vault Authorization" })}</title>
</Helmet>
<AuthPagePanel>
<CardHeader>
diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsx
index 5489535256..7d389fe0fd 100644
--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogRow.tsx
@@ -115,13 +115,11 @@ const PathDetail = ({ record }: { record: TAgentVaultSessionLogRecord }) => (
const McpCallText = ({ call, path }: { call: TAgentVaultSessionLogMcpCall; path: string }) =>
call.tool ? (
<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>
+ <TooltipTrigger className="min-w-0 truncate text-left">{call.tool}</TooltipTrigger>
+ <TooltipContent className="max-w-sm break-all">{call.tool}</TooltipContent>
</Tooltip>
) : (
- <span className="min-w-0 truncate font-mono text-xs text-muted" title={path}>
+ <span className="min-w-0 truncate" title={path}>
{call.method}
</span>
);
@@ -139,7 +137,7 @@ const McpDetail = ({ record }: { record: TAgentVaultSessionLogRecord }) => {
{first ? (
<McpCallText call={first} path={record.path} />
) : (
- <span className="min-w-0 truncate text-muted" title={record.path}>
+ <span className="min-w-0 truncate" title={record.path}>
{record.path}
</span>
)}
@@ -150,7 +148,7 @@ const McpDetail = ({ record }: { record: TAgentVaultSessionLogRecord }) => {
</TooltipTrigger>
<TooltipContent className="max-w-sm">
{rest.length > 0 && (
- <div className="flex flex-col font-mono text-xs">
+ <div className="flex flex-col text-xs">
{groupRepeatedMcpCalls(rest).map(({ label, count }, index) => (
// eslint-disable-next-line react/no-array-index-key
<span key={index}>
diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.tsx
index a995cce4eb..98c607074a 100644
--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionLogsPanel.tsx
@@ -350,7 +350,7 @@ export const SessionLogsPanel = ({ session }: Props) => {
)} and ${format(range.endDate, "MMM d, yyyy HH:mm")}.`;
} else if (isFiltered) {
noRecordsTitle = "No requests match these filters";
- noRecordsDescription = "Try a different search term, type, outcome or time range.";
+ noRecordsDescription = "Try a different search term, outcome or time range.";
} else if (liveState === "live") {
noRecordsLiveState = liveState;
noRecordsTitle = "Waiting for requests";