Files
dockhand-upstream/tests/secret-provider-infisical.test.ts
T
1ad36a83fb feat: Add pluggable secret providers (1Password, Infisical, HashiCorp Vault) (#1360)
* Add pluggable secret provider foundation

Introduces a provider-agnostic secret backend abstraction so stacks can
pull deploy-time secrets from 1Password, Infisical or HashiCorp Vault.

Providers implement the SecretProvider contract in secretproviders/shared.ts
and advertise which of the two resolution modes they support:

  - reference interpolation: a variable's value is an inline reference in
    the backend's own syntax (e.g. 1Password's op://vault/item/field)
  - bulk pull: every secret under a provider-defined selector, fetched as
    a flat key/value map

Adding a backend means dropping a file in secretproviders/ and registering
it in the index; no caller changes.

Four providers ship here: 1Password service account (references + bulk),
1Password Connect (references), Infisical (bulk) and HashiCorp Vault KV v2
(bulk). Provider config is persisted as an encrypted JSON blob in the new
secret_providers table, mirroring the existing notification_settings
type+config pattern, and stack_sources gains a nullable secret_provider_id.

Decrypted tokens stay in the provider modules for the duration of a call
and are never written to disk or returned to the client.

Co-authored-by: GooRoo <sergey.olendarenko@gmail.com>

* Add secret provider API routes and permissions

CRUD plus two test-connection endpoints under /api/secret-providers. The
unsaved variant validates a config posted from the provider form; the
stored variant tests a persisted provider by id.

Responses only ever carry provider summaries (id, type, name, timestamps).
The decrypted config never leaves the server.

Adds a "secrets" permission resource with view/create/edit/delete actions,
wired through the permission type, the role editor and the seeded roles,
and a secret_provider audit entity type so provider changes are logged.
Config rotations are audited as a boolean rather than a value.

* Resolve provider secrets at stack deploy time

Stacks can bind a secret provider; when one is bound, its secrets are
resolved and merged into the vars handed to docker compose.

Bulk pull is triggered by a selector variable: OP_ENVIRONMENT_ID, kept for
compatibility with the original 1Password integration, or the generic
DOCKHAND_SECRET_SELECTOR for any bulk-capable provider. The selector is
consumed by the provider and stripped before the vars reach the stack.
Values the bound provider recognises as inline references are resolved in
place, and references found only in the stack's .env file are promoted into
the secret set so they are never written back as literals.

Resolution is applied on deploy, on up, on recreate and on service update.
Explicitly configured secrets always win over bulk-pulled ones. A missing
or unsupported provider warns and leaves values untouched rather than
failing the deploy; a provider that errors mid-resolution fails it.

* Add secret provider settings UI and stack binding

A Secrets tab under settings lists configured providers and drives the
create/edit modal, which switches its fields on the selected provider type
and can test a connection before saving.

Both stack modals gain a provider selector so a stack can be bound to a
provider or left unbound. When a provider is bound, the bulk selector
variables are no longer reported as unused compose variables, since they
are consumed by the provider rather than the compose file.

---------

Co-authored-by: GooRoo <sergey.olendarenko@gmail.com>
Co-authored-by: Jarek Krochmalski <jotka@users.noreply.github.com>
2026-08-13 10:08:02 +02:00

181 lines
6.6 KiB
TypeScript

/**
* Unit tests for the Infisical secret provider.
*
* Infisical is open-source and self-hostable, so it is integration-testable
* against a real instance later. Here we exercise the provider in isolation by
* mocking undici's `request`, covering:
* - a successful bulk pull mapping { secretKey, secretValue } → Record
* - the selector / config.path / '/' precedence for the queried path
* - an auth failure (HTTP 401) surfacing as a thrown error
* - testConnection returning ok on 2xx and a helpful error otherwise
* - resolveSecretReferences throwing UnsupportedOperationError (bulk-only)
*/
import { describe, it, expect, mock, beforeEach } from 'bun:test';
/**
* A single mock for undici's `request`. Registered before the provider is
* imported so the provider's `import { request } from 'undici'` binds to it.
* Each test sets its behaviour via `requestMock.mockImplementation(...)`.
*/
const requestMock = mock();
mock.module('undici', () => ({ request: requestMock }));
const { infisicalProvider } = await import('../src/lib/server/secretproviders/infisical.ts');
const { UnsupportedOperationError } = await import('../src/lib/server/secretproviders/shared.ts');
/** Builds an undici-style response with json()/text() bodies. */
function response(statusCode: number, json: unknown, text = '') {
return {
statusCode,
body: {
json: async () => json,
text: async () => text
}
};
}
const baseConfig = {
host: 'https://app.infisical.com',
token: 'st.token.value',
projectId: 'proj-123',
environment: 'prod',
path: '/'
};
beforeEach(() => {
requestMock.mockReset();
});
describe('infisicalProvider capabilities', () => {
it('advertises bulk-only, no references', () => {
expect(infisicalProvider.type).toBe('infisical');
expect(infisicalProvider.label).toBe('Infisical');
expect(infisicalProvider.supportsBulk).toBe(true);
expect(infisicalProvider.supportsReferences).toBe(false);
});
it('isReference is always false', () => {
expect(infisicalProvider.isReference('op://vault/item/field')).toBe(false);
expect(infisicalProvider.isReference('anything')).toBe(false);
expect(infisicalProvider.isReference(42)).toBe(false);
});
});
describe('infisicalProvider.resolveBulk', () => {
it('maps secretKey/secretValue pairs into a flat record', async () => {
requestMock.mockImplementation(async () =>
response(200, {
secrets: [
{ secretKey: 'DB_PASSWORD', secretValue: 's3cr3t' },
{ secretKey: 'API_KEY', secretValue: 'abc123' }
]
})
);
const result = await infisicalProvider.resolveBulk(baseConfig, '');
expect(result).toEqual({ DB_PASSWORD: 's3cr3t', API_KEY: 'abc123' });
// Verify the request shape: raw secrets endpoint, bearer auth, and the
// workspace/environment/path query.
const [url, opts] = requestMock.mock.calls[0];
expect(url).toContain('https://app.infisical.com/api/v3/secrets/raw');
expect(url).toContain('workspaceId=proj-123');
expect(url).toContain('environment=prod');
expect(url).toContain('secretPath=%2F');
expect(opts.method).toBe('GET');
expect(opts.headers.authorization).toBe('Bearer st.token.value');
});
it('tolerates an absent secrets array', async () => {
requestMock.mockImplementation(async () => response(200, {}));
const result = await infisicalProvider.resolveBulk(baseConfig, '');
expect(result).toEqual({});
});
it('prefers the selector over config.path for secretPath', async () => {
requestMock.mockImplementation(async () => response(200, { secrets: [] }));
await infisicalProvider.resolveBulk({ ...baseConfig, path: '/config' }, '/services/web');
const [url] = requestMock.mock.calls[0];
expect(url).toContain('secretPath=%2Fservices%2Fweb');
});
it('falls back to config.path when the selector is empty', async () => {
requestMock.mockImplementation(async () => response(200, { secrets: [] }));
await infisicalProvider.resolveBulk({ ...baseConfig, path: '/config' }, '');
const [url] = requestMock.mock.calls[0];
expect(url).toContain('secretPath=%2Fconfig');
});
it('throws on an auth failure (HTTP 401)', async () => {
requestMock.mockImplementation(async () =>
response(401, {}, 'Unauthorized: invalid token')
);
await expect(infisicalProvider.resolveBulk(baseConfig, '')).rejects.toThrow(/401/);
});
it('throws a clear error when the environment is missing', async () => {
await expect(
infisicalProvider.resolveBulk({ ...baseConfig, environment: undefined }, '')
).rejects.toThrow(/Environment is required/);
// No HTTP call should have been attempted.
expect(requestMock).not.toHaveBeenCalled();
});
});
describe('infisicalProvider.resolveSecretReferences', () => {
it('throws UnsupportedOperationError (bulk-only backend)', async () => {
await expect(
infisicalProvider.resolveSecretReferences(baseConfig, ['ref'])
).rejects.toBeInstanceOf(UnsupportedOperationError);
await expect(
infisicalProvider.resolveSecretReferences(baseConfig, ['ref'])
).rejects.toThrow(/does not support inline references/);
expect(requestMock).not.toHaveBeenCalled();
});
});
describe('infisicalProvider.testConnection', () => {
it('returns ok on a 2xx response', async () => {
requestMock.mockImplementation(async () => response(200, { secrets: [] }));
const result = await infisicalProvider.testConnection(baseConfig);
expect(result.ok).toBe(true);
const [url] = requestMock.mock.calls[0];
expect(url).toContain('secretPath=%2F');
});
it('returns ok:false with the status on an auth failure', async () => {
requestMock.mockImplementation(async () => response(401, {}, 'Unauthorized'));
const result = await infisicalProvider.testConnection(baseConfig);
expect(result.ok).toBe(false);
expect(result.error).toContain('401');
});
it('does not throw when the transport fails, returns the message', async () => {
requestMock.mockImplementation(async () => {
throw new Error('ECONNREFUSED');
});
const result = await infisicalProvider.testConnection(baseConfig);
expect(result.ok).toBe(false);
expect(result.error).toContain('ECONNREFUSED');
});
it('returns a helpful error when projectId is empty (no HTTP call)', async () => {
const result = await infisicalProvider.testConnection({ ...baseConfig, projectId: '' });
expect(result.ok).toBe(false);
expect(result.error).toContain('Project ID');
expect(requestMock).not.toHaveBeenCalled();
});
it('returns a helpful error when environment is empty (no HTTP call)', async () => {
const result = await infisicalProvider.testConnection({
...baseConfig,
environment: undefined
});
expect(result.ok).toBe(false);
expect(result.error).toContain('Environment');
expect(requestMock).not.toHaveBeenCalled();
});
});