Files
dockhand-upstream/src/routes/api/stacks/[name]/compose/+server.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

128 lines
4.5 KiB
TypeScript

import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { getStackComposeFile, deployStack, saveStackComposeFile } from '$lib/server/stacks';
import { authorize } from '$lib/server/authorize';
import { createJobResponse } from '$lib/server/sse';
// GET /api/stacks/[name]/compose - Get compose file content
export const GET: RequestHandler = async ({ params, url, cookies }) => {
const auth = await authorize(cookies);
if (auth.authEnabled && !(await auth.can('stacks', 'view'))) {
return json({ error: 'Permission denied' }, { status: 403 });
}
const { name } = params;
const envId = url.searchParams.get('env');
const envIdNum = envId ? parseInt(envId) : undefined;
try {
const result = await getStackComposeFile(name, envIdNum);
if (!result.success) {
// Return info about what's needed - unified response for all missing compose files
return json({
error: result.error,
needsFileLocation: result.needsFileLocation || false,
composePath: result.composePath,
envPath: result.envPath
}, { status: 404 });
}
return json({
content: result.content,
stackDir: result.stackDir,
composePath: result.composePath,
envPath: result.envPath,
suggestedEnvPath: result.suggestedEnvPath
});
} catch (error: any) {
console.error(`Error getting compose file for stack ${name}:`, error);
return json({ error: error.message || 'Failed to get compose file' }, { status: 500 });
}
};
// PUT /api/stacks/[name]/compose - Update compose file content
export const PUT: RequestHandler = async ({ params, request, url, cookies }) => {
const auth = await authorize(cookies);
const { name } = params;
const envId = url.searchParams.get('env');
const envIdNum = envId ? parseInt(envId) : undefined;
// Permission check with environment context
if (auth.authEnabled && !(await auth.can('stacks', 'edit', envIdNum))) {
return json({ error: 'Permission denied' }, { status: 403 });
}
try {
const body = await request.json();
const { content, restart = false, composePath, envPath, moveFromDir, oldComposePath, oldEnvPath, secretProviderId } = body;
if (!content || typeof content !== 'string') {
return json({ error: 'Compose file content is required' }, { status: 400 });
}
if (
'secretProviderId' in body &&
secretProviderId !== null &&
typeof secretProviderId !== 'number'
) {
return json({ error: 'secretProviderId must be a number or null' }, { status: 400 });
}
// Build options object for custom paths, move operation, file renames, and secret provider binding
const pathOptions = (composePath || envPath !== undefined || moveFromDir || oldComposePath || oldEnvPath || secretProviderId !== undefined)
? { composePath, envPath, moveFromDir, oldComposePath, oldEnvPath, secretProviderId }
: undefined;
if (restart) {
// Deploy with docker compose up -d --force-recreate
// Force recreate ensures env var changes are applied
// Save paths first if provided
if (pathOptions) {
const saveResult = await saveStackComposeFile(name, content, false, envIdNum, pathOptions);
if (!saveResult.success) {
return json({ error: saveResult.error }, { status: 500 });
}
}
// Get authoritative paths from DB/filesystem for deploy
const composeInfo = await getStackComposeFile(name, envIdNum);
// Deploy via SSE to keep connection alive during long operations
return createJobResponse(async (send) => {
try {
const result = await deployStack({
name,
compose: content,
envId: envIdNum,
forceRecreate: true,
composePath: composeInfo.composePath || undefined,
envPath: composeInfo.envPath || undefined
});
if (!result.success) {
send('result', { success: false, error: result.error });
return;
}
send('result', { success: true });
} catch (error: any) {
console.error(`Error deploying stack ${name}:`, error);
send('result', { success: false, error: error.message || 'Failed to deploy stack' });
}
}, request);
}
// Just save the file without restarting (update operation, not create)
const result = await saveStackComposeFile(name, content, false, envIdNum, pathOptions);
if (!result.success) {
return json({ error: result.error }, { status: 500 });
}
return json({ success: true });
} catch (error: any) {
console.error(`Error updating compose file for stack ${name}:`, error);
return json({ error: error.message || 'Failed to update compose file' }, { status: 500 });
}
};