From 89f89d5be8a9a9c148c2274df08c2efef3443858 Mon Sep 17 00:00:00 2001 From: Carlos Lopez Date: Wed, 25 Nov 2026 18:51:09 +0100 Subject: [PATCH 1/2] Feat: State IaC organization backends and project bindings (#106) - state_backends / state_bindings in GitDB, credentials AES-GCM encrypted (AAD = backend id) - ObjectStore (GCS, S3 + compatible, in-memory) with streaming gunzip and size limit - Basic Pulumi DIY discovery (project and legacy layouts) to assign projects - organization:stateiac:backends:* and stacks:read permissions, org admin gets all - API /api/state-iac/backends/** and settings page /org//settings/state-iac - state_iac.backend.* and state_iac.binding.updated events (no credentials) - Removes the old storage module and the dead /settings/storage redirect Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 17 +- e2e/fixtures/seed.ts | 21 + e2e/specs/organization-settings.spec.ts | 1 + e2e/specs/state-iac-backends.spec.ts | 97 +++++ src/hooks.server.ts | 3 + src/lib/components/AppSidebar.svelte | 2 +- src/lib/config/permissions.ts | 18 + src/lib/database/schemas.ts | 43 +++ src/lib/events/catalog/index.ts | 3 + src/lib/events/catalog/state-iac.events.ts | 128 ++++++ src/lib/events/catalog/types.ts | 2 +- src/lib/events/domain-events.ts | 33 ++ src/lib/i18n/locales/en.json | 185 ++++++++- src/lib/i18n/locales/es.json | 185 ++++++++- src/lib/navigation.ts | 7 + src/lib/server/state-iac/backends.ts | 266 +++++++++++++ .../auth/domain/role-permissions.data.ts | 2 + .../application/state-backend.service.test.ts | 313 +++++++++++++++ .../application/state-backend.service.ts | 364 ++++++++++++++++++ .../application/state-binding.service.test.ts | 112 ++++++ .../application/state-binding.service.ts | 178 +++++++++ src/modules/state-iac/application/testing.ts | 75 ++++ .../state-iac/domain/state-backend.domain.ts | 154 ++++++++ .../domain/state-backend.validation.ts | 213 ++++++++++ .../state-iac/domain/state-binding.domain.ts | 63 +++ src/modules/state-iac/index.ts | 66 ++++ .../crypto/credentials-cipher.test.ts | 39 ++ .../crypto/credentials-cipher.ts | 66 ++++ .../engines/pulumi/pulumi-discovery.test.ts | 116 ++++++ .../engines/pulumi/pulumi-discovery.ts | 141 +++++++ .../infrastructure/object-store/factory.ts | 36 ++ .../object-store/gcs-object-store.ts | 86 +++++ .../object-store/in-memory-object-store.ts | 109 ++++++ .../object-store/object-store.test.ts | 90 +++++ .../object-store/object-store.ts | 177 +++++++++ .../object-store/s3-object-store.ts | 101 +++++ .../repositories/in-memory.repositories.ts | 76 ++++ .../repositories/state-backend.repository.ts | 48 +++ .../repositories/state-binding.repository.ts | 60 +++ .../storage/application/storage.service.ts | 171 -------- src/modules/storage/domain/entities.ts | 10 - src/modules/storage/index.ts | 3 - src/routes/+layout.server.ts | 3 + src/routes/api/state-iac/backends/+server.ts | 28 ++ .../api/state-iac/backends/[id]/+server.ts | 23 ++ .../backends/[id]/projects/+server.ts | 8 + .../[id]/projects/[pulumiProject]/+server.ts | 20 + .../state-iac/backends/[id]/test/+server.ts | 7 + .../api/state-iac/backends/server.test.ts | 284 ++++++++++++++ .../org/[org]/settings/events/event-view.ts | 1 + .../[org]/settings/state-iac/+page.server.ts | 150 ++++++++ .../org/[org]/settings/state-iac/+page.svelte | 355 +++++++++++++++++ .../state-iac/BackendFormModal.svelte | 286 ++++++++++++++ .../settings/state-iac/BackendProjects.svelte | 210 ++++++++++ .../org/[org]/settings/state-iac/types.ts | 41 ++ .../[org]/settings/storage/+page.server.ts | 5 - 56 files changed, 5105 insertions(+), 196 deletions(-) create mode 100644 e2e/specs/state-iac-backends.spec.ts create mode 100644 src/lib/events/catalog/state-iac.events.ts create mode 100644 src/lib/server/state-iac/backends.ts create mode 100644 src/modules/state-iac/application/state-backend.service.test.ts create mode 100644 src/modules/state-iac/application/state-backend.service.ts create mode 100644 src/modules/state-iac/application/state-binding.service.test.ts create mode 100644 src/modules/state-iac/application/state-binding.service.ts create mode 100644 src/modules/state-iac/application/testing.ts create mode 100644 src/modules/state-iac/domain/state-backend.domain.ts create mode 100644 src/modules/state-iac/domain/state-backend.validation.ts create mode 100644 src/modules/state-iac/domain/state-binding.domain.ts create mode 100644 src/modules/state-iac/index.ts create mode 100644 src/modules/state-iac/infrastructure/crypto/credentials-cipher.test.ts create mode 100644 src/modules/state-iac/infrastructure/crypto/credentials-cipher.ts create mode 100644 src/modules/state-iac/infrastructure/engines/pulumi/pulumi-discovery.test.ts create mode 100644 src/modules/state-iac/infrastructure/engines/pulumi/pulumi-discovery.ts create mode 100644 src/modules/state-iac/infrastructure/object-store/factory.ts create mode 100644 src/modules/state-iac/infrastructure/object-store/gcs-object-store.ts create mode 100644 src/modules/state-iac/infrastructure/object-store/in-memory-object-store.ts create mode 100644 src/modules/state-iac/infrastructure/object-store/object-store.test.ts create mode 100644 src/modules/state-iac/infrastructure/object-store/object-store.ts create mode 100644 src/modules/state-iac/infrastructure/object-store/s3-object-store.ts create mode 100644 src/modules/state-iac/infrastructure/repositories/in-memory.repositories.ts create mode 100644 src/modules/state-iac/infrastructure/repositories/state-backend.repository.ts create mode 100644 src/modules/state-iac/infrastructure/repositories/state-binding.repository.ts delete mode 100644 src/modules/storage/application/storage.service.ts delete mode 100644 src/modules/storage/domain/entities.ts delete mode 100644 src/modules/storage/index.ts create mode 100644 src/routes/api/state-iac/backends/+server.ts create mode 100644 src/routes/api/state-iac/backends/[id]/+server.ts create mode 100644 src/routes/api/state-iac/backends/[id]/projects/+server.ts create mode 100644 src/routes/api/state-iac/backends/[id]/projects/[pulumiProject]/+server.ts create mode 100644 src/routes/api/state-iac/backends/[id]/test/+server.ts create mode 100644 src/routes/api/state-iac/backends/server.test.ts create mode 100644 src/routes/org/[org]/settings/state-iac/+page.server.ts create mode 100644 src/routes/org/[org]/settings/state-iac/+page.svelte create mode 100644 src/routes/org/[org]/settings/state-iac/BackendFormModal.svelte create mode 100644 src/routes/org/[org]/settings/state-iac/BackendProjects.svelte create mode 100644 src/routes/org/[org]/settings/state-iac/types.ts delete mode 100644 src/routes/org/[org]/settings/storage/+page.server.ts diff --git a/CLAUDE.md b/CLAUDE.md index eb807dd1..e6ca754e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -167,7 +167,7 @@ Domain layers include entity classes (e.g., `*.domain.ts`) and centralized data `*.data.ts`) for configuration constants: role permissions, default project settings, risk weights, and tool policy mappings. -Current modules include `auth`, `config`, `organization`, `projects`, `storage`, +Current modules include `auth`, `config`, `organization`, `projects`, `state-iac`, `code-report`, `vault`, `audit`, `alerts`, `monitoring`, and `notifications`. The `notifications` module handles external email recipients of alerts (allowed domains, verification tokens, unsubscribe tracking). Shared infrastructure lives in `src/lib/`. Routes should import module APIs from @@ -194,6 +194,21 @@ origin of the absolute links in emails (`absoluteUrl()`); only under `vite dev` the origin of the requests the dev server receives instead (`rememberDevOrigin()` in `hooks.server.ts`), so they work on port 5173 whatever `ORIGIN` says. +## State IaC + +`$modules/state-iac` reads IaC state from the buckets where teams keep it; design and Pulumi DIY +layout in `docs/adr/0003-state-iac.md`, anonymized real buckets in `test/fixtures/state-iac/` +(load them with `fixtureStore()` from `application/testing.ts`). GitDB only stores configuration: +`state_backends` (one bucket/prefix per row, per organization; credentials AES-GCM encrypted with +the backend id as AAD, never returned, only `hasCredentials`) and `state_bindings` (one per Pulumi +project of a backend → a GitOps project of the same organization; `stacks` empty = all). Bindings +go with their backend and with their GitOps project (`registerStateIac()` listens to +`project.deleted`). Buckets are only read through `ObjectStore` (`GcsObjectStore`, `S3ObjectStore`, +`InMemoryObjectStore` in tests): never add a write. Org settings page `/org//settings/state-iac` +and `/api/state-iac/backends/**` check `organization:stateiac:backends:` (actions include +`test`); a backend of another organization answers 404. Read failures are stored as short codes in +`lastError` (`access_denied`, `bucket_not_found`…), never the provider message. + ## Domain events Services announce what happened on an in-process event bus in `#lib/server/events`; the design is diff --git a/e2e/fixtures/seed.ts b/e2e/fixtures/seed.ts index ef57e642..07b7bc5f 100644 --- a/e2e/fixtures/seed.ts +++ b/e2e/fixtures/seed.ts @@ -14,6 +14,7 @@ export type PersonaKey = | 'orgOutsider' | 'orgNone' | 'orgProjectsReadOnly' + | 'orgStateIacReader' | 'projectAdmin' | 'projectDeveloper' | 'projectViewer' @@ -146,6 +147,22 @@ export async function seedAll(): Promise { email: 'org-projects-read-only@e2e.test', }); + // sees the State IaC backends and their assignments, can't change them + const orgStateIacReaderRole = await roleService.createRole({ + name: 'E2E Org State IaC Reader', + slug: 'e2e-org-stateiac-reader', + scope: 'organization', + organizationId: primaryOrg.id, + permissions: ['organization:stateiac:backends:read'], + }); + const orgStateIacReader = await userAccessService.createOrganizationUser({ + organizationId: primaryOrg.id, + username: 'e2e-org-stateiac-reader', + password: E2E_PASSWORD, + roleId: orgStateIacReaderRole.id, + email: 'org-stateiac-reader@e2e.test', + }); + // --- primary project under the primary org ---------------------------------------------- const primaryProject = await projectService.createProject({ organizationId: primaryOrg.id, @@ -353,6 +370,10 @@ export async function seedAll(): Promise { userId: orgProjectsReadOnly.userId, username: orgProjectsReadOnly.username, }, + orgStateIacReader: { + userId: orgStateIacReader.userId, + username: orgStateIacReader.username, + }, projectAdmin: { userId: projectAdminUser.userId, username: projectAdminUser.username }, projectDeveloper: { userId: projectDeveloperUser.userId, diff --git a/e2e/specs/organization-settings.spec.ts b/e2e/specs/organization-settings.spec.ts index 03781643..843ca195 100644 --- a/e2e/specs/organization-settings.spec.ts +++ b/e2e/specs/organization-settings.spec.ts @@ -14,6 +14,7 @@ const settingsRoutes = [ `/org/${org}/settings/audit`, `/org/${org}/settings/events`, `/org/${org}/settings/alerts`, + `/org/${org}/settings/state-iac`, ]; test.describe('organization settings — org admin', () => { diff --git a/e2e/specs/state-iac-backends.spec.ts b/e2e/specs/state-iac-backends.spec.ts new file mode 100644 index 00000000..0e601a4d --- /dev/null +++ b/e2e/specs/state-iac-backends.spec.ts @@ -0,0 +1,97 @@ +import { test, expect, getSeed } from '../fixtures/auth'; +import { expectAllowed, expectDenied } from '../fixtures/expect-access'; +import { E2E_BASE_URL } from '../global-setup'; + +const seed = getSeed(); +const pageUrl = `/org/${seed.primaryOrgSlug}/settings/state-iac`; +const api = `${E2E_BASE_URL}/api/state-iac/backends`; + +const backendBody = (name: string) => ({ + organizationId: seed.primaryOrgId, + name, + provider: 's3', + bucket: 'e2e-state', + endpoint: 'https://minio.example.com', + auth: 'credentials', + credentials: { accessKeyId: 'AKIAE2E', secretAccessKey: 'e2e-very-secret' }, +}); + +test.describe.configure({ mode: 'serial' }); + +test.describe('state iac backends — org admin', () => { + test('creates a backend from the modal and deletes it typing its name', async ({ + page, + loginAs, + }) => { + await loginAs('orgAdmin'); + await expectAllowed(page, pageUrl); + await page.waitForLoadState('networkidle'); + + await page.getByRole('button', { name: 'Nuevo backend' }).click(); + const modal = page.getByRole('dialog', { name: 'Nuevo backend' }); + await modal.getByLabel('Nombre').fill('e2e-gcs'); + await modal.getByLabel('Bucket').fill('e2e-pulumi-state'); + await modal.getByLabel('Prefijo').fill('infra'); + await modal.getByRole('button', { name: 'Nuevo backend' }).click(); + + const card = page.getByTestId('state-backends').locator('li', { hasText: 'e2e-gcs' }); + await expect(card).toBeVisible(); + await expect(card.getByText('gs://e2e-pulumi-state/infra')).toBeVisible(); + + await card.getByRole('button', { name: 'Eliminar: e2e-gcs' }).click(); + const confirm = page.getByRole('alertdialog', { name: '¿Eliminar backend?' }); + const submit = confirm.getByRole('button', { name: 'Eliminar' }); + await expect(submit).toBeDisabled(); + await confirm.getByLabel('Escribe e2e-gcs para confirmar').fill('e2e-gcs'); + await submit.click(); + await expect(page.getByTestId('state-backends-empty')).toBeVisible(); + }); + + test('the API never returns the credentials', async ({ page, loginAs }) => { + await loginAs('orgAdmin'); + const created = await page.request.post(api, { data: backendBody('e2e-s3') }); + expect(created.status()).toBe(201); + const { id } = (await created.json()) as { id: string }; + const listed = await page.request.get(`${api}?organizationId=${seed.primaryOrgId}`); + const text = await listed.text(); + expect(text).toContain('"hasCredentials":true'); + expect(text).not.toContain('e2e-very-secret'); + expect(text).not.toContain('AKIAE2E'); + expect((await page.request.delete(`${api}/${id}`)).status()).toBe(200); + }); +}); + +test.describe('state iac backends — read only', () => { + test('organization:stateiac:backends:read sees the page but cannot configure', async ({ + page, + loginAs, + }) => { + await loginAs('orgStateIacReader'); + await expectAllowed(page, pageUrl); + await expect(page.getByRole('heading', { name: 'State IaC', level: 1 })).toBeVisible(); + await expect(page.getByRole('button', { name: 'Nuevo backend' })).toHaveCount(0); + + expect((await page.request.post(api, { data: backendBody('nope') })).status()).toBe(403); + expect((await page.request.get(`${api}?organizationId=${seed.primaryOrgId}`)).status()).toBe( + 200, + ); + }); +}); + +test.describe('state iac backends — no stateiac grant', () => { + test('an org developer is denied the page and the API', async ({ page, loginAs }) => { + await loginAs('orgDeveloper'); + await expectDenied(page, pageUrl); + expect((await page.request.get(`${api}?organizationId=${seed.primaryOrgId}`)).status()).toBe( + 403, + ); + expect((await page.request.post(api, { data: backendBody('nope') })).status()).toBe(403); + }); + + test('a member of another organization is denied', async ({ page, loginAs }) => { + await loginAs('orgOutsider'); + expect((await page.request.get(`${api}?organizationId=${seed.primaryOrgId}`)).status()).toBe( + 403, + ); + }); +}); diff --git a/src/hooks.server.ts b/src/hooks.server.ts index 668d0697..8b841e22 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -4,6 +4,7 @@ import { apiKeysService, authService, cancanService, ensureAuthReady } from '#mo import { organizationService } from '#modules/organization'; import { projectService } from '#modules/projects'; import { registerAlertEngine } from '#modules/alerts'; +import { registerStateIac } from '#modules/state-iac'; import { getMonitoringConfig, startMonitoring } from '#modules/monitoring'; import { isInternalMonitoringRequest, @@ -25,6 +26,8 @@ const serverReady = (async () => { await ensureAuthReady(); // once per process (HMR-safe): system notifications and alerts on every published event registerAlertEngine(); + // State IaC bindings follow the projects they point at + registerStateIac(); await refreshBootstrapState(); markServerReady(); // monitoring needs GitDB; if its repository or runtime can't start, the rest of the app still does diff --git a/src/lib/components/AppSidebar.svelte b/src/lib/components/AppSidebar.svelte index 28abb1fe..b31b97e6 100644 --- a/src/lib/components/AppSidebar.svelte +++ b/src/lib/components/AppSidebar.svelte @@ -179,7 +179,7 @@ {#if !isConfigured} 0) { orgModules.push({ diff --git a/src/lib/server/state-iac/backends.ts b/src/lib/server/state-iac/backends.ts new file mode 100644 index 00000000..9f481601 --- /dev/null +++ b/src/lib/server/state-iac/backends.ts @@ -0,0 +1,266 @@ +import { + StateBackendNotFoundError, + StateIacValidationError, + stateBackendService, + stateBindingService, + type BackendInput, + type BackendTestResult, + type BindingInput, + type PulumiLayout, + type StateBackendView, +} from '#modules/state-iac'; +import { organizationService } from '#modules/organization'; +import { callerCan, type AlertLocals } from '#lib/server/alerts/access'; + +/** + * State IaC backends and bindings for the API and the settings page. Every operation checks + * `organization:stateiac:backends:` in the backend's organization; a backend of an + * organization the caller can't read answers 404, like a missing one. + */ +export type BackendAction = 'read' | 'create' | 'update' | 'delete' | 'test'; + +export type StateIacResult = + | { ok: true; status: number; data: T } + | { ok: false; status: number; error: string; errors?: Record }; + +const forbidden = { ok: false as const, status: 403, error: 'Forbidden' }; +const notFound = { ok: false as const, status: 404, error: 'Backend not found' }; + +export function canManageBackends( + locals: AlertLocals, + organizationId: string, + action: BackendAction, +): Promise { + return callerCan(locals, `organization:stateiac:backends:${action}`, { + scope: 'organization', + organizationId, + }); +} + +function failure(error: unknown): StateIacResult { + if (error instanceof StateIacValidationError) { + return { ok: false, status: 400, error: 'Invalid backend', errors: error.errors }; + } + if (error instanceof StateBackendNotFoundError) return notFound; + throw error; +} + +async function loadAuthorized(locals: AlertLocals, id: string, action: BackendAction) { + const backend = await stateBackendService.get(id).catch(() => null); + if (!backend) return notFound; + if (!(await canManageBackends(locals, backend.organizationId, 'read'))) return notFound; + if (action !== 'read' && !(await canManageBackends(locals, backend.organizationId, action))) { + return forbidden; + } + return { ok: true as const, status: 200, data: backend }; +} + +/** `organizationId` of a request, checked to exist. */ +export async function resolveOrganization( + organizationId: unknown, +): Promise> { + const id = typeof organizationId === 'string' ? organizationId.trim() : ''; + if (!id) return { ok: false, status: 400, error: 'organizationId is required' }; + const organization = await organizationService.getOrganization(id).catch(() => null); + if (!organization) return { ok: false, status: 404, error: 'Organization not found' }; + return { ok: true, status: 200, data: { organizationId: id } }; +} + +export async function listBackends( + locals: AlertLocals, + organizationId: string, +): Promise> { + if (!(await canManageBackends(locals, organizationId, 'read'))) return forbidden; + const backends = await stateBackendService.list(organizationId); + return { ok: true, status: 200, data: { backends: backends.map((b) => b.toView()) } }; +} + +export async function getBackend( + locals: AlertLocals, + id: string, +): Promise> { + const loaded = await loadAuthorized(locals, id, 'read'); + return loaded.ok ? { ok: true, status: 200, data: loaded.data.toView() } : loaded; +} + +export async function createBackend( + locals: AlertLocals, + organizationId: string, + input: BackendInput, +): Promise> { + if (!(await canManageBackends(locals, organizationId, 'create'))) return forbidden; + try { + const backend = await stateBackendService.create(organizationId, input); + return { ok: true, status: 201, data: backend.toView() }; + } catch (error) { + return failure(error); + } +} + +export async function updateBackend( + locals: AlertLocals, + id: string, + input: BackendInput, +): Promise> { + const loaded = await loadAuthorized(locals, id, 'update'); + if (!loaded.ok) return loaded; + try { + const backend = await stateBackendService.update(id, input); + return { ok: true, status: 200, data: backend.toView() }; + } catch (error) { + return failure(error); + } +} + +export async function deleteBackend( + locals: AlertLocals, + id: string, +): Promise> { + const loaded = await loadAuthorized(locals, id, 'delete'); + if (!loaded.ok) return loaded; + try { + await stateBackendService.delete(id); + return { ok: true, status: 200, data: { id } }; + } catch (error) { + return failure(error); + } +} + +export async function testBackend( + locals: AlertLocals, + id: string, +): Promise> { + const loaded = await loadAuthorized(locals, id, 'test'); + if (!loaded.ok) return loaded; + return { ok: true, status: 200, data: await stateBackendService.test(id) }; +} + +export type DiscoveredPulumiProject = { + /** `null`: legacy stacks whose project can't be found yet (no resources). */ + name: string | null; + stacks: string[]; + binding: { projectId: string; stacks: string[] } | null; +}; + +export type BackendProjects = + | { + ok: true; + layout: PulumiLayout; + metaVersion: number | null; + truncated: boolean; + projects: DiscoveredPulumiProject[]; + /** Bindings whose Pulumi project is no longer in the bucket. */ + missing: Array<{ pulumiProject: string; projectId: string; stacks: string[] }>; + } + | { + ok: false; + error: string; + projects: []; + missing: Array<{ pulumiProject: string; projectId: string; stacks: string[] }>; + }; + +/** Pulumi projects found in the bucket with their assignment. Needs `backends:read`. */ +export async function listBackendProjects( + locals: AlertLocals, + id: string, +): Promise> { + const loaded = await loadAuthorized(locals, id, 'read'); + if (!loaded.ok) return loaded; + const [discovery, bindings] = await Promise.all([ + stateBackendService.discover(id), + stateBindingService.listByBackend(id), + ]); + const byProject = new Map(bindings.map((binding) => [binding.pulumiProject, binding])); + const found = new Set(); + const projects: DiscoveredPulumiProject[] = discovery.ok + ? discovery.projects.map((project) => { + const binding = project.name ? byProject.get(project.name) : undefined; + if (project.name) found.add(project.name); + return { + name: project.name, + stacks: project.stacks.map((stack) => stack.name), + binding: binding ? { projectId: binding.projectId, stacks: binding.stacks } : null, + }; + }) + : []; + const missing = bindings + .filter((binding) => !found.has(binding.pulumiProject)) + .map((binding) => ({ + pulumiProject: binding.pulumiProject, + projectId: binding.projectId, + stacks: binding.stacks, + })); + const data: BackendProjects = discovery.ok + ? { + ok: true, + layout: discovery.layout, + metaVersion: discovery.metaVersion, + truncated: discovery.truncated, + projects, + missing, + } + : { ok: false, error: discovery.error, projects: [], missing }; + return { ok: true, status: 200, data }; +} + +export async function setBinding( + locals: AlertLocals, + id: string, + pulumiProject: string, + input: BindingInput, +): Promise> { + const loaded = await loadAuthorized(locals, id, 'update'); + if (!loaded.ok) return loaded; + try { + const binding = await stateBindingService.set(loaded.data, pulumiProject, input); + return { + ok: true, + status: 200, + data: { + pulumiProject: binding.pulumiProject, + projectId: binding.projectId, + stacks: binding.stacks, + }, + }; + } catch (error) { + return failure(error); + } +} + +export async function removeBinding( + locals: AlertLocals, + id: string, + pulumiProject: string, +): Promise> { + const loaded = await loadAuthorized(locals, id, 'update'); + if (!loaded.ok) return loaded; + const removed = await stateBindingService.remove(loaded.data, pulumiProject); + return { ok: true, status: 200, data: { pulumiProject, removed } }; +} + +/** Backend fields of a JSON body or a form, credentials included only when typed. */ +export function backendInputFrom(source: Record): BackendInput { + const field = (key: string) => (source[key] === undefined ? undefined : source[key]); + const credentials = + source.credentials && typeof source.credentials === 'object' + ? (source.credentials as Record) + : { + serviceAccountJson: source.serviceAccountJson, + accessKeyId: source.accessKeyId, + secretAccessKey: source.secretAccessKey, + sessionToken: source.sessionToken, + }; + return { + name: field('name'), + engine: field('engine'), + provider: field('provider'), + bucket: field('bucket'), + prefix: field('prefix'), + region: field('region'), + endpoint: field('endpoint'), + forcePathStyle: field('forcePathStyle'), + auth: field('auth'), + credentials, + enabled: field('enabled'), + }; +} diff --git a/src/modules/auth/domain/role-permissions.data.ts b/src/modules/auth/domain/role-permissions.data.ts index 40a25a73..d5ebb387 100644 --- a/src/modules/auth/domain/role-permissions.data.ts +++ b/src/modules/auth/domain/role-permissions.data.ts @@ -19,6 +19,8 @@ export const ORGANIZATION_ADMIN_PERMISSIONS = [ 'organization:events:all', 'organization:alerts:all', 'organization:notifications:all', + 'organization:stateiac:backends:all', + 'organization:stateiac:stacks:all', ]; export const ORGANIZATION_DEVELOPER_PERMISSIONS = [ diff --git a/src/modules/state-iac/application/state-backend.service.test.ts b/src/modules/state-iac/application/state-backend.service.test.ts new file mode 100644 index 00000000..85590e63 --- /dev/null +++ b/src/modules/state-iac/application/state-backend.service.test.ts @@ -0,0 +1,313 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { StateIacValidationError } from '../domain/state-backend.domain'; +import { createStateIacFixture, fixtureStore } from './testing'; + +const SERVICE_ACCOUNT = JSON.stringify({ + type: 'service_account', + project_id: 'acme', + client_email: 'state-reader@acme.iam.gserviceaccount.com', + private_key: '-----BEGIN PRIVATE KEY-----\nsupersecretkey\n-----END PRIVATE KEY-----\n', +}); + +const gcsInput = (overrides: Record = {}) => ({ + name: 'gcs-prod', + provider: 'gcs', + bucket: 'acme-pulumi-state', + ...overrides, +}); + +async function validationErrors(promise: Promise) { + try { + await promise; + } catch (error) { + if (error instanceof StateIacValidationError) return error.errors; + throw error; + } + throw new Error('expected a validation error'); +} + +describe('StateBackendService', () => { + let fx: ReturnType; + beforeEach(() => { + fx = createStateIacFixture(); + }); + + describe('create', () => { + it('creates an ambient-auth backend, normalizing bucket and prefix', async () => { + const backend = await fx.backendService.create( + 'org-1', + gcsInput({ bucket: 'gs://acme-pulumi-state/', prefix: '/infra/.pulumi/' }), + ); + expect(backend.toView()).toMatchObject({ + organizationId: 'org-1', + engine: 'pulumi', + provider: 'gcs', + bucket: 'acme-pulumi-state', + prefix: 'infra', + auth: 'ambient', + hasCredentials: false, + enabled: true, + }); + expect(backend.pulumiRoot).toBe('infra/.pulumi/'); + expect(fx.events.ofType('state_iac.backend.created').map((e) => e.payload)).toEqual([ + { + backendId: backend.id, + name: 'gcs-prod', + engine: 'pulumi', + provider: 'gcs', + bucket: 'acme-pulumi-state', + prefix: 'infra', + }, + ]); + }); + + it('stores credentials encrypted, bound to the backend, and never shows them', async () => { + const backend = await fx.backendService.create( + 'org-1', + gcsInput({ auth: 'credentials', credentials: { serviceAccountJson: SERVICE_ACCOUNT } }), + ); + const stored = fx.backends.rows[0].credentials ?? ''; + expect(stored).not.toContain('supersecretkey'); + expect(JSON.parse(fx.cipher.decrypt(backend.id, stored))).toEqual({ + provider: 'gcs', + serviceAccountJson: SERVICE_ACCOUNT, + }); + const view = backend.toView(); + expect(view.hasCredentials).toBe(true); + expect(JSON.stringify(view)).not.toContain('supersecretkey'); + expect('credentials' in view).toBe(false); + // nor in the event + expect(JSON.stringify(fx.events.events)).not.toContain('supersecretkey'); + }); + + it('returns errors per field', async () => { + expect( + await validationErrors( + fx.backendService.create('org-1', { provider: 'azure', bucket: 'Not A Bucket' }), + ), + ).toEqual({ name: 'required', provider: 'invalid_provider', bucket: 'invalid_bucket' }); + expect( + await validationErrors( + fx.backendService.create( + 'org-1', + gcsInput({ prefix: 'a/../b', endpoint: 'https://minio' }), + ), + ), + ).toEqual({ prefix: 'invalid_prefix', endpoint: 'endpoint_s3_only' }); + }); + + it('requires valid credentials when auth is credentials', async () => { + expect( + await validationErrors( + fx.backendService.create('org-1', gcsInput({ auth: 'credentials' })), + ), + ).toEqual({ credentials: 'required' }); + expect( + await validationErrors( + fx.backendService.create( + 'org-1', + gcsInput({ + auth: 'credentials', + credentials: { serviceAccountJson: '{"type":"user"}' }, + }), + ), + ), + ).toEqual({ credentials: 'invalid_service_account' }); + expect( + await validationErrors( + fx.backendService.create('org-1', { + name: 's3', + provider: 's3', + bucket: 'b-1', + auth: 'credentials', + credentials: { accessKeyId: 'AKIA' }, + }), + ), + ).toEqual({ credentials: 'access_key_required' }); + }); + + it('rejects duplicate names in the organization, not across organizations', async () => { + await fx.backendService.create('org-1', gcsInput()); + expect( + await validationErrors(fx.backendService.create('org-1', gcsInput({ name: 'GCS-PROD' }))), + ).toEqual({ name: 'duplicate_name' }); + await expect(fx.backendService.create('org-2', gcsInput())).resolves.toBeTruthy(); + }); + + it('accepts S3-compatible endpoints but not loopback, link-local or metadata hosts', async () => { + const s3 = (endpoint: string) => ({ + name: `s3-${Math.random()}`, + provider: 's3', + bucket: 'state', + endpoint, + }); + const minio = await fx.backendService.create('org-1', s3('http://10.0.0.5:9000/')); + expect(minio.endpoint).toBe('http://10.0.0.5:9000'); + // an endpoint means path-style by default (MinIO) + expect(minio.forcePathStyle).toBe(true); + for (const endpoint of [ + 'http://127.0.0.1:9000', + 'http://169.254.169.254', + 'http://localhost:9000', + 'http://metadata.google.internal', + 'http://[::1]:9000', + ]) { + expect(await validationErrors(fx.backendService.create('org-1', s3(endpoint)))).toEqual({ + endpoint: 'endpoint_not_allowed', + }); + } + for (const endpoint of ['ftp://minio', 'https://u:p@minio', 'https://minio/path', 'nope']) { + expect(await validationErrors(fx.backendService.create('org-1', s3(endpoint)))).toEqual({ + endpoint: 'invalid_endpoint', + }); + } + }); + }); + + describe('update', () => { + it('keeps the stored credentials when none are typed, replaces them when they are', async () => { + const backend = await fx.backendService.create('org-1', { + name: 's3', + provider: 's3', + bucket: 'state', + auth: 'credentials', + credentials: { accessKeyId: 'AKIA1', secretAccessKey: 'secret-1' }, + }); + const before = fx.backends.rows[0].credentials; + + await fx.backendService.update(backend.id, { name: 's3-renamed', credentials: {} }); + expect(fx.backends.rows[0].credentials).toBe(before); + + await fx.backendService.update(backend.id, { + credentials: { accessKeyId: 'AKIA2', secretAccessKey: 'secret-2' }, + }); + const after = fx.backends.rows[0].credentials ?? ''; + expect(after).not.toBe(before); + expect(JSON.parse(fx.cipher.decrypt(backend.id, after)).accessKeyId).toBe('AKIA2'); + + const updates = fx.events.ofType('state_iac.backend.updated').map((e) => e.payload); + expect(updates.map((p) => p.changedFields)).toEqual([['name'], ['credentials']]); + expect(JSON.stringify(updates)).not.toMatch(/secret-|AKIA/); + }); + + it('switching to ambient removes the credentials', async () => { + const backend = await fx.backendService.create( + 'org-1', + gcsInput({ auth: 'credentials', credentials: { serviceAccountJson: SERVICE_ACCOUNT } }), + ); + const updated = await fx.backendService.update(backend.id, { auth: 'ambient' }); + expect(updated.credentials).toBeNull(); + expect(fx.backends.rows[0].credentials).toBeNull(); + }); + + it('switching to credentials needs them', async () => { + const backend = await fx.backendService.create('org-1', gcsInput()); + expect( + await validationErrors(fx.backendService.update(backend.id, { auth: 'credentials' })), + ).toEqual({ credentials: 'required' }); + }); + + it('does not change the provider nor write when nothing changes', async () => { + const backend = await fx.backendService.create('org-1', gcsInput()); + expect( + await validationErrors(fx.backendService.update(backend.id, { provider: 's3' })), + ).toEqual({ provider: 'provider_immutable' }); + await fx.backendService.update(backend.id, { name: 'gcs-prod', bucket: 'acme-pulumi-state' }); + expect(fx.events.ofType('state_iac.backend.updated')).toHaveLength(0); + }); + + it('clears the last error when the bucket changes', async () => { + const backend = await fx.backendService.create('org-1', gcsInput()); + fx.backends.rows[0].lastError = 'access_denied'; + const updated = await fx.backendService.update(backend.id, { bucket: 'other-bucket' }); + expect(updated.lastError).toBeNull(); + }); + }); + + describe('delete', () => { + it('removes the backend and its bindings, and only those', async () => { + const a = await fx.backendService.create('org-1', gcsInput({ name: 'a' })); + const b = await fx.backendService.create('org-1', gcsInput({ name: 'b' })); + await fx.bindingService.set(a, 'network', { projectId: 'p1' }); + await fx.bindingService.set(b, 'payments', { projectId: 'p2' }); + + await fx.backendService.delete(a.id); + expect(fx.backends.rows.map((row) => row.id)).toEqual([b.id]); + expect(fx.bindings.rows.map((row) => row.pulumiProject)).toEqual(['payments']); + expect(fx.events.ofType('state_iac.backend.deleted')).toHaveLength(1); + }); + }); + + describe('test and discover (read-only)', () => { + it('lists the bucket and reads meta.yaml', async () => { + const backend = await fx.backendService.create('org-1', gcsInput({ prefix: 'infra' })); + fx.buckets.set('acme-pulumi-state', fixtureStore('project-layout', 'infra')); + expect(await fx.backendService.test(backend.id)).toEqual({ + ok: true, + layout: 'project', + metaVersion: 1, + projects: 2, + stacks: 3, + }); + expect(fx.backends.rows[0].lastScanAt).not.toBeNull(); + }); + + it('builds the store with the decrypted credentials, ambient with none', async () => { + const ambient = await fx.backendService.create('org-1', gcsInput({ name: 'ambient' })); + const keyed = await fx.backendService.create( + 'org-1', + gcsInput({ + name: 'keyed', + auth: 'credentials', + credentials: { serviceAccountJson: SERVICE_ACCOUNT }, + }), + ); + await fx.backendService.test(ambient.id); + await fx.backendService.test(keyed.id); + expect(fx.credentialsSeen).toEqual([ + null, + { provider: 'gcs', serviceAccountJson: SERVICE_ACCOUNT }, + ]); + }); + + it('records a failure as a short code, once', async () => { + const backend = await fx.backendService.create('org-1', gcsInput()); + const store = fixtureStore('project-layout'); + store.failWith = Object.assign(new Error('caller does not have storage.objects.list'), { + code: 403, + }); + fx.buckets.set('acme-pulumi-state', store); + + expect(await fx.backendService.test(backend.id)).toEqual({ + ok: false, + error: 'access_denied', + }); + expect(fx.backends.rows[0].lastError).toBe('access_denied'); + + store.failWith = null; + expect((await fx.backendService.discover(backend.id)).ok).toBe(true); + expect(fx.backends.rows[0].lastError).toBeNull(); + }); + + it('reports undecryptable credentials instead of throwing', async () => { + const backend = await fx.backendService.create( + 'org-1', + gcsInput({ auth: 'credentials', credentials: { serviceAccountJson: SERVICE_ACCOUNT } }), + ); + fx.backends.rows[0].credentials = 'v1:broken:value:here'; + expect(await fx.backendService.test(backend.id)).toEqual({ + ok: false, + error: 'undecryptable', + }); + }); + + it('never writes to the bucket', async () => { + const backend = await fx.backendService.create('org-1', gcsInput()); + const store = fixtureStore('project-layout'); + fx.buckets.set('acme-pulumi-state', store); + await fx.backendService.discover(backend.id); + // the store has no write method at all; only reads were made + expect(new Set(store.calls.map((call) => call.op))).toEqual(new Set(['get', 'list'])); + }); + }); +}); diff --git a/src/modules/state-iac/application/state-backend.service.ts b/src/modules/state-iac/application/state-backend.service.ts new file mode 100644 index 00000000..aaaa64b6 --- /dev/null +++ b/src/modules/state-iac/application/state-backend.service.ts @@ -0,0 +1,364 @@ +import type { Logger } from 'pino'; +import type { StateIacBackendChangedField } from '#lib/events/domain-events'; +import { publishAfterWrite, type EventPublisher } from '#lib/server/events/publish'; +import { + StateBackendDomain, + StateBackendNotFoundError, + StateIacValidationError, + type StateBackendCredentials, + type StateBackendRow, +} from '../domain/state-backend.domain'; +import { + hasCredentialsInput, + toBoolean, + validateAuth, + validateBucket, + validateCredentials, + validateEndpoint, + validateEngine, + validateName, + validatePrefix, + validateProvider, + validateRegion, + type CredentialsInput, + type FieldErrors, +} from '../domain/state-backend.validation'; +import type { CredentialsCipher } from '../infrastructure/crypto/credentials-cipher'; +import { + discoverPulumi, + UnsupportedLayoutError, + type PulumiDiscovery, + type PulumiLayout, +} from '../infrastructure/engines/pulumi/pulumi-discovery'; +import type { ObjectStoreFactory } from '../infrastructure/object-store/factory'; +import { + classifyStoreError, + type ObjectStore, + type StoreErrorCode, +} from '../infrastructure/object-store/object-store'; +import type { + StateBackendChanges, + StateBackendRepositoryPort, +} from '../infrastructure/repositories/state-backend.repository'; +import type { StateBindingRepositoryPort } from '../infrastructure/repositories/state-binding.repository'; + +export type BackendInput = { + name?: unknown; + engine?: unknown; + provider?: unknown; + bucket?: unknown; + prefix?: unknown; + region?: unknown; + endpoint?: unknown; + forcePathStyle?: unknown; + auth?: unknown; + /** Only read when `auth` is `credentials`; on update an empty value keeps the stored ones. */ + credentials?: CredentialsInput | null; + enabled?: unknown; +}; + +export type BackendErrorCode = StoreErrorCode | 'unsupported_layout' | 'undecryptable'; + +export type BackendTestResult = + | { + ok: true; + layout: PulumiLayout; + metaVersion: number | null; + projects: number; + stacks: number; + } + | { ok: false; error: BackendErrorCode }; + +export type DiscoveryOutcome = + ({ ok: true } & PulumiDiscovery) | { ok: false; error: BackendErrorCode }; + +export type StateBackendServiceOptions = { + now?: () => Date; + generateId?: () => string; + events?: EventPublisher; + logger?: Pick; + /** How often a successful read records `lastScanAt` (each record is a GitDB commit). */ + scanStampIntervalMs?: number; +}; + +const DEFAULT_SCAN_STAMP_INTERVAL_MS = 60 * 60 * 1000; +const silentLogger = { error: () => {} } as unknown as Pick; + +/** + * State IaC backends of organizations: buckets where Pulumi keeps its state. Only the + * configuration lives in GitDB; credentials are encrypted and never leave this service in clear + * text except to build the bucket client. The bucket itself is only ever read. + */ +export class StateBackendService { + private readonly now: () => Date; + private readonly generateId: () => string; + private readonly log: Pick; + private readonly stampIntervalMs: number; + + constructor( + private readonly repository: StateBackendRepositoryPort, + private readonly bindings: StateBindingRepositoryPort, + private readonly cipher: CredentialsCipher, + private readonly stores: ObjectStoreFactory, + private readonly options: StateBackendServiceOptions = {}, + ) { + this.now = options.now ?? (() => new Date()); + this.generateId = options.generateId ?? (() => crypto.randomUUID()); + this.log = options.logger ?? silentLogger; + this.stampIntervalMs = options.scanStampIntervalMs ?? DEFAULT_SCAN_STAMP_INTERVAL_MS; + } + + async get(id: string): Promise { + const backend = await this.repository.findById(id); + if (!backend) throw new StateBackendNotFoundError(id); + return backend; + } + + list(organizationId: string): Promise { + return this.repository.listByOrganization(organizationId); + } + + async create(organizationId: string, input: BackendInput): Promise { + const errors: FieldErrors = {}; + const name = validateName(input.name, errors); + const engine = validateEngine(input.engine, errors); + const provider = validateProvider(input.provider, errors); + const bucket = validateBucket(input.bucket, errors); + const prefix = validatePrefix(input.prefix, errors); + const region = validateRegion(input.region, errors); + const endpoint = validateEndpoint(input.endpoint, provider, errors); + const auth = validateAuth(input.auth, errors); + const credentials = + auth === 'credentials' && provider + ? validateCredentials(provider, input.credentials ?? {}, errors) + : null; + await this.checkUniqueName(organizationId, name, null, errors); + if (Object.keys(errors).length > 0 || !provider) throw new StateIacValidationError(errors); + + const id = this.generateId(); + const timestamp = this.now().toISOString(); + const row: StateBackendRow = { + id, + organizationId, + name, + engine, + provider, + bucket, + prefix, + region, + endpoint, + forcePathStyle: provider === 's3' && toBoolean(input.forcePathStyle, Boolean(endpoint)), + auth, + credentials: credentials ? this.cipher.encrypt(id, JSON.stringify(credentials)) : null, + enabled: toBoolean(input.enabled, true), + lastScanAt: null, + lastError: null, + createdAt: timestamp, + updatedAt: timestamp, + }; + await this.repository.create(row); + const backend = new StateBackendDomain(row); + await this.publish('state_iac.backend.created', backend); + return backend; + } + + /** + * Partial update: omitted fields keep their value. Credentials are replaced only when new ones + * are typed; switching to `ambient` removes them. The provider can't change: a bucket in + * another cloud is another backend. + */ + async update(id: string, input: BackendInput): Promise { + const backend = await this.get(id); + const errors: FieldErrors = {}; + const changes: StateBackendChanges = {}; + const provider = backend.provider; + + if (input.provider !== undefined && input.provider !== provider) { + errors.provider = 'provider_immutable'; + } + if (input.name !== undefined) { + changes.name = validateName(input.name, errors); + await this.checkUniqueName(backend.organizationId, changes.name, id, errors); + } + if (input.bucket !== undefined) changes.bucket = validateBucket(input.bucket, errors); + if (input.prefix !== undefined) changes.prefix = validatePrefix(input.prefix, errors); + if (input.region !== undefined) changes.region = validateRegion(input.region, errors); + if (input.endpoint !== undefined) { + changes.endpoint = validateEndpoint(input.endpoint, provider, errors); + } + if (input.forcePathStyle !== undefined) { + changes.forcePathStyle = provider === 's3' && toBoolean(input.forcePathStyle, false); + } + if (input.enabled !== undefined) changes.enabled = toBoolean(input.enabled, backend.enabled); + + const auth = input.auth !== undefined ? validateAuth(input.auth, errors) : backend.auth; + if (auth !== backend.auth) changes.auth = auth; + if (auth === 'ambient') { + if (backend.credentials) changes.credentials = null; + } else if (hasCredentialsInput(input.credentials)) { + const credentials = validateCredentials(provider, input.credentials ?? {}, errors); + if (credentials) changes.credentials = this.cipher.encrypt(id, JSON.stringify(credentials)); + } else if (!backend.credentials) { + errors.credentials = provider === 'gcs' ? 'required' : 'access_key_required'; + } + + if (Object.keys(errors).length > 0) throw new StateIacValidationError(errors); + const changedFields = this.changedFields(backend, changes); + if (changedFields.length === 0) return backend; + // another bucket or credentials: the last error no longer applies + if ( + changedFields.some((field) => + ['bucket', 'prefix', 'region', 'endpoint', 'auth', 'credentials'].includes(field), + ) + ) { + changes.lastError = null; + } + await this.repository.update(id, changes); + const updated = new StateBackendDomain({ ...backend.toJson(), ...changes }); + await this.publish('state_iac.backend.updated', updated, changedFields); + return updated; + } + + /** Deletes the backend and its bindings; the bucket is untouched. */ + async delete(id: string): Promise { + const backend = await this.get(id); + for (const binding of await this.bindings.listByBackend(id)) { + await this.bindings.delete(binding.id); + } + await this.repository.delete(id); + await this.publish('state_iac.backend.deleted', backend); + } + + /** "Test connection": lists the bucket and reads `meta.yaml`. Works on disabled backends. */ + async test(id: string): Promise { + const backend = await this.get(id); + const discovery = await this.runDiscovery(backend); + if (!discovery.ok) return discovery; + return { + ok: true, + layout: discovery.layout, + metaVersion: discovery.metaVersion, + projects: discovery.projects.length, + stacks: discovery.projects.reduce((sum, project) => sum + project.stacks.length, 0), + }; + } + + /** Pulumi projects and stacks in the bucket, to assign them. */ + async discover(id: string): Promise { + return this.runDiscovery(await this.get(id)); + } + + /** The bucket client of a backend, credentials decrypted in memory only. */ + storeFor(backend: StateBackendDomain): ObjectStore { + return this.stores(backend, this.decryptCredentials(backend)); + } + + private decryptCredentials(backend: StateBackendDomain): StateBackendCredentials | null { + if (backend.auth !== 'credentials' || !backend.credentials) return null; + const parsed = JSON.parse(this.cipher.decrypt(backend.id, backend.credentials)); + return parsed as StateBackendCredentials; + } + + private async runDiscovery(backend: StateBackendDomain): Promise { + let store: ObjectStore; + try { + store = this.storeFor(backend); + } catch { + await this.recordOutcome(backend, 'undecryptable'); + return { ok: false, error: 'undecryptable' }; + } + try { + const discovery = await discoverPulumi(store, backend.pulumiRoot); + await this.recordOutcome(backend, null); + return { ok: true, ...discovery }; + } catch (error) { + const code: BackendErrorCode = + error instanceof UnsupportedLayoutError ? 'unsupported_layout' : classifyStoreError(error); + // the provider message may echo the bucket or the account: only the code is kept + this.log.error( + { backendId: backend.id, code, err: error instanceof Error ? error.name : 'unknown' }, + '[state-iac] bucket read failed', + ); + await this.recordOutcome(backend, code); + return { ok: false, error: code }; + } + } + + /** Each write is a commit: only when the error changes or the scan stamp got old. */ + private async recordOutcome(backend: StateBackendDomain, error: string | null) { + const now = this.now(); + const last = backend.lastScanAt ? Date.parse(backend.lastScanAt) : 0; + const changes: StateBackendChanges = {}; + if (backend.lastError !== error) changes.lastError = error; + if (!error && now.getTime() - last >= this.stampIntervalMs) { + changes.lastScanAt = now.toISOString(); + } + if (Object.keys(changes).length === 0) return; + await this.repository + .update(backend.id, changes) + .catch((err) => + this.log.error( + { backendId: backend.id, err: err instanceof Error ? err.name : 'unknown' }, + '[state-iac] scan outcome could not be recorded', + ), + ); + } + + private async checkUniqueName( + organizationId: string, + name: string, + exceptId: string | null, + errors: FieldErrors, + ) { + if (!name || errors.name) return; + const taken = (await this.repository.listByOrganization(organizationId)).some( + (other) => other.id !== exceptId && other.name.toLowerCase() === name.toLowerCase(), + ); + if (taken) errors.name = 'duplicate_name'; + } + + private changedFields( + backend: StateBackendDomain, + changes: StateBackendChanges, + ): StateIacBackendChangedField[] { + const fields: StateIacBackendChangedField[] = []; + const tracked = ['name', 'bucket', 'prefix', 'region', 'endpoint', 'auth', 'enabled'] as const; + for (const field of tracked) { + if (field in changes && changes[field] !== backend[field]) fields.push(field); + } + if ('forcePathStyle' in changes && changes.forcePathStyle !== backend.forcePathStyle) { + if (!fields.includes('endpoint')) fields.push('endpoint'); + } + if ('credentials' in changes && changes.credentials !== backend.credentials) { + fields.push('credentials'); + } + return fields; + } + + private async publish( + type: 'state_iac.backend.created' | 'state_iac.backend.updated' | 'state_iac.backend.deleted', + backend: StateBackendDomain, + changedFields: StateIacBackendChangedField[] = [], + ) { + const payload = { + backendId: backend.id, + name: backend.name, + engine: backend.engine, + provider: backend.provider, + bucket: backend.bucket, + prefix: backend.prefix, + }; + const scope = { organizationId: backend.organizationId, projectId: null }; + if (type === 'state_iac.backend.updated') { + await publishAfterWrite( + this.options.events, + this.log, + type, + { ...payload, changedFields }, + scope, + ); + } else { + await publishAfterWrite(this.options.events, this.log, type, payload, scope); + } + } +} diff --git a/src/modules/state-iac/application/state-binding.service.test.ts b/src/modules/state-iac/application/state-binding.service.test.ts new file mode 100644 index 00000000..178b2d33 --- /dev/null +++ b/src/modules/state-iac/application/state-binding.service.test.ts @@ -0,0 +1,112 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { StateIacValidationError, type StateBackendDomain } from '../domain/state-backend.domain'; +import { createStateIacFixture } from './testing'; + +describe('StateBindingService', () => { + let fx: ReturnType; + let backend: StateBackendDomain; + + beforeEach(async () => { + fx = createStateIacFixture(); + backend = await fx.backendService.create('org-1', { + name: 'gcs-prod', + provider: 'gcs', + bucket: 'acme-pulumi-state', + }); + }); + + async function errorsOf(promise: Promise) { + const error = await promise.then( + () => null, + (e) => e, + ); + expect(error).toBeInstanceOf(StateIacValidationError); + return (error as StateIacValidationError).errors; + } + + it('assigns a Pulumi project to a project of the same organization', async () => { + const binding = await fx.bindingService.set(backend, 'network', { projectId: 'p1' }); + expect(binding.toJson()).toMatchObject({ + organizationId: 'org-1', + backendId: backend.id, + pulumiProject: 'network', + projectId: 'p1', + stacks: [], + }); + expect(binding.covers('prod')).toBe(true); + expect(fx.events.ofType('state_iac.binding.updated').map((e) => e.payload)).toEqual([ + { + backendId: backend.id, + backendName: 'gcs-prod', + pulumiProject: 'network', + projectId: 'p1', + previousProjectId: null, + stacks: [], + }, + ]); + }); + + it('a Pulumi project has one assignment: setting it again reassigns', async () => { + await fx.bindingService.set(backend, 'network', { projectId: 'p1' }); + await fx.bindingService.set(backend, 'network', { + projectId: 'p2', + stacks: ['prod', 'dev', 'prod'], + }); + expect(fx.bindings.rows).toHaveLength(1); + expect(fx.bindings.rows[0]).toMatchObject({ projectId: 'p2', stacks: ['dev', 'prod'] }); + const last = fx.events.ofType('state_iac.binding.updated').at(-1)!.payload; + expect(last).toMatchObject({ projectId: 'p2', previousProjectId: 'p1' }); + + // same assignment again: no write, no event + await fx.bindingService.set(backend, 'network', { projectId: 'p2', stacks: ['prod', 'dev'] }); + expect(fx.events.ofType('state_iac.binding.updated')).toHaveLength(2); + }); + + it('only covers the chosen stacks when given', async () => { + const binding = await fx.bindingService.set(backend, 'network', { + projectId: 'p1', + stacks: 'prod, staging', + }); + expect(binding.covers('prod')).toBe(true); + expect(binding.covers('dev')).toBe(false); + }); + + it('refuses projects of another organization as if they did not exist', async () => { + expect( + await errorsOf(fx.bindingService.set(backend, 'network', { projectId: 'other-org-project' })), + ).toEqual({ projectId: 'project_not_found' }); + expect( + await errorsOf(fx.bindingService.set(backend, 'network', { projectId: 'nope' })), + ).toEqual({ projectId: 'project_not_found' }); + expect(fx.bindings.rows).toHaveLength(0); + }); + + it('validates names', async () => { + expect( + await errorsOf(fx.bindingService.set(backend, 'bad name/..', { stacks: ['ok', 'no way'] })), + ).toEqual({ + pulumiProject: 'invalid_pulumi_name', + stacks: 'invalid_stacks', + projectId: 'required', + }); + }); + + it('unassigns', async () => { + await fx.bindingService.set(backend, 'network', { projectId: 'p1' }); + expect(await fx.bindingService.remove(backend, 'network')).toBe(true); + expect(await fx.bindingService.remove(backend, 'network')).toBe(false); + expect(fx.bindings.rows).toHaveLength(0); + expect(fx.events.ofType('state_iac.binding.updated').at(-1)!.payload).toMatchObject({ + projectId: null, + previousProjectId: 'p1', + }); + }); + + it('a deleted GitOps project takes its assignments with it', async () => { + await fx.bindingService.set(backend, 'network', { projectId: 'p1' }); + await fx.bindingService.set(backend, 'sandbox', { projectId: 'p1' }); + await fx.bindingService.set(backend, 'payments', { projectId: 'p2' }); + expect(await fx.bindingService.removeForProject('p1')).toBe(2); + expect(fx.bindings.rows.map((row) => row.pulumiProject)).toEqual(['payments']); + }); +}); diff --git a/src/modules/state-iac/application/state-binding.service.ts b/src/modules/state-iac/application/state-binding.service.ts new file mode 100644 index 00000000..53cbfbd1 --- /dev/null +++ b/src/modules/state-iac/application/state-binding.service.ts @@ -0,0 +1,178 @@ +import type { Logger } from 'pino'; +import { publishAfterWrite, type EventPublisher } from '#lib/server/events/publish'; +import { StateIacValidationError, type StateBackendDomain } from '../domain/state-backend.domain'; +import { + MAX_PULUMI_NAME_LENGTH, + StateBindingDomain, + type StateBindingRow, +} from '../domain/state-binding.domain'; +import type { FieldErrors } from '../domain/state-backend.validation'; +import type { StateBindingRepositoryPort } from '../infrastructure/repositories/state-binding.repository'; + +/** Finds a GitOps project and its organization. */ +export type ProjectLookup = { + getProject(id: string): Promise<{ id: string; organizationId: string | null } | null>; +}; + +export type BindingInput = { projectId?: unknown; stacks?: unknown }; + +export type StateBindingServiceOptions = { + now?: () => Date; + generateId?: () => string; + events?: EventPublisher; + logger?: Pick; +}; + +// Pulumi project and stack names: letters, digits, `-`, `_` and `.` +const PULUMI_NAME = /^[A-Za-z0-9._-]+$/; +const MAX_STACKS = 200; + +const silentLogger = { error: () => {} } as unknown as Pick; + +/** + * Assignments of the Pulumi projects of a backend to GitOps projects. A Pulumi project has at + * most one assignment (`set` replaces it), always to a project of the backend's organization. + */ +export class StateBindingService { + private readonly now: () => Date; + private readonly generateId: () => string; + private readonly log: Pick; + + constructor( + private readonly repository: StateBindingRepositoryPort, + private readonly projects: ProjectLookup, + private readonly options: StateBindingServiceOptions = {}, + ) { + this.now = options.now ?? (() => new Date()); + this.generateId = options.generateId ?? (() => crypto.randomUUID()); + this.log = options.logger ?? silentLogger; + } + + listByBackend(backendId: string): Promise { + return this.repository.listByBackend(backendId); + } + + listByProject(projectId: string): Promise { + return this.repository.listByProject(projectId); + } + + /** Assigns (or reassigns) `pulumiProject` of `backend`; `stacks` empty = all of them. */ + async set( + backend: StateBackendDomain, + pulumiProject: unknown, + input: BindingInput, + ): Promise { + const errors: FieldErrors = {}; + const name = this.validatePulumiName(pulumiProject, 'pulumiProject', errors); + const stacks = this.validateStacks(input.stacks, errors); + const projectId = typeof input.projectId === 'string' ? input.projectId.trim() : ''; + if (!projectId) errors.projectId = 'required'; + else { + const project = await this.projects.getProject(projectId).catch(() => null); + if (!project) errors.projectId = 'project_not_found'; + // another organization's project is not even revealed to exist + else if (project.organizationId !== backend.organizationId) { + errors.projectId = 'project_not_found'; + } + } + if (Object.keys(errors).length > 0) throw new StateIacValidationError(errors); + + const existing = (await this.repository.listByBackend(backend.id)).find( + (binding) => binding.pulumiProject === name, + ); + if (existing) { + if (existing.projectId === projectId && sameStacks(existing.stacks, stacks)) return existing; + await this.repository.update(existing.id, { projectId, stacks }); + const updated = new StateBindingDomain({ ...existing.toJson(), projectId, stacks }); + await this.publish(backend, updated.pulumiProject, projectId, existing.projectId, stacks); + return updated; + } + + const timestamp = this.now().toISOString(); + const row: StateBindingRow = { + id: this.generateId(), + organizationId: backend.organizationId, + backendId: backend.id, + pulumiProject: name, + stacks, + projectId, + createdAt: timestamp, + updatedAt: timestamp, + }; + await this.repository.create(row); + await this.publish(backend, name, projectId, null, stacks); + return new StateBindingDomain(row); + } + + /** Leaves `pulumiProject` unassigned (only the organization sees it). `false` if it wasn't. */ + async remove(backend: StateBackendDomain, pulumiProject: string): Promise { + const existing = (await this.repository.listByBackend(backend.id)).find( + (binding) => binding.pulumiProject === pulumiProject, + ); + if (!existing) return false; + await this.repository.delete(existing.id); + await this.publish(backend, pulumiProject, null, existing.projectId, []); + return true; + } + + /** A deleted GitOps project takes its assignments with it. */ + async removeForProject(projectId: string): Promise { + const bindings = await this.repository.listByProject(projectId); + for (const binding of bindings) await this.repository.delete(binding.id); + return bindings.length; + } + + private validatePulumiName(value: unknown, field: string, errors: FieldErrors): string { + const name = typeof value === 'string' ? value.trim() : ''; + if (!name) errors[field] = 'required'; + else if (name.length > MAX_PULUMI_NAME_LENGTH || !PULUMI_NAME.test(name)) { + errors[field] = 'invalid_pulumi_name'; + } + return name; + } + + private validateStacks(value: unknown, errors: FieldErrors): string[] { + if (value === undefined || value === null || value === '') return []; + const list = Array.isArray(value) ? value : typeof value === 'string' ? value.split(',') : null; + if (!list) { + errors.stacks = 'invalid_stacks'; + return []; + } + const stacks = [ + ...new Set( + list.map((stack) => (typeof stack === 'string' ? stack.trim() : '')).filter(Boolean), + ), + ].sort(); + if (stacks.length > MAX_STACKS || stacks.some((stack) => !PULUMI_NAME.test(stack))) { + errors.stacks = 'invalid_stacks'; + } + return stacks; + } + + private async publish( + backend: StateBackendDomain, + pulumiProject: string, + projectId: string | null, + previousProjectId: string | null, + stacks: string[], + ) { + await publishAfterWrite( + this.options.events, + this.log, + 'state_iac.binding.updated', + { + backendId: backend.id, + backendName: backend.name, + pulumiProject, + projectId, + previousProjectId, + stacks, + }, + { organizationId: backend.organizationId, projectId: null }, + ); + } +} + +function sameStacks(a: string[], b: string[]): boolean { + return a.length === b.length && [...a].sort().every((stack, i) => stack === [...b].sort()[i]); +} diff --git a/src/modules/state-iac/application/testing.ts b/src/modules/state-iac/application/testing.ts new file mode 100644 index 00000000..fd024a6a --- /dev/null +++ b/src/modules/state-iac/application/testing.ts @@ -0,0 +1,75 @@ +import { fileURLToPath } from 'node:url'; +import { RecordingEventBus } from '#lib/server/events/testing'; +import { createCredentialsCipher } from '../infrastructure/crypto/credentials-cipher'; +import { InMemoryObjectStore } from '../infrastructure/object-store/in-memory-object-store'; +import type { ObjectStoreFactory } from '../infrastructure/object-store/factory'; +import type { StateBackendCredentials } from '../domain/state-backend.domain'; +import { + InMemoryStateBackendRepository, + InMemoryStateBindingRepository, +} from '../infrastructure/repositories/in-memory.repositories'; +import { StateBackendService } from './state-backend.service'; +import { StateBindingService } from './state-binding.service'; + +/** `test/fixtures/state-iac/`: buckets copied from real (anonymized) Pulumi state. */ +export function fixtureDir(name: 'project-layout' | 'legacy-layout'): string { + return fileURLToPath(new URL(`../../../../test/fixtures/state-iac/${name}`, import.meta.url)); +} + +/** A bucket with the fixture under `prefix` (`''` for the bucket root). */ +export function fixtureStore( + name: 'project-layout' | 'legacy-layout', + prefix = '', +): InMemoryObjectStore { + return InMemoryObjectStore.fromDirectory(fixtureDir(name), prefix ? `${prefix}/` : ''); +} + +/** + * Services wired to in-memory repositories, a recording event bus and in-memory buckets keyed + * by bucket name. `credentialsSeen` records what each store was built with. + */ +export function createStateIacFixture() { + const backends = new InMemoryStateBackendRepository(); + const bindings = new InMemoryStateBindingRepository(); + const events = new RecordingEventBus(); + const buckets = new Map(); + const credentialsSeen: Array = []; + const projects = new Map([ + ['p1', { id: 'p1', organizationId: 'org-1' }], + ['p2', { id: 'p2', organizationId: 'org-1' }], + ['other-org-project', { id: 'other-org-project', organizationId: 'org-2' }], + ]); + const stores: ObjectStoreFactory = (backend, credentials) => { + credentialsSeen.push(credentials); + let store = buckets.get(backend.bucket); + if (!store) { + store = new InMemoryObjectStore(); + buckets.set(backend.bucket, store); + } + return store; + }; + const cipher = createCredentialsCipher(() => 'test-encryption-key'); + let ids = 0; + const generateId = () => `id-${++ids}`; + + const backendService = new StateBackendService(backends, bindings, cipher, stores, { + events, + generateId, + }); + const bindingService = new StateBindingService( + bindings, + { getProject: async (id) => projects.get(id) ?? null }, + { events, generateId }, + ); + return { + backends, + bindings, + events, + buckets, + credentialsSeen, + projects, + cipher, + backendService, + bindingService, + }; +} diff --git a/src/modules/state-iac/domain/state-backend.domain.ts b/src/modules/state-iac/domain/state-backend.domain.ts new file mode 100644 index 00000000..ed45413b --- /dev/null +++ b/src/modules/state-iac/domain/state-backend.domain.ts @@ -0,0 +1,154 @@ +/** + * A bucket (or a prefix of one) where an IaC tool keeps its state, configured once per + * organization. GitOps only reads it (docs/adr/0003-state-iac.md). + */ + +export const STATE_ENGINES = ['pulumi'] as const; +export type StateEngine = (typeof STATE_ENGINES)[number]; + +export const STATE_PROVIDERS = ['gcs', 's3'] as const; +export type StateProvider = (typeof STATE_PROVIDERS)[number]; + +/** `ambient`: ADC / Workload Identity / IAM role of the server. `credentials`: stored, encrypted. */ +export const STATE_AUTH_MODES = ['ambient', 'credentials'] as const; +export type StateAuthMode = (typeof STATE_AUTH_MODES)[number]; + +export const MAX_BACKEND_NAME_LENGTH = 80; + +/** Plain credentials, only ever held in memory on the server. */ +export type GcsCredentials = { provider: 'gcs'; serviceAccountJson: string }; +export type S3Credentials = { + provider: 's3'; + accessKeyId: string; + secretAccessKey: string; + sessionToken?: string; +}; +export type StateBackendCredentials = GcsCredentials | S3Credentials; + +export type StateBackendRow = { + id: string; + organizationId: string; + name: string; + engine: StateEngine; + provider: StateProvider; + bucket: string; + /** Path inside the bucket that holds `.pulumi/`, without leading or trailing `/`. */ + prefix: string | null; + region: string | null; + /** S3-compatible endpoint (MinIO, R2…); `null` for AWS S3 and GCS. */ + endpoint: string | null; + forcePathStyle: boolean; + auth: StateAuthMode; + /** `StateBackendCredentials` as JSON, encrypted (`credentials-cipher.ts`): never returned. */ + credentials: string | null; + enabled: boolean; + lastScanAt: string | null; + /** Short reason of the last failed read (`access_denied`, `bucket_not_found`…). */ + lastError: string | null; + createdAt: string; + updatedAt: string; +}; + +/** What the API and the pages may show: never the credentials, only whether there are some. */ +export type StateBackendView = Omit & { hasCredentials: boolean }; + +function toIso(value: unknown): string | null { + if (value instanceof Date) return value.toISOString(); + return typeof value === 'string' && value ? value : null; +} + +const pick = (values: readonly T[], value: unknown, fallback: T): T => + values.includes(value as T) ? (value as T) : fallback; + +export class StateBackendDomain implements StateBackendRow { + id: string; + organizationId: string; + name: string; + engine: StateEngine; + provider: StateProvider; + bucket: string; + prefix: string | null; + region: string | null; + endpoint: string | null; + forcePathStyle: boolean; + auth: StateAuthMode; + credentials: string | null; + enabled: boolean; + lastScanAt: string | null; + lastError: string | null; + createdAt: string; + updatedAt: string; + + constructor(row: Record) { + this.id = row.id; + this.organizationId = row.organizationId; + this.name = row.name ?? ''; + this.engine = pick(STATE_ENGINES, row.engine, 'pulumi'); + this.provider = pick(STATE_PROVIDERS, row.provider, 'gcs'); + this.bucket = row.bucket ?? ''; + this.prefix = row.prefix || null; + this.region = row.region || null; + this.endpoint = row.endpoint || null; + this.forcePathStyle = row.forcePathStyle === true; + this.auth = pick(STATE_AUTH_MODES, row.auth, 'ambient'); + this.credentials = row.credentials || null; + this.enabled = row.enabled !== false; + this.lastScanAt = toIso(row.lastScanAt); + this.lastError = row.lastError ?? null; + this.createdAt = toIso(row.createdAt) ?? new Date(0).toISOString(); + this.updatedAt = toIso(row.updatedAt) ?? this.createdAt; + } + + /** Object key prefix of the Pulumi bookkeeping directory: `/.pulumi/`. */ + get pulumiRoot(): string { + return this.prefix ? `${this.prefix}/.pulumi/` : '.pulumi/'; + } + + /** `gs://bucket/prefix`, `s3://bucket/prefix`: display only. */ + get location(): string { + const scheme = this.provider === 'gcs' ? 'gs' : 's3'; + return `${scheme}://${this.bucket}${this.prefix ? `/${this.prefix}` : ''}`; + } + + toJson(): StateBackendRow { + return { + id: this.id, + organizationId: this.organizationId, + name: this.name, + engine: this.engine, + provider: this.provider, + bucket: this.bucket, + prefix: this.prefix, + region: this.region, + endpoint: this.endpoint, + forcePathStyle: this.forcePathStyle, + auth: this.auth, + credentials: this.credentials, + enabled: this.enabled, + lastScanAt: this.lastScanAt, + lastError: this.lastError, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + }; + } + + toView(): StateBackendView { + const { credentials, ...rest } = this.toJson(); + return { ...rest, hasCredentials: Boolean(credentials) }; + } +} + +export class StateIacValidationError extends Error { + /** Field → error code; the UI shows `stateIac.errors.`. */ + constructor(readonly errors: Record) { + super(`Invalid State IaC configuration: ${Object.keys(errors).join(', ')}`); + this.name = 'StateIacValidationError'; + } +} + +export class StateBackendNotFoundError extends Error { + constructor(id: string) { + super(`State backend not found: ${id}`); + this.name = 'StateBackendNotFoundError'; + } +} diff --git a/src/modules/state-iac/domain/state-backend.validation.ts b/src/modules/state-iac/domain/state-backend.validation.ts new file mode 100644 index 00000000..364fad7a --- /dev/null +++ b/src/modules/state-iac/domain/state-backend.validation.ts @@ -0,0 +1,213 @@ +import { isIP } from 'node:net'; +import { + MAX_BACKEND_NAME_LENGTH, + STATE_AUTH_MODES, + STATE_ENGINES, + STATE_PROVIDERS, + type StateAuthMode, + type StateBackendCredentials, + type StateEngine, + type StateProvider, +} from './state-backend.domain'; + +/** Field → error code (`stateIac.errors.`). */ +export type FieldErrors = Record; + +const BUCKET_PATTERN = /^[a-z0-9][a-z0-9._-]{1,220}[a-z0-9]$/; +const REGION_PATTERN = /^[a-z0-9-]{2,40}$/; +const MAX_PREFIX_LENGTH = 512; + +export function validateName(value: unknown, errors: FieldErrors): string { + const name = typeof value === 'string' ? value.trim() : ''; + if (!name) errors.name = 'required'; + else if (name.length > MAX_BACKEND_NAME_LENGTH) errors.name = 'too_long'; + return name; +} + +export function validateEngine(value: unknown, errors: FieldErrors): StateEngine { + if (value === undefined || value === null || value === '') return 'pulumi'; + if (!STATE_ENGINES.includes(value as StateEngine)) errors.engine = 'invalid_engine'; + return 'pulumi'; +} + +export function validateProvider(value: unknown, errors: FieldErrors): StateProvider | null { + if (STATE_PROVIDERS.includes(value as StateProvider)) return value as StateProvider; + errors.provider = typeof value === 'string' && value ? 'invalid_provider' : 'required'; + return null; +} + +export function validateBucket(value: unknown, errors: FieldErrors): string { + const raw = typeof value === 'string' ? value.trim() : ''; + // accept `gs://bucket` and `s3://bucket` as typed in the consoles + const bucket = raw.replace(/^(gs|s3):\/\//, '').replace(/\/+$/, ''); + if (!bucket) errors.bucket = 'required'; + else if (!BUCKET_PATTERN.test(bucket) || bucket.includes('..')) errors.bucket = 'invalid_bucket'; + return bucket; +} + +/** `infra/`, `/infra`, `infra/.pulumi` → `infra`; empty → `null` (bucket root). */ +export function validatePrefix(value: unknown, errors: FieldErrors): string | null { + if (value === undefined || value === null) return null; + if (typeof value !== 'string') { + errors.prefix = 'invalid_prefix'; + return null; + } + const prefix = value + .trim() + .replace(/^\/+|\/+$/g, '') + .replace(/(^|\/)\.pulumi$/, '') + .replace(/\/+$/, ''); + if (!prefix) return null; + if ( + prefix.length > MAX_PREFIX_LENGTH || + prefix.split('/').some((part) => !part || part === '.' || part === '..') || + prefix.includes('\\') || + [...prefix].some((char) => char.charCodeAt(0) < 0x20) + ) { + errors.prefix = 'invalid_prefix'; + } + return prefix; +} + +export function validateRegion(value: unknown, errors: FieldErrors): string | null { + const region = typeof value === 'string' ? value.trim() : ''; + if (!region) return null; + if (!REGION_PATTERN.test(region)) errors.region = 'invalid_region'; + return region; +} + +const BLOCKED_HOSTS = new Set(['localhost', 'metadata.google.internal', 'metadata']); + +function blockedIp(host: string): boolean { + if (isIP(host) === 4) { + const [a, b] = host.split('.').map(Number); + return a === 127 || a === 0 || (a === 169 && b === 254); + } + if (isIP(host) === 6) { + const lower = host.toLowerCase(); + return ( + lower === '::1' || + lower === '::' || + /^fe[89ab]/.test(lower) || + lower.startsWith('::ffff:127.') + ); + } + return false; +} + +/** + * S3-compatible endpoint. Private networks are allowed (MinIO next to the server), but not the + * loopback, link-local or cloud metadata addresses: the server makes requests to it. + */ +export function validateEndpoint( + value: unknown, + provider: StateProvider | null, + errors: FieldErrors, +): string | null { + const raw = typeof value === 'string' ? value.trim() : ''; + if (!raw) return null; + if (provider !== 's3') { + errors.endpoint = 'endpoint_s3_only'; + return null; + } + let url: URL; + try { + url = new URL(raw); + } catch { + errors.endpoint = 'invalid_endpoint'; + return null; + } + const host = url.hostname.replace(/^\[|\]$/g, '').toLowerCase(); + if ( + !['http:', 'https:'].includes(url.protocol) || + url.username || + url.password || + (url.pathname !== '/' && url.pathname !== '') || + url.search || + url.hash + ) { + errors.endpoint = 'invalid_endpoint'; + return null; + } + if (BLOCKED_HOSTS.has(host) || host.endsWith('.localhost') || blockedIp(host)) { + errors.endpoint = 'endpoint_not_allowed'; + return null; + } + return `${url.protocol}//${url.host}`; +} + +export function validateAuth(value: unknown, errors: FieldErrors): StateAuthMode { + if (value === undefined || value === null || value === '') return 'ambient'; + if (!STATE_AUTH_MODES.includes(value as StateAuthMode)) { + errors.auth = 'invalid_auth'; + return 'ambient'; + } + return value as StateAuthMode; +} + +export type CredentialsInput = { + serviceAccountJson?: unknown; + accessKeyId?: unknown; + secretAccessKey?: unknown; + sessionToken?: unknown; +}; + +const text = (value: unknown) => (typeof value === 'string' ? value.trim() : ''); + +/** Whether the input carries any credential value (an empty form keeps the stored ones). */ +export function hasCredentialsInput(input: CredentialsInput | null | undefined): boolean { + if (!input || typeof input !== 'object') return false; + return [ + input.serviceAccountJson, + input.accessKeyId, + input.secretAccessKey, + input.sessionToken, + ].some((value) => text(value) !== ''); +} + +export function validateCredentials( + provider: StateProvider, + input: CredentialsInput, + errors: FieldErrors, +): StateBackendCredentials | null { + if (provider === 'gcs') { + const raw = text(input.serviceAccountJson); + if (!raw) { + errors.credentials = 'required'; + return null; + } + try { + const parsed = JSON.parse(raw) as Record; + if ( + parsed?.type !== 'service_account' || + typeof parsed.client_email !== 'string' || + typeof parsed.private_key !== 'string' + ) { + errors.credentials = 'invalid_service_account'; + return null; + } + } catch { + errors.credentials = 'invalid_service_account'; + return null; + } + return { provider: 'gcs', serviceAccountJson: raw }; + } + const accessKeyId = text(input.accessKeyId); + const secretAccessKey = text(input.secretAccessKey); + if (!accessKeyId || !secretAccessKey) { + errors.credentials = 'access_key_required'; + return null; + } + const sessionToken = text(input.sessionToken); + return { + provider: 's3', + accessKeyId, + secretAccessKey, + ...(sessionToken ? { sessionToken } : {}), + }; +} + +export function toBoolean(value: unknown, fallback: boolean): boolean { + if (value === undefined || value === null || value === '') return fallback; + return value === true || value === 'true' || value === 'on'; +} diff --git a/src/modules/state-iac/domain/state-binding.domain.ts b/src/modules/state-iac/domain/state-binding.domain.ts new file mode 100644 index 00000000..94bfb5c1 --- /dev/null +++ b/src/modules/state-iac/domain/state-binding.domain.ts @@ -0,0 +1,63 @@ +/** + * Assigns a Pulumi project found in a backend to a GitOps project of the same organization. A + * Pulumi project has at most one binding; `stacks` narrows it to some of its stacks (empty = all). + */ +export type StateBindingRow = { + id: string; + organizationId: string; + backendId: string; + pulumiProject: string; + stacks: string[]; + projectId: string; + createdAt: string; + updatedAt: string; +}; + +export const MAX_PULUMI_NAME_LENGTH = 200; + +function toIso(value: unknown): string | null { + if (value instanceof Date) return value.toISOString(); + return typeof value === 'string' && value ? value : null; +} + +export class StateBindingDomain implements StateBindingRow { + id: string; + organizationId: string; + backendId: string; + pulumiProject: string; + stacks: string[]; + projectId: string; + createdAt: string; + updatedAt: string; + + constructor(row: Record) { + this.id = row.id; + this.organizationId = row.organizationId; + this.backendId = row.backendId; + this.pulumiProject = row.pulumiProject ?? ''; + this.stacks = Array.isArray(row.stacks) + ? row.stacks.filter((s: unknown) => typeof s === 'string') + : []; + this.projectId = row.projectId; + this.createdAt = toIso(row.createdAt) ?? new Date(0).toISOString(); + this.updatedAt = toIso(row.updatedAt) ?? this.createdAt; + } + + /** Whether this binding gives its project the stack `stack` of its Pulumi project. */ + covers(stack: string): boolean { + return this.stacks.length === 0 || this.stacks.includes(stack); + } + + toJson(): StateBindingRow { + return { + id: this.id, + organizationId: this.organizationId, + backendId: this.backendId, + pulumiProject: this.pulumiProject, + stacks: [...this.stacks], + projectId: this.projectId, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + }; + } +} diff --git a/src/modules/state-iac/index.ts b/src/modules/state-iac/index.ts new file mode 100644 index 00000000..62d5804b --- /dev/null +++ b/src/modules/state-iac/index.ts @@ -0,0 +1,66 @@ +import { eventBus } from '#lib/server/events'; +import { createLogger } from '#lib/server/logger'; +import { passwordService } from '../auth'; +import { projectService } from '../projects'; +import { StateBackendService } from './application/state-backend.service'; +import { StateBindingService } from './application/state-binding.service'; +import { createCredentialsCipher } from './infrastructure/crypto/credentials-cipher'; +import { createObjectStore } from './infrastructure/object-store/factory'; +import { StateBackendRepository } from './infrastructure/repositories/state-backend.repository'; +import { StateBindingRepository } from './infrastructure/repositories/state-binding.repository'; + +const log = createLogger('state-iac'); +const bindingRepository = new StateBindingRepository(); + +export const stateBackendService = new StateBackendService( + new StateBackendRepository(), + bindingRepository, + createCredentialsCipher(() => passwordService.ensureEncryptionKey()), + createObjectStore, + { events: eventBus, logger: log }, +); + +export const stateBindingService = new StateBindingService( + bindingRepository, + { + async getProject(id) { + const project = await projectService.getProject(id).catch(() => null); + return project ? { id: project.id, organizationId: project.organization?.id ?? null } : null; + }, + }, + { events: eventBus, logger: log }, +); + +const SUBSCRIBED_KEY = Symbol.for('gitops.state-iac.subscribed'); +type GlobalWithFlag = typeof globalThis & { [SUBSCRIBED_KEY]?: boolean }; + +/** Once per process (HMR-safe): a deleted GitOps project takes its State IaC bindings with it. */ +export function registerStateIac(): void { + const scope = globalThis as GlobalWithFlag; + if (scope[SUBSCRIBED_KEY]) return; + scope[SUBSCRIBED_KEY] = true; + eventBus.subscribe('project.deleted', async (event) => { + const removed = await stateBindingService.removeForProject(event.payload.projectId); + if (removed > 0) { + log.info({ projectId: event.payload.projectId, removed }, '[state-iac] bindings removed'); + } + }); +} + +export { + StateBackendNotFoundError, + StateIacValidationError, + STATE_PROVIDERS, + STATE_AUTH_MODES, + type StateBackendView, + type StateProvider, + type StateAuthMode, +} from './domain/state-backend.domain'; +export type { StateBindingRow } from './domain/state-binding.domain'; +export type { + BackendInput, + BackendTestResult, + DiscoveryOutcome, +} from './application/state-backend.service'; +export type { BindingInput } from './application/state-binding.service'; +export type { PulumiLayout } from './infrastructure/engines/pulumi/pulumi-discovery'; diff --git a/src/modules/state-iac/infrastructure/crypto/credentials-cipher.test.ts b/src/modules/state-iac/infrastructure/crypto/credentials-cipher.test.ts new file mode 100644 index 00000000..b2d5d059 --- /dev/null +++ b/src/modules/state-iac/infrastructure/crypto/credentials-cipher.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from 'vitest'; +import { createCredentialsCipher } from './credentials-cipher'; + +describe('credentials cipher', () => { + const cipher = createCredentialsCipher(() => 'key-1'); + + it('round-trips and never stores the plain value', () => { + const stored = cipher.encrypt('backend-1', '{"secretAccessKey":"s3cr3t"}'); + expect(stored).not.toContain('s3cr3t'); + expect(stored.startsWith('v1:')).toBe(true); + expect(cipher.decrypt('backend-1', stored)).toBe('{"secretAccessKey":"s3cr3t"}'); + }); + + it('uses a fresh IV every time', () => { + expect(cipher.encrypt('backend-1', 'x')).not.toBe(cipher.encrypt('backend-1', 'x')); + }); + + it('binds the value to its backend: copied onto another one it does not decrypt', () => { + const stored = cipher.encrypt('backend-1', 'secret'); + expect(() => cipher.decrypt('backend-2', stored)).toThrow(/could not be decrypted/); + }); + + it('fails with another key or a tampered value', () => { + const stored = cipher.encrypt('backend-1', 'secret'); + expect(() => createCredentialsCipher(() => 'key-2').decrypt('backend-1', stored)).toThrow(); + const [version, iv, tag, ciphertext] = stored.split(':'); + const flipped = Buffer.from(ciphertext, 'base64'); + flipped[0] ^= 0xff; + const tampered = [version, iv, tag, flipped.toString('base64')].join(':'); + expect(() => cipher.decrypt('backend-1', tampered)).toThrow(/could not be decrypted/); + expect(() => cipher.decrypt('backend-1', 'plain')).toThrow(/no encrypted credentials/); + }); + + it('requires GITDB_ENCRYPTION_KEY', () => { + expect(() => createCredentialsCipher(() => ' ').encrypt('b', 'x')).toThrow( + /GITDB_ENCRYPTION_KEY/, + ); + }); +}); diff --git a/src/modules/state-iac/infrastructure/crypto/credentials-cipher.ts b/src/modules/state-iac/infrastructure/crypto/credentials-cipher.ts new file mode 100644 index 00000000..44e1fca1 --- /dev/null +++ b/src/modules/state-iac/infrastructure/crypto/credentials-cipher.ts @@ -0,0 +1,66 @@ +import crypto from 'node:crypto'; + +const ALGORITHM = 'aes-256-gcm'; +const VERSION = 'v1'; +const KEY_SALT = 'gitops:state-iac:backend-credentials:v1'; +const IV_BYTES = 12; +const AUTH_TAG_BYTES = 16; + +export interface CredentialsCipher { + encrypt(backendId: string, value: string): string; + decrypt(backendId: string, stored: string): string; +} + +/** + * AES-256-GCM for backend credentials (same scheme as the notification channels), keyed from + * `GITDB_ENCRYPTION_KEY`. The backend id is authenticated data: credentials copied onto another + * backend do not decrypt. + */ +export function createCredentialsCipher(secret: () => string): CredentialsCipher { + let cached: { material: string; key: Buffer } | null = null; + const key = () => { + const material = secret().trim(); + if (!material) throw new Error('Missing GITDB_ENCRYPTION_KEY environment variable'); + if (cached?.material !== material) { + cached = { material, key: crypto.scryptSync(material, KEY_SALT, 32) }; + } + return cached.key; + }; + const aad = (backendId: string) => Buffer.from(`${VERSION}:state-backend:${backendId}`, 'utf8'); + + return { + encrypt(backendId, value) { + const iv = crypto.randomBytes(IV_BYTES); + const cipher = crypto.createCipheriv(ALGORITHM, key(), iv, { + authTagLength: AUTH_TAG_BYTES, + }); + cipher.setAAD(aad(backendId)); + const ciphertext = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]); + return [ + VERSION, + iv.toString('base64'), + cipher.getAuthTag().toString('base64'), + ciphertext.toString('base64'), + ].join(':'); + }, + decrypt(backendId, stored) { + const [version, iv, authTag, ciphertext, ...rest] = stored.split(':'); + if (version !== VERSION || !iv || !authTag || !ciphertext || rest.length > 0) { + throw new Error(`State backend ${backendId} has no encrypted credentials`); + } + try { + const decipher = crypto.createDecipheriv(ALGORITHM, key(), Buffer.from(iv, 'base64'), { + authTagLength: AUTH_TAG_BYTES, + }); + decipher.setAAD(aad(backendId)); + decipher.setAuthTag(Buffer.from(authTag, 'base64')); + return Buffer.concat([ + decipher.update(Buffer.from(ciphertext, 'base64')), + decipher.final(), + ]).toString('utf8'); + } catch { + throw new Error(`State backend ${backendId} credentials could not be decrypted`); + } + }, + }; +} diff --git a/src/modules/state-iac/infrastructure/engines/pulumi/pulumi-discovery.test.ts b/src/modules/state-iac/infrastructure/engines/pulumi/pulumi-discovery.test.ts new file mode 100644 index 00000000..2e77e5d4 --- /dev/null +++ b/src/modules/state-iac/infrastructure/engines/pulumi/pulumi-discovery.test.ts @@ -0,0 +1,116 @@ +import { describe, expect, it } from 'vitest'; +import { fixtureStore } from '../../../application/testing'; +import { InMemoryObjectStore } from '../../object-store/in-memory-object-store'; +import { + UnsupportedLayoutError, + detectPulumiLayout, + discoverPulumi, + parseMetaVersion, + projectFromState, + stackNameOf, +} from './pulumi-discovery'; + +const summary = (projects: { name: string | null; stacks: { name: string }[] }[]) => + projects.map((project) => ({ name: project.name, stacks: project.stacks.map((s) => s.name) })); + +describe('stack file names', () => { + it('accepts plain, gzip and zstd files and ignores backups and retained copies', () => { + expect(stackNameOf('prod.json')).toBe('prod'); + expect(stackNameOf('staging.json.gz')).toBe('staging'); + expect(stackNameOf('dev.json.zst')).toBe('dev'); + expect(stackNameOf('prod.json.bak')).toBeNull(); + expect(stackNameOf('prod.json.1795604215900000000')).toBeNull(); + expect(stackNameOf('notes.txt')).toBeNull(); + }); + + it('reads meta.yaml and URNs', () => { + expect(parseMetaVersion('version: 1\n')).toBe(1); + expect(parseMetaVersion('other: 2')).toBeNull(); + expect(projectFromState('{"urn":"urn:pulumi:prod::acme-legacy::pulumi:pulumi:Stack::x"}')).toBe( + 'acme-legacy', + ); + expect(projectFromState('{"checkpoint":{"stack":"prod"}}')).toBeNull(); + }); +}); + +describe('discoverPulumi on real (anonymized) buckets', () => { + it('project layout: every project and stack, ignoring .bak, retained copies and locks', async () => { + const store = fixtureStore('project-layout'); + const discovery = await discoverPulumi(store, '.pulumi/'); + expect(discovery.layout).toBe('project'); + expect(discovery.metaVersion).toBe(1); + expect(summary(discovery.projects)).toEqual([ + { name: 'acme-infra', stacks: ['prod', 'staging'] }, + { name: 'acme-platform', stacks: ['dev'] }, + ]); + // staging is only gzipped + expect(discovery.projects[0].stacks[1].key).toBe('.pulumi/stacks/acme-infra/staging.json.gz'); + // project layout never reads the states: only listings and meta.yaml + expect(store.calls.filter((call) => call.op === 'get').map((call) => call.key)).toEqual([ + '.pulumi/meta.yaml', + ]); + // nor lists outside stacks/ + expect( + store.calls + .filter((call) => call.op === 'list') + .every((call) => call.key.startsWith('.pulumi/stacks/')), + ).toBe(true); + }); + + it('works under a prefix of the bucket', async () => { + const discovery = await discoverPulumi( + fixtureStore('project-layout', 'infra/state'), + 'infra/state/.pulumi/', + ); + expect(summary(discovery.projects).map((p) => p.name)).toEqual(['acme-infra', 'acme-platform']); + }); + + it('legacy layout: the project comes from the URNs', async () => { + const discovery = await discoverPulumi(fixtureStore('legacy-layout'), '.pulumi/'); + expect(discovery.layout).toBe('legacy'); + expect(discovery.metaVersion).toBeNull(); + expect(summary(discovery.projects)).toEqual([{ name: 'acme-legacy', stacks: ['prod'] }]); + }); + + it('a legacy stack without resources has an unknown project', async () => { + const store = fixtureStore('legacy-layout'); + store.put( + '.pulumi/stacks/empty.json', + '{"version":3,"checkpoint":{"stack":"empty","latest":{}}}', + ); + const discovery = await discoverPulumi(store, '.pulumi/'); + expect(summary(discovery.projects)).toEqual([ + { name: 'acme-legacy', stacks: ['prod'] }, + { name: null, stacks: ['empty'] }, + ]); + }); + + it('an empty bucket has no layout yet', async () => { + const discovery = await discoverPulumi(new InMemoryObjectStore(), '.pulumi/'); + expect(discovery).toEqual({ + layout: 'empty', + metaVersion: null, + projects: [], + truncated: false, + }); + }); + + it('refuses an unknown meta.yaml version instead of guessing', async () => { + const store = new InMemoryObjectStore(); + store.put('.pulumi/meta.yaml', 'version: 2\n'); + await expect(detectPulumiLayout(store, '.pulumi/')).rejects.toBeInstanceOf( + UnsupportedLayoutError, + ); + }); + + it('keeps the most recently modified variant when .json and .json.gz coexist', async () => { + const store = new InMemoryObjectStore(); + store.put('.pulumi/meta.yaml', 'version: 1\n'); + store.put('.pulumi/stacks/p/dev.json', '{}', '2026-01-01T00:00:00Z'); + store.put('.pulumi/stacks/p/dev.json.gz', '{}', '2026-02-01T00:00:00Z'); + const discovery = await discoverPulumi(store, '.pulumi/'); + expect(discovery.projects[0].stacks).toEqual([ + expect.objectContaining({ name: 'dev', key: '.pulumi/stacks/p/dev.json.gz' }), + ]); + }); +}); diff --git a/src/modules/state-iac/infrastructure/engines/pulumi/pulumi-discovery.ts b/src/modules/state-iac/infrastructure/engines/pulumi/pulumi-discovery.ts new file mode 100644 index 00000000..9572cc2b --- /dev/null +++ b/src/modules/state-iac/infrastructure/engines/pulumi/pulumi-discovery.ts @@ -0,0 +1,141 @@ +import { listAll, readText, type ObjectStore } from '../../object-store/object-store'; + +/** + * Basic discovery of a Pulumi DIY backend: its layout and the projects and stacks it holds, so + * they can be assigned to GitOps projects. Reading states is the engine's job (phase 2). + * Layout reference: docs/adr/0003-state-iac.md. + */ + +export type PulumiLayout = 'project' | 'legacy' | 'empty'; + +export type DiscoveredStack = { name: string; key: string; size: number; updatedAt: string | null }; + +export type DiscoveredProject = { + /** `null` for legacy stacks whose project can't be found (no resources yet). */ + name: string | null; + stacks: DiscoveredStack[]; +}; + +export type PulumiDiscovery = { + layout: PulumiLayout; + /** `version` of `meta.yaml`; `null` when there is none. */ + metaVersion: number | null; + projects: DiscoveredProject[]; + /** More stacks than the discovery reads at once. */ + truncated: boolean; +}; + +export class UnsupportedLayoutError extends Error { + constructor(readonly version: number) { + super(`Pulumi meta.yaml version ${version} is not supported`); + this.name = 'UnsupportedLayoutError'; + } +} + +const META_MAX_BYTES = 64 * 1024; +const MAX_STACKS = 2_000; +const LEGACY_READ_CONCURRENCY = 4; + +/** `prod.json`, `prod.json.gz`, `prod.json.zst` → `prod`; `.bak` and retained copies → `null`. */ +export function stackNameOf(fileName: string): string | null { + return fileName.match(/^(.+)\.json(?:\.gz|\.zst)?$/)?.[1] ?? null; +} + +/** `version: 1` → 1; `null` when the file has no version. */ +export function parseMetaVersion(text: string): number | null { + const match = text.match(/^\s*version\s*:\s*(\d+)\s*$/m); + return match ? Number(match[1]) : null; +} + +/** Project of a legacy stack, from its URNs: `urn:pulumi:::::…`. */ +export function projectFromState(text: string): string | null { + return text.match(/"urn:pulumi:[^:"]+::([^:"]+)::/)?.[1] ?? null; +} + +/** `root` is the bookkeeping prefix, `.pulumi/` or `/.pulumi/`. */ +export async function detectPulumiLayout( + store: ObjectStore, + root: string, +): Promise<{ layout: PulumiLayout; metaVersion: number | null }> { + const meta = await readText(store, `${root}meta.yaml`, META_MAX_BYTES); + if (meta !== null) { + const version = parseMetaVersion(meta); + if (version === 1) return { layout: 'project', metaVersion: 1 }; + if (version === 0) return { layout: 'legacy', metaVersion: 0 }; + throw new UnsupportedLayoutError(version ?? -1); + } + // Pulumi only writes meta.yaml for the project layout: without it, look at stacks/ + const page = await store.list(`${root}stacks/`, { delimiter: '/', maxKeys: 100 }); + const legacyStacks = page.objects.some((object) => + stackNameOf(object.key.slice(`${root}stacks/`.length)), + ); + if (legacyStacks) return { layout: 'legacy', metaVersion: null }; + if (page.prefixes.length > 0) return { layout: 'project', metaVersion: null }; + return { layout: 'empty', metaVersion: null }; +} + +function stacksIn(objects: { key: string; size: number; updatedAt: string | null }[], dir: string) { + const byName = new Map(); + for (const object of objects) { + const name = stackNameOf(object.key.slice(dir.length)); + if (!name) continue; + const current = byName.get(name); + // `x.json` and `x.json.gz` at once: the most recently modified wins, like Pulumi does + if (!current || (object.updatedAt ?? '') >= (current.updatedAt ?? '')) { + byName.set(name, { name, key: object.key, size: object.size, updatedAt: object.updatedAt }); + } + } + return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name)); +} + +export async function discoverPulumi(store: ObjectStore, root: string): Promise { + const { layout, metaVersion } = await detectPulumiLayout(store, root); + const stacksDir = `${root}stacks/`; + if (layout === 'empty') return { layout, metaVersion, projects: [], truncated: false }; + + if (layout === 'project') { + const { prefixes } = await listAll(store, stacksDir, { delimiter: '/' }); + const projects: DiscoveredProject[] = []; + let count = 0; + let truncated = false; + for (const projectDir of prefixes.sort()) { + const name = projectDir.slice(stacksDir.length, -1); + const listed = await listAll(store, projectDir, { + delimiter: '/', + maxObjects: MAX_STACKS - count, + }); + const stacks = stacksIn(listed.objects, projectDir); + count += stacks.length; + truncated ||= listed.truncated; + if (stacks.length > 0) projects.push({ name, stacks }); + if (count >= MAX_STACKS) { + truncated = true; + break; + } + } + return { layout, metaVersion, projects, truncated }; + } + + // legacy: one flat folder; the project is only in each state's URNs + const listed = await listAll(store, stacksDir, { delimiter: '/', maxObjects: MAX_STACKS }); + const stacks = stacksIn(listed.objects, stacksDir); + const projectOf = new Map(); + for (let i = 0; i < stacks.length; i += LEGACY_READ_CONCURRENCY) { + await Promise.all( + stacks.slice(i, i + LEGACY_READ_CONCURRENCY).map(async (stack) => { + const text = await readText(store, stack.key); + projectOf.set(stack.name, text ? projectFromState(text) : null); + }), + ); + } + const grouped = new Map(); + for (const stack of stacks) { + const project = projectOf.get(stack.name) ?? null; + grouped.set(project, [...(grouped.get(project) ?? []), stack]); + } + const projects = [...grouped.entries()] + .map(([name, list]) => ({ name, stacks: list })) + // unknown project last + .sort((a, b) => (a.name === null ? 1 : b.name === null ? -1 : a.name.localeCompare(b.name))); + return { layout, metaVersion, projects, truncated: listed.truncated }; +} diff --git a/src/modules/state-iac/infrastructure/object-store/factory.ts b/src/modules/state-iac/infrastructure/object-store/factory.ts new file mode 100644 index 00000000..7b4a4e3b --- /dev/null +++ b/src/modules/state-iac/infrastructure/object-store/factory.ts @@ -0,0 +1,36 @@ +import type { + StateBackendCredentials, + StateBackendDomain, +} from '../../domain/state-backend.domain'; +import { GcsObjectStore } from './gcs-object-store'; +import type { ObjectStore } from './object-store'; +import { S3ObjectStore } from './s3-object-store'; + +/** Builds the store of a backend; `credentials` is `null` for ambient auth. */ +export type ObjectStoreFactory = ( + backend: StateBackendDomain, + credentials: StateBackendCredentials | null, +) => ObjectStore; + +export const createObjectStore: ObjectStoreFactory = (backend, credentials) => { + if (backend.provider === 'gcs') { + return new GcsObjectStore({ + bucket: backend.bucket, + serviceAccountJson: credentials?.provider === 'gcs' ? credentials.serviceAccountJson : null, + }); + } + return new S3ObjectStore({ + bucket: backend.bucket, + region: backend.region, + endpoint: backend.endpoint, + forcePathStyle: backend.forcePathStyle, + credentials: + credentials?.provider === 's3' + ? { + accessKeyId: credentials.accessKeyId, + secretAccessKey: credentials.secretAccessKey, + sessionToken: credentials.sessionToken || undefined, + } + : null, + }); +}; diff --git a/src/modules/state-iac/infrastructure/object-store/gcs-object-store.ts b/src/modules/state-iac/infrastructure/object-store/gcs-object-store.ts new file mode 100644 index 00000000..d3e6e3e7 --- /dev/null +++ b/src/modules/state-iac/infrastructure/object-store/gcs-object-store.ts @@ -0,0 +1,86 @@ +import type { Readable } from 'node:stream'; +import { Storage, type Bucket } from '@google-cloud/storage'; +import { + primeStream, + type ListOptions, + type ListPage, + type ObjectInfo, + type ObjectStore, +} from './object-store'; + +export type GcsObjectStoreConfig = { + bucket: string; + /** Service account key JSON; without it, Application Default Credentials (Workload Identity). */ + serviceAccountJson?: string | null; +}; + +const isNotFound = (error: unknown) => (error as { code?: number })?.code === 404; + +/** + * Google Cloud Storage. Needs `storage.objects.list` and `storage.objects.get` only + * (`roles/storage.objectViewer`): it never writes. + */ +export class GcsObjectStore implements ObjectStore { + private readonly bucket: Bucket; + + constructor(config: GcsObjectStoreConfig) { + const options: ConstructorParameters[0] = {}; + if (config.serviceAccountJson) { + const credentials = JSON.parse(config.serviceAccountJson) as { + project_id?: string; + client_email?: string; + private_key?: string; + }; + options.credentials = credentials; + if (credentials.project_id) options.projectId = credentials.project_id; + } + this.bucket = new Storage(options).bucket(config.bucket); + } + + async list(prefix: string, options: ListOptions = {}): Promise { + const [files, , response] = await this.bucket.getFiles({ + prefix, + delimiter: options.delimiter, + pageToken: options.pageToken, + maxResults: options.maxKeys ?? 1000, + autoPaginate: false, + }); + const body = (response ?? {}) as { prefixes?: string[]; nextPageToken?: string }; + return { + objects: files.map((file) => toInfo(file.name, file.metadata)), + prefixes: body.prefixes ?? [], + nextPageToken: body.nextPageToken ?? null, + }; + } + + async head(key: string): Promise { + try { + const [metadata] = await this.bucket.file(key).getMetadata(); + return toInfo(key, metadata); + } catch (error) { + if (isNotFound(error)) return null; + throw error; + } + } + + async openRead(key: string): Promise { + try { + return await primeStream(this.bucket.file(key).createReadStream()); + } catch (error) { + if (isNotFound(error)) return null; + throw error; + } + } +} + +function toInfo( + key: string, + metadata: { size?: string | number; updated?: string; generation?: string | number } = {}, +): ObjectInfo { + return { + key, + size: Number(metadata.size ?? 0), + updatedAt: metadata.updated ?? null, + version: metadata.generation !== undefined ? String(metadata.generation) : null, + }; +} diff --git a/src/modules/state-iac/infrastructure/object-store/in-memory-object-store.ts b/src/modules/state-iac/infrastructure/object-store/in-memory-object-store.ts new file mode 100644 index 00000000..0a6882b0 --- /dev/null +++ b/src/modules/state-iac/infrastructure/object-store/in-memory-object-store.ts @@ -0,0 +1,109 @@ +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { join, relative, sep } from 'node:path'; +import { Readable } from 'node:stream'; +import type { ListOptions, ListPage, ObjectInfo, ObjectStore } from './object-store'; + +type StoredObject = { body: Buffer; updatedAt: string; version: number }; + +/** Bucket in memory for tests: same listing semantics as GCS/S3 (sorted keys, delimiter, pages). */ +export class InMemoryObjectStore implements ObjectStore { + private readonly objects = new Map(); + /** Every call, to assert that nothing lists the whole bucket or writes. */ + readonly calls: Array<{ op: 'list' | 'head' | 'get'; key: string }> = []; + /** Makes every call fail with this error (simulates a denied or missing bucket). */ + failWith: unknown = null; + + constructor(private readonly pageSize = 1000) {} + + /** Loads a directory as bucket content: `/a/b.json` becomes `a/b.json`. */ + static fromDirectory(dir: string, keyPrefix = ''): InMemoryObjectStore { + const store = new InMemoryObjectStore(); + const walk = (current: string) => { + for (const entry of readdirSync(current)) { + const path = join(current, entry); + if (statSync(path).isDirectory()) walk(path); + else store.put(keyPrefix + relative(dir, path).split(sep).join('/'), readFileSync(path)); + } + }; + walk(dir); + return store; + } + + put(key: string, body: string | Buffer, updatedAt = new Date().toISOString()): void { + const previous = this.objects.get(key); + this.objects.set(key, { + body: typeof body === 'string' ? Buffer.from(body) : body, + updatedAt, + version: (previous?.version ?? 0) + 1, + }); + } + + private check() { + if (this.failWith) throw this.failWith; + } + + private info(key: string, object: StoredObject): ObjectInfo { + return { + key, + size: object.body.length, + updatedAt: object.updatedAt, + version: String(object.version), + }; + } + + async list(prefix: string, options: ListOptions = {}): Promise { + this.calls.push({ op: 'list', key: prefix }); + this.check(); + const pageSize = options.maxKeys ?? this.pageSize; + const keys = [...this.objects.keys()].filter((key) => key.startsWith(prefix)).sort(); + + // entries (objects and folded prefixes) in key order, so pages are stable + const entries: Array<{ object?: ObjectInfo; prefix?: string; sortKey: string }> = []; + const seen = new Set(); + for (const key of keys) { + const rest = key.slice(prefix.length); + const slash = options.delimiter ? rest.indexOf(options.delimiter) : -1; + if (slash >= 0) { + const folded = prefix + rest.slice(0, slash + 1); + if (!seen.has(folded)) { + seen.add(folded); + entries.push({ prefix: folded, sortKey: folded }); + } + } else { + entries.push({ object: this.info(key, this.objects.get(key)!), sortKey: key }); + } + } + + const start = options.pageToken + ? entries.findIndex((entry) => entry.sortKey > options.pageToken!) + : 0; + const page = start < 0 ? [] : entries.slice(start, start + pageSize); + const more = start >= 0 && start + pageSize < entries.length; + return { + objects: page.flatMap((entry) => (entry.object ? [entry.object] : [])), + prefixes: page.flatMap((entry) => (entry.prefix ? [entry.prefix] : [])), + nextPageToken: more ? page[page.length - 1].sortKey : null, + }; + } + + async head(key: string): Promise { + this.calls.push({ op: 'head', key }); + this.check(); + const object = this.objects.get(key); + return object ? this.info(key, object) : null; + } + + async openRead(key: string): Promise { + this.calls.push({ op: 'get', key }); + this.check(); + const object = this.objects.get(key); + if (!object) return null; + // small chunks, so stream handling (gzip detection, size limits) is really exercised + const body = object.body; + return Readable.from( + (function* () { + for (let i = 0; i < body.length; i += 16 * 1024) yield body.subarray(i, i + 16 * 1024); + })(), + ); + } +} diff --git a/src/modules/state-iac/infrastructure/object-store/object-store.test.ts b/src/modules/state-iac/infrastructure/object-store/object-store.test.ts new file mode 100644 index 00000000..9ff9311e --- /dev/null +++ b/src/modules/state-iac/infrastructure/object-store/object-store.test.ts @@ -0,0 +1,90 @@ +import { gzipSync } from 'node:zlib'; +import { describe, expect, it } from 'vitest'; +import { InMemoryObjectStore } from './in-memory-object-store'; +import { + ObjectTooLargeError, + classifyStoreError, + listAll, + readObject, + readText, +} from './object-store'; + +describe('InMemoryObjectStore listing', () => { + const store = new InMemoryObjectStore(2); + for (const key of [ + '.pulumi/meta.yaml', + '.pulumi/stacks/a/dev.json', + '.pulumi/stacks/a/prod.json', + '.pulumi/stacks/b/dev.json', + '.pulumi/stacks/top.json', + ]) { + store.put(key, '{}'); + } + + it('folds deeper keys into prefixes with a delimiter', async () => { + const all = await listAll(store, '.pulumi/stacks/', { delimiter: '/' }); + expect(all.prefixes).toEqual(['.pulumi/stacks/a/', '.pulumi/stacks/b/']); + expect(all.objects.map((o) => o.key)).toEqual(['.pulumi/stacks/top.json']); + }); + + it('pages through every key', async () => { + const first = await store.list('.pulumi/'); + expect(first.objects).toHaveLength(2); + expect(first.nextPageToken).not.toBeNull(); + const all = await listAll(store, '.pulumi/'); + expect(all.objects).toHaveLength(5); + expect(all.truncated).toBe(false); + }); + + it('stops at maxObjects', async () => { + const all = await listAll(store, '.pulumi/', { maxObjects: 3 }); + expect(all.objects).toHaveLength(3); + expect(all.truncated).toBe(true); + }); +}); + +describe('readObject', () => { + it('returns null for a missing object', async () => { + expect(await readObject(new InMemoryObjectStore(), 'nope')).toBeNull(); + }); + + it('detects gzip by content, not by name', async () => { + const store = new InMemoryObjectStore(); + const body = JSON.stringify({ version: 3, big: 'x'.repeat(100_000) }); + store.put('stack.json', gzipSync(body)); + store.put('plain.json.gz', body); + expect(await readText(store, 'stack.json')).toBe(body); + expect(await readText(store, 'plain.json.gz')).toBe(body); + }); + + it('stops past the size limit, also when decompressing (gzip bomb)', async () => { + const store = new InMemoryObjectStore(); + store.put('big.json', 'x'.repeat(2_000)); + store.put('bomb.json.gz', gzipSync(Buffer.alloc(5_000_000))); + await expect(readObject(store, 'big.json', 1_000)).rejects.toBeInstanceOf(ObjectTooLargeError); + await expect(readObject(store, 'bomb.json.gz', 100_000)).rejects.toBeInstanceOf( + ObjectTooLargeError, + ); + }); +}); + +describe('classifyStoreError', () => { + it('maps provider errors to short codes', () => { + expect(classifyStoreError({ name: 'AccessDenied', $metadata: { httpStatusCode: 403 } })).toBe( + 'access_denied', + ); + expect( + classifyStoreError({ code: 403, message: 'x@y.iam does not have storage.objects.list' }), + ).toBe('access_denied'); + expect(classifyStoreError({ name: 'NoSuchBucket' })).toBe('bucket_not_found'); + expect(classifyStoreError({ code: 404, message: 'The specified bucket does not exist.' })).toBe( + 'bucket_not_found', + ); + expect(classifyStoreError({ name: 'InvalidAccessKeyId' })).toBe('invalid_credentials'); + expect(classifyStoreError({ code: 'ENOTFOUND', message: 'getaddrinfo ENOTFOUND' })).toBe( + 'network', + ); + expect(classifyStoreError(new ObjectTooLargeError('k', 1))).toBe('too_large'); + expect(classifyStoreError(new Error('boom'))).toBe('unknown'); + }); +}); diff --git a/src/modules/state-iac/infrastructure/object-store/object-store.ts b/src/modules/state-iac/infrastructure/object-store/object-store.ts new file mode 100644 index 00000000..54981cc2 --- /dev/null +++ b/src/modules/state-iac/infrastructure/object-store/object-store.ts @@ -0,0 +1,177 @@ +import { Readable } from 'node:stream'; +import { createGunzip } from 'node:zlib'; + +/** + * Read-only access to a bucket. Knows nothing about IaC: engines interpret the keys. Every key + * is absolute in the bucket (prefixes are the engine's business). + */ +export interface ObjectStore { + /** + * One page of objects under `prefix`. With `delimiter: '/'`, keys deeper than one level are + * folded into `prefixes` (the "folders"), like GCS and S3 do. + */ + list(prefix: string, options?: ListOptions): Promise; + /** Object metadata, or `null` when it does not exist. */ + head(key: string): Promise; + /** Raw object stream, or `null` when it does not exist. */ + openRead(key: string): Promise; +} + +export type ListOptions = { delimiter?: '/'; pageToken?: string; maxKeys?: number }; + +export type ObjectInfo = { + key: string; + size: number; + updatedAt: string | null; + /** ETag (S3) or generation (GCS): changes whenever the content does. */ + version: string | null; +}; + +export type ListPage = { objects: ObjectInfo[]; prefixes: string[]; nextPageToken: string | null }; + +/** Default limit of a decompressed object (ADR 0003): bigger ones fail, also against gzip bombs. */ +export const DEFAULT_MAX_OBJECT_BYTES = 50 * 1024 * 1024; + +export class ObjectTooLargeError extends Error { + constructor( + readonly key: string, + readonly limit: number, + ) { + super(`Object ${key} is larger than ${limit} bytes`); + this.name = 'ObjectTooLargeError'; + } +} + +/** Every object under `prefix`, following pages (bounded by `maxObjects`). */ +export async function listAll( + store: ObjectStore, + prefix: string, + options: { delimiter?: '/'; maxObjects?: number } = {}, +): Promise<{ objects: ObjectInfo[]; prefixes: string[]; truncated: boolean }> { + const maxObjects = options.maxObjects ?? 10_000; + const objects: ObjectInfo[] = []; + const prefixes = new Set(); + let pageToken: string | undefined; + do { + const page = await store.list(prefix, { delimiter: options.delimiter, pageToken }); + objects.push(...page.objects); + page.prefixes.forEach((p) => prefixes.add(p)); + pageToken = page.nextPageToken ?? undefined; + if (objects.length >= maxObjects) { + return { objects: objects.slice(0, maxObjects), prefixes: [...prefixes], truncated: true }; + } + } while (pageToken); + return { objects, prefixes: [...prefixes], truncated: false }; +} + +const GZIP_MAGIC = [0x1f, 0x8b]; + +/** + * Reads a whole object, gunzipping it when its content is gzip (Pulumi detects compression by + * content, not by name). Stops as soon as the raw or decompressed size passes `maxBytes`. + * `null` when the object does not exist. + */ +export async function readObject( + store: ObjectStore, + key: string, + maxBytes = DEFAULT_MAX_OBJECT_BYTES, +): Promise { + const stream = await store.openRead(key); + if (!stream) return null; + + const iterator = stream[Symbol.asyncIterator](); + const first = await iterator.next(); + if (first.done) return Buffer.alloc(0); + const head = Buffer.from(first.value as Uint8Array); + const rest = Readable.from( + (async function* () { + yield head; + for (let next = await iterator.next(); !next.done; next = await iterator.next()) { + yield next.value; + } + })(), + ); + const gzipped = head[0] === GZIP_MAGIC[0] && head[1] === GZIP_MAGIC[1]; + const source = gzipped ? rest.pipe(createGunzip()) : rest; + + const chunks: Buffer[] = []; + let total = 0; + try { + for await (const chunk of source) { + total += (chunk as Buffer).length; + if (total > maxBytes) throw new ObjectTooLargeError(key, maxBytes); + chunks.push(chunk as Buffer); + } + } finally { + stream.destroy(); + } + return Buffer.concat(chunks); +} + +/** `readObject` + UTF-8 text. */ +export async function readText( + store: ObjectStore, + key: string, + maxBytes?: number, +): Promise { + const buffer = await readObject(store, key, maxBytes); + return buffer ? buffer.toString('utf8') : null; +} + +/** + * Waits for the first chunk (or the first error) of `stream`, so a missing object fails at open + * time instead of in the middle of a read. Returns an equivalent stream. + */ +export async function primeStream(stream: Readable): Promise { + const iterator = stream[Symbol.asyncIterator](); + const first = await iterator.next(); + return Readable.from( + (async function* () { + if (first.done) return; + yield first.value; + for (let next = await iterator.next(); !next.done; next = await iterator.next()) { + yield next.value; + } + })(), + ); +} + +/** Why a bucket read failed, as a short code stored in `lastError` and shown translated. */ +export type StoreErrorCode = + | 'access_denied' + | 'bucket_not_found' + | 'invalid_credentials' + | 'network' + | 'too_large' + | 'unknown'; + +export function classifyStoreError(error: unknown): StoreErrorCode { + if (error instanceof ObjectTooLargeError) return 'too_large'; + const e = (error ?? {}) as { + name?: string; + code?: string | number; + Code?: string; + message?: string; + $metadata?: { httpStatusCode?: number }; + }; + const status = e.$metadata?.httpStatusCode ?? (typeof e.code === 'number' ? e.code : undefined); + const name = String(e.Code ?? e.name ?? e.code ?? ''); + const message = String(e.message ?? ''); + if (/NoSuchBucket/i.test(name) || /bucket does not exist|NoSuchBucket/i.test(message)) { + return 'bucket_not_found'; + } + if ( + /InvalidAccessKeyId|SignatureDoesNotMatch|ExpiredToken|CredentialsProviderError|invalid_grant/i.test( + name + ' ' + message, + ) || + status === 401 + ) { + return 'invalid_credentials'; + } + if (status === 403 || /AccessDenied|Forbidden/i.test(name)) return 'access_denied'; + if (status === 404) return 'bucket_not_found'; + if (/ENOTFOUND|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|TimeoutError/i.test(name + message)) { + return 'network'; + } + return 'unknown'; +} diff --git a/src/modules/state-iac/infrastructure/object-store/s3-object-store.ts b/src/modules/state-iac/infrastructure/object-store/s3-object-store.ts new file mode 100644 index 00000000..c023db57 --- /dev/null +++ b/src/modules/state-iac/infrastructure/object-store/s3-object-store.ts @@ -0,0 +1,101 @@ +import { Readable } from 'node:stream'; +import { + GetObjectCommand, + HeadObjectCommand, + ListObjectsV2Command, + S3Client, + type S3ClientConfig, +} from '@aws-sdk/client-s3'; +import type { ListOptions, ListPage, ObjectInfo, ObjectStore } from './object-store'; + +export type S3ObjectStoreConfig = { + bucket: string; + region?: string | null; + /** S3-compatible endpoint (MinIO, Cloudflare R2…). */ + endpoint?: string | null; + forcePathStyle?: boolean; + /** Without them, the default AWS credential chain (IAM role, env, profile). */ + credentials?: { accessKeyId: string; secretAccessKey: string; sessionToken?: string } | null; +}; + +const isNotFound = (error: unknown) => { + const e = error as { name?: string; $metadata?: { httpStatusCode?: number } }; + return e?.name === 'NoSuchKey' || e?.name === 'NotFound' || e?.$metadata?.httpStatusCode === 404; +}; + +/** + * AWS S3 and S3-compatible stores. Needs `s3:ListBucket` and `s3:GetObject` only: it never writes. + */ +export class S3ObjectStore implements ObjectStore { + private readonly client: S3Client; + private readonly bucket: string; + + constructor(config: S3ObjectStoreConfig) { + const options: S3ClientConfig = { + // the SDK requires a region; S3-compatible stores usually ignore it + region: config.region || 'us-east-1', + endpoint: config.endpoint || undefined, + forcePathStyle: config.forcePathStyle ?? false, + }; + if (config.credentials) options.credentials = { ...config.credentials }; + this.client = new S3Client(options); + this.bucket = config.bucket; + } + + async list(prefix: string, options: ListOptions = {}): Promise { + const response = await this.client.send( + new ListObjectsV2Command({ + Bucket: this.bucket, + Prefix: prefix, + Delimiter: options.delimiter, + ContinuationToken: options.pageToken, + MaxKeys: options.maxKeys ?? 1000, + }), + ); + return { + objects: (response.Contents ?? []).map((item) => ({ + key: item.Key ?? '', + size: item.Size ?? 0, + updatedAt: item.LastModified?.toISOString() ?? null, + version: item.ETag ?? null, + })), + prefixes: (response.CommonPrefixes ?? []).flatMap((p) => (p.Prefix ? [p.Prefix] : [])), + nextPageToken: response.IsTruncated ? (response.NextContinuationToken ?? null) : null, + }; + } + + async head(key: string): Promise { + try { + const response = await this.client.send( + new HeadObjectCommand({ Bucket: this.bucket, Key: key }), + ); + return { + key, + size: response.ContentLength ?? 0, + updatedAt: response.LastModified?.toISOString() ?? null, + version: response.ETag ?? null, + }; + } catch (error) { + if (isNotFound(error)) return null; + throw error; + } + } + + async openRead(key: string): Promise { + try { + const response = await this.client.send( + new GetObjectCommand({ Bucket: this.bucket, Key: key }), + ); + const body = response.Body; + if (!body) return Readable.from([]); + return body instanceof Readable + ? body + : Readable.fromWeb( + (body as { transformToWebStream(): ReadableStream }).transformToWebStream() as never, + ); + } catch (error) { + if (isNotFound(error)) return null; + throw error; + } + } +} diff --git a/src/modules/state-iac/infrastructure/repositories/in-memory.repositories.ts b/src/modules/state-iac/infrastructure/repositories/in-memory.repositories.ts new file mode 100644 index 00000000..df8cf35a --- /dev/null +++ b/src/modules/state-iac/infrastructure/repositories/in-memory.repositories.ts @@ -0,0 +1,76 @@ +import { StateBackendDomain, type StateBackendRow } from '../../domain/state-backend.domain'; +import { StateBindingDomain, type StateBindingRow } from '../../domain/state-binding.domain'; +import type { StateBackendChanges, StateBackendRepositoryPort } from './state-backend.repository'; +import type { StateBindingChanges, StateBindingRepositoryPort } from './state-binding.repository'; + +/** In-memory fakes for unit tests; they store copies so callers can't mutate the stored rows. */ +export class InMemoryStateBackendRepository implements StateBackendRepositoryPort { + rows: StateBackendRow[] = []; + + async findById(id: string) { + const row = this.rows.find((candidate) => candidate.id === id); + return row ? new StateBackendDomain(structuredClone(row)) : null; + } + + async listByOrganization(organizationId: string) { + return this.rows + .filter((row) => row.organizationId === organizationId) + .map((row) => new StateBackendDomain(structuredClone(row))); + } + + async create(row: StateBackendRow) { + this.rows.push(structuredClone(row)); + } + + async update(id: string, changes: StateBackendChanges) { + this.rows = this.rows.map((row) => + row.id === id + ? { ...row, ...structuredClone(changes), updatedAt: new Date().toISOString() } + : row, + ); + } + + async delete(id: string) { + this.rows = this.rows.filter((row) => row.id !== id); + } +} + +export class InMemoryStateBindingRepository implements StateBindingRepositoryPort { + rows: StateBindingRow[] = []; + + private copies(filter: (row: StateBindingRow) => boolean) { + return this.rows.filter(filter).map((row) => new StateBindingDomain(structuredClone(row))); + } + + async findById(id: string) { + return this.copies((row) => row.id === id)[0] ?? null; + } + + async listByBackend(backendId: string) { + return this.copies((row) => row.backendId === backendId); + } + + async listByOrganization(organizationId: string) { + return this.copies((row) => row.organizationId === organizationId); + } + + async listByProject(projectId: string) { + return this.copies((row) => row.projectId === projectId); + } + + async create(row: StateBindingRow) { + this.rows.push(structuredClone(row)); + } + + async update(id: string, changes: StateBindingChanges) { + this.rows = this.rows.map((row) => + row.id === id + ? { ...row, ...structuredClone(changes), updatedAt: new Date().toISOString() } + : row, + ); + } + + async delete(id: string) { + this.rows = this.rows.filter((row) => row.id !== id); + } +} diff --git a/src/modules/state-iac/infrastructure/repositories/state-backend.repository.ts b/src/modules/state-iac/infrastructure/repositories/state-backend.repository.ts new file mode 100644 index 00000000..448f0970 --- /dev/null +++ b/src/modules/state-iac/infrastructure/repositories/state-backend.repository.ts @@ -0,0 +1,48 @@ +import { StateBackendEntity } from '#lib/database/schemas'; +import { Repository } from '#lib/server/infra/repository'; +import { StateBackendDomain, type StateBackendRow } from '../../domain/state-backend.domain'; + +export type StateBackendChanges = Partial< + Omit +>; + +/** Persistence port; `InMemoryStateBackendRepository` implements it in tests. */ +export interface StateBackendRepositoryPort { + findById(id: string): Promise; + listByOrganization(organizationId: string): Promise; + create(row: StateBackendRow): Promise; + update(id: string, changes: StateBackendChanges): Promise; + delete(id: string): Promise; +} + +export class StateBackendRepository extends Repository implements StateBackendRepositoryPort { + async findById(id: string) { + const result = await this.db.select().from(StateBackendEntity).where({ id }).limit(1); + const row = result.rows[0]; + return row ? new StateBackendDomain(row) : null; + } + + async listByOrganization(organizationId: string) { + const result = await this.db + .select() + .from(StateBackendEntity) + .where({ organizationId }) + .orderBy('createdAt', 'asc'); + return result.rows.map((row: any) => new StateBackendDomain(row)); + } + + async create(row: StateBackendRow) { + await this.db.insert(StateBackendEntity).values({ ...row }); + } + + async update(id: string, changes: StateBackendChanges) { + await this.db + .update(StateBackendEntity) + .set({ ...changes, updatedAt: new Date().toISOString() }) + .where({ id }); + } + + async delete(id: string) { + await this.db.delete(StateBackendEntity).where({ id }); + } +} diff --git a/src/modules/state-iac/infrastructure/repositories/state-binding.repository.ts b/src/modules/state-iac/infrastructure/repositories/state-binding.repository.ts new file mode 100644 index 00000000..b2d7552f --- /dev/null +++ b/src/modules/state-iac/infrastructure/repositories/state-binding.repository.ts @@ -0,0 +1,60 @@ +import { StateBindingEntity } from '#lib/database/schemas'; +import { Repository } from '#lib/server/infra/repository'; +import { StateBindingDomain, type StateBindingRow } from '../../domain/state-binding.domain'; + +export type StateBindingChanges = Partial>; + +/** Persistence port; `InMemoryStateBindingRepository` implements it in tests. */ +export interface StateBindingRepositoryPort { + findById(id: string): Promise; + listByBackend(backendId: string): Promise; + listByOrganization(organizationId: string): Promise; + listByProject(projectId: string): Promise; + create(row: StateBindingRow): Promise; + update(id: string, changes: StateBindingChanges): Promise; + delete(id: string): Promise; +} + +export class StateBindingRepository extends Repository implements StateBindingRepositoryPort { + async findById(id: string) { + const result = await this.db.select().from(StateBindingEntity).where({ id }).limit(1); + const row = result.rows[0]; + return row ? new StateBindingDomain(row) : null; + } + + private async listWhere(where: Record) { + const result = await this.db + .select() + .from(StateBindingEntity) + .where(where) + .orderBy('createdAt', 'asc'); + return result.rows.map((row: any) => new StateBindingDomain(row)); + } + + listByBackend(backendId: string) { + return this.listWhere({ backendId }); + } + + listByOrganization(organizationId: string) { + return this.listWhere({ organizationId }); + } + + listByProject(projectId: string) { + return this.listWhere({ projectId }); + } + + async create(row: StateBindingRow) { + await this.db.insert(StateBindingEntity).values({ ...row }); + } + + async update(id: string, changes: StateBindingChanges) { + await this.db + .update(StateBindingEntity) + .set({ ...changes, updatedAt: new Date().toISOString() }) + .where({ id }); + } + + async delete(id: string) { + await this.db.delete(StateBindingEntity).where({ id }); + } +} diff --git a/src/modules/storage/application/storage.service.ts b/src/modules/storage/application/storage.service.ts deleted file mode 100644 index c354e27d..00000000 --- a/src/modules/storage/application/storage.service.ts +++ /dev/null @@ -1,171 +0,0 @@ -import { Storage } from '@google-cloud/storage'; -import { GetObjectCommand, ListObjectsV2Command, S3Client } from '@aws-sdk/client-s3'; -import type { StorageConfig } from '../domain/entities'; - -export class StorageService { - async listPulumiStates(config: StorageConfig) { - if (config.provider === 's3') { - const client = new S3Client({ - region: config.region || undefined, - credentials: { - accessKeyId: config.accessKeyId || '', - secretAccessKey: config.secretAccessKey || '', - }, - endpoint: config.endpoint || undefined, - forcePathStyle: !!config.endpoint, - }); - - const response = await client.send(new ListObjectsV2Command({ Bucket: config.bucket })); - const files = response.Contents?.map((item) => item.Key || '') || []; - - const states = files.filter((file) => { - if (!file.endsWith('.json')) return false; - if (file.includes('/history/')) return false; - if (file.includes('/backups/')) return false; - if (file.endsWith('.json.bak')) return false; - return file.includes('.pulumi/stacks/') || !file.includes('.pulumi/'); - }); - - const locks = files.filter((file) => file.startsWith('.pulumi/locks/')); - return { states, locks }; - } - - if (config.provider === 'gcs') { - const gcsOptions: Record = {}; - if (config.gcpProjectId?.trim()) { - gcsOptions.projectId = config.gcpProjectId; - } - if (config.gcpCredentials?.trim()) { - try { - gcsOptions.credentials = JSON.parse(config.gcpCredentials); - } catch { - throw new Error('Invalid GCP Credentials JSON'); - } - } - - const storage = new Storage(gcsOptions); - const [files] = await storage.bucket(config.bucket).getFiles(); - const fileNames = files.map((file) => file.name); - - const states = fileNames.filter((file) => { - if (!file.endsWith('.json')) return false; - if (file.includes('/history/')) return false; - if (file.includes('/backups/')) return false; - if (file.endsWith('.json.bak')) return false; - return file.includes('.pulumi/stacks/') || !file.includes('.pulumi/'); - }); - - const locks = fileNames.filter((file) => file.startsWith('.pulumi/locks/')); - return { states, locks }; - } - - throw new Error('Unsupported provider'); - } - - async getPulumiState(config: StorageConfig, key: string) { - if (config.provider === 's3') { - const client = new S3Client({ - region: config.region || undefined, - credentials: { - accessKeyId: config.accessKeyId || '', - secretAccessKey: config.secretAccessKey || '', - }, - endpoint: config.endpoint || undefined, - forcePathStyle: !!config.endpoint, - }); - - const response = await client.send(new GetObjectCommand({ Bucket: config.bucket, Key: key })); - const str = await response.Body?.transformToString(); - if (!str) throw new Error('Empty state file'); - return JSON.parse(str); - } - - if (config.provider === 'gcs') { - const gcsOptions: Record = {}; - if (config.gcpProjectId?.trim()) { - gcsOptions.projectId = config.gcpProjectId; - } - if (config.gcpCredentials?.trim()) { - try { - gcsOptions.credentials = JSON.parse(config.gcpCredentials); - } catch { - throw new Error('Invalid GCP Credentials JSON'); - } - } - - const storage = new Storage(gcsOptions); - const file = storage.bucket(config.bucket).file(key); - const [contents] = await file.download(); - return JSON.parse(contents.toString('utf8')); - } - - throw new Error('Unsupported provider'); - } - - async listPulumiHistory(config: StorageConfig, cleanId: string) { - const prefix = `.pulumi/history/${cleanId}/`; - - if (config.provider === 's3') { - const client = new S3Client({ - region: config.region || undefined, - credentials: { - accessKeyId: config.accessKeyId || '', - secretAccessKey: config.secretAccessKey || '', - }, - endpoint: config.endpoint || undefined, - forcePathStyle: !!config.endpoint, - }); - - const response = await client.send( - new ListObjectsV2Command({ Bucket: config.bucket, Prefix: prefix }), - ); - const files = response.Contents?.map((item) => item.Key || '') || []; - const historyFiles = files.filter((file) => file.endsWith('.history.json')); - - const historyData = await Promise.all( - historyFiles.map(async (key) => { - const result = await client.send(new GetObjectCommand({ Bucket: config.bucket, Key: key })); - const str = await result.Body?.transformToString(); - if (!str) return null; - const data = JSON.parse(str); - return { key, ...data }; - }), - ); - - return historyData.filter(Boolean).sort((a, b) => b.startTime - a.startTime); - } - - if (config.provider === 'gcs') { - const gcsOptions: Record = {}; - if (config.gcpProjectId?.trim()) { - gcsOptions.projectId = config.gcpProjectId; - } - if (config.gcpCredentials?.trim()) { - try { - gcsOptions.credentials = JSON.parse(config.gcpCredentials); - } catch { - throw new Error('Invalid GCP Credentials JSON'); - } - } - - const storage = new Storage(gcsOptions); - const [files] = await storage.bucket(config.bucket).getFiles({ prefix }); - const historyFiles = files - .map((file) => file.name) - .filter((name) => name.endsWith('.history.json')); - - const historyData = await Promise.all( - historyFiles.map(async (key) => { - const file = storage.bucket(config.bucket).file(key); - const [contents] = await file.download(); - const data = JSON.parse(contents.toString('utf8')); - return { key, ...data }; - }), - ); - - return historyData.sort((a, b) => b.startTime - a.startTime); - } - - throw new Error('Unsupported provider'); - } -} diff --git a/src/modules/storage/domain/entities.ts b/src/modules/storage/domain/entities.ts deleted file mode 100644 index f4c6d527..00000000 --- a/src/modules/storage/domain/entities.ts +++ /dev/null @@ -1,10 +0,0 @@ -export interface StorageConfig { - provider: 's3' | 'gcs'; - bucket: string; - region?: string | null; - accessKeyId?: string | null; - secretAccessKey?: string | null; - endpoint?: string | null; - gcpProjectId?: string | null; - gcpCredentials?: string | null; -} diff --git a/src/modules/storage/index.ts b/src/modules/storage/index.ts deleted file mode 100644 index 07be32b7..00000000 --- a/src/modules/storage/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { StorageService } from './application/storage.service'; - -export const storageService = new StorageService(); diff --git a/src/routes/+layout.server.ts b/src/routes/+layout.server.ts index 69c6865c..6334e6b1 100644 --- a/src/routes/+layout.server.ts +++ b/src/routes/+layout.server.ts @@ -60,6 +60,7 @@ export async function load({ locals, url }) { canReadOrgAudit, canReadOrgEvents, canReadOrganizationAlerts, + canReadOrgStateIac, ] = await Promise.all([ orgSectionPermission('organization:projects:read'), orgSectionPermission('organization:users:read'), @@ -70,6 +71,7 @@ export async function load({ locals, url }) { orgSectionPermission('organization:audit:read'), orgSectionPermission('organization:events:read'), orgSectionPermission('organization:alerts:read'), + orgSectionPermission('organization:stateiac:backends:read'), ]); const currentProjectSlug = url.pathname.match(/\/projects\/([^/]+)/)?.[1] ?? null; @@ -177,6 +179,7 @@ export async function load({ locals, url }) { canReadOrgAudit, canReadOrgEvents, canReadOrganizationAlerts, + canReadOrgStateIac, canReadProjectInfo, canReadProjectUsers, canReadProjectRoles, diff --git a/src/routes/api/state-iac/backends/+server.ts b/src/routes/api/state-iac/backends/+server.ts new file mode 100644 index 00000000..aabb7e55 --- /dev/null +++ b/src/routes/api/state-iac/backends/+server.ts @@ -0,0 +1,28 @@ +import { json } from '@sveltejs/kit'; +import { readJson, toResponse } from '#lib/server/alerts/http'; +import { + backendInputFrom, + createBackend, + listBackends, + resolveOrganization, +} from '#lib/server/state-iac/backends'; + +// GET /api/state-iac/backends?organizationId=…: the organization's backends. Credentials are never +// returned, only `hasCredentials` +export async function GET({ url, locals }) { + const organization = await resolveOrganization(url.searchParams.get('organizationId')); + if (!organization.ok) return json({ error: organization.error }, { status: organization.status }); + return toResponse(await listBackends(locals, organization.data.organizationId)); +} + +// POST /api/state-iac/backends { organizationId, name, provider, bucket, prefix?, region?, +// endpoint?, forcePathStyle?, auth, credentials?: { serviceAccountJson } | { accessKeyId, +// secretAccessKey, sessionToken? }, enabled? } +export async function POST({ request, locals }) { + const body = await readJson(request); + const organization = await resolveOrganization(body.organizationId); + if (!organization.ok) return json({ error: organization.error }, { status: organization.status }); + return toResponse( + await createBackend(locals, organization.data.organizationId, backendInputFrom(body)), + ); +} diff --git a/src/routes/api/state-iac/backends/[id]/+server.ts b/src/routes/api/state-iac/backends/[id]/+server.ts new file mode 100644 index 00000000..1c6db391 --- /dev/null +++ b/src/routes/api/state-iac/backends/[id]/+server.ts @@ -0,0 +1,23 @@ +import { readJson, toResponse } from '#lib/server/alerts/http'; +import { + backendInputFrom, + deleteBackend, + getBackend, + updateBackend, +} from '#lib/server/state-iac/backends'; + +export async function GET({ params, locals }) { + return toResponse(await getBackend(locals, params.id)); +} + +// PATCH /api/state-iac/backends/: omitted fields keep their value, omitted credentials keep the +// stored ones (they are never returned, so they have to be typed again to change them) +export async function PATCH({ params, request, locals }) { + const body = await readJson(request); + return toResponse(await updateBackend(locals, params.id, backendInputFrom(body))); +} + +// DELETE /api/state-iac/backends/: also removes its bindings; the bucket is never touched +export async function DELETE({ params, locals }) { + return toResponse(await deleteBackend(locals, params.id)); +} diff --git a/src/routes/api/state-iac/backends/[id]/projects/+server.ts b/src/routes/api/state-iac/backends/[id]/projects/+server.ts new file mode 100644 index 00000000..66c73baf --- /dev/null +++ b/src/routes/api/state-iac/backends/[id]/projects/+server.ts @@ -0,0 +1,8 @@ +import { toResponse } from '#lib/server/alerts/http'; +import { listBackendProjects } from '#lib/server/state-iac/backends'; + +// GET /api/state-iac/backends//projects: Pulumi projects and stacks found in the bucket, with +// the GitOps project each one is assigned to +export async function GET({ params, locals }) { + return toResponse(await listBackendProjects(locals, params.id)); +} diff --git a/src/routes/api/state-iac/backends/[id]/projects/[pulumiProject]/+server.ts b/src/routes/api/state-iac/backends/[id]/projects/[pulumiProject]/+server.ts new file mode 100644 index 00000000..2c094c98 --- /dev/null +++ b/src/routes/api/state-iac/backends/[id]/projects/[pulumiProject]/+server.ts @@ -0,0 +1,20 @@ +import { readJson, toResponse } from '#lib/server/alerts/http'; +import { removeBinding, setBinding } from '#lib/server/state-iac/backends'; + +// PUT /api/state-iac/backends//projects/ { projectId, stacks?: string[] }: +// assigns the Pulumi project (all its stacks when `stacks` is empty) to a project of the same +// organization, replacing any previous assignment +export async function PUT({ params, request, locals }) { + const body = await readJson(request); + return toResponse( + await setBinding(locals, params.id, params.pulumiProject, { + projectId: body.projectId, + stacks: body.stacks, + }), + ); +} + +// DELETE /api/state-iac/backends//projects/: leaves it unassigned +export async function DELETE({ params, locals }) { + return toResponse(await removeBinding(locals, params.id, params.pulumiProject)); +} diff --git a/src/routes/api/state-iac/backends/[id]/test/+server.ts b/src/routes/api/state-iac/backends/[id]/test/+server.ts new file mode 100644 index 00000000..d881318b --- /dev/null +++ b/src/routes/api/state-iac/backends/[id]/test/+server.ts @@ -0,0 +1,7 @@ +import { toResponse } from '#lib/server/alerts/http'; +import { testBackend } from '#lib/server/state-iac/backends'; + +// POST /api/state-iac/backends//test: lists the bucket and reads meta.yaml (read-only) +export async function POST({ params, locals }) { + return toResponse(await testBackend(locals, params.id)); +} diff --git a/src/routes/api/state-iac/backends/server.test.ts b/src/routes/api/state-iac/backends/server.test.ts new file mode 100644 index 00000000..45d88571 --- /dev/null +++ b/src/routes/api/state-iac/backends/server.test.ts @@ -0,0 +1,284 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +// grants per caller and context key (`org:`) +const grants: { users: Record> } = { users: {} }; + +vi.mock('#modules/auth', () => ({ + cancanService: { + canSessionUser: async ( + user: { id?: string } | null, + permission: string, + context: { organizationId?: string }, + ) => { + const owned = grants.users[user?.id ?? '']?.[`org:${context.organizationId}`] ?? []; + const [scope, ...rest] = permission.split(':'); + const resource = rest.slice(0, -1).join(':'); + return owned.includes(permission) || owned.includes(`${scope}:${resource}:all`); + }, + canApiKey: () => false, + }, +})); + +vi.mock('#modules/organization', () => ({ + organizationService: { + getOrganization: async (id: string) => + ['org-1', 'org-2'].includes(id) ? { id, name: id, slug: id } : null, + }, +})); + +vi.mock('#modules/projects', () => ({ projectService: { getProject: async () => null } })); + +vi.mock('#modules/state-iac', async () => { + const { createStateIacFixture } = await import('#modules/state-iac/application/testing'); + const domain = await import('#modules/state-iac/domain/state-backend.domain'); + const fixture = createStateIacFixture(); + return { + ...domain, + stateBackendService: fixture.backendService, + stateBindingService: fixture.bindingService, + fixture, + }; +}); + +const stateIac = (await import('#modules/state-iac')) as unknown as { + fixture: ReturnType< + typeof import('#modules/state-iac/application/testing').createStateIacFixture + >; +}; +const { fixtureStore } = await import('#modules/state-iac/application/testing'); +const collection = await import('./+server'); +const item = await import('./[id]/+server'); +const testRoute = await import('./[id]/test/+server'); +const projectsRoute = await import('./[id]/projects/+server'); +const bindingRoute = await import('./[id]/projects/[pulumiProject]/+server'); + +const ADMIN = ['organization:stateiac:backends:all']; +const SECRET = 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'; + +function call( + handler: (event: never) => Promise, + input: { + user?: string; + body?: unknown; + url?: string; + params?: Record; + }, +) { + return handler({ + locals: input.user ? { user: { id: input.user } } : {}, + params: input.params ?? {}, + url: new URL(input.url ?? 'http://localhost/api/state-iac/backends'), + request: { json: async () => input.body ?? {} }, + } as never); +} + +async function createBackend(user = 'admin') { + const response = await call(collection.POST, { + user, + body: { + organizationId: 'org-1', + name: 's3-prod', + provider: 's3', + bucket: 'acme-state', + auth: 'credentials', + credentials: { accessKeyId: 'AKIAEXAMPLE', secretAccessKey: SECRET }, + }, + }); + return { response, body: (await response.json()) as { id: string; [key: string]: unknown } }; +} + +describe('/api/state-iac/backends', () => { + beforeEach(() => { + stateIac.fixture.backends.rows = []; + stateIac.fixture.bindings.rows = []; + stateIac.fixture.buckets.clear(); + grants.users = { + admin: { 'org-1': [], 'org:org-1': ADMIN }, + reader: { 'org:org-1': ['organization:stateiac:backends:read'] }, + tester: { + 'org:org-1': ['organization:stateiac:backends:read', 'organization:stateiac:backends:test'], + }, + otherOrgAdmin: { 'org:org-2': ADMIN }, + notificationsAdmin: { 'org:org-1': ['organization:notifications:all'] }, + }; + }); + + it('never returns the credentials, only hasCredentials', async () => { + const created = await createBackend(); + expect(created.response.status).toBe(201); + const listed = await call(collection.GET, { + user: 'reader', + url: 'http://localhost/api/state-iac/backends?organizationId=org-1', + }); + const fetched = await call(item.GET, { user: 'reader', params: { id: created.body.id } }); + for (const response of [listed, fetched]) { + expect(response.status).toBe(200); + const text = await response.text(); + expect(text).not.toContain(SECRET); + expect(text).not.toContain('AKIAEXAMPLE'); + expect(text).toContain('"hasCredentials":true'); + } + expect(created.body).not.toHaveProperty('credentials'); + }); + + it('only organization:stateiac:backends:* can configure backends', async () => { + expect((await createBackend('reader')).response.status).toBe(403); + expect((await createBackend('notificationsAdmin')).response.status).toBe(403); + expect( + ( + await call(collection.GET, { + user: 'notificationsAdmin', + url: 'http://localhost/api/state-iac/backends?organizationId=org-1', + }) + ).status, + ).toBe(403); + + const { body } = await createBackend(); + const id = body.id; + expect( + (await call(item.PATCH, { user: 'reader', params: { id }, body: { name: 'x' } })).status, + ).toBe(403); + expect((await call(item.DELETE, { user: 'reader', params: { id } })).status).toBe(403); + expect((await call(testRoute.POST, { user: 'reader', params: { id } })).status).toBe(403); + expect((await call(testRoute.POST, { user: 'tester', params: { id } })).status).toBe(200); + expect( + ( + await call(bindingRoute.PUT, { + user: 'tester', + params: { id, pulumiProject: 'network' }, + body: { projectId: 'p1' }, + }) + ).status, + ).toBe(403); + }); + + it("another organization's backend answers 404, like a missing one", async () => { + const { body } = await createBackend(); + for (const handler of [item.GET, item.DELETE, projectsRoute.GET]) { + expect((await call(handler, { user: 'otherOrgAdmin', params: { id: body.id } })).status).toBe( + 404, + ); + } + expect((await call(item.GET, { user: 'admin', params: { id: 'missing' } })).status).toBe(404); + }); + + it('returns validation errors per field', async () => { + const response = await call(collection.POST, { + user: 'admin', + body: { + organizationId: 'org-1', + provider: 's3', + bucket: '!!', + endpoint: 'http://169.254.169.254', + }, + }); + expect(response.status).toBe(400); + expect(await response.json()).toEqual({ + error: 'Invalid backend', + errors: { name: 'required', bucket: 'invalid_bucket', endpoint: 'endpoint_not_allowed' }, + }); + }); + + it('requires an existing organizationId', async () => { + expect((await call(collection.GET, { user: 'admin' })).status).toBe(400); + expect( + (await call(collection.GET, { user: 'admin', url: 'http://localhost/x?organizationId=nope' })) + .status, + ).toBe(404); + }); + + it('PATCH without credentials keeps them; DELETE removes the bindings', async () => { + const { body } = await createBackend(); + const stored = stateIac.fixture.backends.rows[0].credentials; + const patched = await call(item.PATCH, { + user: 'admin', + params: { id: body.id }, + body: { name: 's3-renamed' }, + }); + expect(patched.status).toBe(200); + expect(stateIac.fixture.backends.rows[0]).toMatchObject({ + name: 's3-renamed', + credentials: stored, + }); + + stateIac.fixture.projects.set('p1', { id: 'p1', organizationId: 'org-1' }); + await call(bindingRoute.PUT, { + user: 'admin', + params: { id: body.id, pulumiProject: 'network' }, + body: { projectId: 'p1' }, + }); + expect(stateIac.fixture.bindings.rows).toHaveLength(1); + expect((await call(item.DELETE, { user: 'admin', params: { id: body.id } })).status).toBe(200); + expect(stateIac.fixture.bindings.rows).toHaveLength(0); + }); + + it('lists discovered Pulumi projects with their assignment, and assigns them', async () => { + const { body } = await createBackend(); + stateIac.fixture.buckets.set('acme-state', fixtureStore('project-layout')); + + const put = await call(bindingRoute.PUT, { + user: 'admin', + params: { id: body.id, pulumiProject: 'acme-infra' }, + body: { projectId: 'p1', stacks: ['prod'] }, + }); + expect(put.status).toBe(200); + // a binding left over from a project that is no longer in the bucket + await call(bindingRoute.PUT, { + user: 'admin', + params: { id: body.id, pulumiProject: 'gone' }, + body: { projectId: 'p2' }, + }); + + const listed = await call(projectsRoute.GET, { user: 'reader', params: { id: body.id } }); + expect(listed.status).toBe(200); + expect(await listed.json()).toEqual({ + ok: true, + layout: 'project', + metaVersion: 1, + truncated: false, + projects: [ + { + name: 'acme-infra', + stacks: ['prod', 'staging'], + binding: { projectId: 'p1', stacks: ['prod'] }, + }, + { name: 'acme-platform', stacks: ['dev'], binding: null }, + ], + missing: [{ pulumiProject: 'gone', projectId: 'p2', stacks: [] }], + }); + + const removed = await call(bindingRoute.DELETE, { + user: 'admin', + params: { id: body.id, pulumiProject: 'acme-infra' }, + }); + expect(await removed.json()).toEqual({ pulumiProject: 'acme-infra', removed: true }); + }); + + it('a project of another organization cannot be assigned', async () => { + const { body } = await createBackend(); + const response = await call(bindingRoute.PUT, { + user: 'admin', + params: { id: body.id, pulumiProject: 'network' }, + body: { projectId: 'other-org-project' }, + }); + expect(response.status).toBe(400); + expect((await response.json()).errors).toEqual({ projectId: 'project_not_found' }); + }); + + it('reports a bucket that cannot be read without leaking the provider message', async () => { + const { body } = await createBackend(); + const store = fixtureStore('project-layout'); + store.failWith = Object.assign( + new Error('User arn:aws:iam::123456789012:user/x is not authorized'), + { + name: 'AccessDenied', + $metadata: { httpStatusCode: 403 }, + }, + ); + stateIac.fixture.buckets.set('acme-state', store); + const response = await call(testRoute.POST, { user: 'admin', params: { id: body.id } }); + const text = await response.text(); + expect(JSON.parse(text)).toEqual({ ok: false, error: 'access_denied' }); + expect(text).not.toContain('123456789012'); + }); +}); diff --git a/src/routes/org/[org]/settings/events/event-view.ts b/src/routes/org/[org]/settings/events/event-view.ts index d1d7cdf9..b1dd07e0 100644 --- a/src/routes/org/[org]/settings/events/event-view.ts +++ b/src/routes/org/[org]/settings/events/event-view.ts @@ -13,6 +13,7 @@ export const EVENT_MODULES: readonly EventModule[] = [ 'projects', 'organization', 'access', + 'state_iac', ]; export type EventStatusFilter = 'all' | 'pending' | 'acked'; diff --git a/src/routes/org/[org]/settings/state-iac/+page.server.ts b/src/routes/org/[org]/settings/state-iac/+page.server.ts new file mode 100644 index 00000000..09e0df51 --- /dev/null +++ b/src/routes/org/[org]/settings/state-iac/+page.server.ts @@ -0,0 +1,150 @@ +import { error, fail } from '@sveltejs/kit'; +import { organizationService } from '#modules/organization'; +import { projectService } from '#modules/projects'; +import { + backendInputFrom, + canManageBackends, + createBackend, + deleteBackend, + getBackend, + listBackends, + testBackend, + updateBackend, +} from '#lib/server/state-iac/backends'; + +export async function load({ parent, locals }) { + const { organization } = await parent(); + const listed = await listBackends(locals, organization.id); + if (!listed.ok) throw error(listed.status, listed.error); + + const [canCreate, canUpdate, canDelete, canTest, projects] = await Promise.all([ + canManageBackends(locals, organization.id, 'create'), + canManageBackends(locals, organization.id, 'update'), + canManageBackends(locals, organization.id, 'delete'), + canManageBackends(locals, organization.id, 'test'), + projectService.listProjectsByOrganization(organization.id), + ]); + + return { + organizationId: organization.id as string, + backends: listed.data.backends, + // only what the assignment selector needs + projects: projects + .map((project: { id: string; name: string; slug?: string | null }) => ({ + id: project.id, + name: project.name, + slug: project.slug ?? '', + })) + .sort((a: { name: string }, b: { name: string }) => a.name.localeCompare(b.name)), + canCreate, + canUpdate, + canDelete, + canTest, + }; +} + +async function organizationOf(slug: string) { + const organization = await organizationService.tryFindBySlug(slug); + if (!organization) throw error(404, 'Organization not found'); + return organization; +} + +/** Form fields → backend input; empty credential fields keep the stored ones. */ +function formInput(form: FormData) { + const value = (key: string) => { + const raw = form.get(key); + return raw === null ? undefined : String(raw); + }; + return backendInputFrom({ + name: value('name'), + provider: value('provider'), + bucket: value('bucket'), + prefix: value('prefix') ?? '', + region: value('region') ?? '', + endpoint: value('endpoint') ?? '', + forcePathStyle: form.get('forcePathStyle') === 'on' || form.get('forcePathStyle') === 'true', + auth: value('auth'), + serviceAccountJson: value('serviceAccountJson'), + accessKeyId: value('accessKeyId'), + secretAccessKey: value('secretAccessKey'), + sessionToken: value('sessionToken'), + }); +} + +/** What the form gets back on a failure: never the credentials, they are typed again. */ +function draftOf(form: FormData) { + const draft: Record = {}; + for (const key of ['name', 'provider', 'bucket', 'prefix', 'region', 'endpoint', 'auth']) { + draft[key] = String(form.get(key) ?? ''); + } + return draft; +} + +export const actions = { + async createBackend({ request, locals, params }) { + const organization = await organizationOf(params.org); + const form = await request.formData(); + const result = await createBackend(locals, organization.id, formInput(form)); + if (!result.ok) { + return fail(result.status, { + backendForm: 'create', + draft: draftOf(form), + error: result.error, + errors: result.errors ?? {}, + }); + } + return { saved: result.data.id, created: true }; + }, + + async updateBackend({ request, locals, params }) { + await organizationOf(params.org); + const form = await request.formData(); + const id = String(form.get('backendId') ?? ''); + const input = formInput(form); + // the provider can't change and is not posted by the edit form + delete input.provider; + const result = await updateBackend(locals, id, input); + if (!result.ok) { + return fail(result.status, { + backendForm: id, + draft: draftOf(form), + error: result.error, + errors: result.errors ?? {}, + }); + } + return { saved: id }; + }, + + async toggleBackend({ request, locals, params }) { + await organizationOf(params.org); + const form = await request.formData(); + const id = String(form.get('backendId') ?? ''); + const result = await updateBackend(locals, id, { enabled: form.get('enabled') === 'true' }); + if (!result.ok) return fail(result.status, { backendForm: id, error: result.error }); + return { saved: id }; + }, + + async deleteBackend({ request, locals, params }) { + await organizationOf(params.org); + const form = await request.formData(); + const id = String(form.get('backendId') ?? ''); + // deleting a backend asks to type its name: checked here too, not only in the browser + const current = await getBackend(locals, id); + if (!current.ok) return fail(current.status, { backendForm: id, error: current.error }); + if (String(form.get('confirmName') ?? '') !== current.data.name) { + return fail(400, { backendForm: id, error: 'confirm_name' }); + } + const result = await deleteBackend(locals, id); + if (!result.ok) return fail(result.status, { backendForm: id, error: result.error }); + return { deleted: id }; + }, + + async testBackend({ request, locals, params }) { + await organizationOf(params.org); + const form = await request.formData(); + const id = String(form.get('backendId') ?? ''); + const result = await testBackend(locals, id); + if (!result.ok) return fail(result.status, { backendForm: id, error: result.error }); + return { test: { backendId: id, ...result.data } }; + }, +}; diff --git a/src/routes/org/[org]/settings/state-iac/+page.svelte b/src/routes/org/[org]/settings/state-iac/+page.svelte new file mode 100644 index 00000000..83c9d70b --- /dev/null +++ b/src/routes/org/[org]/settings/state-iac/+page.svelte @@ -0,0 +1,355 @@ + + + + {$_('stateIac.settings.title')} · GitOps + + +
+
+
+

{$_('stateIac.settings.title')}

+

{$_('stateIac.settings.description')}

+
+ {#if data.canCreate} + + {/if} +
+ + {#if data.backends.length === 0} +
+ +

{$_('stateIac.backends.emptyTitle')}

+

{$_('stateIac.backends.emptyDescription')}

+
+ {:else} +
    + {#each data.backends as backend (backend.id)} +
  • +
    + +
    +

    + {backend.name} + {$_(`stateIac.providers.${backend.provider}`)} + {$_(`stateIac.auth.${backend.auth}`)} + {#if !backend.enabled} + {$_('stateIac.backends.disabled')} + {/if} +

    +

    {location(backend)}

    + {#if backend.endpoint} +

    {backend.endpoint}

    + {/if} + {#if backend.lastError} +

    + {$_('stateIac.backends.lastError', { + values: { error: errorMessage(backend.lastError) }, + })} +

    + {/if} +
    + +
    + {#if data.canTest} +
    + + +
    + {/if} + {#if data.canUpdate} +
    + + + +
    + + {/if} + {#if data.canDelete} +
    + + +
    + {/if} +
    +
    + +
    + + {#if expanded[backend.id]} +
    + +
    + {/if} +
    +
  • + {/each} +
+ {/if} +
+ +{#if data.canCreate || data.canUpdate} + +{/if} + +{#if data.canDelete} + + {#snippet icon()} + + {/snippet} + {#if deleteTarget} +
+ + + {#snippet children(control)} + + {/snippet} + +
+ {/if} + {#snippet footer()} + + + {/snippet} +
+{/if} diff --git a/src/routes/org/[org]/settings/state-iac/BackendFormModal.svelte b/src/routes/org/[org]/settings/state-iac/BackendFormModal.svelte new file mode 100644 index 00000000..8260fa39 --- /dev/null +++ b/src/routes/org/[org]/settings/state-iac/BackendFormModal.svelte @@ -0,0 +1,286 @@ + + + + +
+ {#if backend}{/if} + + + {#snippet children(control)} + + {/snippet} + + + + {#snippet children(control)} + + {/snippet} + + + + {#snippet children(control)} + + {/snippet} + + + + {#snippet children(control)} + + {/snippet} + + + {#if provider === 's3'} + + {#snippet children(control)} + + {/snippet} + + + {#snippet children(control)} + + {/snippet} + + + {/if} + +
+ {$_('stateIac.backends.fields.auth')} + + +
+ + {#if auth === 'credentials'} + {#if backend?.hasCredentials} +

+ {$_('stateIac.backends.credentialsKept')} +

+ {/if} + {#if provider === 'gcs'} +
+ + {#snippet children(control)} + + {/snippet} + +
+ {:else} + + {#snippet children(control)} + + {/snippet} + + + {#snippet children(control)} + + {/snippet} + +
+ + {#snippet children(control)} + + {/snippet} + +
+ {/if} + {/if} + +

{$_('stateIac.backends.readOnlyNotice')}

+
+ + {#snippet footer()} + + + {/snippet} +
diff --git a/src/routes/org/[org]/settings/state-iac/BackendProjects.svelte b/src/routes/org/[org]/settings/state-iac/BackendProjects.svelte new file mode 100644 index 00000000..4cf62175 --- /dev/null +++ b/src/routes/org/[org]/settings/state-iac/BackendProjects.svelte @@ -0,0 +1,210 @@ + + + +
+
+

{$_('stateIac.projects.title')}

+ +
+ + {#if !result && loading} +

{$_('stateIac.projects.loading')}

+ {:else if result} + {#if !result.ok} + + {:else if result.projects.length === 0} +

+ {$_('stateIac.projects.empty')} +

+ {:else} + {#if result.layout === 'legacy'} +

{$_('stateIac.projects.legacyNotice')}

+ {/if} +
+ + + + + + + + + + {#each result.projects as project (project.name ?? '__unknown__')} + + + + + + {/each} + +
{$_('stateIac.projects.pulumiProject')}{$_('stateIac.projects.stacks')}{$_('stateIac.projects.gitopsProject')}
+ {project.name ?? $_('stateIac.projects.unknownProject')} + + + {#each project.stacks as stack (stack)} + {stack} + {/each} + + + {#if project.name === null} + {$_('stateIac.projects.unknownHelp')} + {:else if canUpdate} + {@const pulumiProject = project.name} + + {#if saving === pulumiProject}{/if} + {:else} + + {project.binding + ? projectName(project.binding.projectId) + : $_('stateIac.projects.unassignedOption')} + + {/if} + {#if project.binding && project.binding.stacks.length > 0} + + {$_('stateIac.projects.onlyStacks', { + values: { stacks: project.binding.stacks.join(', ') }, + })} + + {/if} +
+
+ {#if result.truncated} +

{$_('stateIac.projects.truncated')}

+ {/if} + {/if} + + {#if result.missing.length > 0} +
+

{$_('stateIac.projects.missingTitle')}

+
    + {#each result.missing as binding (binding.pulumiProject)} +
  • + {binding.pulumiProject} + → {projectName(binding.projectId)} + {#if canUpdate} + + {/if} +
  • + {/each} +
+
+ {/if} + {/if} +
diff --git a/src/routes/org/[org]/settings/state-iac/types.ts b/src/routes/org/[org]/settings/state-iac/types.ts new file mode 100644 index 00000000..4bf5864c --- /dev/null +++ b/src/routes/org/[org]/settings/state-iac/types.ts @@ -0,0 +1,41 @@ +/** Shapes the State IaC settings page receives (client-safe: no credentials). */ +export type BackendView = { + id: string; + organizationId: string; + name: string; + engine: 'pulumi'; + provider: 'gcs' | 's3'; + bucket: string; + prefix: string | null; + region: string | null; + endpoint: string | null; + forcePathStyle: boolean; + auth: 'ambient' | 'credentials'; + hasCredentials: boolean; + enabled: boolean; + lastScanAt: string | null; + lastError: string | null; + createdAt: string; + updatedAt: string; +}; + +export type ProjectOption = { id: string; name: string; slug: string }; + +export type DiscoveredProject = { + name: string | null; + stacks: string[]; + binding: { projectId: string; stacks: string[] } | null; +}; + +export type MissingBinding = { pulumiProject: string; projectId: string; stacks: string[] }; + +export type BackendProjectsResponse = + | { + ok: true; + layout: 'project' | 'legacy' | 'empty'; + metaVersion: number | null; + truncated: boolean; + projects: DiscoveredProject[]; + missing: MissingBinding[]; + } + | { ok: false; error: string; projects: []; missing: MissingBinding[] }; diff --git a/src/routes/org/[org]/settings/storage/+page.server.ts b/src/routes/org/[org]/settings/storage/+page.server.ts deleted file mode 100644 index 0a44aac7..00000000 --- a/src/routes/org/[org]/settings/storage/+page.server.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { redirect } from '@sveltejs/kit'; - -export function load() { - throw redirect(302, '/pulumi-state/backends'); -} From 5def6d5e57595534cd910e650c34e3e5ff89d46a Mon Sep 17 00:00:00 2001 From: Carlos Lopez Date: Wed, 25 Nov 2026 19:42:14 +0100 Subject: [PATCH 2/2] Feat: allow enabling the State IaC module in project settings (#106) The project service no longer forces `modules.stateiac` to false and the settings switch is no longer "coming soon". It stays off by default. Co-Authored-By: Claude Opus 5.5 --- e2e/specs/project-settings.spec.ts | 31 ++++++++++++++----- e2e/specs/sidebar-visibility.spec.ts | 15 +++------ .../application/project.service.test.ts | 8 ++--- .../projects/application/project.service.ts | 2 +- .../[slug]/settings/overview/+page.svelte | 4 +-- 5 files changed, 34 insertions(+), 26 deletions(-) diff --git a/e2e/specs/project-settings.spec.ts b/e2e/specs/project-settings.spec.ts index aa514086..1b8d8a38 100644 --- a/e2e/specs/project-settings.spec.ts +++ b/e2e/specs/project-settings.spec.ts @@ -81,10 +81,7 @@ test.describe('server access keys — real revoke mutation', () => { // client-side hydration, which is unrelated to what this test cares about — whether the // server actually revokes the key for a role with delete permission, not whether the click // wiring works. - test('a role with delete permission can actually revoke a key', async ({ - page, - loginAs, - }) => { + test('a role with delete permission can actually revoke a key', async ({ page, loginAs }) => { await loginAs('projectAdmin'); await page.goto(`${base}/settings/server-access-keys`); const before = await page.getByRole('button', { name: /revocar/i }).count(); @@ -145,10 +142,7 @@ test.describe('project users — role-change control (canUpdate)', () => { }); test.describe('project roles — real create mutation', () => { - test('project admin can create a role and see it in the list', async ({ - page, - loginAs, - }) => { + test('project admin can create a role and see it in the list', async ({ page, loginAs }) => { await loginAs('projectAdmin'); const response = await page.request.post(`${base}/settings/roles-permissions/new?/createRole`, { form: { @@ -183,3 +177,24 @@ test.describe('project roles — real create mutation', () => { expect(body.status).toBe(403); }); }); + +test.describe('project settings — State IaC module', () => { + test('a project admin can turn the State IaC module off and on', async ({ page, loginAs }) => { + await loginAs('projectAdmin'); + await page.goto(`${base}/settings/overview`); + await page.waitForLoadState('networkidle'); + const toggle = page.getByRole('switch', { name: 'State IaC' }); + const sidebar = page.locator('aside').first(); + const save = page.getByRole('button', { name: 'Guardar cambios' }); + + await expect(toggle).toBeEnabled(); + await expect(toggle).toBeChecked(); + await toggle.click(); + await save.click(); + await expect(sidebar.locator(`a[href^="${base}/state-iac"]`)).toHaveCount(0); + + await toggle.click(); + await save.click(); + await expect(sidebar.locator(`a[href^="${base}/state-iac"]`).first()).toBeVisible(); + }); +}); diff --git a/e2e/specs/sidebar-visibility.spec.ts b/e2e/specs/sidebar-visibility.spec.ts index 13a070b0..44e347ad 100644 --- a/e2e/specs/sidebar-visibility.spec.ts +++ b/e2e/specs/sidebar-visibility.spec.ts @@ -5,10 +5,7 @@ const seed = getSeed(); const org = seed.primaryOrgSlug; const project = seed.primaryProjectSlug; -test('org developer only has a link into "Proyectos", nothing else', async ({ - page, - loginAs, -}) => { +test('org developer only has a link into "Proyectos", nothing else', async ({ page, loginAs }) => { await loginAs('orgDeveloper'); await page.goto(`/org/${org}/settings/projects`); const sidebar = page.locator('aside').first(); @@ -20,10 +17,7 @@ test('org developer only has a link into "Proyectos", nothing else', async ({ await expect(page.locator('#section-nav')).toHaveCount(0); }); -test('org admin has links into every organization settings resource', async ({ - page, - loginAs, -}) => { +test('org admin has links into every organization settings resource', async ({ page, loginAs }) => { await loginAs('orgAdmin'); await page.goto(`/org/${org}/settings/projects`); // el sidebar enlaza el módulo; cada recurso está en las pestañas de sección @@ -60,8 +54,7 @@ test('project admin has a sidebar link into Code Report', async ({ page, loginAs const sidebar = page.locator('aside').first(); const base = `/org/${org}/projects/${project}`; await expect(sidebar.getByText('Code Report', { exact: true })).toBeVisible(); - // Vault is enabled for the seeded project, so the admin gets it too. State IaC is "coming soon": - // the service forces it off, so it never reaches the sidebar regardless of permissions. + // Vault and State IaC are enabled for the seeded project, so the admin gets them too await expect(sidebar.locator(`a[href="${base}/vault"]`)).toBeVisible(); - await expect(sidebar.locator(`a[href^="${base}/state-iac"]`)).toHaveCount(0); + await expect(sidebar.locator(`a[href^="${base}/state-iac"]`).first()).toBeVisible(); }); diff --git a/src/modules/projects/application/project.service.test.ts b/src/modules/projects/application/project.service.test.ts index d111a7f5..276c841f 100644 --- a/src/modules/projects/application/project.service.test.ts +++ b/src/modules/projects/application/project.service.test.ts @@ -182,7 +182,7 @@ describe('ProjectService', () => { }); }); - it('keeps only unavailable modules disabled while accepting available module overrides', async () => { + it('accepts module overrides, State IaC included', async () => { const project = await createProject({ name: 'Project D', modules: { vault: true, codereport: false, stateiac: true }, @@ -190,7 +190,7 @@ describe('ProjectService', () => { expect(project.modules).toEqual({ vault: true, codereport: false, - stateiac: false, + stateiac: true, monitoring: false, }); }); @@ -246,7 +246,7 @@ describe('ProjectService', () => { expect(updated.modules).toEqual({ vault: true, codereport: true, - stateiac: false, + stateiac: true, monitoring: false, }); @@ -256,7 +256,7 @@ describe('ProjectService', () => { expect(updatedAgain.modules).toEqual({ vault: true, codereport: false, - stateiac: false, + stateiac: true, monitoring: false, }); }); diff --git a/src/modules/projects/application/project.service.ts b/src/modules/projects/application/project.service.ts index cae26654..ec8478fb 100644 --- a/src/modules/projects/application/project.service.ts +++ b/src/modules/projects/application/project.service.ts @@ -269,7 +269,7 @@ export class ProjectService { return { vault: modules?.vault ?? DEFAULT_PROJECT_MODULES.vault, codereport: modules?.codereport ?? DEFAULT_PROJECT_MODULES.codereport, - stateiac: false, + stateiac: modules?.stateiac ?? DEFAULT_PROJECT_MODULES.stateiac, monitoring: modules?.monitoring ?? DEFAULT_PROJECT_MODULES.monitoring, }; } diff --git a/src/routes/org/[org]/projects/[slug]/settings/overview/+page.svelte b/src/routes/org/[org]/projects/[slug]/settings/overview/+page.svelte index dead24b3..4fd3dd3c 100644 --- a/src/routes/org/[org]/projects/[slug]/settings/overview/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/settings/overview/+page.svelte @@ -70,6 +70,7 @@ editDescription !== (project.description ?? '') || Boolean(editModules.vault) !== Boolean(project.modules.vault) || Boolean(editModules.codereport) !== Boolean(project.modules.codereport) || + Boolean(editModules.stateiac) !== Boolean(project.modules.stateiac) || Boolean(editModules.monitoring) !== Boolean(project.modules.monitoring), ); @@ -118,7 +119,6 @@ description: $_('projectSettings.overview.moduleStateIac'), icon: GitBranch, href: `${projectBase}/state-iac`, - soon: true, }, ]); @@ -217,7 +217,7 @@ - +