diff --git a/sink/agent-vault.test.ts b/sink/agent-vault.test.ts index 1f9c603..a3f9b33 100644 --- a/sink/agent-vault.test.ts +++ b/sink/agent-vault.test.ts @@ -50,7 +50,8 @@ const SESSION = { revokedAt: null, createdAt: CREATED_AT, accessBundle: SESSION_ACCESS_BUNDLE, - services: [] + services: [], + metadata: {} }; const CREATED_SESSION = { id: SESSION_ID, @@ -60,7 +61,8 @@ const CREATED_SESSION = { expiresAt: SESSION.expiresAt, createdAt: CREATED_AT, accessBundle: SESSION_ACCESS_BUNDLE, - services: [] + services: [], + metadata: {} }; // A service sent with a session, as the SDK takes it and as the API returns it (without its secrets). const INLINE_SERVICE_INPUT = { @@ -809,13 +811,39 @@ describe("agent vault sessions", () => { expect(created.projectId).toBe(PROJECT_ID); }); - it.each(["nightly deploy", null])("update always sends the label (%j)", async (label) => { + it.each(["nightly deploy", null])("update sends a label it's given (%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 sends metadata and reads it back", async () => { + const metadata = { runId: "8812", team: "platform" }; + respondWith({ session: { ...CREATED_SESSION, metadata } }); + const created = await agentVault.sessions.create({ ...PROJECT, accessBundle: "release", metadata }); + expect(lastRequest().body).toEqual({ projectId: PROJECT_ID, accessBundle: "release", metadata }); + expect(created.metadata).toEqual(metadata); + }); + + it("reads a session's metadata", async () => { + respondWith({ session: { ...SESSION, metadata: { runId: "8812" } } }); + expect((await agentVault.sessions.get(SESSION_ID)).metadata.runId).toBe("8812"); + }); + + it.each>([{ runId: "8812" }, {}])("update sends only metadata (%j)", async (metadata) => { + respondWith({ session: { ...SESSION, metadata } }); + const updated = await agentVault.sessions.update(SESSION_ID, { metadata }); + expect(lastRequest().body).toEqual({ metadata }); + expect(updated.metadata).toEqual(metadata); + }); + + it("update sends a label and metadata together", async () => { + respondWith({ session: { ...SESSION, label: "nightly deploy", metadata: { runId: "8812" } } }); + await agentVault.sessions.update(SESSION_ID, { label: "nightly deploy", metadata: { runId: "8812" } }); + expect(lastRequest().body).toEqual({ label: "nightly deploy", metadata: { runId: "8812" } }); + }); + it("create leaves out ttl so the server picks the default", async () => { respondWith({ session: CREATED_SESSION }); await agentVault.sessions.create({ ...PROJECT, accessBundle: "release" }); @@ -853,6 +881,22 @@ describe("agent vault sessions", () => { }); expect(lastRequest().query).toMatchObject({ scope: "all", status: "active,expired" }); }); + + it("list sends each metadata pair as its own metadata parameter", async () => { + respondWith({ sessions: [], totalCount: 0 }); + await agentVault.sessions.list({ ...PROJECT, metadata: { runId: "8812", env: "prod" } }); + const [url] = fetchSpy.mock.calls.at(-1) as [string]; + expect(url).toBe( + `https://infisical.example.com/api/v1/agent-vault/sessions?projectId=${PROJECT_ID}&scope=mine&metadata=runId%3D8812&metadata=env%3Dprod&limit=20&offset=0` + ); + expect(new URL(url).searchParams.getAll("metadata")).toEqual(["runId=8812", "env=prod"]); + }); + + it("list leaves out an empty metadata filter", async () => { + respondWith({ sessions: [], totalCount: 0 }); + await agentVault.sessions.list({ ...PROJECT, metadata: {} }); + expect(lastRequest().query).not.toHaveProperty("metadata"); + }); }); describe("agent vault access bundles", () => { diff --git a/sink/fetch-base.test.ts b/sink/fetch-base.test.ts index 90ae72f..7c3468e 100644 --- a/sink/fetch-base.test.ts +++ b/sink/fetch-base.test.ts @@ -94,6 +94,12 @@ describe("buildUrl", () => { expect(url.searchParams.get("limit")).toBe("100"); }); + it("repeats the parameter for each array item", () => { + expect(buildUrl(base, "sessions", { metadata: ["a=1", "b=2"] })).toBe( + "https://example.com/api/v1/sessions?metadata=a%3D1&metadata=b%3D2" + ); + }); + it("works with baseURL that has a path component", () => { const result = buildUrl( "https://app.infisical.com/api/", diff --git a/src/api/base.ts b/src/api/base.ts index 9c51156..f8591b1 100644 --- a/src/api/base.ts +++ b/src/api/base.ts @@ -35,7 +35,9 @@ export const buildUrl = ( const url = new URL(relative, baseURL); for (const [key, value] of Object.entries(params)) { if (value === undefined || value === null) continue; - url.searchParams.append(key, String(value)); + for (const item of Array.isArray(value) ? value : [value]) { + url.searchParams.append(key, String(item)); + } } return url.toString(); }; diff --git a/src/api/types/agent-vault.ts b/src/api/types/agent-vault.ts index 7a5ba14..47c156c 100644 --- a/src/api/types/agent-vault.ts +++ b/src/api/types/agent-vault.ts @@ -383,6 +383,8 @@ export interface AgentVaultSession { 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[]; + /** The session's metadata as key-value pairs, such as { runId: "8812" }. Empty if it has none. */ + metadata: Record; } /** An Agent Vault session as returned at creation. */ @@ -400,6 +402,8 @@ export interface CreatedAgentVaultSession { accessBundle: AgentVaultSessionAccessBundle | null; /** The services sent with the session, without their secrets. Empty if it carries only an access bundle. */ services: AgentVaultInlineService[]; + /** The session's metadata as key-value pairs. Empty if it has none. */ + metadata: Record; } export interface ListAgentVaultSessionsResponse { @@ -730,6 +734,8 @@ export interface ListAgentVaultSessionsRequest { /** Statuses, separated by commas. */ status?: string; search?: string; + /** Metadata filters, each "key=value". */ + metadata?: string[]; limit: number; offset: number; } @@ -740,11 +746,13 @@ export interface CreateAgentVaultSessionRequest { services?: AgentVaultInlineServiceInput[]; ttl?: string; label?: string; + metadata?: Record; onBehalfOf?: { userEmail: string } | { userId: string }; } export interface UpdateAgentVaultSessionRequest { - label: string | null; + label?: string | null; + metadata?: Record; } export interface ListAgentVaultAccessBundlesRequest { @@ -870,6 +878,8 @@ export type ListAgentVaultSessionsOptions = { 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; + /** Only return sessions whose metadata matches every one of these key-value pairs exactly, such as { runId: "8812" }. Up to 20 pairs. */ + metadata?: Record; /** The maximum number of sessions to return (1-100). Defaults to 20. */ limit?: number; /** How many sessions to skip. Defaults to 0. */ @@ -892,15 +902,28 @@ export type CreateAgentVaultSessionOptions = { 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; + /** + * Key-value pairs to tag the session with, such as { runId: "8812" }. Up to 20 keys. A key is 1 to 255 characters + * and a value up to 1020, without line breaks, tabs, or invisible characters. Keys that match once trimmed are + * rejected. + */ + metadata?: Record; /** 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; }; +/** Pass label, metadata, or both. A value you leave out stays as it is. */ 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; + /** The new label, up to 128 characters, without line breaks, tabs, or invisible characters. Pass null or an empty string to remove the label. */ + label?: string | null; + /** + * The session's new metadata, which replaces all of it. Pass {} to remove it. Up to 20 keys. A key is 1 to 255 + * characters and a value up to 1020, without line breaks, tabs, or invisible characters. Keys that match once + * trimmed are rejected. + */ + metadata?: Record; }; export type ListAgentVaultAccessBundlesOptions = { diff --git a/src/custom/agent-vault.ts b/src/custom/agent-vault.ts index b9ca1a1..646086a 100644 --- a/src/custom/agent-vault.ts +++ b/src/custom/agent-vault.ts @@ -37,6 +37,12 @@ const joinHosts = (allowedHosts: string | string[] | undefined): string | 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 API takes each metadata filter as its own "key=value" query parameter, repeated rather than comma-separated. */ +const metadataFilters = (metadata: Record | undefined) => { + const filters = Object.entries(metadata ?? {}).map(([key, value]) => `${key}=${value}`); + return filters.length ? filters : 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. @@ -175,6 +181,7 @@ export default class AgentVaultClient { scope: options.scope ?? AgentVaultSessionScope.Mine, status: joinList(options.statuses), search: options.search, + metadata: metadataFilters(options.metadata), limit: options.limit ?? 20, offset: options.offset ?? 0 }); @@ -225,19 +232,24 @@ export default class AgentVaultClient { // 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, + metadata: options.metadata, onBehalfOf }); return withServices(res.session); }), /** - * Updates the label of an Agent Vault session. This also works after the session expires or is revoked. + * Updates the label or metadata of an Agent Vault session. Pass label, metadata, or both; a value you leave out + * stays as it is. This also works after the session expires or is revoked, but not once the session's owner, or + * the user it was started on behalf of, is deleted. * @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 }); + const res = await this.apiClient.sessions.update(sessionId, { + label: options.label, + metadata: options.metadata + }); return withServices(res.session); }),