diff --git a/sink/agent-vault.test.ts b/sink/agent-vault.test.ts new file mode 100644 index 0000000..3c80b16 --- /dev/null +++ b/sink/agent-vault.test.ts @@ -0,0 +1,856 @@ +import { inspect } from "node:util"; +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { InfisicalSDK, InfisicalSDKError, InfisicalSDKRequestError } from "../src"; +import { FetchHttpError } from "../src/api/fetch-errors"; +import { + AgentVaultDelegationScope, + AgentVaultMemberType, + AgentVaultSessionScope, + AgentVaultSessionStatus, + AgentVaultTrafficPolicy +} from "../src/api/types/agent-vault"; + +type AgentVault = ReturnType; + +const PROXY_ID = "a2b5e0d1-6f3e-4c55-9a43-3f0c1f0a2b7e"; +const SESSION_ID = "6f1c2a9e-3b7d-4e8a-9c41-2d5f7b8e0a13"; +const BUNDLE_ID = "5e2d8c1a-7b3f-4a9e-8d6c-1f0b2a3c4d5e"; +const SERVICE_ID = "3a5c7e9b-2d4f-4a6c-8e1b-5d7f9a2c4e6b"; +const MACHINE_IDENTITY_ID = "9c4b2a1d-3e5f-4a6b-8c7d-2e1f0a9b8c7d"; +const OTHER_MACHINE_IDENTITY_ID = "2f6e8a4c-1b3d-4c5e-9f7a-6b8c0d2e4f1a"; +const USER_ID = "0d9a7c3e-5b1f-4e2a-8c6d-7f4b2e1a9c50"; +const USER_EMAIL = "jsmith@example.com"; +const GROUP_ID = "7b1e4f2a-9c3d-4a6b-8e5f-1d2c3b4a5e6f"; +const CREATED_AT = "2026-10-27T00:00:00.000Z"; + +const PROXY = { + id: PROXY_ID, + name: "edge-proxy", + description: null, + heartbeat: null, + isHealthy: false, + rootCaFingerprint: "AB:CD:EF", + rootCaExpiresAt: "2036-10-27T00:00:00.000Z", + trafficPolicy: "any-host", + allowedHosts: null, + pollInterval: 60, + createdAt: CREATED_AT +}; +const USER = { id: USER_ID, username: USER_EMAIL, email: USER_EMAIL, firstName: "Jane", lastName: "Smith" }; +const SESSION_ACCESS_BUNDLE = { id: BUNDLE_ID, name: "release" }; +const SESSION = { + id: SESSION_ID, + label: null, + actor: { type: "machineIdentity", id: MACHINE_IDENTITY_ID, name: "slack-bot" }, + onBehalfOf: { type: "user", ...USER }, + status: "active", + expiresAt: "2026-10-27T01:00:00.000Z", + revokedAt: null, + createdAt: CREATED_AT, + accessBundle: SESSION_ACCESS_BUNDLE, + services: [] +}; +const CREATED_SESSION = { + id: SESSION_ID, + label: null, + token: "session-token", + expiresAt: SESSION.expiresAt, + createdAt: CREATED_AT, + accessBundle: SESSION_ACCESS_BUNDLE, + services: [] +}; +// A service sent with a session, as the SDK takes it and as the API returns it (without its secrets). +const INLINE_SERVICE_INPUT = { + type: "http" as const, + name: "github", + hostPattern: "api.github.com", + allowedMethods: ["GET" as const], + credential: { type: "bearer" as const, value: "github-token" }, + customHeaders: [{ name: "X-Team", value: "platform" }] +}; +const INLINE_SERVICE = { + id: "8e2f4a6c-1b3d-4e5f-9a7b-2c4d6e8f0a1b", + name: "github", + type: "http", + serverUrl: null, + transport: null, + hostPattern: "api.github.com", + allowedMethods: ["GET"], + allowedPathPrefixes: null, + credential: { type: "bearer", headerName: "Authorization", headerPrefix: "Bearer" }, + customHeaders: [{ name: "X-Team", prefix: "" }], + substitutions: [] +}; +const BUNDLE = { id: BUNDLE_ID, name: "release", description: null, createdAt: CREATED_AT, updatedAt: CREATED_AT }; +const SERVICE = { + id: SERVICE_ID, + accessBundleId: BUNDLE_ID, + name: "github", + type: "http", + serverUrl: null, + transport: null, + hostPattern: "api.github.com", + allowedMethods: null, + allowedPathPrefixes: null, + credential: { type: "bearer", memberProvidedFields: [] }, + customHeaders: [], + substitutions: [], + personalValues: null, + createdAt: CREATED_AT, + updatedAt: CREATED_AT +}; +const DELEGATION = { + machineIdentity: { id: MACHINE_IDENTITY_ID, name: "slack-bot" }, + scope: "selected", + users: [{ ...USER, addedAt: CREATED_AT }], + groups: [{ id: GROUP_ID, name: "Engineering", addedAt: CREATED_AT }], + createdAt: CREATED_AT, + updatedAt: CREATED_AT +}; +const MISSING_ACCESS_BUNDLES = [{ id: BUNDLE_ID, name: "release" }]; +const DELEGATION_DETAIL = { + ...DELEGATION, + users: [{ ...DELEGATION.users[0], missingAccessBundles: MISSING_ACCESS_BUNDLES }], + groups: [{ ...DELEGATION.groups[0], missingAccessBundles: [] }], + missingAccessBundles: MISSING_ACCESS_BUNDLES +}; +const AVAILABLE_MEMBER = { type: "group", id: GROUP_ID, name: "Engineering", role: "member", isActive: true, addedAt: CREATED_AT }; + +let fetchSpy: ReturnType; +let agentVault: AgentVault; + +const respondWith = (payload: unknown, status = 200) => { + fetchSpy.mockImplementation(async () => new Response(JSON.stringify(payload), { status })); +}; + +const lastRequest = () => { + const [url, init] = fetchSpy.mock.calls.at(-1) as [string, RequestInit]; + const { pathname, searchParams } = new URL(url); + return { + method: init.method, + path: pathname, + query: Object.fromEntries(searchParams), + body: init.body === undefined ? undefined : JSON.parse(init.body as string) + }; +}; + +beforeEach(() => { + fetchSpy = vi.fn(); + vi.stubGlobal("fetch", fetchSpy); + agentVault = new InfisicalSDK({ siteUrl: "https://infisical.example.com" }).agentVault(); +}); + +afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); +}); + +// Every method, with the route it calls in the Infisical API, the request it sends with only the required +// arguments, and what it returns from the response. +const ROUTES: { + name: string; + call: (agentVault: AgentVault) => Promise; + method: string; + path: string; + query?: Record; + body?: unknown; + response: unknown; + returns: (response: any) => unknown; +}[] = [ + { + name: "proxies.list", + call: (av) => av.proxies.list(), + method: "GET", + path: "/proxies", + query: { orderBy: "createdAt", orderDirection: "desc", limit: "20", offset: "0" }, + response: { proxies: [PROXY], totalCount: 1 }, + returns: (res) => res + }, + { + name: "proxies.create", + call: (av) => av.proxies.create({ name: "edge-proxy" }), + method: "POST", + path: "/proxies", + body: { name: "edge-proxy", trafficPolicy: "any-host", pollInterval: 60 }, + response: { proxy: PROXY, proxyToken: "proxy-token" }, + returns: (res) => res + }, + { + name: "proxies.update", + call: (av) => av.proxies.update(PROXY_ID, { pollInterval: 30 }), + method: "PATCH", + path: `/proxies/${PROXY_ID}`, + body: { pollInterval: 30 }, + response: { proxy: { ...PROXY, pollInterval: 30 } }, + returns: (res) => res.proxy + }, + { + name: "proxies.delete", + call: (av) => av.proxies.delete(PROXY_ID), + method: "DELETE", + path: `/proxies/${PROXY_ID}`, + response: { proxy: { id: PROXY_ID, name: "edge-proxy" } }, + returns: (res) => res.proxy + }, + { + name: "proxies.rotateToken", + call: (av) => av.proxies.rotateToken(PROXY_ID), + method: "POST", + path: `/proxies/${PROXY_ID}/token-auth/proxy-token`, + response: { proxy: PROXY, proxyToken: "new-proxy-token" }, + returns: (res) => res + }, + { + name: "proxies.revoke", + call: (av) => av.proxies.revoke(PROXY_ID), + method: "POST", + path: `/proxies/${PROXY_ID}/revoke`, + response: { proxy: PROXY }, + returns: (res) => res.proxy + }, + { + name: "sessions.list", + call: (av) => av.sessions.list(), + method: "GET", + path: "/sessions", + query: { scope: "mine", limit: "20", offset: "0" }, + response: { sessions: [SESSION], totalCount: 1 }, + returns: (res) => res + }, + { + name: "sessions.get", + call: (av) => av.sessions.get(SESSION_ID), + method: "GET", + path: `/sessions/${SESSION_ID}`, + response: { session: SESSION }, + returns: (res) => res.session + }, + { + name: "sessions.create", + call: (av) => av.sessions.create({ accessBundle: "release" }), + method: "POST", + path: "/sessions", + body: { accessBundle: "release" }, + response: { session: CREATED_SESSION }, + returns: (res) => res.session + }, + { + name: "sessions.update", + call: (av) => av.sessions.update(SESSION_ID, { label: "nightly deploy" }), + method: "PATCH", + path: `/sessions/${SESSION_ID}`, + body: { label: "nightly deploy" }, + response: { session: { ...SESSION, label: "nightly deploy" } }, + returns: (res) => res.session + }, + { + name: "sessions.revoke", + call: (av) => av.sessions.revoke(SESSION_ID), + method: "POST", + path: `/sessions/${SESSION_ID}/revoke`, + response: { session: { ...SESSION, accessBundle: undefined, services: undefined, status: "revoked", revokedAt: CREATED_AT } }, + returns: (res) => res.session + }, + { + name: "accessBundles.list", + call: (av) => av.accessBundles.list(), + method: "GET", + path: "/access-bundles", + query: { orderBy: "createdAt", orderDirection: "desc", limit: "20", offset: "0" }, + response: { + accessBundles: [ + { + ...BUNDLE, + serviceCount: 1, + memberCount: 2, + hostPatterns: ["api.github.com"], + servicesRequiringSetup: [{ id: SERVICE_ID, name: "github" }] + } + ], + totalCount: 1 + }, + returns: (res) => res + }, + { + name: "accessBundles.get", + call: (av) => av.accessBundles.get(BUNDLE_ID), + method: "GET", + path: `/access-bundles/${BUNDLE_ID}`, + response: { accessBundle: { ...BUNDLE, services: [SERVICE] } }, + returns: (res) => res.accessBundle + }, + { + name: "accessBundles.create", + call: (av) => av.accessBundles.create({ name: "release" }), + method: "POST", + path: "/access-bundles", + body: { name: "release" }, + response: { accessBundle: BUNDLE }, + returns: (res) => res.accessBundle + }, + { + name: "accessBundles.update", + call: (av) => av.accessBundles.update(BUNDLE_ID, { name: "release-2" }), + method: "PATCH", + path: `/access-bundles/${BUNDLE_ID}`, + body: { name: "release-2" }, + response: { accessBundle: { ...BUNDLE, name: "release-2" } }, + returns: (res) => res.accessBundle + }, + { + name: "accessBundles.delete", + call: (av) => av.accessBundles.delete(BUNDLE_ID), + method: "DELETE", + path: `/access-bundles/${BUNDLE_ID}`, + response: { accessBundle: BUNDLE }, + returns: (res) => res.accessBundle + }, + { + name: "accessBundles.listGrantees", + call: (av) => av.accessBundles.listGrantees(BUNDLE_ID), + method: "GET", + path: `/access-bundles/${BUNDLE_ID}/members`, + query: { limit: "20", offset: "0" }, + response: { members: [{ type: "user", ...USER, grantedAt: CREATED_AT }], totalCount: 1 }, + returns: (res) => res + }, + { + name: "accessBundles.listAvailableGrantees", + call: (av) => av.accessBundles.listAvailableGrantees(BUNDLE_ID), + method: "GET", + path: `/access-bundles/${BUNDLE_ID}/members/available`, + query: { limit: "20", offset: "0" }, + response: { members: [AVAILABLE_MEMBER], totalCount: 1 }, + returns: (res) => res + }, + { + name: "accessBundles.grant", + call: (av) => av.accessBundles.grant(BUNDLE_ID, { userIds: [USER_ID] }), + method: "POST", + path: `/access-bundles/${BUNDLE_ID}/members`, + body: { userIds: [USER_ID] }, + response: { members: [{ type: "user", id: USER_ID, grantedAt: CREATED_AT }], skipped: [] }, + returns: (res) => res + }, + { + name: "accessBundles.revoke", + call: (av) => av.accessBundles.revoke(BUNDLE_ID, { groupIds: [GROUP_ID] }), + method: "DELETE", + path: `/access-bundles/${BUNDLE_ID}/members`, + body: { groupIds: [GROUP_ID] }, + response: { members: [{ type: "group", id: GROUP_ID }], skipped: [] }, + returns: (res) => res + }, + { + name: "delegations.list", + call: (av) => av.delegations.list(), + method: "GET", + path: "/delegations", + query: { limit: "100", offset: "0" }, + response: { delegations: [DELEGATION], totalCount: 1 }, + returns: (res) => res + }, + { + name: "delegations.get", + call: (av) => av.delegations.get(MACHINE_IDENTITY_ID), + method: "GET", + path: `/delegations/${MACHINE_IDENTITY_ID}`, + response: { delegation: DELEGATION_DETAIL }, + returns: (res) => res.delegation + }, + { + name: "delegations.set", + call: (av) => av.delegations.set(MACHINE_IDENTITY_ID, { scope: AgentVaultDelegationScope.AllMembers }), + method: "PUT", + path: `/delegations/${MACHINE_IDENTITY_ID}`, + body: { scope: "all-members" }, + response: { delegation: { ...DELEGATION_DETAIL, scope: "all-members", users: [], groups: [] } }, + returns: (res) => res.delegation + }, + { + name: "delegations.delete", + call: (av) => av.delegations.delete(MACHINE_IDENTITY_ID), + method: "DELETE", + path: `/delegations/${MACHINE_IDENTITY_ID}`, + response: { delegation: DELEGATION }, + returns: (res) => res.delegation + }, + { + name: "delegations.addSubjects", + call: (av) => av.delegations.addSubjects(MACHINE_IDENTITY_ID, { userIds: [USER_ID] }), + method: "POST", + path: `/delegations/${MACHINE_IDENTITY_ID}/subjects`, + body: { userIds: [USER_ID] }, + response: { delegation: DELEGATION_DETAIL }, + returns: (res) => res.delegation + }, + { + name: "delegations.removeSubjects", + call: (av) => av.delegations.removeSubjects(MACHINE_IDENTITY_ID, { groupIds: [GROUP_ID] }), + method: "DELETE", + path: `/delegations/${MACHINE_IDENTITY_ID}/subjects`, + body: { groupIds: [GROUP_ID] }, + response: { delegation: { ...DELEGATION_DETAIL, groups: [] } }, + returns: (res) => res.delegation + }, + { + name: "delegations.listAvailableSubjects", + call: (av) => av.delegations.listAvailableSubjects(MACHINE_IDENTITY_ID), + method: "GET", + path: `/delegations/${MACHINE_IDENTITY_ID}/subjects/available`, + query: { limit: "20", offset: "0" }, + response: { members: [AVAILABLE_MEMBER], totalCount: 1 }, + returns: (res) => res + } +]; + +describe("agent vault routes", () => { + it.each(ROUTES)("$name sends $method $path", async ({ call, method, path, query, body, response, returns }) => { + respondWith(response); + const result = await call(agentVault); + expect(lastRequest()).toEqual({ method, path: `/api/v1/agent-vault${path}`, query: query ?? {}, body }); + expect(result).toEqual(returns(response)); + }); +}); + +describe("agent vault proxies", () => { + it.each([[[]], [""], [" "]])("update sends null to remove every allowed host when given %j", async (allowedHosts) => { + respondWith({ proxy: PROXY }); + await agentVault.proxies.update(PROXY_ID, { allowedHosts }); + expect(lastRequest().body).toEqual({ allowedHosts: null }); + }); + + it("update leaves out the values you don't pass", async () => { + respondWith({ proxy: PROXY }); + await agentVault.proxies.update(PROXY_ID, { name: "edge-proxy" }); + expect(lastRequest().body).toEqual({ name: "edge-proxy" }); + }); + + it("create sends and returns the description", async () => { + respondWith({ proxy: { ...PROXY, description: "Edge traffic" }, proxyToken: "proxy-token" }); + const created = await agentVault.proxies.create({ name: "edge-proxy", description: "Edge traffic" }); + expect(lastRequest().body.description).toBe("Edge traffic"); + expect(created.proxy.description).toBe("Edge traffic"); + }); + + it.each([ + { name: "description", options: { description: "" }, body: { description: "" } }, + { + name: "description and allowed hosts", + options: { description: "", allowedHosts: [] }, + body: { description: "", allowedHosts: null } + } + ])("update sends an empty description to remove it ($name)", async ({ options, body }) => { + respondWith({ proxy: PROXY }); + await agentVault.proxies.update(PROXY_ID, options); + expect(lastRequest().body).toEqual(body); + }); + + it.each([[[]], [""]])("create leaves out empty allowed hosts when given %j", async (allowedHosts) => { + respondWith({ proxy: PROXY, proxyToken: "proxy-token" }); + await agentVault.proxies.create({ name: "edge-proxy", allowedHosts }); + expect(lastRequest().body).not.toHaveProperty("allowedHosts"); + }); + + it("create joins a list of allowed hosts into the comma-separated string the API takes", async () => { + respondWith({ proxy: PROXY, proxyToken: "proxy-token" }); + await agentVault.proxies.create({ + name: "edge-proxy", + trafficPolicy: AgentVaultTrafficPolicy.ServiceHosts, + allowedHosts: ["api.github.com", "*.slack.com"] + }); + expect(lastRequest().body).toMatchObject({ allowedHosts: "api.github.com,*.slack.com" }); + }); +}); + +describe("agent vault traffic policy", () => { + // service-hosts is the new name of bundle-hosts. Infisical still accepts bundle-hosts and stores it, and a version + // from before the rename accepts only bundle-hosts, so the SDK sends service-hosts as bundle-hosts. + const hostsOnly = [AgentVaultTrafficPolicy.ServiceHosts, "service-hosts" as const]; + + it.each(hostsOnly)("create sends %s as bundle-hosts, which every Infisical version accepts", async (trafficPolicy) => { + respondWith({ proxy: PROXY, proxyToken: "proxy-token" }); + await agentVault.proxies.create({ name: "edge-proxy", trafficPolicy }); + expect(lastRequest().body.trafficPolicy).toBe("bundle-hosts"); + }); + + it.each(hostsOnly)("update sends %s as bundle-hosts, which every Infisical version accepts", async (trafficPolicy) => { + respondWith({ proxy: PROXY }); + await agentVault.proxies.update(PROXY_ID, { trafficPolicy }); + expect(lastRequest().body).toEqual({ trafficPolicy: "bundle-hosts" }); + }); + + it("sends any-host as it is", async () => { + respondWith({ proxy: PROXY, proxyToken: "proxy-token" }); + await agentVault.proxies.create({ name: "edge-proxy", trafficPolicy: AgentVaultTrafficPolicy.AnyHost }); + expect(lastRequest().body.trafficPolicy).toBe("any-host"); + await agentVault.proxies.update(PROXY_ID, { trafficPolicy: "any-host" }); + expect(lastRequest().body).toEqual({ trafficPolicy: "any-host" }); + }); + + // Infisical with service-hosts returns it, and a version from before the rename returns bundle-hosts. + it.each(["service-hosts", "bundle-hosts"])("reports %s from every proxy response as service-hosts", async (returned) => { + const proxy = { ...PROXY, trafficPolicy: returned }; + const reported: unknown[] = []; + + respondWith({ proxies: [proxy], totalCount: 1 }); + reported.push((await agentVault.proxies.list()).proxies[0].trafficPolicy); + respondWith({ proxy, proxyToken: "proxy-token" }); + reported.push((await agentVault.proxies.create({ name: "edge-proxy" })).proxy.trafficPolicy); + respondWith({ proxy }); + reported.push((await agentVault.proxies.update(PROXY_ID, { pollInterval: 30 })).trafficPolicy); + respondWith({ proxy, proxyToken: "proxy-token" }); + reported.push((await agentVault.proxies.rotateToken(PROXY_ID)).proxy.trafficPolicy); + respondWith({ proxy }); + reported.push((await agentVault.proxies.revoke(PROXY_ID)).trafficPolicy); + + expect(reported).toEqual(Array(5).fill("service-hosts")); + }); + + it("leaves any-host, and a member's proxy without settings, as they are", async () => { + const { trafficPolicy, allowedHosts, pollInterval, createdAt, ...memberView } = PROXY; + respondWith({ proxies: [PROXY, memberView], totalCount: 2 }); + const { proxies } = await agentVault.proxies.list(); + expect(proxies).toEqual([PROXY, memberView]); + }); +}); + +describe("agent vault inline services", () => { + it("create sends services without an access bundle", async () => { + respondWith({ session: { ...CREATED_SESSION, accessBundle: null, services: [INLINE_SERVICE] } }); + const created = await agentVault.sessions.create({ services: [INLINE_SERVICE_INPUT], ttl: "15m" }); + expect(lastRequest().body).toEqual({ services: [INLINE_SERVICE_INPUT], ttl: "15m" }); + expect(created.services).toEqual([INLINE_SERVICE]); + expect(created.accessBundle).toBeNull(); + }); + + it("create sends an access bundle and services together", async () => { + respondWith({ session: { ...CREATED_SESSION, services: [INLINE_SERVICE] } }); + await agentVault.sessions.create({ accessBundle: "release", services: [INLINE_SERVICE_INPUT] }); + expect(lastRequest().body).toEqual({ accessBundle: "release", services: [INLINE_SERVICE_INPUT] }); + }); + + it("create sends an empty access bundle name, so the server rejects it instead of dropping it", async () => { + respondWith({ session: CREATED_SESSION }); + await agentVault.sessions.create({ accessBundle: "" }); + expect(lastRequest().body).toEqual({ accessBundle: "" }); + }); + + it("returns a session's services as the API sends them", async () => { + respondWith({ session: { ...SESSION, services: [INLINE_SERVICE] } }); + expect((await agentVault.sessions.get(SESSION_ID)).services).toEqual([INLINE_SERVICE]); + }); + + // Infisical's validation errors list their issues in message, as an array rather than a string. + it("keeps the server's explanation when it refuses a request with 422", async () => { + respondWith( + { + reqId: "req-1", + statusCode: 422, + message: [ + { + code: "too_big", + maximum: 20, + path: ["services"], + message: "A session can have at most 20 services. Add the others to an access bundle and name it in accessBundles." + } + ], + error: "ValidationFailure" + }, + 422 + ); + await expect(agentVault.sessions.create({ services: [INLINE_SERVICE_INPUT] })).rejects.toThrow( + /\[StatusCode=422\].*at most 20 services/ + ); + }); + + it("uses the server's message for a refusal that isn't a validation error", async () => { + respondWith( + { + statusCode: 403, + message: "Only an Agent Vault admin can send services with a session. Name an access bundle instead.", + error: "PermissionDenied" + }, + 403 + ); + await expect(agentVault.sessions.create({ services: [INLINE_SERVICE_INPUT] })).rejects.toThrow( + /\[StatusCode=403\] Only an Agent Vault admin can send services with a session/ + ); + }); + + // An Infisical version without inline services leaves services out of every session. + it("gives sessions from an Infisical version without inline services an empty list of them", async () => { + const { services, ...olderSession } = SESSION; + const { services: createdServices, ...olderCreated } = CREATED_SESSION; + + respondWith({ sessions: [olderSession], totalCount: 1 }); + expect((await agentVault.sessions.list()).sessions[0].services).toEqual([]); + respondWith({ session: olderSession }); + expect((await agentVault.sessions.get(SESSION_ID)).services).toEqual([]); + respondWith({ session: olderSession }); + expect((await agentVault.sessions.update(SESSION_ID, { label: null })).services).toEqual([]); + respondWith({ session: olderCreated }); + expect((await agentVault.sessions.create({ accessBundle: "release" })).services).toEqual([]); + }); +}); + +describe("agent vault sessions", () => { + it("get reads the one access bundle a session carries, which keeps its name once deleted", async () => { + respondWith({ session: SESSION }); + expect((await agentVault.sessions.get(SESSION_ID)).accessBundle).toEqual({ id: BUNDLE_ID, name: "release" }); + + respondWith({ session: { ...SESSION, accessBundle: { id: null, name: "release" } } }); + expect((await agentVault.sessions.get(SESSION_ID)).accessBundle).toEqual({ id: null, name: "release" }); + }); + + it("create sends one access bundle and reads it back", async () => { + respondWith({ session: CREATED_SESSION }); + const created = await agentVault.sessions.create({ accessBundle: "release", ttl: "1h" }); + expect(lastRequest().body).toEqual({ accessBundle: "release", ttl: "1h" }); + expect(created.accessBundle).toEqual({ id: BUNDLE_ID, name: "release" }); + }); + + it.each(["nightly deploy", null])("update always sends the label (%j)", async (label) => { + respondWith({ session: { ...SESSION, label } }); + const updated = await agentVault.sessions.update(SESSION_ID, { label }); + expect(lastRequest().body).toEqual({ label }); + expect(updated.label).toBe(label); + }); + + it("create leaves out ttl so the server picks the default", async () => { + respondWith({ session: CREATED_SESSION }); + await agentVault.sessions.create({ accessBundle: "release" }); + expect(lastRequest().body).toEqual({ accessBundle: "release" }); + }); + + it.each([ + { name: "email", options: { onBehalfOfUserEmail: USER_EMAIL }, onBehalfOf: { userEmail: USER_EMAIL } }, + { name: "ID", options: { onBehalfOfUserId: USER_ID }, onBehalfOf: { userId: USER_ID } }, + { name: "empty email", options: { onBehalfOfUserEmail: "" }, onBehalfOf: { userEmail: "" } } + ])("create names the user it acts for by $name", async ({ options, onBehalfOf }) => { + respondWith({ session: CREATED_SESSION }); + await agentVault.sessions.create({ accessBundle: "release", ...options }); + expect(lastRequest().body).toEqual({ accessBundle: "release", onBehalfOf }); + }); + + it("create rejects both a user email and a user ID before sending a request", async () => { + const created = agentVault.sessions.create({ + accessBundle: "release", + onBehalfOfUserEmail: USER_EMAIL, + onBehalfOfUserId: USER_ID + }); + await expect(created).rejects.toThrow(InfisicalSDKError); + await expect(created).rejects.toThrow("not both"); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it("list takes enum values or their strings, and joins the statuses", async () => { + respondWith({ sessions: [], totalCount: 0 }); + await agentVault.sessions.list({ + scope: AgentVaultSessionScope.All, + statuses: [AgentVaultSessionStatus.Active, "expired"] + }); + expect(lastRequest().query).toMatchObject({ scope: "all", status: "active,expired" }); + }); +}); + +describe("agent vault access bundles", () => { + it("list sends booleans the way the API reads them", async () => { + respondWith({ accessBundles: [], totalCount: 0 }); + await agentVault.accessBundles.list({ requiresSetup: true, granted: false }); + expect(lastRequest().query).toMatchObject({ requiresSetup: "true", granted: "false" }); + }); + + it("list names the user a session would act for", async () => { + respondWith({ accessBundles: [], totalCount: 0 }); + await agentVault.accessBundles.list({ onBehalfOfUserEmail: USER_EMAIL }); + const { query } = lastRequest(); + expect(query.onBehalfOfUserEmail).toBe(USER_EMAIL); + expect(query).not.toHaveProperty("onBehalfOfUserId"); + }); + + it("list rejects both a user email and a user ID before sending a request", async () => { + const listed = agentVault.accessBundles.list({ onBehalfOfUserEmail: USER_EMAIL, onBehalfOfUserId: USER_ID }); + await expect(listed).rejects.toThrow("not both"); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it("update sends an empty description to remove it", async () => { + respondWith({ accessBundle: BUNDLE }); + await agentVault.accessBundles.update(BUNDLE_ID, { description: "" }); + expect(lastRequest().body).toEqual({ description: "" }); + }); + + it("listGrantees and listAvailableGrantees send the actor type value", async () => { + respondWith({ members: [], totalCount: 0 }); + await agentVault.accessBundles.listGrantees(BUNDLE_ID, { actorType: AgentVaultMemberType.Group }); + expect(lastRequest().query.actorType).toBe("group"); + await agentVault.accessBundles.listAvailableGrantees(BUNDLE_ID, { actorType: "machineIdentity" }); + expect(lastRequest().query.actorType).toBe("machineIdentity"); + }); + + it("grant and revoke send only the grantees you name", async () => { + respondWith({ members: [{ type: "machineIdentity", id: MACHINE_IDENTITY_ID, grantedAt: CREATED_AT }], skipped: [] }); + await agentVault.accessBundles.grant(BUNDLE_ID, { machineIdentityIds: [MACHINE_IDENTITY_ID] }); + expect(lastRequest()).toMatchObject({ method: "POST", body: { machineIdentityIds: [MACHINE_IDENTITY_ID] } }); + + respondWith({ members: [{ type: "user", id: USER_ID }], skipped: [] }); + const revoked = await agentVault.accessBundles.revoke(BUNDLE_ID, { userIds: [USER_ID] }); + expect(lastRequest()).toMatchObject({ method: "DELETE", body: { userIds: [USER_ID] } }); + expect(revoked.members).toEqual([{ type: "user", id: USER_ID }]); + }); +}); + +describe("agent vault delegations", () => { + it("set puts the scope value", async () => { + respondWith({ delegation: DELEGATION_DETAIL }); + await agentVault.delegations.set(MACHINE_IDENTITY_ID, { + scope: AgentVaultDelegationScope.Selected, + groupIds: [GROUP_ID] + }); + expect(lastRequest()).toMatchObject({ method: "PUT", body: { scope: "selected", groupIds: [GROUP_ID] } }); + }); + + it("list joins the machine identity IDs", async () => { + respondWith({ delegations: [DELEGATION], totalCount: 1 }); + await agentVault.delegations.list({ machineIdentityIds: [MACHINE_IDENTITY_ID, OTHER_MACHINE_IDENTITY_ID] }); + expect(lastRequest().query.machineIdentityIds).toBe(`${MACHINE_IDENTITY_ID},${OTHER_MACHINE_IDENTITY_ID}`); + }); + + it("removeSubjects returns null once the last one is gone", async () => { + respondWith({ delegation: null }); + const delegation = await agentVault.delegations.removeSubjects(MACHINE_IDENTITY_ID, { userIds: [USER_ID] }); + expect(delegation).toBeNull(); + expect(lastRequest().body).toEqual({ userIds: [USER_ID] }); + }); + + it("listAvailableSubjects sends the actor type value", async () => { + respondWith({ members: [], totalCount: 0 }); + await agentVault.delegations.listAvailableSubjects(MACHINE_IDENTITY_ID, { actorType: AgentVaultMemberType.Group }); + expect(lastRequest().query.actorType).toBe("group"); + }); +}); + +describe("agent vault retries", () => { + // What the SDK's request timeout throws. The server may have handled the request before it fired. + const timeoutError = () => new DOMException("The request timed out after 10 seconds", "TimeoutError"); + + it.each([ + { name: "proxies.create", call: (av: AgentVault) => av.proxies.create({ name: "edge-proxy" }) }, + { name: "proxies.rotateToken", call: (av: AgentVault) => av.proxies.rotateToken(PROXY_ID) }, + { name: "sessions.create", call: (av: AgentVault) => av.sessions.create({ accessBundle: "release" }) }, + { name: "accessBundles.create", call: (av: AgentVault) => av.accessBundles.create({ name: "release" }) }, + // A retry after a lost response would report every grantee as skipped. + { name: "accessBundles.grant", call: (av: AgentVault) => av.accessBundles.grant(BUNDLE_ID, { userIds: [USER_ID] }) }, + { name: "accessBundles.revoke", call: (av: AgentVault) => av.accessBundles.revoke(BUNDLE_ID, { userIds: [USER_ID] }) }, + // A retry after a lost response would fail with a 404 for a delete that worked. + { name: "proxies.delete", call: (av: AgentVault) => av.proxies.delete(PROXY_ID) }, + { name: "accessBundles.delete", call: (av: AgentVault) => av.accessBundles.delete(BUNDLE_ID) }, + { name: "delegations.delete", call: (av: AgentVault) => av.delegations.delete(MACHINE_IDENTITY_ID) }, + { + name: "delegations.removeSubjects", + call: (av: AgentVault) => av.delegations.removeSubjects(MACHINE_IDENTITY_ID, { userIds: [USER_ID] }) + } + ])("$name isn't retried once the request may have reached the server", async ({ call }) => { + vi.useFakeTimers(); + fetchSpy.mockImplementation(async () => { + throw timeoutError(); + }); + + const assertion = expect(call(agentVault)).rejects.toThrow("The request timed out after 10 seconds"); + await vi.runAllTimersAsync(); + await assertion; + expect(fetchSpy).toHaveBeenCalledTimes(1); + }); + + it("an update is still retried after the same error", async () => { + vi.useFakeTimers(); + fetchSpy + .mockImplementationOnce(async () => { + throw timeoutError(); + }) + .mockImplementationOnce(async () => new Response(JSON.stringify({ proxy: PROXY }), { status: 200 })); + + const updated = agentVault.proxies.update(PROXY_ID, { name: "edge-proxy" }); + await vi.runAllTimersAsync(); + expect(await updated).toEqual(PROXY); + expect(fetchSpy).toHaveBeenCalledTimes(2); + }); +}); + +describe("agent vault IDs", () => { + // fetch resolves "." and ".." like directories, so revoke("..") would reach the route that removes members from + // Agent Vault, which takes the same body. + it.each(["", ".", ".."])("refuses the ID %j before sending a request", async (id) => { + await expect(agentVault.accessBundles.revoke(id, { userIds: [USER_ID] })).rejects.toThrow(InfisicalSDKError); + await expect(agentVault.sessions.get(id)).rejects.toThrow(/^Invalid ID/); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it("sends an ID that is a dot segment only once decoded, encoded so it stays one segment", async () => { + respondWith({ session: SESSION }); + await agentVault.sessions.get("%2e%2e"); + expect(lastRequest().path).toBe("/api/v1/agent-vault/sessions/%252e%252e"); + }); +}); + +describe("agent vault errors", () => { + it("throws an InfisicalSDKRequestError, exported from the package root, with the status code", async () => { + respondWith({ statusCode: 404, message: "This machine identity has no delegation", error: "NotFound" }, 404); + const error = await agentVault.delegations.get(MACHINE_IDENTITY_ID).catch((err: unknown) => err); + expect(error).toBeInstanceOf(InfisicalSDKRequestError); + expect((error as InfisicalSDKRequestError).statusCode).toBe(404); + expect((error as Error).message).toMatch(/\[StatusCode=404\] This machine identity has no delegation$/); + expect((error as Error).cause).toBeDefined(); + }); + + it("says a request timed out, and after how long, with the timeout in cause", async () => { + vi.useFakeTimers(); + fetchSpy.mockImplementation( + (_url: string, init: RequestInit) => + new Promise((_resolve, reject) => init.signal!.addEventListener("abort", () => reject(init.signal!.reason))) + ); + + const error = agentVault.sessions.create({ accessBundle: "release" }).catch((err: unknown) => err); + await vi.advanceTimersByTimeAsync(10_000); + const thrown = (await error) as InfisicalSDKError; + + expect(thrown).toBeInstanceOf(InfisicalSDKError); + expect(thrown.message).toBe("The request timed out after 10 seconds"); + expect((thrown.cause as DOMException).name).toBe("TimeoutError"); + expect(fetchSpy).toHaveBeenCalledTimes(1); + }); + + it("keeps the network error in cause, so a reset connection can be told apart from a timeout", async () => { + const reset = new TypeError("fetch failed", { cause: Object.assign(new Error("ECONNRESET"), { code: "ECONNRESET" }) }); + fetchSpy.mockRejectedValue(reset); + + const thrown = (await agentVault.sessions.create({ accessBundle: "release" }).catch((err: unknown) => err)) as Error; + + expect(thrown).toBeInstanceOf(InfisicalSDKError); + expect(thrown.message).toBe("fetch failed"); + expect(thrown.cause).toBe(reset); + }); + + it("keeps a large response body out of the printed error, but readable in cause.response.data", async () => { + const page = `${"

Bad gateway

".repeat(8500)}`; + fetchSpy.mockImplementation(async () => new Response(page, { status: 502, headers: { "Content-Type": "text/html" } })); + + const error = (await agentVault.sessions.get(SESSION_ID).catch((err: unknown) => err)) as InfisicalSDKError; + + expect(error).toBeInstanceOf(InfisicalSDKError); + expect(error.message).toBe("Request failed with status 502"); + expect(inspect(error)).not.toContain("Bad gateway"); + expect(Object.keys(error.cause as object)).not.toContain("response"); + expect((error.cause as FetchHttpError).response.data).toBe(page); + expect((error.cause as FetchHttpError).response.status).toBe(502); + }); + + it("throws an error the SDK raised itself as it is, without wrapping it", async () => { + const error = await agentVault.accessBundles + .list({ onBehalfOfUserEmail: USER_EMAIL, onBehalfOfUserId: USER_ID }) + .catch((err: unknown) => err); + expect(error).toBeInstanceOf(InfisicalSDKError); + expect((error as Error).cause).toBeUndefined(); + }); +}); diff --git a/sink/fetch-base.test.ts b/sink/fetch-base.test.ts index 5cfd9cd..90ae72f 100644 --- a/sink/fetch-base.test.ts +++ b/sink/fetch-base.test.ts @@ -242,3 +242,125 @@ describe("serializeBody", () => { expect(fetchSpy).not.toHaveBeenCalled(); }); }); + +describe("postOnce", () => { + const baseURL = "https://example.com/api/v1/"; + + let fetchSpy: ReturnType; + let client: ApiClient; + + // Node's fetch throws a TypeError with the network error as its cause. + const networkError = (code: string) => + new TypeError("fetch failed", { cause: Object.assign(new Error(code), { code }) }); + const okResponse = () => new Response('{"ok":true}', { status: 200 }); + + beforeEach(() => { + vi.useFakeTimers(); + fetchSpy = vi.fn(); + vi.stubGlobal("fetch", fetchSpy); + client = new ApiClient({ baseURL }); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); + }); + + it.each(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "UND_ERR_CONNECT_TIMEOUT"])( + "retries when the connection never opened (%s)", + async (code) => { + fetchSpy.mockRejectedValueOnce(networkError(code)).mockResolvedValueOnce(okResponse()); + + const promise = client.postOnce("/x", { a: 1 }); + await vi.runAllTimersAsync(); + + expect(await promise).toEqual({ ok: true }); + expect(fetchSpy).toHaveBeenCalledTimes(2); + } + ); + + it.each([ + ["a timeout", new DOMException("The request timed out after 10 seconds", "TimeoutError")], + ["a reset connection", networkError("ECONNRESET")], + ["a socket closed after the request was sent", networkError("UND_ERR_SOCKET")], + ])("doesn't retry %s, since the request may have reached the server", async (_, error) => { + fetchSpy.mockRejectedValue(error); + + const assertion = expect(client.postOnce("/x", { a: 1 })).rejects.toBe(error); + await vi.runAllTimersAsync(); + await assertion; + + expect(fetchSpy).toHaveBeenCalledTimes(1); + }); + + it("retries a rate-limited response, since the server turned the request away", async () => { + fetchSpy + .mockResolvedValueOnce(new Response("rate limited", { status: 429 })) + .mockResolvedValueOnce(okResponse()); + + const promise = client.postOnce("/x", { a: 1 }); + await vi.runAllTimersAsync(); + + expect(await promise).toEqual({ ok: true }); + expect(fetchSpy).toHaveBeenCalledTimes(2); + }); + + it("sends the body and method like post", async () => { + fetchSpy.mockResolvedValueOnce(okResponse()); + + await client.postOnce("/x", { a: 1 }); + + const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit]; + expect(url).toBe("https://example.com/api/v1/x"); + expect(init).toMatchObject({ method: "POST", body: '{"a":1}' }); + }); + + it("rejects with a TimeoutError that says how long it waited", async () => { + // fetch rejects with the abort reason, as Node's fetch does. + fetchSpy.mockImplementation( + (_url: string, init: RequestInit) => + new Promise((_resolve, reject) => init.signal!.addEventListener("abort", () => reject(init.signal!.reason))) + ); + const client = new ApiClient({ baseURL, timeout: 2_500 }); + + const assertion = expect(client.postOnce("/x", { a: 1 })).rejects.toMatchObject({ + name: "TimeoutError", + message: "The request timed out after 2.5 seconds" + }); + await vi.advanceTimersByTimeAsync(2_500); + await assertion; + expect(fetchSpy).toHaveBeenCalledTimes(1); + }); + + it("deleteOnce sends a JSON body, and retries when the connection never opened", async () => { + fetchSpy.mockRejectedValueOnce(networkError("ECONNREFUSED")).mockResolvedValueOnce(okResponse()); + + const promise = client.deleteOnce("/x", { data: { a: 1 } }); + await vi.runAllTimersAsync(); + + expect(await promise).toEqual({ ok: true }); + expect(fetchSpy).toHaveBeenCalledTimes(2); + expect(fetchSpy.mock.calls[1][1]).toMatchObject({ method: "DELETE", body: '{"a":1}' }); + }); + + it("deleteOnce doesn't retry a timeout, since the request may have reached the server", async () => { + const timeout = new DOMException("The request timed out after 10 seconds", "TimeoutError"); + fetchSpy.mockRejectedValue(timeout); + + const assertion = expect(client.deleteOnce("/x", { data: { a: 1 } })).rejects.toBe(timeout); + await vi.runAllTimersAsync(); + await assertion; + + expect(fetchSpy).toHaveBeenCalledTimes(1); + }); + + it("post still retries a network error that postOnce doesn't", async () => { + fetchSpy.mockRejectedValueOnce(networkError("ECONNRESET")).mockResolvedValueOnce(okResponse()); + + const promise = client.post("/x", { a: 1 }); + await vi.runAllTimersAsync(); + + expect(await promise).toEqual({ ok: true }); + expect(fetchSpy).toHaveBeenCalledTimes(2); + }); +}); diff --git a/sink/retry.test.ts b/sink/retry.test.ts index 805fbe6..43b3b9f 100644 --- a/sink/retry.test.ts +++ b/sink/retry.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; -import { fetchWithRetry } from "../src/api/retry"; +import { fetchWithRetry, isConnectError } from "../src/api/retry"; const okResponse = () => new Response("ok", { status: 200 }); const rateLimitResponse = () => new Response("rate limited", { status: 429 }); @@ -189,4 +189,51 @@ describe("fetchWithRetry", () => { setTimeoutSpy.mockRestore(); }); + + it("throws a network error that shouldRetryError rejects without retrying", async () => { + const error = new TypeError("fetch failed"); + const fn = vi.fn().mockRejectedValue(error); + const shouldRetryError = vi.fn().mockReturnValue(false); + + await expect( + fetchWithRetry(fn, { maxRetries: 3, shouldRetryError }) + ).rejects.toBe(error); + expect(fn).toHaveBeenCalledTimes(1); + expect(shouldRetryError).toHaveBeenCalledWith(error); + }); +}); + +describe("isConnectError", () => { + const withCode = (code: string) => Object.assign(new Error(code), { code }); + const fetchFailed = (cause: unknown) => new TypeError("fetch failed", { cause }); + + it.each(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "UND_ERR_CONNECT_TIMEOUT"])( + "is true for %s, the way Node's fetch reports it", + (code) => { + expect(isConnectError(fetchFailed(withCode(code)))).toBe(true); + } + ); + + it("is true when every address of a host refuses the connection", () => { + // Node tries each address of a host like localhost, and reports one AggregateError with the first error's code. + const refused = Object.assign( + new AggregateError([withCode("ECONNREFUSED"), withCode("ECONNREFUSED")]), + { code: "ECONNREFUSED" } + ); + expect(isConnectError(fetchFailed(refused))).toBe(true); + }); + + it("is true for a fetch implementation that throws the network error itself", () => { + expect(isConnectError(withCode("ECONNREFUSED"))).toBe(true); + }); + + it.each([ + ["a timeout", new DOMException("The request timed out after 10 seconds", "TimeoutError")], + ["a reset connection", fetchFailed(withCode("ECONNRESET"))], + ["a socket closed after the request was sent", fetchFailed(withCode("UND_ERR_SOCKET"))], + ["an error without a code", new TypeError("fetch failed")], + ["a value that isn't an error", undefined], + ])("is false for %s", (_, error) => { + expect(isConnectError(error)).toBe(false); + }); }); diff --git a/sink/test-agent-vault.ts b/sink/test-agent-vault.ts new file mode 100644 index 0000000..afb6a82 --- /dev/null +++ b/sink/test-agent-vault.ts @@ -0,0 +1,353 @@ +// Walks through every Agent Vault method against a live Infisical instance, the way the Python SDK's +// release was verified: an admin sets up an access bundle and a delegation, then a machine identity +// starts a session on behalf of a user. The admin also starts sessions with inline services. +// +// You need, on an Infisical version with sessions on behalf of users, proxy descriptions, inline services and the +// service-hosts traffic policy: +// - ADMIN_CLIENT_ID / ADMIN_CLIENT_SECRET: universal auth for a machine identity with the Admin role in Agent Vault. +// - AGENT_CLIENT_ID / AGENT_CLIENT_SECRET / AGENT_MACHINE_IDENTITY_ID: a machine identity that's a member of +// Agent Vault and has no delegation yet. delegations.set replaces a delegation, so the script stops if it has one. +// - USER_ID / USER_EMAIL: a user who's a member of Agent Vault directly, not only through a group. +// - SITE_URL: optional, defaults to http://localhost:8080. +// +// It only deletes what it creates: a proxy, an access bundle (with its grants) and the agent's delegation, and it +// revokes the sessions it starts. +// +// Run it with a TypeScript runner, such as: npx tsx sink/test-agent-vault.ts +import { InfisicalSDK, InfisicalSDKRequestError } from "../src"; +import { AgentVaultDelegationScope, AgentVaultMemberType, AgentVaultTrafficPolicy } from "../src/api/types/agent-vault"; + +const env = (name: string) => { + const value = process.env[name]; + if (!value) throw new Error(`${name} must be set`); + return value; +}; + +const step = async (label: string, run: () => Promise, check?: (value: T) => string | undefined): Promise => { + let value: T; + try { + value = await run(); + } catch (err) { + throw new Error(`${label}: ${(err as Error).message}`); + } + const problem = check?.(value); + if (problem) throw new Error(`${label}: ${problem}`); + console.log(`ok ${label}`); + return value; +}; + +const expectRejection = async (label: string, run: () => Promise, pattern: RegExp) => { + try { + await run(); + } catch (err) { + if (!pattern.test((err as Error).message)) throw new Error(`${label}: unexpected error ${(err as Error).message}`); + console.log(`ok ${label} (${(err as Error).message})`); + return; + } + throw new Error(`${label}: expected an error`); +}; + +(async () => { + const siteUrl = process.env.SITE_URL || "http://localhost:8080"; + const agentId = env("AGENT_MACHINE_IDENTITY_ID"); + const userId = env("USER_ID"); + const userEmail = env("USER_EMAIL"); + const suffix = Math.random().toString(36).slice(2, 8); + + const admin = await new InfisicalSDK({ siteUrl }).auth().universalAuth.login({ + clientId: env("ADMIN_CLIENT_ID"), + clientSecret: env("ADMIN_CLIENT_SECRET") + }); + const agent = await new InfisicalSDK({ siteUrl }).auth().universalAuth.login({ + clientId: env("AGENT_CLIENT_ID"), + clientSecret: env("AGENT_CLIENT_SECRET") + }); + const adminVault = admin.agentVault(); + const agentVault = agent.agentVault(); + + // What the script created and hasn't removed yet. Each one is set as soon as its request resolves, before + // the step checks the response, so a failed check still leaves it for cleanup. + let proxyId: string | undefined; + let bundleId: string | undefined; + const openSessionIds = new Set(); + let delegationSet = false; + + try { + // delegations.set replaces a delegation, so the script must not run against one someone set up. + const existing = await adminVault.delegations.get(agentId).catch((err: Error) => { + if (err instanceof InfisicalSDKRequestError && err.statusCode === 404) return null; + throw err; + }); + if (existing) { + throw new Error(`Machine identity ${agentId} already has a delegation, which this script would replace. Use one without a delegation.`); + } + console.log("ok the agent has no delegation yet"); + + console.log("\n== proxies =="); + const created = await step( + "proxies.create", + async () => { + const res = await adminVault.proxies.create({ + name: `sdk-check-${suffix}`, + description: "Node SDK check", + trafficPolicy: AgentVaultTrafficPolicy.ServiceHosts, + allowedHosts: ["api.github.com", "*.slack.com"] + }); + proxyId = res.proxy.id; + return res; + }, + (res) => + res.proxyToken && + res.proxy.trafficPolicy === AgentVaultTrafficPolicy.ServiceHosts && + res.proxy.allowedHosts === "api.github.com,*.slack.com" + ? undefined + : `got ${JSON.stringify(res.proxy)}` + ); + const proxy = created.proxy; + await step("proxies.list by description", () => adminVault.proxies.list({ search: "Node SDK check" }), (res) => + res.proxies.some((listed) => listed.id === proxy.id) ? undefined : "proxy not listed" + ); + await step("proxies.update removes the description and allowed hosts", () => + adminVault.proxies.update(proxy.id, { description: "", allowedHosts: [], pollInterval: 30 }), + (updated) => (updated.description === null && updated.allowedHosts === null && updated.pollInterval === 30 ? undefined : `got ${JSON.stringify(updated)}`) + ); + await step("proxies.rotateToken", () => adminVault.proxies.rotateToken(proxy.id), (res) => + res.proxyToken && res.proxyToken !== created.proxyToken ? undefined : "token didn't change" + ); + await step("proxies.revoke", () => adminVault.proxies.revoke(proxy.id)); + await step( + "proxies.delete", + async () => { + const deleted = await adminVault.proxies.delete(proxy.id); + proxyId = undefined; + return deleted; + }, + (deleted) => (deleted.id === proxy.id ? undefined : "wrong proxy") + ); + + console.log("\n== access bundles =="); + const bundle = await step("accessBundles.create", async () => { + const res = await adminVault.accessBundles.create({ name: `sdk-check-${suffix}`, description: "Node SDK check" }); + bundleId = res.id; + return res; + }); + await step("accessBundles.get", () => adminVault.accessBundles.get(bundle.id), (res) => + Array.isArray(res.services) ? undefined : "no services list" + ); + await step("accessBundles.update removes the description", () => adminVault.accessBundles.update(bundle.id, { description: "" }), (res) => + res.description === null ? undefined : `description is ${JSON.stringify(res.description)}` + ); + await step("accessBundles.list", () => adminVault.accessBundles.list({ search: bundle.name }), (res) => + res.accessBundles.some((listed) => listed.id === bundle.id) ? undefined : "bundle not listed" + ); + await step("accessBundles.listAvailableGrantees", () => adminVault.accessBundles.listAvailableGrantees(bundle.id)); + await step("accessBundles.grant to the agent and the user", () => + adminVault.accessBundles.grant(bundle.id, { machineIdentityIds: [agentId], userIds: [userId] }), + (res) => (res.members.length + res.skipped.length === 2 ? undefined : `got ${JSON.stringify(res)}`) + ); + await step("accessBundles.grant again skips them", () => + adminVault.accessBundles.grant(bundle.id, { userIds: [userId] }), + (res) => (res.skipped.some((skipped) => skipped.id === userId) ? undefined : `got ${JSON.stringify(res)}`) + ); + await step("accessBundles.listGrantees", () => adminVault.accessBundles.listGrantees(bundle.id), (res) => + res.members.some((member) => member.id === agentId) ? undefined : "agent isn't a grantee" + ); + + console.log("\n== delegations =="); + await step("delegations.listAvailableSubjects (users)", () => + adminVault.delegations.listAvailableSubjects(agentId, { actorType: AgentVaultMemberType.User, search: userEmail }), + (res) => (res.members.some((member) => member.id === userId) ? undefined : "user isn't available") + ); + await step( + "delegations.set", + async () => { + const delegation = await adminVault.delegations.set(agentId, { scope: AgentVaultDelegationScope.Selected, userIds: [userId] }); + delegationSet = true; + return delegation; + }, + (delegation) => (delegation.users.some((user) => user.id === userId) ? undefined : `got ${JSON.stringify(delegation)}`) + ); + await step("delegations.get", () => adminVault.delegations.get(agentId), (delegation) => + Array.isArray(delegation.missingAccessBundles) ? undefined : "no missingAccessBundles" + ); + await step("delegations.list for the agent", () => adminVault.delegations.list({ machineIdentityIds: [agentId] }), (res) => + res.delegations.length === 1 ? undefined : `got ${res.delegations.length} delegations` + ); + await step("delegations.addSubjects skips a user it already names", () => + adminVault.delegations.addSubjects(agentId, { userIds: [userId] }), + (delegation) => (delegation.users.length === 1 ? undefined : `got ${delegation.users.length} users`) + ); + + console.log("\n== sessions on behalf of the user =="); + await step("accessBundles.list on behalf of the user", () => agentVault.accessBundles.list({ onBehalfOfUserEmail: userEmail }), (res) => + res.accessBundles.some((listed) => listed.id === bundle.id) ? undefined : "bundle not listed for the user" + ); + await expectRejection("sessions.create with both an email and an ID", () => + agentVault.sessions.create({ accessBundle: bundle.name, onBehalfOfUserEmail: userEmail, onBehalfOfUserId: userId }), + /not both/ + ); + const session = await step( + "sessions.create on behalf of the user", + async () => { + const res = await agentVault.sessions.create({ accessBundle: bundle.name, onBehalfOfUserEmail: userEmail, label: "node sdk check" }); + openSessionIds.add(res.id); + return res; + }, + (res) => { + const hours = (Date.parse(res.expiresAt ?? "") - Date.parse(res.createdAt)) / 3_600_000; + return res.token && Math.abs(hours - 1) < 0.05 ? undefined : `expires in ${hours} hours`; + } + ); + await step("sessions.get names the user", () => agentVault.sessions.get(session.id), (res) => + res.onBehalfOf?.id === userId ? undefined : `onBehalfOf is ${JSON.stringify(res.onBehalfOf)}` + ); + await step("sessions.list by the user's email", () => agentVault.sessions.list({ search: userEmail }), (res) => + res.sessions.some((listed) => listed.id === session.id) ? undefined : "session not listed" + ); + await step("sessions.update removes the label", () => agentVault.sessions.update(session.id, { label: null }), (res) => + res.label === null ? undefined : `label is ${JSON.stringify(res.label)}` + ); + await step( + "sessions.revoke", + async () => { + const revoked = await agentVault.sessions.revoke(session.id); + openSessionIds.delete(session.id); + return revoked; + }, + (res) => (res.status === "revoked" ? undefined : `status is ${res.status}`) + ); + + console.log("\n== inline services =="); + // Unique values, so a check can tell if one of them comes back in a response. + const token = `sdk-check-token-${suffix}`; + const headerValue = `sdk-check-team-${suffix}`; + const inlineService = { + type: "http" as const, + name: "httpbin", + hostPattern: "httpbin.org", + allowedMethods: ["GET" as const], + credential: { type: "bearer" as const, value: token }, + customHeaders: [{ name: "X-Team", value: headerValue }] + }; + const inline = await step( + "sessions.create with only inline services, as the admin", + async () => { + const res = await adminVault.sessions.create({ services: [inlineService], ttl: "15m", label: "node sdk inline check" }); + openSessionIds.add(res.id); + return res; + }, + (res) => { + const returned = JSON.stringify(res.services); + if (returned.includes(token) || returned.includes(headerValue)) return "the response includes a secret"; + const [service] = res.services; + return res.accessBundle === null && res.services.length === 1 && service.name === "httpbin" && service.credential.type === "bearer" + ? undefined + : `got ${JSON.stringify(res)}`; + } + ); + await step("sessions.get returns the inline services", () => adminVault.sessions.get(inline.id), (res) => + res.services.length === 1 && res.services[0].hostPattern === "httpbin.org" && res.services[0].customHeaders[0]?.name === "X-Team" + ? undefined + : `got ${JSON.stringify(res.services)}` + ); + const withBundle = await step( + "sessions.create with an access bundle and inline services, as the admin", + async () => { + const res = await adminVault.sessions.create({ + accessBundle: bundle.name, + services: [{ ...inlineService, name: "httpbin-eu", hostPattern: "eu.httpbin.org" }], + ttl: "15m" + }); + openSessionIds.add(res.id); + return res; + }, + (res) => (res.accessBundle?.name === bundle.name && res.services.length === 1 ? undefined : `got ${JSON.stringify(res)}`) + ); + // The agent is a member, not an admin. If the server lets it through anyway, the session is still revoked below. + await step( + "sessions.create with inline services as a member is refused", + async () => { + try { + const res = await agentVault.sessions.create({ services: [inlineService], ttl: "15m" }); + openSessionIds.add(res.id); + return "the session was created"; + } catch (err) { + return (err as Error).message; + } + }, + (outcome) => (/Only an Agent Vault admin can send services/.test(outcome) ? undefined : `got ${outcome}`) + ); + for (const created of [inline, withBundle]) { + await step( + `sessions.revoke ${created.label ?? created.id}`, + async () => { + const revoked = await adminVault.sessions.revoke(created.id); + openSessionIds.delete(created.id); + return revoked; + }, + (res) => (res.status === "revoked" ? undefined : `status is ${res.status}`) + ); + } + + console.log("\n== cleanup =="); + await step( + "delegations.removeSubjects of the last user returns null", + async () => { + const delegation = await adminVault.delegations.removeSubjects(agentId, { userIds: [userId] }); + if (delegation === null) delegationSet = false; + return delegation; + }, + (delegation) => (delegation === null ? undefined : `got ${JSON.stringify(delegation)}`) + ); + await step( + "delegations.addSubjects creates a delegation", + async () => { + const delegation = await adminVault.delegations.addSubjects(agentId, { userIds: [userId] }); + delegationSet = true; + return delegation; + }, + (delegation) => (delegation.scope === AgentVaultDelegationScope.Selected ? undefined : `scope is ${delegation.scope}`) + ); + await step("delegations.delete", async () => { + const deleted = await adminVault.delegations.delete(agentId); + delegationSet = false; + return deleted; + }); + await step("accessBundles.revoke", () => adminVault.accessBundles.revoke(bundle.id, { userIds: [userId], machineIdentityIds: [agentId] }), (res) => + res.members.length === 2 ? undefined : `got ${JSON.stringify(res)}` + ); + await step("accessBundles.delete", async () => { + const deleted = await adminVault.accessBundles.delete(bundle.id); + bundleId = undefined; + return deleted; + }); + + console.log("\nEvery Agent Vault flow worked."); + } catch (err) { + console.error(`FAIL ${(err as Error).message}`); + process.exitCode = 1; + } finally { + // Remove what a failed step left behind. If a removal fails too, name what's left so it can be removed by hand. + const leftovers: [string, () => Promise][] = []; + const leftBundle = bundleId; + const leftProxy = proxyId; + // The admin can revoke every session, including the agent's. + for (const id of openSessionIds) leftovers.push([`revoke session ${id}`, () => adminVault.sessions.revoke(id)]); + if (delegationSet) leftovers.push([`delete the delegation of machine identity ${agentId}`, () => adminVault.delegations.delete(agentId)]); + if (leftBundle) leftovers.push([`delete access bundle ${leftBundle}`, () => adminVault.accessBundles.delete(leftBundle)]); + if (leftProxy) leftovers.push([`delete proxy ${leftProxy}`, () => adminVault.proxies.delete(leftProxy)]); + + for (const [action, run] of leftovers) { + try { + await run(); + console.log(`ok cleanup: ${action}`); + } catch (err) { + console.error(`FAIL cleanup: couldn't ${action}, so do it by hand: ${(err as Error).message}`); + process.exitCode = 1; + } + } + } +})().catch((err) => { + console.error(`FAIL ${err.message}`); + process.exitCode = 1; +}); diff --git a/src/api/base.ts b/src/api/base.ts index 9c7c7de..9c51156 100644 --- a/src/api/base.ts +++ b/src/api/base.ts @@ -1,5 +1,5 @@ import { FetchHttpError } from "./fetch-errors"; -import { fetchWithRetry } from "./retry"; +import { FetchRetryOptions, fetchWithRetry, isConnectError } from "./retry"; export type HttpMethod = "GET" | "POST" | "PATCH" | "DELETE" | "PUT" | "OPTIONS" | "HEAD"; @@ -109,6 +109,28 @@ export class ApiClient { }); } + /** + * Makes a POST request that must not run twice, such as one that creates something. A network error is only + * retried if the connection never opened, so a lost response can't make the server handle the request again. + * A request that times out isn't retried, even if its connection stalled before opening, since both cases end + * in the same TimeoutError. A rate-limited (429) response is still retried, since the server turned the request + * away. + */ + public postOnce( + url: string, + data?: unknown, + config?: RequestConfig + ): Promise { + const { body, headers } = this.serializeBody(data, config); + return this.request( + "POST", + url, + body, + { ...config, headers }, + { shouldRetryError: isConnectError } + ); + } + public put( url: string, data?: unknown, @@ -141,6 +163,18 @@ export class ApiClient { }); } + /** Makes a DELETE request that must not run twice. It's retried in the same cases as postOnce. */ + public deleteOnce(url: string, config?: RequestConfig): Promise { + const { body, headers } = this.serializeBody(config?.data, config); + return this.request( + "DELETE", + url, + body, + { ...config, headers }, + { shouldRetryError: isConnectError } + ); + } + private serializeBody( data: unknown, config?: RequestConfig @@ -181,7 +215,8 @@ export class ApiClient { method: HttpMethod, url: string, body: string | undefined, - config?: RequestConfig + config?: RequestConfig, + retryOptions?: FetchRetryOptions ): Promise { const fullUrl = buildUrl(this.baseURL, url, config?.params); @@ -194,7 +229,14 @@ export class ApiClient { const doFetch = async (): Promise => { const controller = new AbortController(); - const timer = setTimeout(() => controller.abort(), timeoutMs); + // fetch rejects with the abort reason, so the error says the request timed out, and after how long. + const timer = setTimeout( + () => + controller.abort( + new DOMException(`The request timed out after ${timeoutMs / 1000} seconds`, "TimeoutError") + ), + timeoutMs + ); try { return await fetch(fullUrl, { method, @@ -207,7 +249,7 @@ export class ApiClient { } }; - const response = await fetchWithRetry(doFetch); + const response = await fetchWithRetry(doFetch, retryOptions); if (!response.ok) { throw new FetchHttpError( diff --git a/src/api/endpoints/agent-vault.ts b/src/api/endpoints/agent-vault.ts new file mode 100644 index 0000000..3bd7548 --- /dev/null +++ b/src/api/endpoints/agent-vault.ts @@ -0,0 +1,187 @@ +import { InfisicalSDKError } from "../../custom/errors"; +import { ApiClient } from "../base"; +import { + AgentVaultProxyWithTokenResponse, + ChangeAgentVaultAccessBundleGrantsRequest, + ChangeAgentVaultDelegationSubjectsRequest, + CreateAgentVaultAccessBundleRequest, + CreateAgentVaultProxyRequest, + CreateAgentVaultSessionRequest, + CreateAgentVaultSessionResponse, + DeleteAgentVaultDelegationResponse, + DeleteAgentVaultProxyResponse, + GetAgentVaultAccessBundleResponse, + GrantAgentVaultAccessBundleResponse, + ListAgentVaultAccessBundleMembersRequest, + ListAgentVaultAccessBundlesRequest, + ListAgentVaultAccessBundlesResponse, + ListAgentVaultDelegationsRequest, + ListAgentVaultDelegationsResponse, + ListAgentVaultGranteesResponse, + ListAgentVaultMembersResponse, + ListAgentVaultProxiesRequest, + ListAgentVaultProxiesResponse, + ListAgentVaultSessionsRequest, + ListAgentVaultSessionsResponse, + ListAvailableAgentVaultDelegationSubjectsRequest, + RemoveAgentVaultDelegationSubjectsResponse, + RevokeAgentVaultAccessBundleResponse, + RevokeAgentVaultSessionResponse, + SetAgentVaultDelegationRequest, + SingleAgentVaultAccessBundleResponse, + SingleAgentVaultDelegationResponse, + SingleAgentVaultProxyResponse, + SingleAgentVaultSessionResponse, + UpdateAgentVaultAccessBundleRequest, + UpdateAgentVaultProxyRequest, + UpdateAgentVaultSessionRequest +} from "../types/agent-vault"; + +const BASE_PATH = "/api/v1/agent-vault"; + +/** + * Encodes an ID as one path segment. fetch resolves "." and ".." like directories, so `accessBundles.revoke("..")` + * would reach the route that removes members from Agent Vault, which takes the same body. An empty ID would reach a + * route that isn't the one meant either, so all three are refused before any request. + */ +const segment = (id: string) => { + if (!id || id === "." || id === "..") { + throw new InfisicalSDKError(`Invalid ID ${JSON.stringify(id)}: an ID can't be empty, "." or ".."`); + } + return encodeURIComponent(id); +}; + +// Creates and token rotations use postOnce, so a network error after the request may have reached the server +// isn't retried: a retry could create a second proxy, session or access bundle, or rotate a token twice. Grants +// and revokes use postOnce and deleteOnce too: they report which grantees changed, so after a lost response, a +// retry would report each one as skipped. Deletes use deleteOnce as well: after a lost response, a retry would fail +// with a 404 for a delete that worked. +export class AgentVaultApi { + constructor(private apiClient: ApiClient) {} + + proxies = { + list: (params: ListAgentVaultProxiesRequest) => + this.apiClient.get(`${BASE_PATH}/proxies`, { params }), + + create: (data: CreateAgentVaultProxyRequest) => + this.apiClient.postOnce(`${BASE_PATH}/proxies`, data), + + update: (proxyId: string, data: UpdateAgentVaultProxyRequest) => + this.apiClient.patch(`${BASE_PATH}/proxies/${segment(proxyId)}`, data), + + delete: (proxyId: string) => + this.apiClient.deleteOnce(`${BASE_PATH}/proxies/${segment(proxyId)}`), + + rotateToken: (proxyId: string) => + this.apiClient.postOnce( + `${BASE_PATH}/proxies/${segment(proxyId)}/token-auth/proxy-token` + ), + + revoke: (proxyId: string) => + this.apiClient.post(`${BASE_PATH}/proxies/${segment(proxyId)}/revoke`) + }; + + sessions = { + list: (params: ListAgentVaultSessionsRequest) => + this.apiClient.get(`${BASE_PATH}/sessions`, { params }), + + get: (sessionId: string) => + this.apiClient.get(`${BASE_PATH}/sessions/${segment(sessionId)}`), + + create: (data: CreateAgentVaultSessionRequest) => + this.apiClient.postOnce(`${BASE_PATH}/sessions`, data), + + update: (sessionId: string, data: UpdateAgentVaultSessionRequest) => + this.apiClient.patch(`${BASE_PATH}/sessions/${segment(sessionId)}`, data), + + revoke: (sessionId: string) => + this.apiClient.post(`${BASE_PATH}/sessions/${segment(sessionId)}/revoke`) + }; + + accessBundles = { + list: (params: ListAgentVaultAccessBundlesRequest) => + this.apiClient.get(`${BASE_PATH}/access-bundles`, { params }), + + get: (accessBundleId: string) => + this.apiClient.get( + `${BASE_PATH}/access-bundles/${segment(accessBundleId)}` + ), + + create: (data: CreateAgentVaultAccessBundleRequest) => + this.apiClient.postOnce(`${BASE_PATH}/access-bundles`, data), + + update: (accessBundleId: string, data: UpdateAgentVaultAccessBundleRequest) => + this.apiClient.patch( + `${BASE_PATH}/access-bundles/${segment(accessBundleId)}`, + data + ), + + delete: (accessBundleId: string) => + this.apiClient.deleteOnce( + `${BASE_PATH}/access-bundles/${segment(accessBundleId)}` + ), + + listGrantees: (accessBundleId: string, params: ListAgentVaultAccessBundleMembersRequest) => + this.apiClient.get( + `${BASE_PATH}/access-bundles/${segment(accessBundleId)}/members`, + { params } + ), + + listAvailableGrantees: (accessBundleId: string, params: ListAgentVaultAccessBundleMembersRequest) => + this.apiClient.get( + `${BASE_PATH}/access-bundles/${segment(accessBundleId)}/members/available`, + { params } + ), + + grant: (accessBundleId: string, data: ChangeAgentVaultAccessBundleGrantsRequest) => + this.apiClient.postOnce( + `${BASE_PATH}/access-bundles/${segment(accessBundleId)}/members`, + data + ), + + revoke: (accessBundleId: string, data: ChangeAgentVaultAccessBundleGrantsRequest) => + this.apiClient.deleteOnce( + `${BASE_PATH}/access-bundles/${segment(accessBundleId)}/members`, + { data } + ) + }; + + delegations = { + list: (params: ListAgentVaultDelegationsRequest) => + this.apiClient.get(`${BASE_PATH}/delegations`, { params }), + + get: (machineIdentityId: string) => + this.apiClient.get( + `${BASE_PATH}/delegations/${segment(machineIdentityId)}` + ), + + set: (machineIdentityId: string, data: SetAgentVaultDelegationRequest) => + this.apiClient.put( + `${BASE_PATH}/delegations/${segment(machineIdentityId)}`, + data + ), + + delete: (machineIdentityId: string) => + this.apiClient.deleteOnce( + `${BASE_PATH}/delegations/${segment(machineIdentityId)}` + ), + + addSubjects: (machineIdentityId: string, data: ChangeAgentVaultDelegationSubjectsRequest) => + this.apiClient.post( + `${BASE_PATH}/delegations/${segment(machineIdentityId)}/subjects`, + data + ), + + removeSubjects: (machineIdentityId: string, data: ChangeAgentVaultDelegationSubjectsRequest) => + this.apiClient.deleteOnce( + `${BASE_PATH}/delegations/${segment(machineIdentityId)}/subjects`, + { data } + ), + + listAvailableSubjects: (machineIdentityId: string, params: ListAvailableAgentVaultDelegationSubjectsRequest) => + this.apiClient.get( + `${BASE_PATH}/delegations/${segment(machineIdentityId)}/subjects/available`, + { params } + ) + }; +} diff --git a/src/api/fetch-errors.ts b/src/api/fetch-errors.ts index c7c26d3..b77c1b2 100644 --- a/src/api/fetch-errors.ts +++ b/src/api/fetch-errors.ts @@ -10,12 +10,15 @@ export interface FetchHttpErrorResponse { export class FetchHttpError extends Error { public readonly name = "FetchHttpError"; - public readonly response: FetchHttpErrorResponse; - + /** + * The response, readable as before but not enumerable, so printing or logging this error, or an SDK error that has + * it as its cause, leaves out the body, which can be a whole HTML error page. + */ + declare public readonly response: FetchHttpErrorResponse; constructor(message: string, response: FetchHttpErrorResponse) { super(message); - this.response = response; + Object.defineProperty(this, "response", { value: response, enumerable: false }); } } diff --git a/src/api/retry.ts b/src/api/retry.ts index 06fb29b..1f68300 100644 --- a/src/api/retry.ts +++ b/src/api/retry.ts @@ -2,6 +2,8 @@ export interface FetchRetryOptions { maxRetries?: number; initialDelayMs?: number; backoffFactor?: number; + /** Whether to retry an error thrown by fetch, such as a network error. Defaults to retrying every one. */ + shouldRetryError?: (err: unknown) => boolean; } const DEFAULT_MAX_RETRIES = 4; @@ -9,6 +11,28 @@ const DEFAULT_INITIAL_DELAY_MS = 1000; const DEFAULT_BACKOFF_FACTOR = 2; const JITTER_FRACTION = 0.2; +// Raised before a connection opens, so the request never reached the server: a failed DNS lookup, a refused +// connection, an unreachable host or network, or undici's connect timeout. The connect timeout shows up only if it +// fires before the request timeout. With the SDK's 10-second request timeout, a stalled connection ends in the +// SDK's TimeoutError instead, which can't be retried safely, since a timeout looks the same whether or not the +// request was sent. +const CONNECT_ERROR_CODES = new Set([ + "ENOTFOUND", + "EAI_AGAIN", + "ECONNREFUSED", + "EHOSTUNREACH", + "ENETUNREACH", + "UND_ERR_CONNECT_TIMEOUT", +]); + +/** Whether a fetch error was raised before the request could reach the server, so retrying it can't make the server handle it twice. */ +export const isConnectError = (err: unknown): boolean => { + // Node's fetch throws a TypeError with the network error as its cause. Other fetch implementations throw the network error itself. + const networkError = (err as { cause?: unknown } | null | undefined)?.cause ?? err; + const code = (networkError as { code?: unknown } | null | undefined)?.code; + return typeof code === "string" && CONNECT_ERROR_CODES.has(code); +}; + const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); @@ -25,6 +49,7 @@ export const fetchWithRetry = async ( const initialDelayMs = opts.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS; const backoffFactor = opts.backoffFactor ?? DEFAULT_BACKOFF_FACTOR; + const shouldRetryError = opts.shouldRetryError ?? (() => true); const delayFor = (attempt: number): number => { const base = initialDelayMs * Math.pow(backoffFactor, attempt - 1); @@ -47,7 +72,7 @@ export const fetchWithRetry = async ( return response; } catch (err) { attempt++; - if (attempt > maxRetries) throw err; + if (attempt > maxRetries || !shouldRetryError(err)) throw err; await sleep(delayFor(attempt)); } } diff --git a/src/api/types/agent-vault.ts b/src/api/types/agent-vault.ts new file mode 100644 index 0000000..ec15dca --- /dev/null +++ b/src/api/types/agent-vault.ts @@ -0,0 +1,807 @@ +// Infisical Agent Vault: proxies, sessions, access bundles and delegations. +// Timestamps are ISO 8601 strings, as the API sends them. + +/** Which hosts an agent may reach through an Agent Vault proxy. */ +export enum AgentVaultTrafficPolicy { + /** Agents can reach any host. */ + AnyHost = "any-host", + /** Agents can reach only the hosts that the session's services cover, plus the proxy's allowed hosts. */ + ServiceHosts = "service-hosts" +} + +/** The status of an Agent Vault session. */ +export enum AgentVaultSessionStatus { + Active = "active", + Revoked = "revoked", + Expired = "expired" +} + +/** Whose Agent Vault sessions to list. */ +export enum AgentVaultSessionScope { + Mine = "mine", + All = "all" +} + +/** The kinds of Agent Vault member: users, machine identities and groups. */ +export enum AgentVaultMemberType { + User = "user", + MachineIdentity = "machineIdentity", + Group = "group" +} + +/** Which users a machine identity can create Agent Vault sessions on behalf of. */ +export enum AgentVaultDelegationScope { + AllMembers = "all-members", + Selected = "selected" +} + +export type AgentVaultOrderDirection = "asc" | "desc"; + +// Proxies + +/** An Agent Vault proxy. Only admins see its settings: trafficPolicy, allowedHosts, pollInterval and createdAt. */ +export interface AgentVaultProxy { + id: string; + name: string; + /** What the proxy is for, or null if it has no description. */ + description: string | null; + /** When the proxy last checked in, or null if it never has. */ + heartbeat: string | null; + /** Whether the proxy has checked in recently enough to be considered up. */ + isHealthy: boolean; + /** The SHA-256 fingerprint of the proxy's certificate authority. */ + rootCaFingerprint: string | null; + /** When the proxy's certificate authority expires. */ + rootCaExpiresAt: string | null; + trafficPolicy?: AgentVaultTrafficPolicy; + /** Hosts that stay reachable under the "service-hosts" traffic policy, as one comma-separated string. */ + allowedHosts?: string | null; + /** How often, in seconds, the proxy refreshes its sessions and settings. */ + pollInterval?: number; + createdAt?: string; +} + +/** An Agent Vault proxy with its settings, as admins see it. */ +export interface AgentVaultProxyWithSettings extends AgentVaultProxy { + trafficPolicy: AgentVaultTrafficPolicy; + allowedHosts: string | null; + pollInterval: number; + createdAt: string; +} + +export interface AgentVaultProxyWithTokenResponse { + proxy: AgentVaultProxyWithSettings; + /** The proxy token. It's only returned once. */ + proxyToken: string; +} + +export interface ListAgentVaultProxiesResponse { + proxies: AgentVaultProxy[]; + totalCount: number; +} + +export interface SingleAgentVaultProxyResponse { + proxy: AgentVaultProxyWithSettings; +} + +export interface DeleteAgentVaultProxyResponse { + proxy: Pick; +} + +// Sessions + +/** The user an Agent Vault session belongs to, or the user it was started on behalf of. */ +export interface AgentVaultSessionUser { + type: AgentVaultMemberType.User; + /** The ID of the user, or null once the user is deleted. */ + id: string | null; + /** The username of the user. Once the user is deleted, the email address recorded when the session was created. */ + username: string; + email: string | null; + firstName: string | null; + /** The last name of the user, or null once the user is deleted. */ + lastName: string | null; +} + +/** The machine identity an Agent Vault session belongs to. */ +export interface AgentVaultSessionMachineIdentity { + type: AgentVaultMemberType.MachineIdentity; + /** The ID of the machine identity, or null once it's deleted. */ + id: string | null; + /** The name of the machine identity. Once it's deleted, the name recorded when the session was created. */ + name: string; +} + +/** The user or machine identity an Agent Vault session belongs to. */ +export type AgentVaultSessionActor = AgentVaultSessionUser | AgentVaultSessionMachineIdentity; + +/** The access bundle an Agent Vault session carries. */ +export interface AgentVaultSessionAccessBundle { + /** The ID of the access bundle, or null once it's deleted. */ + id: string | null; + name: string; +} + +// Inline services: services sent with a session, instead of added to an access bundle. Their values are sent exactly +// as given, since inline services can't use variables, so no value can contain text in double braces. + +/** An HTTP method that a service can allow. */ +export type AgentVaultHttpMethod = "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS"; + +/** A part of a request where the proxy replaces a substitution's placeholder with its value. */ +export type AgentVaultSubstitutionSurface = "path" | "query" | "header" | "body"; + +/** How an agent talks to an MCP server: "streamable-http", or "sse" for the legacy HTTP+SSE transport. */ +export type AgentVaultMcpTransport = "streamable-http" | "sse"; + +/** A token that the proxy writes to a header of each request. */ +export interface AgentVaultInlineBearerCredential { + type: "bearer"; + /** The token. */ + value: string; + /** The header the token is written to. Defaults to "Authorization". */ + headerName?: string; + /** Written before the token, separated by one space. Defaults to "Bearer" for the Authorization header, and to nothing for any other header. */ + headerPrefix?: string; +} + +/** A username and password that the proxy sends as HTTP basic authentication. Set a username, a password, or both. */ +export interface AgentVaultInlineBasicCredential { + type: "basic"; + username?: string; + password?: string; +} + +/** No credential: the proxy lets requests to the service's hosts through without attaching one. */ +export interface AgentVaultInlinePassthroughCredential { + type: "passthrough"; +} + +/** A header that the proxy attaches to each request, besides the credential. */ +export interface AgentVaultInlineCustomHeader { + name: string; + /** Written before the value, separated by one space. */ + prefix?: string; + value: string; +} + +/** A placeholder that the proxy replaces with a real value before forwarding a request. */ +export interface AgentVaultInlineSubstitution { + placeholder: string; + /** The parts of each request where the proxy replaces the placeholder. */ + surfaces: AgentVaultSubstitutionSurface[]; + value: string; +} + +/** An HTTP API sent with a session. */ +export interface AgentVaultInlineHttpServiceInput { + type: "http"; + /** A name for the service, in lowercase letters, numbers and hyphens. Without one, the service goes by its first host. */ + name?: string; + /** The hosts the service covers, separated by commas, such as "api.github.com". A leading "*." matches exactly one label. */ + hostPattern: string; + /** The HTTP methods the service allows. Defaults to every method. */ + allowedMethods?: AgentVaultHttpMethod[]; + /** The path prefixes the service allows, matched on whole segments. Defaults to every path. */ + allowedPathPrefixes?: string[]; + credential: AgentVaultInlineBearerCredential | AgentVaultInlineBasicCredential | AgentVaultInlinePassthroughCredential; + /** Up to 20. */ + customHeaders?: AgentVaultInlineCustomHeader[]; + /** Up to 20. */ + substitutions?: AgentVaultInlineSubstitution[]; +} + +/** An MCP server sent with a session. */ +export interface AgentVaultInlineMcpServiceInput { + type: "mcp"; + /** A name for the service, in lowercase letters, numbers and hyphens. Without one, the service goes by its host. */ + name?: string; + /** The MCP server's URL, such as "https://mcp.example.com/mcp". The service covers its host. */ + serverUrl: string; + transport: AgentVaultMcpTransport; + credential: AgentVaultInlineBearerCredential; + /** Up to 20. */ + customHeaders?: AgentVaultInlineCustomHeader[]; +} + +/** A service sent with a session: an HTTP API or an MCP server. */ +export type AgentVaultInlineServiceInput = AgentVaultInlineHttpServiceInput | AgentVaultInlineMcpServiceInput; + +/** A service sent with a session, as Infisical returns it: without its token, password or values. */ +export interface AgentVaultInlineService { + id: string; + /** The name the service was sent with, or its first host if it was sent without one. */ + name: string; + type: "http" | "mcp"; + serverUrl: string | null; + transport: AgentVaultMcpTransport | null; + hostPattern: string; + /** The HTTP methods the service allows, or null for every method. */ + allowedMethods: AgentVaultHttpMethod[] | null; + /** The path prefixes the service allows, or null for every path. */ + allowedPathPrefixes: string[] | null; + credential: { type: "bearer"; headerName: string; headerPrefix: string } | { type: "basic" } | { type: "passthrough" }; + customHeaders: { name: string; prefix: string }[]; + substitutions: { placeholder: string; surfaces: AgentVaultSubstitutionSurface[] }[]; +} + +export interface AgentVaultSession { + id: string; + label: string | null; + actor: AgentVaultSessionActor; + /** The user the session was started on behalf of, or null when the session is the actor's own. */ + onBehalfOf: AgentVaultSessionUser | null; + status: AgentVaultSessionStatus; + /** When the session expires, or null when it never does. */ + expiresAt: string | null; + revokedAt: string | null; + createdAt: string; + /** The access bundle the session carries, or null if it carries only inline services. */ + accessBundle: AgentVaultSessionAccessBundle | null; + /** The services sent with the session when it was created, without their secrets. Empty if it carries only an access bundle. */ + services: AgentVaultInlineService[]; +} + +/** An Agent Vault session as returned at creation. */ +export interface CreatedAgentVaultSession { + id: string; + label: string | null; + /** The session token. It's only returned once. */ + token: string; + /** When the session expires, or null when it never does. */ + expiresAt: string | null; + createdAt: string; + /** The access bundle the session carries, or null if it carries only inline services. */ + accessBundle: AgentVaultSessionAccessBundle | null; + /** The services sent with the session, without their secrets. Empty if it carries only an access bundle. */ + services: AgentVaultInlineService[]; +} + +export interface ListAgentVaultSessionsResponse { + sessions: AgentVaultSession[]; + totalCount: number; +} + +export interface SingleAgentVaultSessionResponse { + session: AgentVaultSession; +} + +export interface CreateAgentVaultSessionResponse { + session: CreatedAgentVaultSession; +} + +export interface RevokeAgentVaultSessionResponse { + /** The revoked session. The response leaves out its access bundle and inline services. */ + session: Omit; +} + +// Access bundles + +/** An Agent Vault service, by ID and name. */ +export interface AgentVaultServiceRef { + id: string; + name: string; +} + +/** An Agent Vault access bundle, by ID and name. */ +export interface AgentVaultAccessBundleRef { + id: string; + name: string; +} + +export interface AgentVaultAccessBundle { + id: string; + name: string; + /** What the access bundle is for, or null if it has no description. */ + description?: string | null; + createdAt: string; + updatedAt: string; +} + +/** An Agent Vault access bundle as listed, with what it holds. */ +export interface AgentVaultAccessBundleSummary extends AgentVaultAccessBundle { + /** How many services the access bundle holds. */ + serviceCount: number; + /** How many users, machine identities and groups can reach the access bundle. */ + memberCount: number; + /** Every host pattern the access bundle's services cover. */ + hostPatterns: string[]; + /** The services that still need your personal values, or, when listed on behalf of a user, that user's. */ + servicesRequiringSetup: AgentVaultServiceRef[]; +} + +/** + * A service in an Agent Vault access bundle. The SDK doesn't manage services, so a service's nested + * settings, such as its credential, are left as the API returns them. + */ +export interface AgentVaultService { + id: string; + accessBundleId: string; + name: string; + /** The kind of service, such as "http" or "mcp". */ + type: string; + serverUrl: string | null; + transport: string | null; + hostPattern: string; + allowedMethods: string[] | null; + allowedPathPrefixes: string[] | null; + /** The MCP tools that agents can call through the service, by exact name, or null for every tool. */ + allowedTools?: string[] | null; + credential: Record; + customHeaders: Record[]; + substitutions: Record[]; + /** Only set for admins. */ + variableReferences?: Record[]; + /** Your own values for the service, or null when the admin sets the whole credential. */ + personalValues: Record | null; + createdAt: string; + updatedAt: string; +} + +/** An Agent Vault access bundle with its services. */ +export interface AgentVaultAccessBundleWithServices extends AgentVaultAccessBundle { + services: AgentVaultService[]; +} + +export interface ListAgentVaultAccessBundlesResponse { + accessBundles: AgentVaultAccessBundleSummary[]; + totalCount: number; +} + +export interface GetAgentVaultAccessBundleResponse { + accessBundle: AgentVaultAccessBundleWithServices; +} + +export interface SingleAgentVaultAccessBundleResponse { + accessBundle: AgentVaultAccessBundle; +} + +// Grants and members + +/** A user, machine identity or group, by type and ID. */ +export interface AgentVaultActorRef { + type: AgentVaultMemberType; + id: string; +} + +export interface AgentVaultUser { + type: AgentVaultMemberType.User; + id: string; + username: string; + email: string | null; + firstName: string | null; + lastName: string | null; +} + +export interface AgentVaultMachineIdentity { + type: AgentVaultMemberType.MachineIdentity; + id: string; + name: string; +} + +export interface AgentVaultGroup { + type: AgentVaultMemberType.Group; + id: string; + name: string; +} + +/** A user, machine identity or group that an Agent Vault access bundle is granted to. */ +export type AgentVaultGrantee = ( + | (AgentVaultUser & { + /** Whether the user still has an unaccepted invitation to the organization. */ + isOrgMembershipPending: boolean; + }) + | AgentVaultMachineIdentity + | AgentVaultGroup +) & { + /** When the access bundle was granted. */ + grantedAt: string; +}; + +/** A user, machine identity or group that's a member of Agent Vault, with its Agent Vault role. */ +export type AgentVaultMember = ( + | (AgentVaultUser & { + /** Whether the user still has an unaccepted invitation to the organization. */ + isOrgMembershipPending: boolean; + }) + | (AgentVaultMachineIdentity & { + /** Whether Agent Vault created the machine identity. */ + isManagedByAgentVault: boolean; + /** The ID of the organization the machine identity belongs to. */ + orgId: string | null; + }) + | AgentVaultGroup +) & { + /** The Agent Vault role, such as "admin" or "member". */ + role: string; + /** Whether the member can currently reach Agent Vault. */ + isActive: boolean; + /** When the member was added to Agent Vault. */ + addedAt: string; +}; + +export interface ListAgentVaultGranteesResponse { + members: AgentVaultGrantee[]; + totalCount: number; +} + +export interface ListAgentVaultMembersResponse { + members: AgentVaultMember[]; + totalCount: number; +} + +export interface GrantAgentVaultAccessBundleResponse { + /** The new grants. */ + members: (AgentVaultActorRef & { grantedAt: string })[]; + /** The grantees that already had the access bundle, left as they were. */ + skipped: AgentVaultActorRef[]; +} + +export interface RevokeAgentVaultAccessBundleResponse { + /** The revoked grants. */ + members: AgentVaultActorRef[]; + /** The grantees that didn't have the access bundle, so nothing was revoked. */ + skipped: AgentVaultActorRef[]; +} + +// Delegations + +export interface AgentVaultDelegationUser { + id: string; + username: string; + email: string | null; + firstName: string | null; + lastName: string | null; + /** When the user was added to the delegation. */ + addedAt: string; +} + +/** A group in an Agent Vault delegation. Its members are covered while they stay in the group. */ +export interface AgentVaultDelegationGroup { + id: string; + name: string; + /** When the group was added to the delegation. */ + addedAt: string; +} + +/** Which users a machine identity can create Agent Vault sessions on behalf of. */ +export interface AgentVaultDelegation { + machineIdentity: { id: string; name: string }; + scope: AgentVaultDelegationScope; + users: AgentVaultDelegationUser[]; + groups: AgentVaultDelegationGroup[]; + createdAt: string; + updatedAt: string; +} + +/** + * An Agent Vault delegation with the access bundles its machine identity can't create sessions over. A session on + * behalf of a user can use only an access bundle that both the user and the machine identity can use. The lists are + * empty when a machine identity that isn't an admin gets its own delegation. + */ +export interface AgentVaultDelegationDetail extends AgentVaultDelegation { + users: (AgentVaultDelegationUser & { + /** The access bundles this user can use and the machine identity can't. */ + missingAccessBundles: AgentVaultAccessBundleRef[]; + })[]; + groups: (AgentVaultDelegationGroup & { + /** The access bundles this group can use and the machine identity can't. */ + missingAccessBundles: AgentVaultAccessBundleRef[]; + })[]; + /** The access bundles that users the delegation covers can use and the machine identity can't. */ + missingAccessBundles: AgentVaultAccessBundleRef[]; +} + +export interface ListAgentVaultDelegationsResponse { + delegations: AgentVaultDelegation[]; + totalCount: number; +} + +export interface SingleAgentVaultDelegationResponse { + delegation: AgentVaultDelegationDetail; +} + +export interface DeleteAgentVaultDelegationResponse { + delegation: AgentVaultDelegation; +} + +export interface RemoveAgentVaultDelegationSubjectsResponse { + /** The delegation after the change, or null if it no longer names anyone. */ + delegation: AgentVaultDelegationDetail | null; +} + +// Requests, as sent to the API + +export interface ListAgentVaultProxiesRequest { + search?: string; + orderBy: "name" | "createdAt"; + orderDirection: AgentVaultOrderDirection; + limit: number; + offset: number; +} + +export interface CreateAgentVaultProxyRequest { + name: string; + /** "bundle-hosts" is the old name of "service-hosts", and the only one an Infisical version from before the rename accepts. */ + trafficPolicy: AgentVaultTrafficPolicy | `${AgentVaultTrafficPolicy}` | "bundle-hosts"; + allowedHosts?: string; + pollInterval: number; + description?: string; +} + +export interface UpdateAgentVaultProxyRequest { + name?: string; + /** "bundle-hosts" is the old name of "service-hosts", and the only one an Infisical version from before the rename accepts. */ + trafficPolicy?: AgentVaultTrafficPolicy | `${AgentVaultTrafficPolicy}` | "bundle-hosts"; + /** null removes every allowed host. */ + allowedHosts?: string | null; + pollInterval?: number; + description?: string; +} + +export interface ListAgentVaultSessionsRequest { + scope: AgentVaultSessionScope | `${AgentVaultSessionScope}`; + /** Statuses, separated by commas. */ + status?: string; + search?: string; + limit: number; + offset: number; +} + +export interface CreateAgentVaultSessionRequest { + accessBundle?: string; + services?: AgentVaultInlineServiceInput[]; + ttl?: string; + label?: string; + onBehalfOf?: { userEmail: string } | { userId: string }; +} + +export interface UpdateAgentVaultSessionRequest { + label: string | null; +} + +export interface ListAgentVaultAccessBundlesRequest { + search?: string; + requiresSetup?: boolean; + granted?: boolean; + onBehalfOfUserEmail?: string; + onBehalfOfUserId?: string; + orderBy: "name" | "serviceCount" | "createdAt"; + orderDirection: AgentVaultOrderDirection; + limit: number; + offset: number; +} + +export interface CreateAgentVaultAccessBundleRequest { + name: string; + description?: string; +} + +export interface UpdateAgentVaultAccessBundleRequest { + name?: string; + description?: string; +} + +export interface ListAgentVaultAccessBundleMembersRequest { + actorType?: AgentVaultMemberType | `${AgentVaultMemberType}`; + search?: string; + limit: number; + offset: number; +} + +export interface ChangeAgentVaultAccessBundleGrantsRequest { + userIds?: string[]; + machineIdentityIds?: string[]; + groupIds?: string[]; +} + +export interface ListAgentVaultDelegationsRequest { + /** Machine identity IDs, separated by commas. */ + machineIdentityIds?: string; + limit: number; + offset: number; +} + +export interface SetAgentVaultDelegationRequest { + scope: AgentVaultDelegationScope | `${AgentVaultDelegationScope}`; + userIds?: string[]; + groupIds?: string[]; +} + +export interface ChangeAgentVaultDelegationSubjectsRequest { + userIds?: string[]; + groupIds?: string[]; +} + +export interface ListAvailableAgentVaultDelegationSubjectsRequest { + actorType?: AgentVaultMemberType.User | AgentVaultMemberType.Group | "user" | "group"; + search?: string; + limit: number; + offset: number; +} + +// Options for the SDK's Agent Vault methods + +export type ListAgentVaultProxiesOptions = { + /** Match proxies by name or description. */ + search?: string; + /** What to sort proxies by. Defaults to "createdAt". */ + orderBy?: "name" | "createdAt"; + /** Which way to sort. Defaults to "desc". */ + orderDirection?: AgentVaultOrderDirection; + /** The maximum number of proxies to return (1-100). Defaults to 20. */ + limit?: number; + /** How many proxies to skip. Defaults to 0. */ + offset?: number; +}; + +export type CreateAgentVaultProxyOptions = { + /** The name of the proxy (a slug, at most 64 characters). */ + name: string; + /** Which hosts an agent may reach through this proxy: "any-host", or "service-hosts" for only the hosts that the session's services cover. Defaults to "any-host". */ + trafficPolicy?: AgentVaultTrafficPolicy | `${AgentVaultTrafficPolicy}`; + /** Hosts that stay reachable under the "service-hosts" traffic policy even though none of the session's services cover them. A list or a comma-separated string. */ + allowedHosts?: string | string[]; + /** How often, in seconds, the proxy refreshes its sessions and settings (10-300). Defaults to 60. */ + pollInterval?: number; + /** What the proxy is for, up to 256 characters, without line breaks or other control characters. */ + description?: string; +}; + +export type UpdateAgentVaultProxyOptions = { + /** The new name of the proxy (a slug, at most 64 characters). */ + name?: string; + /** Which hosts an agent may reach through this proxy: "any-host", or "service-hosts" for only the hosts that the session's services cover. */ + trafficPolicy?: AgentVaultTrafficPolicy | `${AgentVaultTrafficPolicy}`; + /** Hosts that stay reachable under the "service-hosts" traffic policy. A list or a comma-separated string. Pass an empty list or string to remove every allowed host. */ + allowedHosts?: string | string[]; + /** How often, in seconds, the proxy refreshes its sessions and settings (10-300). */ + pollInterval?: number; + /** The new description, up to 256 characters, without line breaks or other control characters. Pass an empty string to remove the description. */ + description?: string; +}; + +export type ListAgentVaultSessionsOptions = { + /** Whose sessions to list: your own ("mine") or everyone's ("all", admins only). Defaults to "mine". */ + scope?: AgentVaultSessionScope | `${AgentVaultSessionScope}`; + /** Only return sessions with any of these statuses. */ + statuses?: (AgentVaultSessionStatus | `${AgentVaultSessionStatus}`)[]; + /** Match sessions by label, actor name, actor email, the name or email of the user a session was started on behalf of, or access bundle name. */ + search?: string; + /** The maximum number of sessions to return (1-100). Defaults to 20. */ + limit?: number; + /** How many sessions to skip. Defaults to 0. */ + offset?: number; +}; + +export type CreateAgentVaultSessionOptions = { + /** The name of the access bundle the session carries. Pass accessBundle, services, or both. */ + accessBundle?: string; + /** + * Services the session carries itself, instead of or beside its access bundle's: up to 20. Only Agent Vault admins + * can send them. Each has the same fields as a service in an access bundle, except that its name is optional, its + * values can't use variables, it can't use OAuth or member-provided values, and an MCP server can't be limited to + * some of its tools. To limit an MCP server's tools, add it to an access bundle instead. + */ + services?: AgentVaultInlineServiceInput[]; + /** How long the session lasts: a duration such as "30m", "8h" or "7d" (at least 1m), or "never". Defaults to "7d", or to "1h" for a session on behalf of a user. */ + ttl?: string; + /** A short description of what the session is for, such as "nightly deploy". Up to 128 characters, without line breaks, tabs, or invisible characters. */ + label?: string; + /** The email address of the user to start the session on behalf of. Can't be combined with onBehalfOfUserId. */ + onBehalfOfUserEmail?: string; + /** The ID of the user to start the session on behalf of. Can't be combined with onBehalfOfUserEmail. */ + onBehalfOfUserId?: string; +}; + +export type UpdateAgentVaultSessionOptions = { + /** The new label, up to 128 characters, without line breaks, tabs, or invisible characters. Pass null or an empty string to remove the label. You can't change the label once the session's owner, or the user it was started on behalf of, is deleted. */ + label: string | null; +}; + +export type ListAgentVaultAccessBundlesOptions = { + /** Match access bundles by name or description. */ + search?: string; + /** true lists only the access bundles with services that still need your personal values, and false lists the rest. Defaults to both. */ + requiresSetup?: boolean; + /** true lists only the access bundles granted to you, directly or through a group, and false lists the ones you reach only as an admin. Defaults to both. Can't be combined with onBehalfOfUserEmail or onBehalfOfUserId. */ + granted?: boolean; + /** As a machine identity whose delegation covers the user with this email address, list the access bundles that a session on the user's behalf could use: those both the user and your machine identity can use. requiresSetup and servicesRequiringSetup then refer to the user's personal values. Can't be combined with onBehalfOfUserId. */ + onBehalfOfUserEmail?: string; + /** Like onBehalfOfUserEmail, naming the user by ID instead. Can't be combined with onBehalfOfUserEmail. */ + onBehalfOfUserId?: string; + /** What to sort access bundles by. Defaults to "createdAt". */ + orderBy?: "name" | "serviceCount" | "createdAt"; + /** Which way to sort. Defaults to "desc". */ + orderDirection?: AgentVaultOrderDirection; + /** The maximum number of access bundles to return (1-100). Defaults to 20. */ + limit?: number; + /** How many access bundles to skip. Defaults to 0. */ + offset?: number; +}; + +export type CreateAgentVaultAccessBundleOptions = { + /** The name of the access bundle (a slug, at most 64 characters). */ + name: string; + /** What the access bundle is for, up to 256 characters, without line breaks or other control characters. */ + description?: string; +}; + +export type UpdateAgentVaultAccessBundleOptions = { + /** The new name of the access bundle (a slug, at most 64 characters). */ + name?: string; + /** The new description, up to 256 characters, without line breaks or other control characters. Pass an empty string to remove the description. */ + description?: string; +}; + +export type ListAgentVaultGranteesOptions = { + /** List only users, only machine identities, or only groups. Defaults to all three. */ + actorType?: AgentVaultMemberType | `${AgentVaultMemberType}`; + /** Match by name, username or email address. */ + search?: string; + /** The maximum number to return (1-100). Defaults to 20. */ + limit?: number; + /** How many to skip. Defaults to 0. */ + offset?: number; +}; + +export type GrantAgentVaultAccessBundleOptions = { + /** The IDs of the users to grant the access bundle to. */ + userIds?: string[]; + /** The IDs of the machine identities to grant the access bundle to. */ + machineIdentityIds?: string[]; + /** The IDs of the groups to grant the access bundle to. */ + groupIds?: string[]; +}; + +export type RevokeAgentVaultAccessBundleOptions = { + /** The IDs of the users to revoke the access bundle from. */ + userIds?: string[]; + /** The IDs of the machine identities to revoke the access bundle from. */ + machineIdentityIds?: string[]; + /** The IDs of the groups to revoke the access bundle from. */ + groupIds?: string[]; +}; + +export type ListAgentVaultDelegationsOptions = { + /** Only return the delegations of these machine identities, up to 100. */ + machineIdentityIds?: string[]; + /** The maximum number of delegations to return (1-100). Defaults to 100. */ + limit?: number; + /** How many delegations to skip. Defaults to 0. */ + offset?: number; +}; + +export type SetAgentVaultDelegationOptions = { + /** "all-members" for every Agent Vault member, admins included, or "selected" for only the users and groups you name. */ + scope: AgentVaultDelegationScope | `${AgentVaultDelegationScope}`; + /** With the "selected" scope, the users the machine identity can act on behalf of, up to 100. Each must be a member of Agent Vault. For a user who's in Agent Vault only through a group, name the group instead. */ + userIds?: string[]; + /** With the "selected" scope, the groups whose members the machine identity can act on behalf of, up to 100. Each must be a member of Agent Vault. */ + groupIds?: string[]; +}; + +export type AddAgentVaultDelegationSubjectsOptions = { + /** The users to add, up to 100. Each must be a member of Agent Vault. Users the delegation already names are skipped. */ + userIds?: string[]; + /** The groups to add, up to 100. Each must be a member of Agent Vault. Groups the delegation already names are skipped. */ + groupIds?: string[]; +}; + +export type RemoveAgentVaultDelegationSubjectsOptions = { + /** The users to take out, up to 100. Users the delegation doesn't name are skipped. */ + userIds?: string[]; + /** The groups to take out, up to 100. Groups the delegation doesn't name are skipped. */ + groupIds?: string[]; +}; + +export type ListAvailableAgentVaultDelegationSubjectsOptions = { + /** List only users or only groups. Defaults to both. */ + actorType?: AgentVaultMemberType.User | AgentVaultMemberType.Group | "user" | "group"; + /** Match users by name, username or email address, and groups by name. */ + search?: string; + /** The maximum number of users and groups to return (1-100). Defaults to 20. */ + limit?: number; + /** How many users and groups to skip. Defaults to 0. */ + offset?: number; +}; diff --git a/src/api/types/index.ts b/src/api/types/index.ts index 7a03cd9..e811631 100644 --- a/src/api/types/index.ts +++ b/src/api/types/index.ts @@ -7,6 +7,7 @@ export * from "./environments"; export * from "./projects"; export * from "./folders"; export * from "./kms"; +export * from "./agent-vault"; export interface ApiResponse { statusCode: number; diff --git a/src/custom/agent-vault.ts b/src/custom/agent-vault.ts new file mode 100644 index 0000000..b50faa3 --- /dev/null +++ b/src/custom/agent-vault.ts @@ -0,0 +1,480 @@ +import { AgentVaultApi } from "../api/endpoints/agent-vault"; +import { + AddAgentVaultDelegationSubjectsOptions, + AgentVaultInlineService, + AgentVaultSessionScope, + AgentVaultTrafficPolicy, + CreateAgentVaultAccessBundleOptions, + CreateAgentVaultProxyOptions, + CreateAgentVaultSessionOptions, + CreateAgentVaultSessionRequest, + GrantAgentVaultAccessBundleOptions, + ListAgentVaultAccessBundlesOptions, + ListAgentVaultDelegationsOptions, + ListAgentVaultGranteesOptions, + ListAgentVaultProxiesOptions, + ListAgentVaultSessionsOptions, + ListAvailableAgentVaultDelegationSubjectsOptions, + RemoveAgentVaultDelegationSubjectsOptions, + RevokeAgentVaultAccessBundleOptions, + SetAgentVaultDelegationOptions, + UpdateAgentVaultAccessBundleOptions, + UpdateAgentVaultProxyOptions, + UpdateAgentVaultSessionOptions +} from "../api/types/agent-vault"; +import { InfisicalSDKError, newInfisicalError } from "./errors"; + +const isSet = (value: T | null | undefined): value is T => value !== undefined && value !== null; + +/** The API takes host patterns as one comma-separated string and rejects an empty one, so an empty value becomes null. */ +const joinHosts = (allowedHosts: string | string[] | undefined): string | null | undefined => { + if (!isSet(allowedHosts)) return undefined; + const hosts = Array.isArray(allowedHosts) ? allowedHosts.join(",") : allowedHosts; + return hosts.trim() ? hosts : null; +}; + +/** The API takes a list in a query parameter as one comma-separated string. */ +const joinList = (values: string[] | undefined) => (values?.length ? values.join(",") : undefined); + +/** + * The old name of service-hosts. Infisical stores service-hosts under this name and still accepts it, while a version + * from before the rename accepts and returns only this name. + */ +const SERVICE_HOSTS_OLD_NAME = "bundle-hosts"; + +/** Sends service-hosts by its old name, which every Infisical version accepts. */ +const toWireTrafficPolicy = (trafficPolicy: AgentVaultTrafficPolicy | `${AgentVaultTrafficPolicy}` | undefined) => + trafficPolicy === AgentVaultTrafficPolicy.ServiceHosts ? SERVICE_HOSTS_OLD_NAME : trafficPolicy; + +/** Reports the old name, which an Infisical version from before the rename returns, as service-hosts. */ +const viewProxy = (proxy: T): T => + (proxy.trafficPolicy as string | undefined) === SERVICE_HOSTS_OLD_NAME + ? { ...proxy, trafficPolicy: AgentVaultTrafficPolicy.ServiceHosts } + : proxy; + +/** Gives a session from an Infisical version without inline services an empty list of them, rather than none. */ +const withServices = (session: T): T => + session.services ? session : { ...session, services: [] }; + +/** The API names a user by email address or by ID, not both. */ +const checkOneUser = (onBehalfOfUserEmail: string | undefined, onBehalfOfUserId: string | undefined) => { + if (isSet(onBehalfOfUserEmail) && isSet(onBehalfOfUserId)) { + throw new InfisicalSDKError("Pass either onBehalfOfUserEmail or onBehalfOfUserId, not both"); + } +}; + +/** Runs an Agent Vault request and turns any failure into an Infisical SDK error. */ +const run = async (request: () => Promise): Promise => { + try { + return await request(); + } catch (err) { + throw newInfisicalError(err); + } +}; + +/** Manages Infisical Agent Vault. */ +export default class AgentVaultClient { + constructor(private apiClient: AgentVaultApi) {} + + /** Manages Agent Vault proxies. */ + proxies = { + /** + * Lists the organization's Agent Vault proxies. + * @returns The proxies and totalCount. A proxy's settings are only set for admins. + */ + list: (options: ListAgentVaultProxiesOptions = {}) => + run(async () => { + const res = await this.apiClient.proxies.list({ + search: options.search, + orderBy: options.orderBy ?? "createdAt", + orderDirection: options.orderDirection ?? "desc", + limit: options.limit ?? 20, + offset: options.offset ?? 0 + }); + return { ...res, proxies: res.proxies.map(viewProxy) }; + }), + + /** + * Registers an Agent Vault proxy and issues its proxy token. + * @returns The proxy and its proxyToken. The token is only returned once. + */ + create: (options: CreateAgentVaultProxyOptions) => + run(async () => { + const res = await this.apiClient.proxies.create({ + name: options.name, + trafficPolicy: toWireTrafficPolicy(options.trafficPolicy) ?? AgentVaultTrafficPolicy.AnyHost, + // An empty value means no allowed hosts, so it's left out. + allowedHosts: joinHosts(options.allowedHosts) ?? undefined, + pollInterval: options.pollInterval ?? 60, + description: options.description + }); + return { ...res, proxy: viewProxy(res.proxy) }; + }), + + /** + * Updates an Agent Vault proxy's name, description or settings. Only the values you pass are changed. + * @returns The updated proxy. + */ + update: (proxyId: string, options: UpdateAgentVaultProxyOptions) => + run(async () => { + const res = await this.apiClient.proxies.update(proxyId, { + name: options.name, + trafficPolicy: toWireTrafficPolicy(options.trafficPolicy), + // An empty value removes every allowed host, which the API takes as null. + allowedHosts: joinHosts(options.allowedHosts), + pollInterval: options.pollInterval, + description: options.description + }); + return viewProxy(res.proxy); + }), + + /** + * Deletes an Agent Vault proxy. + * @returns The deleted proxy's id and name. + */ + delete: (proxyId: string) => + run(async () => { + const res = await this.apiClient.proxies.delete(proxyId); + return res.proxy; + }), + + /** + * Issues a new proxy token. The proxy's earlier tokens stop working and it gets a new certificate authority. + * @returns The proxy and its new proxyToken. The token is only returned once. + */ + rotateToken: (proxyId: string) => + run(async () => { + const res = await this.apiClient.proxies.rotateToken(proxyId); + return { ...res, proxy: viewProxy(res.proxy) }; + }), + + /** + * Revokes an Agent Vault proxy's token. Rotate its token to bring it back. + * @returns The revoked proxy. + */ + revoke: (proxyId: string) => + run(async () => { + const res = await this.apiClient.proxies.revoke(proxyId); + return viewProxy(res.proxy); + }) + }; + + /** Manages Agent Vault sessions. */ + sessions = { + /** + * Lists Agent Vault sessions. + * @returns The sessions and totalCount. + */ + list: (options: ListAgentVaultSessionsOptions = {}) => + run(async () => { + const res = await this.apiClient.sessions.list({ + scope: options.scope ?? AgentVaultSessionScope.Mine, + status: joinList(options.statuses), + search: options.search, + limit: options.limit ?? 20, + offset: options.offset ?? 0 + }); + return { ...res, sessions: res.sessions.map(withServices) }; + }), + + /** + * Gets an Agent Vault session. + * @returns The session. + */ + get: (sessionId: string) => + run(async () => { + const res = await this.apiClient.sessions.get(sessionId); + return withServices(res.session); + }), + + /** + * Creates an Agent Vault session with an access bundle you can reach, services of its own, or both, for yourself + * or, as a machine identity with a delegation, on behalf of a user. + * + * Only Agent Vault admins can send services with a session. On behalf of a user, that's your machine identity: + * the user doesn't need the Admin role, and the services don't use the user's personal values. + * + * To start a session on behalf of a user, you must be a machine identity whose delegation covers the user. The + * proxy then uses the user's personal values, and the session can use only an access bundle that both the user + * and your machine identity can use. The session still belongs to your machine identity, so the user can't see + * it unless they're an Agent Vault admin. + * @returns The created session, including its token. The token is only returned once. + */ + create: (options: CreateAgentVaultSessionOptions) => + run(async () => { + checkOneUser(options.onBehalfOfUserEmail, options.onBehalfOfUserId); + + // An empty email or ID is sent rather than dropped, so the server rejects it instead of the SDK + // quietly creating the session for the caller. + let onBehalfOf: CreateAgentVaultSessionRequest["onBehalfOf"]; + if (isSet(options.onBehalfOfUserEmail)) { + onBehalfOf = { userEmail: options.onBehalfOfUserEmail }; + } else if (isSet(options.onBehalfOfUserId)) { + onBehalfOf = { userId: options.onBehalfOfUserId }; + } + + const res = await this.apiClient.sessions.create({ + // Left out without an access bundle, for a session that carries only services of its own. + accessBundle: isSet(options.accessBundle) ? options.accessBundle : undefined, + services: options.services, + // Left out unless you pass it, so the server picks the default: 7d, or 1h on behalf of a user. + ttl: options.ttl, + label: options.label, + onBehalfOf + }); + return withServices(res.session); + }), + + /** + * Updates the label of an Agent Vault session. This also works after the session expires or is revoked. + * @returns The updated session. + */ + update: (sessionId: string, options: UpdateAgentVaultSessionOptions) => + run(async () => { + // The label is always sent: null removes it, and the API rejects a request without one. + const res = await this.apiClient.sessions.update(sessionId, { label: options.label }); + return withServices(res.session); + }), + + /** + * Revokes an Agent Vault session. Revoking an already revoked session changes nothing. + * @returns The revoked session. The response leaves out its access bundle and inline services; call get for them. + */ + revoke: (sessionId: string) => + run(async () => { + const res = await this.apiClient.sessions.revoke(sessionId); + return res.session; + }) + }; + + /** + * Manages Agent Vault access bundles and who they're granted to. Every method except list and get requires the + * Admin role in Agent Vault. + */ + accessBundles = { + /** + * Lists the Agent Vault access bundles you can reach. Admins reach every access bundle. + * @returns The access bundles and totalCount. + */ + list: (options: ListAgentVaultAccessBundlesOptions = {}) => + run(() => { + checkOneUser(options.onBehalfOfUserEmail, options.onBehalfOfUserId); + + return this.apiClient.accessBundles.list({ + search: options.search, + requiresSetup: options.requiresSetup, + granted: options.granted, + onBehalfOfUserEmail: options.onBehalfOfUserEmail, + onBehalfOfUserId: options.onBehalfOfUserId, + orderBy: options.orderBy ?? "createdAt", + orderDirection: options.orderDirection ?? "desc", + limit: options.limit ?? 20, + offset: options.offset ?? 0 + }); + }), + + /** + * Gets an Agent Vault access bundle you can reach, with its services. + * @returns The access bundle, with its services. A service's variableReferences is only set for admins. + */ + get: (accessBundleId: string) => + run(async () => { + const res = await this.apiClient.accessBundles.get(accessBundleId); + return res.accessBundle; + }), + + /** + * Creates an Agent Vault access bundle. It's granted to you, unless you're in Agent Vault only through a group. + * @returns The created access bundle. + */ + create: (options: CreateAgentVaultAccessBundleOptions) => + run(async () => { + const res = await this.apiClient.accessBundles.create({ + name: options.name, + description: options.description + }); + return res.accessBundle; + }), + + /** + * Updates an Agent Vault access bundle's name or description. Only the values you pass are changed. + * @returns The updated access bundle. + */ + update: (accessBundleId: string, options: UpdateAgentVaultAccessBundleOptions) => + run(async () => { + const res = await this.apiClient.accessBundles.update(accessBundleId, { + name: options.name, + description: options.description + }); + return res.accessBundle; + }), + + /** + * Deletes an Agent Vault access bundle. + * @returns The deleted access bundle. + */ + delete: (accessBundleId: string) => + run(async () => { + const res = await this.apiClient.accessBundles.delete(accessBundleId); + return res.accessBundle; + }), + + /** + * Lists the users, machine identities and groups that an Agent Vault access bundle is granted to. + * @returns The grantees in members, and totalCount. + */ + listGrantees: (accessBundleId: string, options: ListAgentVaultGranteesOptions = {}) => + run(() => + this.apiClient.accessBundles.listGrantees(accessBundleId, { + actorType: options.actorType, + search: options.search, + limit: options.limit ?? 20, + offset: options.offset ?? 0 + }) + ), + + /** + * Lists the Agent Vault members that an access bundle isn't granted to yet, so you can grant it to them. + * @returns The members and totalCount. + */ + listAvailableGrantees: (accessBundleId: string, options: ListAgentVaultGranteesOptions = {}) => + run(() => + this.apiClient.accessBundles.listAvailableGrantees(accessBundleId, { + actorType: options.actorType, + search: options.search, + limit: options.limit ?? 20, + offset: options.offset ?? 0 + }) + ), + + /** + * Grants an Agent Vault access bundle to users, machine identities or groups. Each must be a member of Agent + * Vault. Name at least one, and at most 100 in total. + * @returns The new grants in members, and the grantees that already had the access bundle in skipped. + */ + grant: (accessBundleId: string, options: GrantAgentVaultAccessBundleOptions) => + run(() => + this.apiClient.accessBundles.grant(accessBundleId, { + userIds: options.userIds, + machineIdentityIds: options.machineIdentityIds, + groupIds: options.groupIds + }) + ), + + /** + * Revokes an Agent Vault access bundle from users, machine identities or groups. Name at least one, and at most + * 100 in total. + * @returns The revoked grants in members, and the grantees that didn't have the access bundle in skipped. + */ + revoke: (accessBundleId: string, options: RevokeAgentVaultAccessBundleOptions) => + run(() => + this.apiClient.accessBundles.revoke(accessBundleId, { + userIds: options.userIds, + machineIdentityIds: options.machineIdentityIds, + groupIds: options.groupIds + }) + ) + }; + + /** + * Manages Agent Vault delegations, which let machine identities create sessions on behalf of users. Every method + * requires the Admin role in Agent Vault, except that a machine identity can get its own delegation. + */ + delegations = { + /** + * Lists the machine identities that can create Agent Vault sessions on behalf of users. + * @returns The delegations and totalCount. A listed delegation has no missingAccessBundles; call get for them. + */ + list: (options: ListAgentVaultDelegationsOptions = {}) => + run(() => + this.apiClient.delegations.list({ + machineIdentityIds: joinList(options.machineIdentityIds), + limit: options.limit ?? 100, + offset: options.offset ?? 0 + }) + ), + + /** + * Gets which users a machine identity can create Agent Vault sessions on behalf of. If the machine identity has no + * delegation, throws an InfisicalSDKRequestError whose statusCode is 404. + * @returns The delegation, with the access bundles the machine identity can't create sessions with. + */ + get: (machineIdentityId: string) => + run(async () => { + const res = await this.apiClient.delegations.get(machineIdentityId); + return res.delegation; + }), + + /** + * Sets which users a machine identity can create Agent Vault sessions on behalf of, replacing any delegation it + * has. The machine identity must be a member of Agent Vault. + * @returns The saved delegation, with missingAccessBundles. + */ + set: (machineIdentityId: string, options: SetAgentVaultDelegationOptions) => + run(async () => { + const res = await this.apiClient.delegations.set(machineIdentityId, { + scope: options.scope, + userIds: options.userIds, + groupIds: options.groupIds + }); + return res.delegation; + }), + + /** + * Stops a machine identity from creating Agent Vault sessions on behalf of users. The proxy refuses the sessions it + * already created on their behalf until a delegation covers those users again, so revoke the sessions to end them + * for good. + * @returns The deleted delegation, without missingAccessBundles. + */ + delete: (machineIdentityId: string) => + run(async () => { + const res = await this.apiClient.delegations.delete(machineIdentityId); + return res.delegation; + }), + + /** + * Adds users and groups to a machine identity's delegation, keeping the ones it already names. If the machine + * identity has no delegation, this creates one with the "selected" scope. A delegation to all members can't + * take users or groups. + * @returns The delegation after the change, with missingAccessBundles. + */ + addSubjects: (machineIdentityId: string, options: AddAgentVaultDelegationSubjectsOptions) => + run(async () => { + const res = await this.apiClient.delegations.addSubjects(machineIdentityId, { + userIds: options.userIds, + groupIds: options.groupIds + }); + return res.delegation; + }), + + /** + * Takes users and groups out of a machine identity's delegation. The proxy refuses the sessions it created on + * behalf of the users you take out until the delegation covers them again, so revoke the sessions to end them for + * good. Taking out the last user or group removes the delegation. + * @returns The delegation after the change, with missingAccessBundles, or null if it no longer names anyone. + */ + removeSubjects: (machineIdentityId: string, options: RemoveAgentVaultDelegationSubjectsOptions) => + run(async () => { + const res = await this.apiClient.delegations.removeSubjects(machineIdentityId, { + userIds: options.userIds, + groupIds: options.groupIds + }); + return res.delegation; + }), + + /** + * Lists the Agent Vault users and groups that can still be added to a machine identity's delegation. The machine + * identity must be a member of Agent Vault. + * @returns The users and groups in members, and totalCount. + */ + listAvailableSubjects: (machineIdentityId: string, options: ListAvailableAgentVaultDelegationSubjectsOptions = {}) => + run(() => + this.apiClient.delegations.listAvailableSubjects(machineIdentityId, { + actorType: options.actorType, + search: options.search, + limit: options.limit ?? 20, + offset: options.offset ?? 0 + }) + ) + }; +} diff --git a/src/custom/errors.ts b/src/custom/errors.ts index 928c2db..c9b05aa 100644 --- a/src/custom/errors.ts +++ b/src/custom/errors.ts @@ -1,49 +1,69 @@ import { isFetchHttpError } from "../api/fetch-errors"; +// Written out rather than ErrorOptions, which exists only in TypeScript's ES2022 library, so a project that compiles +// the SDK's types against an older library doesn't fail. +type InfisicalErrorOptions = { cause?: unknown }; + export class InfisicalSDKError extends Error { - constructor(message: string) { - super(message); + constructor(message: string, options?: InfisicalErrorOptions) { + super(message, options); this.message = message; this.name = "InfisicalSDKError"; } } export class InfisicalSDKRequestError extends Error { + /** The HTTP status code that Infisical responded with. */ + public readonly statusCode: number; + constructor( message: string, requestData: { url: string; method: string; statusCode: number; - } + }, + options?: InfisicalErrorOptions ) { - super(message); + super(message, options); this.message = `[URL=${requestData.url}] [Method=${requestData.method}] [StatusCode=${requestData.statusCode}] ${message}`; this.name = "InfisicalSDKRequestError"; + this.statusCode = requestData.statusCode; } } +// Every error keeps the one it came from in cause. For a request that failed without a response, that's how a caller +// tells a timeout (a TimeoutError) from a connection that never opened (a TypeError whose cause has a code such as +// ECONNREFUSED), which matters when deciding whether to retry a request that must not run twice. export const newInfisicalError = (error: any) => { + // An error the SDK raised itself, such as for a refused argument, is already the one to throw. + if (error instanceof InfisicalSDKError || error instanceof InfisicalSDKRequestError) { + return error; + } + if (isFetchHttpError(error)) { const data = error.response.data as Record | null | undefined; + // A validation error (422) lists its issues in message, which isn't a string, so the whole body is the message. + const isValidationError = error.response.status === 422 && typeof data === "object" && data !== null; + + if (typeof data?.message === "string" || isValidationError) { + const message = isValidationError ? JSON.stringify(data) : String(data?.message); - if (typeof data?.message === "string") { - let message: string = data.message; - if (error.response.status === 422) { - message = JSON.stringify(data); - } - - return new InfisicalSDKRequestError(message, { - url: error.response.config.url, - method: error.response.config.method, - statusCode: error.response.status, - }); + return new InfisicalSDKRequestError( + message, + { + url: error.response.config.url, + method: error.response.config.method, + statusCode: error.response.status, + }, + { cause: error } + ); } else if (error.message) { - return new InfisicalSDKError(error.message); + return new InfisicalSDKError(error.message, { cause: error }); } else { - return new InfisicalSDKError("Request failed with unknown error"); + return new InfisicalSDKError("Request failed with unknown error", { cause: error }); } } - return new InfisicalSDKError(error?.message || "An error occurred"); + return new InfisicalSDKError(error?.message || "An error occurred", { cause: error }); }; diff --git a/src/index.ts b/src/index.ts index 7d0a7a5..3f85497 100644 --- a/src/index.ts +++ b/src/index.ts @@ -14,6 +14,8 @@ import ProjectsClient from "./custom/projects"; import FoldersClient from "./custom/folders"; import { KmsApi } from "./api/endpoints/kms"; import KmsClient from "./custom/kms"; +import { AgentVaultApi } from "./api/endpoints/agent-vault"; +import AgentVaultClient from "./custom/agent-vault"; type InfisicalSDKOptions = { siteUrl?: string; @@ -30,6 +32,7 @@ class InfisicalSDK { private projectsApi: ProjectsApi; private foldersApi: FoldersApi; private kmsApi: KmsApi; + private agentVaultApi: AgentVaultApi; // Domain clients private authClient: AuthClient; @@ -39,6 +42,7 @@ class InfisicalSDK { private projectsClient: ProjectsClient; private foldersClient: FoldersClient; private kmsClient: KmsClient; + private agentVaultClient: AgentVaultClient; constructor(options?: InfisicalSDKOptions) { const baseURL = options?.siteUrl || "https://app.infisical.com"; @@ -54,6 +58,7 @@ class InfisicalSDK { this.projectsApi = new ProjectsApi(this.apiClient); this.foldersApi = new FoldersApi(this.apiClient); this.kmsApi = new KmsApi(this.apiClient); + this.agentVaultApi = new AgentVaultApi(this.apiClient); // Initialize domain clients this.authClient = new AuthClient(this.authenticate.bind(this), this.authApi); @@ -63,6 +68,7 @@ class InfisicalSDK { this.projectsClient = new ProjectsClient(this.projectsApi); this.foldersClient = new FoldersClient(this.foldersApi); this.kmsClient = new KmsClient(this.kmsApi); + this.agentVaultClient = new AgentVaultClient(this.agentVaultApi); } private authenticate(accessToken: string) { @@ -83,6 +89,7 @@ class InfisicalSDK { dynamicSecrets = () => this.dynamicSecretsClient; auth = () => this.authClient; kms = () => this.kmsClient; + agentVault = () => this.agentVaultClient; } // Export main SDK class @@ -90,5 +97,7 @@ export { InfisicalSDK }; export * from "./api/types"; +export { InfisicalSDKError, InfisicalSDKRequestError } from "./custom/errors"; + // Export types and enums from schemas export { TDynamicSecretProvider, DynamicSecretProviders, SqlProviders } from "./custom/schemas";