Skip to content

Commit 5611662

Browse files
author
Artur Spatari
committed
feat(vault): address an Infisical folder from the reference
An Infisical provider is pinned to one non-recursive `secretPath`, so reading two folders means two providers, two machine identities and two sets of credentials to rotate. This lets a reference name the folder instead: ${{vault.my-provider.external/sentry:SENTRY_DSN}} `<path>:<KEY>` mirrors the HashiCorp client in this directory, which already documents that exact format. A relative path resolves against the provider's `secretPath`, a leading slash is absolute, and a ref without a colon keeps its current meaning — the whole ref is the secret name at the provider's own path. A dot cannot be the separator here: Infisical accepts dots inside secret names (`A.B.C` is a valid key), so `provider.a.b.C` cannot be split unambiguously and would silently break anyone using such a name. Refs are grouped by resolved path so each path is listed once, and the login happens once per batch rather than once per path. Tests cover the bare ref, relative and absolute paths, a provider at `/`, grouping with a single login, the error naming the path, and a malformed ref.
1 parent 887a457 commit 5611662

2 files changed

Lines changed: 171 additions & 17 deletions

File tree

‎apps/dokploy/__test__/env/vault.test.ts‎

Lines changed: 101 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -444,13 +444,22 @@ describe("infisical client", () => {
444444
};
445445

446446
const loginResponse = () => jsonResponse({ accessToken: "token-1" });
447+
const list = (secrets: Record<string, string>) =>
448+
jsonResponse({
449+
secrets: Object.entries(secrets).map(([secretKey, secretValue]) => ({
450+
secretKey,
451+
secretValue,
452+
})),
453+
});
454+
const listPathOf = (callIndex: number) => {
455+
const [url] = mockFetch.mock.calls[callIndex] as [string];
456+
return new URL(url).searchParams.get("secretPath");
457+
};
447458

448459
it("asks the list endpoint to expand secret references", async () => {
449-
mockFetch.mockResolvedValueOnce(loginResponse()).mockResolvedValueOnce(
450-
jsonResponse({
451-
secrets: [{ secretKey: "DB_URL", secretValue: "postgres://real" }],
452-
}),
453-
);
460+
mockFetch
461+
.mockResolvedValueOnce(loginResponse())
462+
.mockResolvedValueOnce(list({ DB_URL: "postgres://real" }));
454463

455464
const result = await infisicalClient.getSecrets(config, ["DB_URL"]);
456465

@@ -480,6 +489,93 @@ describe("infisical client", () => {
480489
infisicalClient.getSecrets(config, ["DB_URL"]),
481490
).rejects.toThrow("authentication failed (status 401)");
482491
});
492+
493+
it("resolves a relative <path>:<KEY> ref against the provider path", async () => {
494+
mockFetch
495+
.mockResolvedValueOnce(loginResponse())
496+
.mockResolvedValueOnce(list({ SENTRY_DSN: "https://[email protected]/1" }));
497+
498+
const result = await infisicalClient.getSecrets(config, [
499+
"shared/sentry:SENTRY_DSN",
500+
]);
501+
502+
expect(result).toEqual({
503+
"shared/sentry:SENTRY_DSN": "https://[email protected]/1",
504+
});
505+
expect(listPathOf(1)).toBe("/frontend/shared/sentry");
506+
});
507+
508+
it("treats a leading slash as an absolute path", async () => {
509+
mockFetch
510+
.mockResolvedValueOnce(loginResponse())
511+
.mockResolvedValueOnce(list({ SENTRY_DSN: "https://[email protected]/1" }));
512+
513+
await infisicalClient.getSecrets(config, ["/external/sentry:SENTRY_DSN"]);
514+
515+
expect(listPathOf(1)).toBe("/external/sentry");
516+
});
517+
518+
it("keeps the root path clean when the provider sits at /", async () => {
519+
mockFetch
520+
.mockResolvedValueOnce(loginResponse())
521+
.mockResolvedValueOnce(list({ KEY: "value" }));
522+
523+
await infisicalClient.getSecrets({ ...config, secretPath: "/" }, [
524+
"external/sentry:KEY",
525+
]);
526+
527+
expect(listPathOf(1)).toBe("/external/sentry");
528+
});
529+
530+
it("logs in once and fetches each path once", async () => {
531+
const byPath: Record<string, Record<string, string>> = {
532+
"/frontend": { A: "a", B: "b" },
533+
"/frontend/other": { C: "c" },
534+
};
535+
mockFetch.mockImplementation(async (url: string) => {
536+
if (url.includes("/auth/universal-auth/login")) return loginResponse();
537+
const path = new URL(url).searchParams.get("secretPath") as string;
538+
return list(byPath[path] ?? {});
539+
});
540+
541+
const result = await infisicalClient.getSecrets(config, [
542+
"A",
543+
"B",
544+
"other:C",
545+
]);
546+
547+
expect(result).toEqual({ A: "a", B: "b", "other:C": "c" });
548+
549+
const urls = mockFetch.mock.calls.map(([url]) => url as string);
550+
expect(urls.filter((u) => u.includes("/login"))).toHaveLength(1);
551+
expect(
552+
urls
553+
.filter((u) => u.includes("/secrets/raw?"))
554+
.map((u) => new URL(u).searchParams.get("secretPath"))
555+
.sort(),
556+
).toEqual(["/frontend", "/frontend/other"]);
557+
});
558+
559+
it("names the path when a secret is missing from an explicit one", async () => {
560+
mockFetch
561+
.mockResolvedValueOnce(loginResponse())
562+
.mockResolvedValueOnce(list({}));
563+
564+
await expect(
565+
infisicalClient.getSecrets(config, ["external/sentry:ABSENT"]),
566+
).rejects.toThrow(
567+
'secret "ABSENT" not found at "/frontend/external/sentry"',
568+
);
569+
});
570+
571+
it("rejects a ref with an empty path or key", async () => {
572+
await expect(infisicalClient.getSecrets(config, [":KEY"])).rejects.toThrow(
573+
"expected format <path>:<KEY>",
574+
);
575+
await expect(
576+
infisicalClient.getSecrets(config, ["external/sentry:"]),
577+
).rejects.toThrow("expected format <path>:<KEY>");
578+
});
483579
});
484580

485581
describe("doppler client", () => {

‎packages/server/src/utils/vault/infisical.ts‎

Lines changed: 70 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,47 @@ const login = async (config: InfisicalConfig) => {
3232
return body.accessToken;
3333
};
3434

35-
const fetchSecrets = async (config: InfisicalConfig) => {
36-
const accessToken = await login(config);
35+
// A reference may address a folder: `<path>:<KEY>`, mirroring the HashiCorp
36+
// client in this directory. Without a colon the whole ref is the secret name
37+
// and the provider's own `secretPath` is used, which is the previous
38+
// behaviour. Dots cannot serve as the separator here because Infisical allows
39+
// them inside secret names, so `a.b.C` is genuinely ambiguous.
40+
const parseRef = (ref: string) => {
41+
const separatorIndex = ref.lastIndexOf(":");
42+
if (separatorIndex === -1) {
43+
return { path: null, key: ref };
44+
}
45+
const path = ref.slice(0, separatorIndex);
46+
const key = ref.slice(separatorIndex + 1);
47+
if (!path || !key) {
48+
throw new Error(
49+
`Invalid Infisical reference "${ref}": expected format <path>:<KEY> (e.g. external/sentry:SENTRY_DSN)`,
50+
);
51+
}
52+
return { path, key };
53+
};
54+
55+
const resolveSecretPath = (config: InfisicalConfig, refPath: string | null) => {
56+
if (!refPath) {
57+
return config.secretPath;
58+
}
59+
if (refPath.startsWith("/")) {
60+
return refPath;
61+
}
62+
const base = config.secretPath.replace(/\/+$/, "");
63+
return `${base}/${refPath}`;
64+
};
65+
66+
// One login serves every path a batch of refs touches.
67+
const readPath = async (
68+
config: InfisicalConfig,
69+
accessToken: string,
70+
secretPath: string,
71+
) => {
3772
const params = new URLSearchParams({
3873
workspaceId: config.projectId,
3974
environment: config.environmentSlug,
40-
secretPath: config.secretPath,
75+
secretPath,
4176
// Infisical's list endpoint leaves secret references (`${env.folder.KEY}`)
4277
// unexpanded unless asked, so without this a referencing secret arrives as
4378
// the literal `${...}` string, lands in the generated .env and the deploy
@@ -52,7 +87,7 @@ const fetchSecrets = async (config: InfisicalConfig) => {
5287

5388
if (!response.ok) {
5489
throw new Error(
55-
`Infisical: failed to fetch secrets (status ${response.status})`,
90+
`Infisical: failed to fetch secrets at "${secretPath}" (status ${response.status})`,
5691
);
5792
}
5893

@@ -67,18 +102,41 @@ const fetchSecrets = async (config: InfisicalConfig) => {
67102
return secrets;
68103
};
69104

105+
const fetchSecrets = async (
106+
config: InfisicalConfig,
107+
secretPath = config.secretPath,
108+
) => readPath(config, await login(config), secretPath);
109+
70110
export const infisicalClient: VaultClient<InfisicalConfig> = {
71111
async getSecrets(config, refs) {
72-
const secrets = await fetchSecrets(config);
73-
const result: Record<string, string> = {};
112+
const byPath = new Map<string, string[]>();
74113
for (const ref of refs) {
75-
if (secrets[ref] === undefined) {
76-
throw new Error(
77-
`Infisical: secret "${ref}" not found in environment "${config.environmentSlug}"`,
78-
);
79-
}
80-
result[ref] = secrets[ref];
114+
const { path } = parseRef(ref);
115+
const secretPath = resolveSecretPath(config, path);
116+
byPath.set(secretPath, [...(byPath.get(secretPath) ?? []), ref]);
81117
}
118+
119+
const accessToken = await login(config);
120+
const result: Record<string, string> = {};
121+
await Promise.all(
122+
[...byPath.entries()].map(async ([secretPath, pathRefs]) => {
123+
const secrets = await readPath(config, accessToken, secretPath);
124+
for (const ref of pathRefs) {
125+
const { path, key } = parseRef(ref);
126+
if (secrets[key] === undefined) {
127+
// The path is only worth naming when the ref asked for one;
128+
// for a bare ref the wording stays as it was, so existing
129+
// error messages don't change for anyone.
130+
throw new Error(
131+
path
132+
? `Infisical: secret "${key}" not found at "${secretPath}" in environment "${config.environmentSlug}"`
133+
: `Infisical: secret "${key}" not found in environment "${config.environmentSlug}"`,
134+
);
135+
}
136+
result[ref] = secrets[key];
137+
}
138+
}),
139+
);
82140
return result;
83141
},
84142

0 commit comments

Comments
 (0)