Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 47 additions & 3 deletions sink/agent-vault.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ const SESSION = {
revokedAt: null,
createdAt: CREATED_AT,
accessBundle: SESSION_ACCESS_BUNDLE,
services: []
services: [],
metadata: {}
};
const CREATED_SESSION = {
id: SESSION_ID,
Expand All @@ -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 = {
Expand Down Expand Up @@ -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<Record<string, string>>([{ 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" });
Expand Down Expand Up @@ -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", () => {
Expand Down
6 changes: 6 additions & 0 deletions sink/fetch-base.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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/",
Expand Down
4 changes: 3 additions & 1 deletion src/api/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
};
Expand Down
29 changes: 26 additions & 3 deletions src/api/types/agent-vault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>;
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
}

/** An Agent Vault session as returned at creation. */
Expand All @@ -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<string, string>;
}

export interface ListAgentVaultSessionsResponse {
Expand Down Expand Up @@ -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;
}
Expand All @@ -740,11 +746,13 @@ export interface CreateAgentVaultSessionRequest {
services?: AgentVaultInlineServiceInput[];
ttl?: string;
label?: string;
metadata?: Record<string, string>;
onBehalfOf?: { userEmail: string } | { userId: string };
}

export interface UpdateAgentVaultSessionRequest {
label: string | null;
label?: string | null;
metadata?: Record<string, string>;
}

export interface ListAgentVaultAccessBundlesRequest {
Expand Down Expand Up @@ -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<string, string>;
/** The maximum number of sessions to return (1-100). Defaults to 20. */
limit?: number;
/** How many sessions to skip. Defaults to 0. */
Expand All @@ -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<string, 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;
};

/** 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<string, string>;
};

export type ListAgentVaultAccessBundlesOptions = {
Expand Down
18 changes: 15 additions & 3 deletions src/custom/agent-vault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> | 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.
Expand Down Expand Up @@ -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
});
Expand Down Expand Up @@ -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);
}),

Expand Down
Loading