import { test, beforeEach, afterEach } from 'node:test' import assert from 'node:assert/strict' import secretProvider from '../src/secret-provider.ts' import describe from '../src/index.ts' // Obviously fake test fixtures. Not real Doppler credentials. const FAKE_TOKEN = 'dp.st.test.FAKE_TOKEN_FOR_UNIT_TESTS_ONLY' const FAKE_VALUE = 'fake-value-for-tests' type Call = { url: URL; init: RequestInit | undefined } let calls: Call[] = [] const realFetch = globalThis.fetch function mockFetch(handler: (url: URL, init?: RequestInit) => Response | Promise) { globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { const url = new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url) calls.push({ url, init }) return handler(url, init) }) as typeof fetch } function json(body: unknown, status = 200, headers: Record = {}) { return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', ...headers }, }) } beforeEach(() => { calls = [] }) afterEach(() => { globalThis.fetch = realFetch }) function resolve(ref: string, config: Record = { hosts: 'api.example.com' }, token = FAKE_TOKEN) { return secretProvider({ action: 'resolve', providerId: 'doppler', ref, canonicalRef: null, doorSecretName: 'dopplerServiceToken', doorSecretValue: token, config, }) } /** Every error must be free of the token and the value. */ async function rejectsClean(p: Promise, pattern: RegExp) { await assert.rejects(p, (err: unknown) => { assert.ok(err instanceof Error) assert.match(err.message, pattern) assert.ok(!err.message.includes(FAKE_TOKEN), 'error leaked token') assert.ok(!err.message.includes('FAKE_TOKEN'), 'error leaked token fragment') assert.ok(!err.message.includes(FAKE_VALUE), 'error leaked value') return true }) } // canonicalize test('canonicalize maps synonyms to one canonical ref without network', async () => { mockFetch(() => { throw new Error('network must not be used') }) for (const [ref, expected] of [ ['STRIPE_KEY', 's/STRIPE_KEY'], ['s/STRIPE_KEY', 's/STRIPE_KEY'], ['s/STRIPE_KEY/computed', 's/STRIPE_KEY'], ['s/STRIPE_KEY/RAW', 's/STRIPE_KEY/raw'], [' s/_X1 ', 's/_X1'], ]) { const out = await secretProvider({ action: 'canonicalize', ref, canonicalRef: null }) assert.deepEqual(out, { canonicalRef: expected }) } assert.equal(calls.length, 0) }) test('canonicalize prefers canonicalRef over ref', async () => { const out = await secretProvider({ action: 'canonicalize', ref: 'OTHER', canonicalRef: 's/MAIN/raw' }) assert.deepEqual(out, { canonicalRef: 's/MAIN/raw' }) }) test('canonicalize rejects bad refs', async () => { for (const ref of ['', '1ABC', 's/', 's/A-B', 's/A/notes', 'op://x/y/z', 'i/abc/password', 's/A/raw/extra']) { await assert.rejects(secretProvider({ action: 'canonicalize', ref, canonicalRef: null })) } }) test('unknown action is rejected', async () => { await assert.rejects( secretProvider({ action: 'delete' as never, ref: 's/A' }), /Unknown secret provider action/, ) }) // resolve success test('resolve computed uses download endpoint limited to one secret with Bearer auth', async () => { mockFetch(() => json({ STRIPE_KEY: FAKE_VALUE })) const out = await resolve('s/STRIPE_KEY', { hosts: 'api.example.com, API.Example.com,hooks.example.com' }) assert.deepEqual(out, { value: FAKE_VALUE, hosts: ['api.example.com', 'hooks.example.com'], canonicalRef: 's/STRIPE_KEY', }) assert.equal(calls.length, 1) const { url, init } = calls[0]! assert.equal(url.origin, 'https://api.doppler.com') assert.equal(url.pathname, '/v3/configs/config/secrets/download') assert.equal(url.searchParams.get('format'), 'json') assert.equal(url.searchParams.get('secrets'), 'STRIPE_KEY') assert.equal(url.searchParams.has('project'), false) assert.equal(url.searchParams.has('config'), false) assert.equal((init?.headers as Record).Authorization, `Bearer ${FAKE_TOKEN}`) assert.equal(init?.method, 'GET') }) test('resolve passes project and config when bound', async () => { mockFetch(() => json({ A: FAKE_VALUE })) await resolve('A', { hosts: 'api.example.com', project: 'backend', config: 'prd' }) assert.equal(calls[0]!.url.searchParams.get('project'), 'backend') assert.equal(calls[0]!.url.searchParams.get('config'), 'prd') }) test('resolve raw uses single-secret endpoint', async () => { mockFetch(() => json({ name: 'DB_URL', value: { raw: '${USER}@db', computed: FAKE_VALUE } })) const out = await resolve('s/DB_URL/raw') assert.deepEqual(out, { value: '${USER}@db', hosts: ['api.example.com'], canonicalRef: 's/DB_URL/raw' }) assert.equal(calls[0]!.url.pathname, '/v3/configs/config/secret') assert.equal(calls[0]!.url.searchParams.get('name'), 'DB_URL') }) test('per-secret hosts override shared hosts', async () => { mockFetch(() => json({ A: FAKE_VALUE })) const out = (await resolve('s/A', { hosts: 'api.example.com', 'hosts.A': 'special.example.org' })) as { hosts: string[] } assert.deepEqual(out.hosts, ['special.example.org']) }) test('service account tokens are accepted', async () => { mockFetch(() => json({ A: FAKE_VALUE })) await resolve('s/A', { hosts: 'api.example.com' }, 'dp.sa.FAKE_TOKEN_FOR_UNIT_TESTS_ONLY') assert.equal(calls.length, 1) }) // resolve config and token errors (no network) test('empty hosts fail closed before any network call', async () => { mockFetch(() => json({ A: FAKE_VALUE })) await rejectsClean(resolve('s/A', {}), /fail closed/) await rejectsClean(resolve('s/A', { hosts: ' , ' }), /fail closed/) assert.equal(calls.length, 0) }) test('bad host entries are rejected', async () => { mockFetch(() => json({ A: FAKE_VALUE })) for (const hosts of ['https://api.example.com', 'api.example.com/path', '*.example.com', 'localhost', 'api.example.com:443']) { await rejectsClean(resolve('s/A', { hosts }), /not a plain hostname/) } assert.equal(calls.length, 0) }) test('project without config is rejected', async () => { mockFetch(() => json({ A: FAKE_VALUE })) await rejectsClean(resolve('s/A', { hosts: 'api.example.com', project: 'p' }), /both "project" and "config"/) await rejectsClean(resolve('s/A', { hosts: 'api.example.com', project: 'p', config: 'bad slug' }), /slugs/) assert.equal(calls.length, 0) }) test('empty or non-service tokens are refused without echoing them', async () => { mockFetch(() => json({ A: FAKE_VALUE })) await rejectsClean(resolve('s/A', undefined, ''), /door secret is empty/) await rejectsClean(resolve('s/A', undefined, 'dp.pt.FAKE_TOKEN_FOR_UNIT_TESTS_ONLY'), /Personal and CLI tokens are refused/) await rejectsClean(resolve('s/A', undefined, 'dp.ct.FAKE_TOKEN_FOR_UNIT_TESTS_ONLY'), /Personal and CLI tokens are refused/) assert.equal(calls.length, 0) }) // resolve HTTP errors for (const [status, pattern] of [ [400, /HTTP 400/], [401, /HTTP 401.*new service token/], [403, /HTTP 403.*different project\/config/], [404, /not found \(HTTP 404\)/], [500, /unavailable \(HTTP 500\)/], [418, /failed \(HTTP 418\)/], ] as const) { test(`HTTP ${status} maps to a clean error (computed and raw)`, async () => { // Response body deliberately echoes the token and a value; neither may surface. mockFetch(() => json({ messages: [`bad token ${FAKE_TOKEN}`, FAKE_VALUE], success: false }, status)) await rejectsClean(resolve('s/A'), pattern) await rejectsClean(resolve('s/A/raw'), pattern) }) } test('429 reports Retry-After seconds', async () => { mockFetch(() => json({ messages: ['slow down'] }, 429, { 'retry-after': '12' })) await rejectsClean(resolve('s/A'), /rate limit.*Retry after 12s/) }) test('429 without Retry-After still reports rate limit', async () => { mockFetch(() => json({}, 429)) await rejectsClean(resolve('s/A'), /rate limit.*Retry later/) }) test('missing secret in download body is not found', async () => { mockFetch(() => json({ OTHER: FAKE_VALUE })) await rejectsClean(resolve('s/A'), /not found/) }) test('empty value, non-string value, and non-JSON body are errors', async () => { mockFetch(() => json({ A: '' })) await rejectsClean(resolve('s/A'), /is empty/) mockFetch(() => json({ A: 123 })) await rejectsClean(resolve('s/A'), /not download as a string/) mockFetch(() => json([FAKE_VALUE])) await rejectsClean(resolve('s/A'), /unexpected body shape/) mockFetch(() => new Response('not json', { status: 200 })) await rejectsClean(resolve('s/A'), /not JSON/) mockFetch(() => json({ name: 'A', value: { computed: FAKE_VALUE } })) await rejectsClean(resolve('s/A/raw'), /no readable raw value/) }) test('network failure does not forward underlying message', async () => { mockFetch(() => { throw new TypeError(`connect failed with Authorization Bearer ${FAKE_TOKEN}`) }) await rejectsClean(resolve('s/A'), /Could not reach api.doppler.com/) }) test('abort maps to timeout error', async () => { mockFetch(() => { const err = new Error('aborted') err.name = 'AbortError' throw err }) await rejectsClean(resolve('s/A'), /timed out/) }) test('provider never logs', async () => { const original = { log: console.log, error: console.error, warn: console.warn, info: console.info, debug: console.debug } const logged: unknown[] = [] for (const k of Object.keys(original) as (keyof typeof original)[]) console[k] = (...a: unknown[]) => logged.push(a) try { mockFetch(() => json({ A: FAKE_VALUE })) await resolve('s/A') mockFetch(() => json({}, 401)) await resolve('s/A').catch(() => {}) } finally { Object.assign(console, original) } assert.equal(logged.length, 0) }) // overview export test('describe returns grammar and a bind template without network', async () => { mockFetch(() => { throw new Error('network must not be used') }) const out = await describe({ project: 'backend', config: 'prd', hosts: ['API.example.com'] }) assert.equal(out.providerId, 'doppler') assert.deepEqual(out.bindTemplate.config, { project: 'backend', config: 'prd', hosts: 'api.example.com' }) assert.equal(out.bindTemplate.door_secret_name, 'dopplerServiceToken') const plain = await describe() assert.deepEqual(plain.bindTemplate.config, { hosts: 'api.example.com' }) assert.equal(calls.length, 0) }) test('describe rejects unknown keys and bad values', async () => { await assert.rejects(describe({ projct: 'x' }), /Unknown key "projct"/) await assert.rejects(describe({ project: 'x' }), /both/) await assert.rejects(describe({ hosts: ['https://x.com'] }), /plain hostname/) await assert.rejects(describe('nope'), /Expected an optional object/) })