diff --git a/.env.example b/.env.example index 05d93c1c..fe846c23 100644 --- a/.env.example +++ b/.env.example @@ -111,3 +111,13 @@ GITDB_ENCRYPTION_KEY="development" # MONITORING_HOURLY_RETENTION_DAYS=30 # Closed incidents older than this are deleted (default 365) # MONITORING_INCIDENT_RETENTION_DAYS=365 + +# --- State IaC (docs/adr/0003-state-iac.md) --------------------------------------------------- +# Backends (buckets) are configured per organization at /org//settings/state-iac; their +# credentials live encrypted in GitDB (GITDB_ENCRYPTION_KEY), not here. Ambient auth uses the +# server's ADC / Workload Identity (GCS) or AWS credential chain (S3). +# Largest state file read, decompressed, in MB (default 50, max 500). Bigger ones fail cleanly. +# STATE_IAC_MAX_STATE_MB=50 +# How long stack listings and states stay cached in memory, in seconds (default 60). Unchanged +# states are reused after that too: the cache is keyed by the object's ETag / generation. +# STATE_IAC_CACHE_SECONDS=60 diff --git a/CLAUDE.md b/CLAUDE.md index e6ca754e..5ccfb4af 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -209,6 +209,17 @@ and `/api/state-iac/backends/**` check `organization:stateiac:backends:` `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. +Reading states: `stateIacService` uses a `StateEngine` (`PulumiStateEngine`: both layouts, `.gz`) +that turns checkpoints and history into the normalized model in `domain/iac.model.ts`; secrets are +replaced by `{ $iac: 'secret' }` while parsing (`pulumi-state.ts`), and `secrets_providers`, emails +and local paths never leave it. A project sees only the stacks its bindings cover (any other stack +is a 404) with `project:stateiac:stacks:read`, and resources/outputs need `project:stateiac:states:read`; +`/org//state-iac` shows every stack with `organization:stateiac:stacks:read`. Listings are cached +for `STATE_IAC_CACHE_SECONDS` and states by object version, so an unchanged state is read once; +`?refresh=1` skips the cache. States over `STATE_IAC_MAX_STATE_MB` fail with `too_large`. In e2e the +dev server reads the fixtures through a local S3 endpoint (`e2e/fixtures/fake-s3.ts`, seeded backend +`e2e-shared-state`: `acme-infra` → primary project, `acme-platform` → secondary project). + ## Domain events Services announce what happened on an in-process event bus in `#lib/server/events`; the design is diff --git a/e2e/fixtures/fake-s3.ts b/e2e/fixtures/fake-s3.ts new file mode 100644 index 00000000..eed6ed0f --- /dev/null +++ b/e2e/fixtures/fake-s3.ts @@ -0,0 +1,95 @@ +import { createServer, type Server } from 'node:http'; +import { InMemoryObjectStore } from '../../src/modules/state-iac/infrastructure/object-store/in-memory-object-store'; + +/** + * A read-only, path-style S3 endpoint over a local folder: enough of ListObjectsV2, GetObject and + * HeadObject for the AWS SDK used by `S3ObjectStore`. The e2e dev server reads the State IaC + * fixtures through it, so the whole read path (SDK, streaming, gunzip) is exercised. Requests are + * not authenticated. + */ +export const FAKE_S3_BUCKET = 'e2e-state'; + +const xml = (value: string) => + value.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); + +function notFound(code: 'NoSuchKey' | 'NoSuchBucket') { + return `${code}${code}`; +} + +export function startFakeS3(directory: string, port: number): Promise { + const store = InMemoryObjectStore.fromDirectory(directory); + const server = createServer(async (request, response) => { + try { + const url = new URL(request.url ?? '/', `http://localhost:${port}`); + const [, bucket, ...rest] = url.pathname.split('/'); + const key = decodeURIComponent(rest.join('/')); + if (decodeURIComponent(bucket ?? '') !== FAKE_S3_BUCKET) { + response + .writeHead(404, { 'content-type': 'application/xml' }) + .end(notFound('NoSuchBucket')); + return; + } + + if (!key && request.method === 'GET') { + const prefix = url.searchParams.get('prefix') ?? ''; + const delimiter = url.searchParams.get('delimiter') === '/' ? '/' : undefined; + const maxKeys = Number(url.searchParams.get('max-keys') ?? 1000) || 1000; + const token = url.searchParams.get('continuation-token') ?? undefined; + const page = await store.list(prefix, { delimiter, maxKeys, pageToken: token }); + const body = [ + '', + '', + `${FAKE_S3_BUCKET}${xml(prefix)}`, + `${page.objects.length + page.prefixes.length}${maxKeys}`, + delimiter ? `${delimiter}` : '', + `${page.nextPageToken ? 'true' : 'false'}`, + page.nextPageToken + ? `${xml(page.nextPageToken)}` + : '', + ...page.objects.map( + (object) => + `${xml(object.key)}${object.updatedAt}"${object.version}"${object.size}STANDARD`, + ), + ...page.prefixes.map( + (p) => `${xml(p)}`, + ), + '', + ].join(''); + response.writeHead(200, { 'content-type': 'application/xml' }).end(body); + return; + } + + const info = await store.head(key); + if (!info) { + response + .writeHead(404, { 'content-type': 'application/xml' }) + .end(request.method === 'HEAD' ? undefined : notFound('NoSuchKey')); + return; + } + const headers = { + 'content-length': String(info.size), + etag: `"${info.version}"`, + 'last-modified': new Date(info.updatedAt ?? Date.now()).toUTCString(), + 'content-type': 'application/octet-stream', + }; + if (request.method === 'HEAD') { + response.writeHead(200, headers).end(); + return; + } + // raw bytes (gzip included): the client decompresses + const body = await readRaw(store, key); + response.writeHead(200, headers).end(body); + } catch (error) { + response.writeHead(500).end(String(error)); + } + }); + return new Promise((resolve) => server.listen(port, '127.0.0.1', () => resolve(server))); +} + +async function readRaw(store: InMemoryObjectStore, key: string): Promise { + const stream = await store.openRead(key); + if (!stream) return Buffer.alloc(0); + const chunks: Buffer[] = []; + for await (const chunk of stream) chunks.push(chunk as Buffer); + return Buffer.concat(chunks); +} diff --git a/e2e/fixtures/seed.ts b/e2e/fixtures/seed.ts index 07b7bc5f..7359ed56 100644 --- a/e2e/fixtures/seed.ts +++ b/e2e/fixtures/seed.ts @@ -3,6 +3,10 @@ import { organizationService } from '#modules/organization'; import { projectService } from '#modules/projects'; import { codeReportService } from '#modules/code-report'; import { NotificationSettingsRepository } from '#modules/notifications/infrastructure/repositories/notification-settings.repository'; +import { StateBackendRepository } from '#modules/state-iac/infrastructure/repositories/state-backend.repository'; +import { StateBindingRepository } from '#modules/state-iac/infrastructure/repositories/state-binding.repository'; +import { FAKE_S3_BUCKET } from './fake-s3'; +import { E2E_S3_ENDPOINT } from '../global-setup'; export const E2E_PASSWORD = 'E2ePassword!123'; @@ -37,6 +41,11 @@ export type SeedOutput = { primaryOrgSlug: string; primaryOrgId: string; primaryProjectSlug: string; + primaryProjectId: string; + projectViewerRoleId: string; + /** Second project of the primary org: shares the State IaC bucket with the primary one. */ + secondaryProjectSlug: string; + stateBackendId: string; outsiderOrgSlug: string; outsiderProjectSlug: string; seededServiceSlug: string; @@ -294,6 +303,52 @@ export async function seedAll(): Promise { stateiacStacksOnlyRole.id, ); + // --- State IaC: one bucket (the fake S3 over test/fixtures/state-iac), two projects ---------- + const secondaryProject = await projectService.createProject({ + organizationId: primaryOrg.id, + name: 'E2E Secondary Project', + slug: 'e2e-project-b', + modules: { vault: false, codereport: false, stateiac: true, monitoring: false }, + }); + const now = new Date().toISOString(); + const stateBackendId = crypto.randomUUID(); + // written directly: the API refuses loopback endpoints on purpose (anti-SSRF) + await new StateBackendRepository().create({ + id: stateBackendId, + organizationId: primaryOrg.id, + name: 'e2e-shared-state', + engine: 'pulumi', + provider: 's3', + bucket: FAKE_S3_BUCKET, + prefix: null, + region: 'us-east-1', + endpoint: E2E_S3_ENDPOINT, + forcePathStyle: true, + auth: 'ambient', + credentials: null, + enabled: true, + lastScanAt: null, + lastError: null, + createdAt: now, + updatedAt: now, + }); + const bindings = new StateBindingRepository(); + for (const [pulumiProject, projectId] of [ + ['acme-infra', primaryProject.id], + ['acme-platform', secondaryProject.id], + ] as const) { + await bindings.create({ + id: crypto.randomUUID(), + organizationId: primaryOrg.id, + backendId: stateBackendId, + pulumiProject, + stacks: [], + projectId, + createdAt: now, + updatedAt: now, + }); + } + const seededService = await codeReportService.createService({ project: requireSeedSlug(primaryProject.slug, 'primary project'), name: 'E2E Seeded Service', @@ -416,6 +471,10 @@ export async function seedAll(): Promise { primaryOrgSlug: primaryOrg.slug, primaryOrgId: primaryOrg.id, primaryProjectSlug: requireSeedSlug(primaryProject.slug, 'primary project'), + primaryProjectId: primaryProject.id, + projectViewerRoleId, + secondaryProjectSlug: requireSeedSlug(secondaryProject.slug, 'secondary project'), + stateBackendId, outsiderOrgSlug: requireSeedSlug(outsiderOrg.slug, 'outsider organization'), outsiderProjectSlug: requireSeedSlug(outsiderProject.slug, 'outsider project'), seededServiceSlug: seededService.slug, diff --git a/e2e/global-setup.ts b/e2e/global-setup.ts index 81464eef..84b624cc 100644 --- a/e2e/global-setup.ts +++ b/e2e/global-setup.ts @@ -15,6 +15,9 @@ export const E2E_PORT = 5390; export const E2E_BASE_URL = `http://localhost:${E2E_PORT}`; export const E2E_ENCRYPTION_KEY = 'e2e-test-encryption-key-do-not-use-in-prod'; export const E2E_MONITORING_WORKER_TOKEN = 'e2e-monitoring-worker-token'; +/** Local S3-compatible endpoint serving the State IaC fixtures (`fixtures/fake-s3.ts`). */ +export const E2E_S3_PORT = 5391; +export const E2E_S3_ENDPOINT = `http://127.0.0.1:${E2E_S3_PORT}`; const ROOT = path.resolve(__dirname, '..'); // deliberately OUTSIDE the repo (not e2e/.tmp): a throwaway git repo nested inside this repo's @@ -34,7 +37,16 @@ function initThrowawayRemote() { const git = (args: string[]) => execFileSync('git', args, { cwd: REMOTE_DIR, stdio: 'ignore' }); git(['init', '-b', 'main']); - git(['-c', 'user.email=e2e@gitops.local', '-c', 'user.name=e2e', 'commit', '--allow-empty', '-m', 'init']); + git([ + '-c', + 'user.email=e2e@gitops.local', + '-c', + 'user.name=e2e', + 'commit', + '--allow-empty', + '-m', + 'init', + ]); } function buildEnv(): Record { @@ -66,6 +78,10 @@ function buildEnv(): Record { MONITORING_INTERNAL_HOSTS: '', MONITORING_EMBEDDED_WORKER: 'true', MONITORING_ALLOW_PRIVATE_TARGETS: 'true', + // State IaC reads the fake S3 bucket with "ambient" auth: dummy static credentials + AWS_ACCESS_KEY_ID: 'e2e', + AWS_SECRET_ACCESS_KEY: 'e2e', + AWS_EC2_METADATA_DISABLED: 'true', PORT: String(E2E_PORT), }; } @@ -99,6 +115,12 @@ export default async function globalSetup() { const { startGitDb } = await import('../src/lib/server/gitdb'); await startGitDb(); + const { startFakeS3 } = await import('./fixtures/fake-s3'); + const fakeS3 = await startFakeS3( + path.join(ROOT, 'test/fixtures/state-iac/project-layout'), + E2E_S3_PORT, + ); + const { seedAll } = await import('./fixtures/seed'); const seedOutput = await seedAll(); writeFileSync(SEED_OUTPUT_PATH, JSON.stringify(seedOutput, null, 2)); @@ -142,5 +164,6 @@ export default async function globalSetup() { if (!server.killed) { server.kill(); } + fakeS3.close(); }; } diff --git a/e2e/specs/state-iac-backends.spec.ts b/e2e/specs/state-iac-backends.spec.ts index 0e601a4d..28272e8e 100644 --- a/e2e/specs/state-iac-backends.spec.ts +++ b/e2e/specs/state-iac-backends.spec.ts @@ -44,7 +44,8 @@ test.describe('state iac backends — org admin', () => { 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(); + // the seeded backend stays; only the one created here is gone + await expect(card).toHaveCount(0); }); test('the API never returns the credentials', async ({ page, loginAs }) => { diff --git a/e2e/specs/state-iac-stacks.spec.ts b/e2e/specs/state-iac-stacks.spec.ts new file mode 100644 index 00000000..7f38d0ab --- /dev/null +++ b/e2e/specs/state-iac-stacks.spec.ts @@ -0,0 +1,144 @@ +import { test, expect, getSeed } from '../fixtures/auth'; +import { expectAllowed, expectDenied } from '../fixtures/expect-access'; +import { E2E_BASE_URL } from '../global-setup'; + +// one bucket (the fake S3 over test/fixtures/state-iac/project-layout), two projects of the same +// organization: acme-infra → primary project, acme-platform → secondary project +const seed = getSeed(); +const org = seed.primaryOrgSlug; +const projectA = `/org/${org}/projects/${seed.primaryProjectSlug}/state-iac`; +const projectB = `/org/${org}/projects/${seed.secondaryProjectSlug}/state-iac`; +const backend = seed.stateBackendId; +const api = `${E2E_BASE_URL}/api/state-iac/stacks`; + +test.describe('state iac stacks — project view', () => { + test('a user of project A sees its stacks and not those of project B in the same bucket', async ({ + page, + loginAs, + }) => { + await loginAs('projectAdmin'); + await expectAllowed(page, projectA); + const list = page.getByTestId('stack-backend'); + await expect(list.getByRole('heading', { name: 'e2e-shared-state' })).toBeVisible(); + await expect(list.locator('tr[data-stack="acme-infra/prod"]')).toBeVisible(); + await expect(list.locator('tr[data-stack="acme-infra/staging"]')).toBeVisible(); + await expect(list.locator('tr[data-stack="acme-platform/dev"]')).toHaveCount(0); + // the lock fixture: an operation in progress on prod + await expect( + list.locator('tr[data-stack="acme-infra/prod"]').getByText('En curso'), + ).toBeVisible(); + + // B's stack through A's project, and B's project itself: not found / denied + const response = await page.goto(`${projectA}/${backend}/acme-platform/dev`); + expect(response?.status()).toBe(404); + await expectDenied(page, projectB); + }); + + test('the stack detail shows the resource tree, masked secrets and outputs', async ({ + page, + loginAs, + }) => { + await loginAs('projectAdmin'); + await expectAllowed(page, `${projectA}/${backend}/acme-infra/prod`); + await expect(page.getByRole('heading', { name: 'prod', level: 1 })).toBeVisible(); + // interactive only once hydrated + await page.waitForLoadState('networkidle'); + const tree = page.getByTestId('resource-tree'); + await expect(tree.getByRole('button', { name: /acme-infra-prod/ }).first()).toBeVisible(); + + // a Cloud SQL user: its password is a secret, never shown + await page.getByPlaceholder('Buscar recurso por nombre, tipo o ID').fill('user-api'); + await tree.getByRole('button', { name: /cloud-sql-acme-prod-user-api/ }).click(); + const drawer = page.getByRole('dialog', { name: 'cloud-sql-acme-prod-user-api' }); + await expect(drawer).toBeVisible(); + await expect(drawer.getByText('[secret]').first()).toBeVisible(); + await expect(drawer).not.toContainText('ciphertext'); + await page.keyboard.press('Escape'); + + await expect(drawer).toBeHidden(); + await page + .getByRole('tablist', { name: 'Contenido del stack' }) + .getByRole('tab', { name: /Outputs/ }) + .click(); + await expect(page.getByTestId('stack-outputs')).toContainText('acme-assets-prod'); + }); + + test('stacks:read alone lists the stacks but does not open their resources', async ({ + page, + loginAs, + }) => { + await loginAs('stateiacStacksOnly'); + await expectAllowed(page, projectA); + await expect(page.locator('tr[data-stack="acme-infra/prod"]')).toBeVisible(); + await expectAllowed(page, `${projectA}/${backend}/acme-infra/prod`); + await expect(page.getByTestId('states-forbidden')).toBeVisible(); + await expect(page.getByTestId('resource-tree')).toHaveCount(0); + }); +}); + +test.describe('state iac stacks — API scoping', () => { + test("a project API key only reaches its project's stacks", async ({ + page, + loginAs, + request, + }) => { + // its own viewer key: other specs revoke seeded keys + await loginAs('projectAdmin'); + const created = await page.request.post( + `/org/${org}/projects/${seed.primaryProjectSlug}/settings/server-access-keys?/create`, + { + form: { name: 'e2e-stateiac-reader', roleId: seed.projectViewerRoleId, expiresInDays: '' }, + }, + ); + const token = (await created.text()).match(/gvs_[A-Za-z0-9_-]+/)?.[0]; + expect(token, 'expected the created key in the action response').toBeTruthy(); + const headers = { Authorization: `Bearer ${token}` }; + const projectStacks = `${api}?projectId=${seed.primaryProjectId}`; + const listed = await request.get(projectStacks, { headers }); + expect(listed.status()).toBe(200); + const body = (await listed.json()) as { + backends: { stacks: { ref: { project: string } }[] }[]; + }; + const projects = body.backends.flatMap((b) => b.stacks.map((s) => s.ref.project)); + expect(projects).toContain('acme-infra'); + expect(projects).not.toContain('acme-platform'); + + const other = await request.get( + `${api}/${backend}/acme-platform/dev?projectId=${seed.primaryProjectId}`, + { headers }, + ); + expect(other.status()).toBe(404); + const orgListing = await request.get(`${api}?organizationId=${seed.primaryOrgId}`, { headers }); + expect(orgListing.status()).toBe(403); + + const detail = await request.get( + `${api}/${backend}/acme-infra/prod?projectId=${seed.primaryProjectId}&include=resources,outputs`, + { headers }, + ); + const text = await detail.text(); + expect(text).not.toMatch(/ciphertext|secrets_providers/); + }); +}); + +test.describe('state iac stacks — organization view', () => { + test('the organization sees every stack with its assigned project', async ({ page, loginAs }) => { + await loginAs('orgAdmin'); + await expectAllowed(page, `/org/${org}/state-iac`); + const staging = page.locator('tr[data-stack="acme-infra/staging"]'); + await expect(page.locator('tr[data-stack="acme-infra/prod"]')).toContainText( + 'E2E Primary Project', + ); + await expect(page.locator('tr[data-stack="acme-platform/dev"]')).toContainText( + 'E2E Secondary Project', + ); + await expect(staging).toBeVisible(); + }); + + test('without organization:stateiac:stacks:read the organization view is denied', async ({ + page, + loginAs, + }) => { + await loginAs('orgDeveloper'); + await expectDenied(page, `/org/${org}/state-iac`); + }); +}); diff --git a/src/env.ts b/src/env.ts index 8394cfaa..a6f23c92 100644 --- a/src/env.ts +++ b/src/env.ts @@ -40,6 +40,8 @@ export const variables = defineEnvVars({ MONITORING_EMBEDDED_WORKER_CONCURRENCY: optional, MONITORING_ALLOW_PRIVATE_TARGETS: optional, MONITORING_CHECK_LOGS: optional, + STATE_IAC_MAX_STATE_MB: optional, + STATE_IAC_CACHE_SECONDS: optional, MONITORING_FLUSH_SECONDS: optional, MONITORING_HOURLY_RETENTION_DAYS: optional, MONITORING_INCIDENT_RETENTION_DAYS: optional, diff --git a/src/lib/components/state-iac/IacValue.svelte b/src/lib/components/state-iac/IacValue.svelte new file mode 100644 index 00000000..cc867769 --- /dev/null +++ b/src/lib/components/state-iac/IacValue.svelte @@ -0,0 +1,71 @@ + + + +{#if value === null} + null +{:else if isSpecial(value)} + {#if value.$iac === 'secret'} + [secret] + {:else if value.$iac === 'resource-ref'} + + {:else if value.$iac === 'unknown'} + [unknown] + {:else} + [{value.$iac}] {value.summary} + {/if} +{:else if Array.isArray(value)} + {#if value.length === 0} + [] + {:else} +
    + {#each value as item, index (index)} +
  1. + {index} + +
  2. + {/each} +
+ {/if} +{:else if typeof value === 'object'} + {#if entries.length === 0} + {'{}'} + {:else} +
+ {#each entries as [key, item] (key)} +
+
{key}
+
+
+ {/each} +
+ {/if} +{:else if typeof value === 'string'} + {value} +{:else} + {String(value)} +{/if} diff --git a/src/lib/components/state-iac/StackDetail.svelte b/src/lib/components/state-iac/StackDetail.svelte new file mode 100644 index 00000000..d8635199 --- /dev/null +++ b/src/lib/components/state-iac/StackDetail.svelte @@ -0,0 +1,393 @@ + + + +
+
+
+ ← {$_('stateIac.detail.back')} +

+ {summary.ref.stack} + {#if summary.lock} + {$_('stateIac.stacks.locked')} + {/if} +

+

+ {summary.ref.project ?? $_('stateIac.projects.unknownProject')} + · {detail.backend.name} + {detail.backend.location} + {#if projectName}· {$_('stateIac.stacks.assignedTo', { + values: { project: projectName }, + })}{/if} +

+
+ +
+ +
+
+
{$_('stateIac.stacks.resources')}
+
{summary.resourceCount}
+
+
+
{$_('stateIac.stacks.lastUpdate')}
+
+ {#if summary.lastUpdate} + {$_(`stateIac.kinds.${summary.lastUpdate.kind}`)} · {$_( + `stateIac.results.${summary.lastUpdate.result}`, + )} + {date(summary.lastUpdate.endedAt)} + {:else} + {date(summary.updatedAt)} + {/if} +
+
+
+
{$_('stateIac.detail.toolVersion')}
+
{summary.toolVersion ?? '—'}
+
+
+
{$_('stateIac.detail.pendingOperations')}
+
+ {summary.pendingOperations} +
+
+
+ + {#if summary.error} + + {:else if !canReadStates} +

+ {$_('stateIac.detail.noStatesPermission')} +

+ {:else} + + + {#if tab === 'resources'} +
+ + + + +
+ +
    + {#each rows as { resource, depth } (resource.address)} + {@const hasChildren = !filtering && (children.get(resource.address)?.length ?? 0) > 0} +
  • + {#if hasChildren} + + {:else} + + {/if} + {#if resource.managed}{:else}{/if} + + {#if resource.flags.protect} + protect + {/if} + {#if resource.flags.pendingReplacement || resource.flags.pendingDelete} + {$_('stateIac.detail.pendingChange')} + {/if} +
  • + {:else} +
  • + {$_('stateIac.detail.noResources')} +
  • + {/each} +
+ {:else} +
+ {#if outputs.length === 0} +

{$_('stateIac.detail.noOutputs')}

+ {:else} +
+ {#each outputs as [name, value] (name)} +
+
{name}
+
+
+ {/each} +
+ {/if} +
+ {/if} + {/if} +
+ + + {#if selected} +
+
+
URN
+
{selected.address}
+
ID
+
{selected.externalId ?? '—'}
+
{$_('stateIac.detail.provider')}
+
{selected.provider?.split('::').at(-1) ?? '—'}
+ {#if selected.parent} +
{$_('stateIac.detail.parent')}
+
+ +
+ {/if} +
{$_('stateIac.detail.modified')}
+
{date(selected.modifiedAt)}
+
+ + +
+ {#if drawerTab === 'dependencies'} + {#if selected.dependencies.length === 0} +

—

+ {:else} +
    + {#each selected.dependencies as dependency (dependency)} +
  • + + {dependency.split('::').at(-2)} +
  • + {/each} +
+ {/if} + {:else} + + {/if} +
+
+ {/if} +
diff --git a/src/lib/components/state-iac/StackList.svelte b/src/lib/components/state-iac/StackList.svelte new file mode 100644 index 00000000..c961f5e9 --- /dev/null +++ b/src/lib/components/state-iac/StackList.svelte @@ -0,0 +1,220 @@ + + + +
+
+
+ + +
+ +
+ + {#each view as { group, projects } (group.backend.id)} +
+
+ +

{group.backend.name}

+ {group.backend.location} +
+ + {#if group.error} + + {:else if projects.length === 0} +

+ {query ? $_('stateIac.stacks.noMatches') : $_('stateIac.stacks.backendEmpty')} +

+ {:else} + {#each projects as [project, stacks] (project)} +
+

+ + {project || $_('stateIac.projects.unknownProject')} +

+
+ + + + + + + {#if projectNames} + + {/if} + + + + {#each stacks as stack (stack.ref.stack)} + + + + + {#if projectNames} + + {/if} + + {/each} + +
{$_('stateIac.stacks.stack')}{$_('stateIac.stacks.resources')}{$_('stateIac.stacks.lastUpdate')}{$_('stateIac.stacks.assignedProject')}
+ {stack.ref.stack} + + {#if stack.lock} + {$_('stateIac.stacks.locked')} + {/if} + {#if stack.pendingOperations > 0} + {$_('stateIac.stacks.pending', { + values: { count: stack.pendingOperations }, + })} + {/if} + {#if stack.error} + {errorText(stack.error)} + {/if} + + {stack.error ? '—' : stack.resourceCount} + {#if stack.lastUpdate} + + {#if stack.lastUpdate.result === 'succeeded'}{:else if stack.lastUpdate.result === 'failed'}{/if} + {$_(`stateIac.kinds.${stack.lastUpdate.kind}`)} · {relative( + stack.lastUpdate.endedAt ?? stack.lastUpdate.startedAt, + )} + + {:else} + {relative(stack.updatedAt)} + {/if} + + {#if stack.assignedProjectId} + {projectNames[stack.assignedProjectId] ?? '—'} + {:else} + {$_('stateIac.projects.unassignedOption')} + {/if} +
+
+
+ {/each} + {/if} + {#if group.truncated} +

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

+ {/if} +
+ {/each} + +

{$_('stateIac.stacks.count', { values: { count: total } })}

+
diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index a18b89c2..024982b9 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -2398,7 +2398,72 @@ "too_large": "A state file is larger than the maximum size", "unsupported_layout": "Unsupported meta.yaml version", "undecryptable": "The credentials can't be decrypted (did GITDB_ENCRYPTION_KEY change?)", - "unknown": "Unknown error" + "unknown": "Unknown error", + "unsupported_state": "Unsupported state file version", + "invalid_state": "The state file is not valid", + "state_missing": "The state file disappeared; refresh" + }, + "stacks": { + "search": "Search stack, project or backend", + "refresh": "Refresh", + "backendFailed": "This backend could not be read: {error}", + "noMatches": "No stack matches the search.", + "backendEmpty": "There are no stacks in this backend.", + "stack": "Stack", + "resources": "Resources", + "lastUpdate": "Last update", + "assignedProject": "Assigned project", + "lockedSince": "Operation in progress since {date}", + "locked": "In progress", + "pending": "{count} pending operations", + "count": "{count} stacks", + "projectDescription": "Pulumi stacks assigned to this project. GitOps only reads the state from the bucket.", + "emptyTitle": "No stacks are assigned to this project", + "emptyDescription": "Backends and assignments are configured in the organization settings (State IaC). Ask an administrator to assign the Pulumi projects here.", + "organizationTitle": "State IaC", + "organizationDescription": "Every stack of the organization's backends, assigned to a project or not.", + "manageBackends": "Manage backends", + "assignedTo": "assigned to {project}" + }, + "kinds": { + "update": "Update", + "refresh": "Refresh", + "destroy": "Destroy", + "import": "Import", + "rename": "Rename", + "other": "Other operation" + }, + "results": { + "succeeded": "succeeded", + "failed": "failed", + "in-progress": "in progress", + "unknown": "unknown" + }, + "detail": { + "back": "Back to the stacks", + "secretHelp": "Secret value: GitOps never decrypts it.", + "toolVersion": "Pulumi version", + "pendingOperations": "Pending operations", + "noStatesPermission": "You are not allowed to see the resources and outputs of this stack (project:stateiac:states:read).", + "tabs": "Stack contents", + "outputs": "Outputs", + "searchResources": "Search resource by name, type or ID", + "type": "Type", + "allTypes": "All types", + "provider": "Provider", + "allProviders": "All providers", + "protectedOnly": "Protected only", + "expand": "Expand", + "collapse": "Collapse", + "protected": "Protected against deletion", + "pendingChange": "Pending change", + "noResources": "No resource matches.", + "noOutputs": "This stack has no outputs.", + "parent": "Parent", + "modified": "Modified", + "resourceTabs": "Resource data", + "inputs": "Inputs", + "dependencies": "Dependencies" } } } diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index f5c46baf..8395db45 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -2398,7 +2398,72 @@ "too_large": "Un fichero de estado supera el tamaño máximo", "unsupported_layout": "Versión de meta.yaml no soportada", "undecryptable": "No se pueden descifrar las credenciales (¿ha cambiado GITDB_ENCRYPTION_KEY?)", - "unknown": "Error desconocido" + "unknown": "Error desconocido", + "unsupported_state": "Versión del fichero de estado no soportada", + "invalid_state": "El fichero de estado no es válido", + "state_missing": "El fichero de estado ha desaparecido; refresca" + }, + "stacks": { + "search": "Buscar stack, proyecto o backend", + "refresh": "Refrescar", + "backendFailed": "No se pudo leer este backend: {error}", + "noMatches": "Ningún stack coincide con la búsqueda.", + "backendEmpty": "No hay stacks en este backend.", + "stack": "Stack", + "resources": "Recursos", + "lastUpdate": "Último update", + "assignedProject": "Proyecto asignado", + "lockedSince": "Operación en curso desde {date}", + "locked": "En curso", + "pending": "{count} operaciones pendientes", + "count": "{count} stacks", + "projectDescription": "Stacks de Pulumi asignados a este proyecto. GitOps solo lee el estado del bucket.", + "emptyTitle": "No hay stacks asignados a este proyecto", + "emptyDescription": "Los backends y las asignaciones se configuran en los ajustes de la organización (State IaC). Pide a un administrador que asigne aquí los proyectos de Pulumi.", + "organizationTitle": "State IaC", + "organizationDescription": "Todos los stacks de los backends de la organización, asignados o no a un proyecto.", + "manageBackends": "Gestionar backends", + "assignedTo": "asignado a {project}" + }, + "kinds": { + "update": "Update", + "refresh": "Refresh", + "destroy": "Destroy", + "import": "Import", + "rename": "Rename", + "other": "Otra operación" + }, + "results": { + "succeeded": "correcto", + "failed": "fallido", + "in-progress": "en curso", + "unknown": "desconocido" + }, + "detail": { + "back": "Volver a los stacks", + "secretHelp": "Valor secreto: GitOps nunca lo descifra.", + "toolVersion": "Versión de Pulumi", + "pendingOperations": "Operaciones pendientes", + "noStatesPermission": "No tienes permiso para ver los recursos y outputs de este stack (project:stateiac:states:read).", + "tabs": "Contenido del stack", + "outputs": "Outputs", + "searchResources": "Buscar recurso por nombre, tipo o ID", + "type": "Tipo", + "allTypes": "Todos los tipos", + "provider": "Provider", + "allProviders": "Todos los providers", + "protectedOnly": "Solo protegidos", + "expand": "Desplegar", + "collapse": "Plegar", + "protected": "Protegido contra borrado", + "pendingChange": "Cambio pendiente", + "noResources": "Ningún recurso coincide.", + "noOutputs": "Este stack no tiene outputs.", + "parent": "Padre", + "modified": "Modificado", + "resourceTabs": "Datos del recurso", + "inputs": "Inputs", + "dependencies": "Dependencias" } } } diff --git a/src/lib/navigation.ts b/src/lib/navigation.ts index 73ab2d76..dd639940 100644 --- a/src/lib/navigation.ts +++ b/src/lib/navigation.ts @@ -56,6 +56,7 @@ export type NavAccess = { canReadOrgEvents?: boolean; canReadOrganizationAlerts?: boolean; canReadOrgStateIac?: boolean; + canReadOrgStateIacStacks?: boolean; canReadProjectInfo?: boolean; canReadProjectUsers?: boolean; canReadProjectRoles?: boolean; @@ -282,6 +283,23 @@ export function buildNavigation( }, ); + // every stack of the organization's backends, assigned or not + if (access.canReadOrgStateIacStacks) { + orgModules.push({ + id: 'org-state-iac', + name: t('sidebar.modules.stateIac'), + icon: GitBranch, + base: `/org/${organizationSlug}/state-iac`, + items: [ + { + label: t('sidebar.modules.stateIac'), + href: `/org/${organizationSlug}/state-iac`, + icon: GitBranch, + }, + ], + }); + } + if (access.canManageOrganization) { const items = visibleItems([ { diff --git a/src/lib/server/state-iac/stacks.ts b/src/lib/server/state-iac/stacks.ts new file mode 100644 index 00000000..dfeb505c --- /dev/null +++ b/src/lib/server/state-iac/stacks.ts @@ -0,0 +1,145 @@ +import { + stateIacService, + type BackendStacks, + type IacResource, + type IacValue, + type StackListItem, +} from '#modules/state-iac'; +import { organizationService } from '#modules/organization'; +import { projectService } from '#modules/projects'; +import { callerCan, type AlertLocals } from '#lib/server/alerts/access'; +import type { StateIacResult } from './backends'; + +/** + * Who sees which stacks: + * - from a project: `project:stateiac:stacks:read` lists the stacks assigned to it and + * `project:stateiac:states:read` opens their resources and outputs. A stack that is not + * assigned to the project answers 404, like a missing one; + * - from the organization: `organization:stateiac:stacks:read` sees every stack, assigned or not. + * A project API key only ever reaches its own project (`callerCan`). + */ +export type StackScope = + | { scope: 'project'; projectId: string; organizationId: string } + | { scope: 'organization'; organizationId: string }; + +const forbidden = { ok: false as const, status: 403, error: 'Forbidden' }; +const notFound = { ok: false as const, status: 404, error: 'Stack not found' }; + +function can(locals: AlertLocals, scope: StackScope, permission: 'stacks' | 'states') { + if (scope.scope === 'project') { + return callerCan(locals, `project:stateiac:${permission}:read`, { + scope: 'project', + projectId: scope.projectId, + organizationId: scope.organizationId, + }); + } + // the organization view has a single grant for the list and the contents + return callerCan(locals, 'organization:stateiac:stacks:read', { + scope: 'organization', + organizationId: scope.organizationId, + }); +} + +/** `projectId` (preferred) or `organizationId` of a request, checked to exist. */ +export async function resolveStackScope(ids: { + projectId?: unknown; + organizationId?: unknown; +}): Promise> { + const text = (value: unknown) => (typeof value === 'string' ? value.trim() : ''); + const projectId = text(ids.projectId); + if (projectId) { + const project = await projectService.getProject(projectId).catch(() => null); + const organizationId = project?.organization?.id; + if (!project || !organizationId) return { ok: false, status: 404, error: 'Project not found' }; + return { ok: true, status: 200, data: { scope: 'project', projectId, organizationId } }; + } + const organizationId = text(ids.organizationId); + if (!organizationId) { + return { ok: false, status: 400, error: 'projectId or organizationId is required' }; + } + const organization = await organizationService.getOrganization(organizationId).catch(() => null); + if (!organization) return { ok: false, status: 404, error: 'Organization not found' }; + return { ok: true, status: 200, data: { scope: 'organization', organizationId } }; +} + +export async function canReadStates(locals: AlertLocals, scope: StackScope): Promise { + return can(locals, scope, 'states'); +} + +export async function listStacks( + locals: AlertLocals, + scope: StackScope, + options: { refresh?: boolean } = {}, +): Promise> { + if (!(await can(locals, scope, 'stacks'))) return forbidden; + const backends = + scope.scope === 'project' + ? await stateIacService.listProjectStacks(scope.projectId, options) + : await stateIacService.listOrganizationStacks(scope.organizationId, options); + return { ok: true, status: 200, data: { backends } }; +} + +export type StackInclude = 'resources' | 'outputs'; + +export type StackDetailView = { + summary: StackListItem; + backend: { id: string; name: string; location: string }; + resources?: IacResource[]; + outputs?: Record; +}; + +/** One stack; `include` adds its resources and/or outputs (needs `states:read` in a project). */ +export async function getStack( + locals: AlertLocals, + scope: StackScope, + ref: { backendId: string; project: string; stack: string }, + include: StackInclude[], + options: { refresh?: boolean } = {}, +): Promise> { + if (!(await can(locals, scope, 'stacks'))) return notFound; + if (include.length > 0 && !(await can(locals, scope, 'states'))) return forbidden; + const detail = + scope.scope === 'project' + ? await stateIacService.getProjectStack( + scope.projectId, + ref.backendId, + ref.project, + ref.stack, + options, + ) + : await stateIacService.getOrganizationStack( + scope.organizationId, + ref.backendId, + ref.project, + ref.stack, + options, + ); + if (!detail) return notFound; + const backend = (await stateIacService.backendHead(ref.backendId)) ?? { + id: ref.backendId, + name: '', + location: '', + }; + return { + ok: true, + status: 200, + data: { + summary: detail.summary, + backend, + ...(include.includes('resources') ? { resources: detail.snapshot.resources } : {}), + ...(include.includes('outputs') ? { outputs: detail.snapshot.outputs } : {}), + }, + }; +} + +export function parseInclude(value: string | null): StackInclude[] { + if (!value) return []; + return [ + ...new Set( + value + .split(',') + .map((part) => part.trim()) + .filter((part): part is StackInclude => part === 'resources' || part === 'outputs'), + ), + ]; +} diff --git a/src/lib/state-iac/refresh.ts b/src/lib/state-iac/refresh.ts new file mode 100644 index 00000000..cd751d8d --- /dev/null +++ b/src/lib/state-iac/refresh.ts @@ -0,0 +1,16 @@ +import { goto } from '$app/navigation'; + +/** + * Reloads the page skipping the State IaC cache (`?refresh=1`), then drops the parameter so the + * next navigations use the cache again. + */ +export async function refreshStacks(current: URL): Promise { + const url = new URL(current); + url.searchParams.set('refresh', '1'); + // the current page itself, already resolved (same rule as the .svelte files, where it is off) + // eslint-disable-next-line svelte/no-navigation-without-resolve + await goto(`${url.pathname}${url.search}`, { replace: true, invalidateAll: true }); + url.searchParams.delete('refresh'); + // eslint-disable-next-line svelte/no-navigation-without-resolve + await goto(`${url.pathname}${url.search}`, { replace: true, shallow: true }); +} diff --git a/src/lib/state-iac/types.ts b/src/lib/state-iac/types.ts new file mode 100644 index 00000000..8af962ad --- /dev/null +++ b/src/lib/state-iac/types.ts @@ -0,0 +1,114 @@ +/** + * Client-safe shapes of the State IaC views (mirrors `$modules/state-iac` without importing + * server code). Secret values are already `{ $iac: 'secret' }` here. + */ +export type IacValue = + | null + | boolean + | number + | string + | IacValue[] + | { [key: string]: IacValue } + | { $iac: 'secret' } + | { $iac: 'resource-ref'; address: string; id?: string } + | { $iac: 'asset' | 'archive'; summary: string } + | { $iac: 'unknown' }; + +export type IacResourceView = { + address: string; + type: string; + name: string; + parent: string | null; + provider: string | null; + providerType: string | null; + externalId: string | null; + managed: boolean; + flags: { + protect: boolean; + retainOnDelete: boolean; + external: boolean; + pendingReplacement: boolean; + pendingDelete: boolean; + }; + inputs: Record; + outputs: Record; + dependencies: string[]; + createdAt: string | null; + modifiedAt: string | null; +}; + +export type IacUpdateView = { + id: string; + kind: string; + result: 'succeeded' | 'failed' | 'in-progress' | 'unknown'; + startedAt: string | null; + endedAt: string | null; + message: string; + changes: Record; + toolVersion: string | null; + vcs: { + kind: string | null; + owner: string | null; + repo: string | null; + commit: string | null; + branch: string | null; + dirty: boolean | null; + author: string | null; + }; +}; + +export type StackSummaryView = { + ref: { + backendId: string; + engine: string; + project: string | null; + stack: string; + layout: 'project' | 'legacy'; + }; + resourceCount: number; + updatedAt: string | null; + toolVersion: string | null; + lastUpdate: IacUpdateView | null; + lock: { since: string | null } | null; + pendingOperations: number; + sizeBytes: number; + assignedProjectId: string | null; + error: string | null; +}; + +export type BackendStacksView = { + backend: { + id: string; + name: string; + provider: string; + location: string; + lastError: string | null; + }; + error: string | null; + truncated: boolean; + stacks: StackSummaryView[]; +}; + +export type StackDetailView = { + summary: StackSummaryView; + backend: { id: string; name: string; location: string }; + resources?: IacResourceView[]; + outputs?: Record; +}; + +/** URL token of a legacy stack whose project is unknown. */ +export const UNKNOWN_PROJECT = '~'; + +/** `///` */ +export function stackPath(base: string, ref: StackSummaryView['ref']): string { + return `${base}/${ref.backendId}/${encodeURIComponent(ref.project ?? UNKNOWN_PROJECT)}/${encodeURIComponent(ref.stack)}`; +} + +export function isSpecial(value: unknown): value is Extract { + return ( + Boolean(value) && + typeof value === 'object' && + !Array.isArray(value) && + '$iac' in (value as object) + ); +} diff --git a/src/modules/state-iac/application/state-backend.service.ts b/src/modules/state-iac/application/state-backend.service.ts index aaaa64b6..d07c04b5 100644 --- a/src/modules/state-iac/application/state-backend.service.ts +++ b/src/modules/state-iac/application/state-backend.service.ts @@ -30,6 +30,11 @@ import { type PulumiDiscovery, type PulumiLayout, } from '../infrastructure/engines/pulumi/pulumi-discovery'; +import { + InvalidStateError, + UnsupportedStateVersionError, +} from '../infrastructure/engines/pulumi/pulumi-state'; +import { StackStateMissingError } from '../infrastructure/engines/pulumi/pulumi-state-engine'; import type { ObjectStoreFactory } from '../infrastructure/object-store/factory'; import { classifyStoreError, @@ -57,7 +62,23 @@ export type BackendInput = { enabled?: unknown; }; -export type BackendErrorCode = StoreErrorCode | 'unsupported_layout' | 'undecryptable'; +export type BackendErrorCode = + | StoreErrorCode + | 'unsupported_layout' + | 'unsupported_state' + | 'invalid_state' + | 'state_missing' + | 'undecryptable'; + +/** Short code of a failed read: stored in `lastError` and shown translated, never the message. */ +export function readErrorCode(error: unknown): BackendErrorCode { + if (error instanceof UnsupportedLayoutError || error instanceof UnsupportedStateVersionError) { + return error instanceof UnsupportedLayoutError ? 'unsupported_layout' : 'unsupported_state'; + } + if (error instanceof InvalidStateError) return 'invalid_state'; + if (error instanceof StackStateMissingError) return 'state_missing'; + return classifyStoreError(error); +} export type BackendTestResult = | { @@ -272,8 +293,7 @@ export class StateBackendService { await this.recordOutcome(backend, null); return { ok: true, ...discovery }; } catch (error) { - const code: BackendErrorCode = - error instanceof UnsupportedLayoutError ? 'unsupported_layout' : classifyStoreError(error); + const code = readErrorCode(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' }, @@ -284,6 +304,11 @@ export class StateBackendService { } } + /** Records the outcome of a read made elsewhere (stack listings): the same rules as `test`. */ + reportRead(backend: StateBackendDomain, error: BackendErrorCode | null): Promise { + return this.recordOutcome(backend, error); + } + /** 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(); diff --git a/src/modules/state-iac/application/state-iac.service.test.ts b/src/modules/state-iac/application/state-iac.service.test.ts new file mode 100644 index 00000000..827f08a9 --- /dev/null +++ b/src/modules/state-iac/application/state-iac.service.test.ts @@ -0,0 +1,184 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import type { StateBackendDomain } from '../domain/state-backend.domain'; +import { createStateIacFixture, fixtureStore } from './testing'; +import { UNKNOWN_PROJECT } from './state-iac.service'; + +const names = (groups: { stacks: { ref: { project: string | null; stack: string } }[] }[]) => + groups.flatMap((group) => group.stacks.map((s) => `${s.ref.project}/${s.ref.stack}`)); + +describe('StateIacService', () => { + let fx: ReturnType; + let shared: StateBackendDomain; + + beforeEach(async () => { + fx = createStateIacFixture(); + // one bucket holding the stacks of two GitOps projects + shared = await fx.backendService.create('org-1', { + name: 'shared', + provider: 'gcs', + bucket: 'shared-state', + }); + fx.buckets.set('shared-state', fixtureStore('project-layout')); + await fx.bindingService.set(shared, 'acme-infra', { projectId: 'p1', stacks: ['prod'] }); + await fx.bindingService.set(shared, 'acme-platform', { projectId: 'p2' }); + }); + + describe('visibility', () => { + it('a project only lists the stacks assigned to it', async () => { + expect(names(await fx.stateIacService.listProjectStacks('p1'))).toEqual(['acme-infra/prod']); + expect(names(await fx.stateIacService.listProjectStacks('p2'))).toEqual([ + 'acme-platform/dev', + ]); + expect(await fx.stateIacService.listProjectStacks('nobody')).toEqual([]); + }); + + it('the organization lists every stack with the project it is assigned to', async () => { + const groups = await fx.stateIacService.listOrganizationStacks('org-1'); + expect( + groups[0].stacks.map((s) => [`${s.ref.project}/${s.ref.stack}`, s.assignedProjectId]), + ).toEqual([ + ['acme-infra/prod', 'p1'], + ['acme-infra/staging', null], + ['acme-platform/dev', 'p2'], + ]); + expect(await fx.stateIacService.listOrganizationStacks('org-2')).toEqual([]); + }); + + it('a stack not assigned to the project, or assigned to another one, is not found', async () => { + const { getProjectStack } = fx.stateIacService; + const get = getProjectStack.bind(fx.stateIacService); + expect(await get('p1', shared.id, 'acme-infra', 'prod')).not.toBeNull(); + // same Pulumi project, stack not in the binding + expect(await get('p1', shared.id, 'acme-infra', 'staging')).toBeNull(); + // assigned to p2 + expect(await get('p1', shared.id, 'acme-platform', 'dev')).toBeNull(); + expect(await get('p2', shared.id, 'acme-infra', 'prod')).toBeNull(); + // does not exist at all + expect(await get('p1', shared.id, 'acme-infra', 'nope')).toBeNull(); + }); + + it("the organization opens any stack of its backends, not another organization's", async () => { + const detail = await fx.stateIacService.getOrganizationStack( + 'org-1', + shared.id, + 'acme-infra', + 'staging', + ); + expect(detail?.summary.assignedProjectId).toBeNull(); + expect(detail?.snapshot.resources).toHaveLength(45); + expect( + await fx.stateIacService.getOrganizationStack('org-2', shared.id, 'acme-infra', 'staging'), + ).toBeNull(); + }); + + it('summarizes each stack: resources, last update, lock', async () => { + const [group] = await fx.stateIacService.listProjectStacks('p1'); + expect(group.backend).toMatchObject({ name: 'shared', location: 'gs://shared-state' }); + expect(group.stacks[0]).toMatchObject({ + resourceCount: 48, + toolVersion: 'v3.276.0', + pendingOperations: 0, + lock: { since: '2026-11-25T10:56:00.000000Z' }, + lastUpdate: { id: '1795604216162649000', kind: 'update', result: 'succeeded' }, + error: null, + }); + }); + + it('legacy stacks without a project are only reachable from the organization', async () => { + const legacy = await fx.backendService.create('org-1', { + name: 'legacy', + provider: 's3', + bucket: 'legacy-state', + }); + const store = fixtureStore('legacy-layout'); + store.put( + '.pulumi/stacks/new.json', + '{"version":3,"checkpoint":{"stack":"new","latest":{}}}', + ); + fx.buckets.set('legacy-state', store); + const detail = await fx.stateIacService.getOrganizationStack( + 'org-1', + legacy.id, + UNKNOWN_PROJECT, + 'new', + ); + expect(detail?.summary.ref).toMatchObject({ project: null, stack: 'new', layout: 'legacy' }); + }); + }); + + describe('failures', () => { + it('a backend that fails does not break the others and records its error', async () => { + const broken = await fx.backendService.create('org-1', { + name: 'broken', + provider: 'gcs', + bucket: 'broken-state', + }); + const store = fixtureStore('project-layout'); + store.failWith = Object.assign(new Error('denied'), { code: 403 }); + fx.buckets.set('broken-state', store); + await fx.bindingService.set(broken, 'acme-infra', { projectId: 'p1' }); + + const groups = await fx.stateIacService.listProjectStacks('p1'); + expect(groups.map((g) => [g.backend.name, g.error, g.stacks.length])).toEqual([ + ['shared', null, 1], + ['broken', 'access_denied', 0], + ]); + expect(fx.backends.rows.find((row) => row.id === broken.id)?.lastError).toBe('access_denied'); + }); + + it('a state over the size limit is listed with an error', async () => { + fx.config.maxStateBytes = 10_000; + const [group] = await fx.stateIacService.listProjectStacks('p1'); + expect(group.stacks[0]).toMatchObject({ error: 'too_large', resourceCount: 0 }); + }); + + it('disabled backends are not read', async () => { + await fx.backendService.update(shared.id, { enabled: false }); + expect(await fx.stateIacService.listProjectStacks('p1')).toEqual([]); + }); + }); + + describe('cache', () => { + const stateReads = (store: ReturnType) => + store.calls.filter((c) => c.op === 'get' && c.key.startsWith('.pulumi/stacks/')).length; + + it('reuses listings for the TTL and unchanged states after it', async () => { + const store = fx.buckets.get('shared-state')!; + await fx.stateIacService.listOrganizationStacks('org-1'); + const lists = store.calls.filter((c) => c.op === 'list').length; + const reads = stateReads(store); + expect(reads).toBe(3); + + await fx.stateIacService.listOrganizationStacks('org-1'); + expect(store.calls.filter((c) => c.op === 'list').length).toBe(lists); + expect(stateReads(store)).toBe(reads); + + // TTL over: listed again, but the states have the same version and are not read again + fx.advance(61_000); + await fx.stateIacService.listOrganizationStacks('org-1'); + expect(store.calls.filter((c) => c.op === 'list').length).toBeGreaterThan(lists); + expect(stateReads(store)).toBe(reads); + }); + + it('reads a state again when its object changes, and on refresh', async () => { + const store = fx.buckets.get('shared-state')!; + await fx.stateIacService.listProjectStacks('p2'); + const reads = stateReads(store); + + store.put( + '.pulumi/stacks/acme-platform/dev.json', + '{"version":3,"checkpoint":{"stack":"organization/acme-platform/dev","latest":{"resources":[{"urn":"urn:pulumi:dev::acme-platform::pulumi:pulumi:Stack::acme-platform-dev","type":"pulumi:pulumi:Stack","outputs":{"url":"https://x"}}]}}}', + ); + const [group] = await fx.stateIacService.listProjectStacks('p2', { refresh: true }); + expect(stateReads(store)).toBe(reads + 1); + const detail = await fx.stateIacService.getProjectStack( + 'p2', + shared.id, + 'acme-platform', + 'dev', + ); + expect(detail?.snapshot.outputs).toEqual({ url: 'https://x' }); + expect(group.stacks[0].resourceCount).toBe(0); + }); + }); +}); diff --git a/src/modules/state-iac/application/state-iac.service.ts b/src/modules/state-iac/application/state-iac.service.ts new file mode 100644 index 00000000..ac2a028d --- /dev/null +++ b/src/modules/state-iac/application/state-iac.service.ts @@ -0,0 +1,407 @@ +import type { Logger } from 'pino'; +import type { IacLock, IacSnapshot, IacStackSummary, IacUpdate } from '../domain/iac.model'; +import type { StateBackendDomain } from '../domain/state-backend.domain'; +import type { StateBindingDomain } from '../domain/state-binding.domain'; +import type { + EngineDiscovery, + EngineStack, + StateEngine, +} from '../infrastructure/engines/state-engine'; +import type { StateBindingRepositoryPort } from '../infrastructure/repositories/state-binding.repository'; +import type { StateIacConfig } from '../infrastructure/config'; +import { + readErrorCode, + type BackendErrorCode, + type StateBackendService, +} from './state-backend.service'; + +/** URL token of a legacy stack whose project is unknown (`~` is not valid in Pulumi names). */ +export const UNKNOWN_PROJECT = '~'; + +export type StackListItem = IacStackSummary & { + /** GitOps project the stack is assigned to (organization listings only). */ + assignedProjectId: string | null; + /** The stack is listed but its state could not be read. */ + error: BackendErrorCode | null; +}; + +export type BackendStacks = { + backend: { + id: string; + name: string; + provider: string; + location: string; + lastError: string | null; + }; + /** The bucket could not be read: the other backends are still listed. */ + error: BackendErrorCode | null; + truncated: boolean; + stacks: StackListItem[]; +}; + +export type StackDetail = { summary: StackListItem; snapshot: IacSnapshot }; + +export type StateIacServiceOptions = { + now?: () => number; + logger?: Pick; + /** Bound of the in-memory state cache, in (raw state) bytes. */ + maxCacheBytes?: number; +}; + +type CachedDiscovery = { expires: number; value: EngineDiscovery | { error: BackendErrorCode } }; +type CachedExtras = { expires: number; lastUpdate: IacUpdate | null; lock: IacLock | null }; + +const READ_CONCURRENCY = 4; +const DEFAULT_MAX_CACHE_BYTES = 256 * 1024 * 1024; +const silentLogger = { warn: () => {} } as unknown as Pick; + +/** + * Reads the stacks of the backends (read-only) and decides who sees what: a GitOps project only + * sees the stacks assigned to it; the organization sees all of them. Everything read is kept in + * memory: listings for `cacheTtlMs`, states by object version (an unchanged state is never read + * twice), bounded in bytes. + */ +export class StateIacService { + private readonly discoveries = new Map(); + private readonly snapshots = new Map(); + private snapshotBytes = 0; + private readonly extras = new Map(); + private readonly now: () => number; + private readonly log: Pick; + private readonly maxCacheBytes: number; + + constructor( + private readonly backends: StateBackendService, + private readonly bindings: StateBindingRepositoryPort, + private readonly engine: StateEngine, + private readonly config: () => StateIacConfig, + options: StateIacServiceOptions = {}, + ) { + this.now = options.now ?? (() => Date.now()); + this.log = options.logger ?? silentLogger; + this.maxCacheBytes = options.maxCacheBytes ?? DEFAULT_MAX_CACHE_BYTES; + } + + /** Stacks assigned to a GitOps project, grouped by backend. */ + async listProjectStacks(projectId: string, options: { refresh?: boolean } = {}) { + const bindings = await this.bindings.listByProject(projectId); + const byBackend = groupBy(bindings, (binding) => binding.backendId); + const groups: BackendStacks[] = []; + for (const [backendId, backendBindings] of byBackend) { + const backend = await this.backends.get(backendId).catch(() => null); + if (!backend || !backend.enabled) continue; + groups.push( + await this.listBackend(backend, options, (stack) => + backendBindings.some( + (binding) => + binding.pulumiProject === stack.ref.project && binding.covers(stack.ref.stack), + ) + ? projectId + : undefined, + ), + ); + } + return groups; + } + + /** Every stack of the organization's backends, assigned or not. */ + async listOrganizationStacks(organizationId: string, options: { refresh?: boolean } = {}) { + const backends = (await this.backends.list(organizationId)).filter((b) => b.enabled); + const groups: BackendStacks[] = []; + for (const backend of backends) { + const bindings = await this.bindings.listByBackend(backend.id); + groups.push( + await this.listBackend( + backend, + options, + (stack) => assignedTo(bindings, stack.ref.project, stack.ref.stack) ?? null, + ), + ); + } + return groups; + } + + /** A stack seen from a project: `null` (404) unless it is assigned to that project. */ + async getProjectStack( + projectId: string, + backendId: string, + project: string, + stack: string, + options: { refresh?: boolean } = {}, + ): Promise { + const bindings = await this.bindings.listByProject(projectId); + const visible = bindings.some( + (binding) => + binding.backendId === backendId && + binding.pulumiProject === project && + binding.covers(stack), + ); + if (!visible) return null; + const backend = await this.backends.get(backendId).catch(() => null); + if (!backend || !backend.enabled) return null; + return this.detail(backend, project, stack, projectId, options); + } + + /** A stack seen from its organization: any stack of its backends. */ + async getOrganizationStack( + organizationId: string, + backendId: string, + project: string, + stack: string, + options: { refresh?: boolean } = {}, + ): Promise { + const backend = await this.backends.get(backendId).catch(() => null); + if (!backend || backend.organizationId !== organizationId || !backend.enabled) return null; + const bindings = await this.bindings.listByBackend(backend.id); + const projectName = project === UNKNOWN_PROJECT ? null : project; + return this.detail( + backend, + project, + stack, + assignedTo(bindings, projectName, stack) ?? null, + options, + ); + } + + /** Name and location of a backend, for headings. */ + async backendHead( + backendId: string, + ): Promise<{ id: string; name: string; location: string } | null> { + const backend = await this.backends.get(backendId).catch(() => null); + return backend ? { id: backend.id, name: backend.name, location: backend.location } : null; + } + + /** Forgets everything read from a backend (after it changes, or on "Refresh"). */ + invalidate(backendId: string): void { + for (const key of this.discoveries.keys()) + if (key.startsWith(`${backendId}:`)) this.discoveries.delete(key); + for (const key of this.extras.keys()) + if (key.startsWith(`${backendId}|`)) this.extras.delete(key); + } + + private async detail( + backend: StateBackendDomain, + project: string, + stackName: string, + assignedProjectId: string | null, + options: { refresh?: boolean }, + ): Promise { + const discovery = await this.discover(backend, options); + if ('error' in discovery) return null; + const projectName = project === UNKNOWN_PROJECT ? null : project; + const stack = discovery.stacks.find( + (candidate) => candidate.ref.project === projectName && candidate.ref.stack === stackName, + ); + if (!stack) return null; + const summary = await this.summarize(backend, stack, assignedProjectId); + if (summary.error) return { summary, snapshot: emptySnapshot(stack) }; + const snapshot = await this.snapshot(backend, stack); + return { summary, snapshot }; + } + + private async listBackend( + backend: StateBackendDomain, + options: { refresh?: boolean }, + include: (stack: EngineStack) => string | null | undefined, + ): Promise { + const head = { + id: backend.id, + name: backend.name, + provider: backend.provider, + location: backend.location, + lastError: backend.lastError, + }; + const discovery = await this.discover(backend, options); + if ('error' in discovery) { + return { + backend: { ...head, lastError: discovery.error }, + error: discovery.error, + truncated: false, + stacks: [], + }; + } + const selected = discovery.stacks.flatMap((stack) => { + const assigned = include(stack); + return assigned === undefined ? [] : [{ stack, assigned }]; + }); + const stacks: StackListItem[] = []; + for (let i = 0; i < selected.length; i += READ_CONCURRENCY) { + stacks.push( + ...(await Promise.all( + selected + .slice(i, i + READ_CONCURRENCY) + .map(({ stack, assigned }) => this.summarize(backend, stack, assigned)), + )), + ); + } + return { + backend: { ...head, lastError: null }, + error: null, + truncated: discovery.truncated, + stacks, + }; + } + + private async discover( + backend: StateBackendDomain, + options: { refresh?: boolean }, + ): Promise { + // a backend whose connection changed (bucket, credentials…) is a different cache entry; its + // `updatedAt` is not used: recording the scan outcome changes it + const key = `${backend.id}:${connectionKey(backend)}`; + if (options.refresh) this.invalidate(backend.id); + const cached = this.discoveries.get(key); + if (cached && cached.expires > this.now()) return cached.value; + + let value: EngineDiscovery | { error: BackendErrorCode }; + try { + value = await this.engine.discoverStacks( + this.backends.storeFor(backend), + backend.pulumiRoot, + backend.id, + ); + await this.backends.reportRead(backend, null); + } catch (error) { + const code = + error instanceof Error && /decrypt|encrypted credentials/i.test(error.message) + ? 'undecryptable' + : readErrorCode(error); + this.log.warn({ backendId: backend.id, code }, '[state-iac] backend listing failed'); + await this.backends.reportRead(backend, code); + value = { error: code }; + } + this.discoveries.set(key, { expires: this.now() + this.config().cacheTtlMs, value }); + return value; + } + + private async snapshot(backend: StateBackendDomain, stack: EngineStack): Promise { + // keyed by object version: an unchanged state is never read twice + const key = `${backend.id}|${stack.key}|${stack.version ?? stack.updatedAt ?? ''}`; + const cached = this.snapshots.get(key); + if (cached) { + this.snapshots.delete(key); + this.snapshots.set(key, cached); + return cached; + } + const snapshot = await this.engine.readSnapshot( + this.backends.storeFor(backend), + backend.pulumiRoot, + stack, + { + maxBytes: this.config().maxStateBytes, + }, + ); + this.snapshots.set(key, snapshot); + this.snapshotBytes += snapshot.sizeBytes; + for (const [oldKey, old] of this.snapshots) { + if (this.snapshotBytes <= this.maxCacheBytes || oldKey === key) break; + this.snapshots.delete(oldKey); + this.snapshotBytes -= old.sizeBytes; + } + return snapshot; + } + + private async summarize( + backend: StateBackendDomain, + stack: EngineStack, + assignedProjectId: string | null, + ): Promise { + const base: StackListItem = { + ref: stack.ref, + resourceCount: 0, + updatedAt: stack.updatedAt, + toolVersion: null, + lastUpdate: null, + lock: null, + pendingOperations: 0, + sizeBytes: stack.size, + assignedProjectId, + error: null, + }; + try { + const [snapshot, extras] = await Promise.all([ + this.snapshot(backend, stack), + this.stackExtras(backend, stack), + ]); + return { + ...base, + // the stack resource itself is not one of "its" resources + resourceCount: snapshot.resources.filter((r) => r.type !== 'pulumi:pulumi:Stack').length, + updatedAt: snapshot.takenAt ?? stack.updatedAt, + toolVersion: snapshot.toolVersion, + pendingOperations: snapshot.pendingOperations, + lastUpdate: extras.lastUpdate, + lock: extras.lock, + }; + } catch (error) { + const code = readErrorCode(error); + this.log.warn( + { backendId: backend.id, stack: stack.ref.stack, code }, + '[state-iac] stack read failed', + ); + return { ...base, error: code }; + } + } + + private async stackExtras(backend: StateBackendDomain, stack: EngineStack) { + const key = `${backend.id}|${stack.ref.project ?? UNKNOWN_PROJECT}|${stack.ref.stack}|${stack.version ?? ''}`; + const cached = this.extras.get(key); + if (cached && cached.expires > this.now()) return cached; + const store = this.backends.storeFor(backend); + const { maxStateBytes } = this.config(); + const [updates, lock] = await Promise.all([ + this.engine.listUpdates(store, backend.pulumiRoot, stack, { + limit: 1, + maxBytes: maxStateBytes, + }), + this.engine.readLock(store, backend.pulumiRoot, stack), + ]); + const value = { + expires: this.now() + this.config().cacheTtlMs, + lastUpdate: updates[0] ?? null, + lock, + }; + this.extras.set(key, value); + return value; + } +} + +function assignedTo(bindings: StateBindingDomain[], project: string | null, stack: string) { + if (project === null) return undefined; + return bindings.find((binding) => binding.pulumiProject === project && binding.covers(stack)) + ?.projectId; +} + +function connectionKey(backend: StateBackendDomain): string { + const { provider, bucket, prefix, region, endpoint, forcePathStyle, auth, credentials } = backend; + return JSON.stringify([ + provider, + bucket, + prefix, + region, + endpoint, + forcePathStyle, + auth, + credentials, + ]); +} + +function groupBy(items: T[], key: (item: T) => string): Map { + const groups = new Map(); + for (const item of items) groups.set(key(item), [...(groups.get(key(item)) ?? []), item]); + return groups; +} + +function emptySnapshot(stack: EngineStack): IacSnapshot { + return { + ref: stack.ref, + source: 'current', + versionId: stack.version, + takenAt: null, + toolVersion: null, + resources: [], + outputs: {}, + pendingOperations: 0, + sizeBytes: 0, + }; +} diff --git a/src/modules/state-iac/application/testing.ts b/src/modules/state-iac/application/testing.ts index fd024a6a..724f7db6 100644 --- a/src/modules/state-iac/application/testing.ts +++ b/src/modules/state-iac/application/testing.ts @@ -10,6 +10,9 @@ import { } from '../infrastructure/repositories/in-memory.repositories'; import { StateBackendService } from './state-backend.service'; import { StateBindingService } from './state-binding.service'; +import { StateIacService } from './state-iac.service'; +import { PulumiStateEngine } from '../infrastructure/engines/pulumi/pulumi-state-engine'; +import type { StateIacConfig } from '../infrastructure/config'; /** `test/fixtures/state-iac/`: buckets copied from real (anonymized) Pulumi state. */ export function fixtureDir(name: 'project-layout' | 'legacy-layout'): string { @@ -61,7 +64,24 @@ export function createStateIacFixture() { { getProject: async (id) => projects.get(id) ?? null }, { events, generateId }, ); + const config: StateIacConfig = { maxStateBytes: 50 * 1024 * 1024, cacheTtlMs: 60_000 }; + let clock = 1_000_000; + const stateIacService = new StateIacService( + backendService, + bindings, + new PulumiStateEngine(), + () => config, + { + now: () => clock, + }, + ); return { + config, + /** Moves the cache clock forward. */ + advance(ms: number) { + clock += ms; + }, + stateIacService, backends, bindings, events, diff --git a/src/modules/state-iac/domain/iac.model.ts b/src/modules/state-iac/domain/iac.model.ts new file mode 100644 index 00000000..bbaae079 --- /dev/null +++ b/src/modules/state-iac/domain/iac.model.ts @@ -0,0 +1,115 @@ +/** + * Normalized IaC model (docs/adr/0003-state-iac.md). Nothing here is Pulumi-specific: engines + * translate their tool's format into it, so Terraform can be one more engine. Secrets are masked + * before a value reaches this model: it never holds ciphertexts nor plain secret values. + */ + +export type IacEngineKind = 'pulumi'; + +/** A JSON value with the special values of the tools made explicit. */ +export type IacValue = + null | boolean | number | string | IacValue[] | { [key: string]: IacValue } | IacSpecialValue; + +export type IacSpecialValue = + | { $iac: 'secret' } + | { $iac: 'resource-ref'; address: string; id?: string } + | { $iac: 'asset' | 'archive'; summary: string } + | { $iac: 'unknown' }; + +export function isSpecialValue(value: unknown): value is IacSpecialValue { + return Boolean(value) && typeof value === 'object' && '$iac' in (value as object); +} + +/** Where a stack lives: a backend, a tool project (`null`: legacy, unknown) and the stack name. */ +export type IacStackRef = { + backendId: string; + engine: IacEngineKind; + project: string | null; + stack: string; + layout: 'project' | 'legacy'; +}; + +export type IacResource = { + /** Pulumi URN; a Terraform resource address later. */ + address: string; + type: string; + name: string; + parent: string | null; + /** Provider address, without the trailing `::`. */ + provider: string | null; + /** Provider package (`gcp`, `aws`…) or `null` for components. */ + providerType: string | null; + /** Cloud id. */ + externalId: string | null; + /** A cloud resource (vs a component that only groups others). */ + managed: boolean; + flags: { + protect: boolean; + retainOnDelete: boolean; + external: boolean; + pendingReplacement: boolean; + pendingDelete: boolean; + }; + inputs: Record; + outputs: Record; + /** Sorted, de-duplicated. */ + dependencies: string[]; + createdAt: string | null; + modifiedAt: string | null; +}; + +export type IacSnapshot = { + ref: IacStackRef; + source: 'current' | 'history' | 'backup' | 'retained' | 'previous' | 'object-version'; + /** Object version (ETag / generation) or `` of a history entry. */ + versionId: string | null; + takenAt: string | null; + toolVersion: string | null; + resources: IacResource[]; + /** Outputs of the stack (the root resource). */ + outputs: Record; + pendingOperations: number; + sizeBytes: number; +}; + +export type IacUpdateKind = 'update' | 'refresh' | 'destroy' | 'import' | 'rename' | 'other'; + +export type IacUpdate = { + /** `` of the history file. */ + id: string; + kind: IacUpdateKind; + result: 'succeeded' | 'failed' | 'in-progress' | 'unknown'; + startedAt: string | null; + endedAt: string | null; + message: string; + changes: Partial>; + toolVersion: string | null; + /** Allow-listed environment only: never emails nor local paths. */ + vcs: { + kind: string | null; + owner: string | null; + repo: string | null; + commit: string | null; + branch: string | null; + dirty: boolean | null; + author: string | null; + }; + execKind: string | null; + /** Stack configuration; secret values masked. */ + config: Record; + snapshotAvailable: boolean; +}; + +/** An operation in progress on the stack (the tool's lock). Who holds it is not exposed. */ +export type IacLock = { since: string | null }; + +export type IacStackSummary = { + ref: IacStackRef; + resourceCount: number; + updatedAt: string | null; + toolVersion: string | null; + lastUpdate: IacUpdate | null; + lock: IacLock | null; + pendingOperations: number; + sizeBytes: number; +}; diff --git a/src/modules/state-iac/index.ts b/src/modules/state-iac/index.ts index 62d5804b..47add62e 100644 --- a/src/modules/state-iac/index.ts +++ b/src/modules/state-iac/index.ts @@ -4,6 +4,9 @@ import { passwordService } from '../auth'; import { projectService } from '../projects'; import { StateBackendService } from './application/state-backend.service'; import { StateBindingService } from './application/state-binding.service'; +import { StateIacService } from './application/state-iac.service'; +import { readStateIacConfig } from './infrastructure/config'; +import { PulumiStateEngine } from './infrastructure/engines/pulumi/pulumi-state-engine'; import { createCredentialsCipher } from './infrastructure/crypto/credentials-cipher'; import { createObjectStore } from './infrastructure/object-store/factory'; import { StateBackendRepository } from './infrastructure/repositories/state-backend.repository'; @@ -31,6 +34,14 @@ export const stateBindingService = new StateBindingService( { events: eventBus, logger: log }, ); +export const stateIacService = new StateIacService( + stateBackendService, + bindingRepository, + new PulumiStateEngine(), + readStateIacConfig, + { logger: log }, +); + const SUBSCRIBED_KEY = Symbol.for('gitops.state-iac.subscribed'); type GlobalWithFlag = typeof globalThis & { [SUBSCRIBED_KEY]?: boolean }; @@ -64,3 +75,10 @@ export type { } from './application/state-backend.service'; export type { BindingInput } from './application/state-binding.service'; export type { PulumiLayout } from './infrastructure/engines/pulumi/pulumi-discovery'; +export { + UNKNOWN_PROJECT, + type BackendStacks, + type StackDetail, + type StackListItem, +} from './application/state-iac.service'; +export type * from './domain/iac.model'; diff --git a/src/modules/state-iac/infrastructure/config.ts b/src/modules/state-iac/infrastructure/config.ts new file mode 100644 index 00000000..215fc47f --- /dev/null +++ b/src/modules/state-iac/infrastructure/config.ts @@ -0,0 +1,22 @@ +import * as env from '$app/env/private'; + +export type StateIacConfig = { + /** Largest state object read, decompressed. */ + maxStateBytes: number; + /** How long listings stay cached; states are also keyed by object version. */ + cacheTtlMs: number; +}; + +function int(raw: string | undefined, fallback: number, min: number, max: number): number { + const value = Number.parseInt(raw?.trim().replace(/^["']|["']$/g, '') ?? '', 10); + if (!Number.isFinite(value)) return fallback; + return Math.min(max, Math.max(min, value)); +} + +/** `STATE_IAC_MAX_STATE_MB` (default 50) and `STATE_IAC_CACHE_SECONDS` (default 60). */ +export function readStateIacConfig(): StateIacConfig { + return { + maxStateBytes: int(env.STATE_IAC_MAX_STATE_MB, 50, 1, 500) * 1024 * 1024, + cacheTtlMs: int(env.STATE_IAC_CACHE_SECONDS, 60, 0, 3600) * 1000, + }; +} diff --git a/src/modules/state-iac/infrastructure/engines/pulumi/pulumi-discovery.ts b/src/modules/state-iac/infrastructure/engines/pulumi/pulumi-discovery.ts index 9572cc2b..213115f0 100644 --- a/src/modules/state-iac/infrastructure/engines/pulumi/pulumi-discovery.ts +++ b/src/modules/state-iac/infrastructure/engines/pulumi/pulumi-discovery.ts @@ -8,7 +8,14 @@ import { listAll, readText, type ObjectStore } from '../../object-store/object-s export type PulumiLayout = 'project' | 'legacy' | 'empty'; -export type DiscoveredStack = { name: string; key: string; size: number; updatedAt: string | null }; +export type DiscoveredStack = { + name: string; + key: string; + size: number; + updatedAt: string | null; + /** ETag / generation: changes whenever the state does (cache key). */ + version: string | null; +}; export type DiscoveredProject = { /** `null` for legacy stacks whose project can't be found (no resources yet). */ @@ -74,7 +81,10 @@ export async function detectPulumiLayout( return { layout: 'empty', metaVersion: null }; } -function stacksIn(objects: { key: string; size: number; updatedAt: string | null }[], dir: string) { +function stacksIn( + objects: { key: string; size: number; updatedAt: string | null; version: string | null }[], + dir: string, +) { const byName = new Map(); for (const object of objects) { const name = stackNameOf(object.key.slice(dir.length)); @@ -82,7 +92,13 @@ function stacksIn(objects: { key: string; size: number; updatedAt: string | null 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 }); + byName.set(name, { + name, + key: object.key, + size: object.size, + updatedAt: object.updatedAt, + version: object.version, + }); } } return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name)); diff --git a/src/modules/state-iac/infrastructure/engines/pulumi/pulumi-state-engine.test.ts b/src/modules/state-iac/infrastructure/engines/pulumi/pulumi-state-engine.test.ts new file mode 100644 index 00000000..6784949d --- /dev/null +++ b/src/modules/state-iac/infrastructure/engines/pulumi/pulumi-state-engine.test.ts @@ -0,0 +1,237 @@ +import { describe, expect, it } from 'vitest'; +import { fixtureStore } from '../../../application/testing'; +import type { EngineStack } from '../state-engine'; +import { PulumiStateEngine } from './pulumi-state-engine'; +import { normalizeValue, parseCheckpoint, UnsupportedStateVersionError } from './pulumi-state'; + +const engine = new PulumiStateEngine(); +const MAX = 50 * 1024 * 1024; +// the fake ciphertexts of the fixtures all encode "fixture-ciphertext-" +const FAKE_CIPHERTEXT = Buffer.from('fixture-ciphertext').toString('base64').slice(0, 20); + +async function stacksOf(layout: 'project-layout' | 'legacy-layout') { + const store = fixtureStore(layout); + const discovery = await engine.discoverStacks(store, '.pulumi/', 'b1'); + const find = (project: string | null, stack: string) => + discovery.stacks.find((s) => s.ref.project === project && s.ref.stack === stack) as EngineStack; + return { store, discovery, find }; +} + +describe('PulumiStateEngine on the real (anonymized) fixtures', () => { + it('discovers stacks with their reference and object version', async () => { + const { discovery } = await stacksOf('project-layout'); + expect(discovery.stacks.map((s) => `${s.ref.project}/${s.ref.stack}`)).toEqual([ + 'acme-infra/prod', + 'acme-infra/staging', + 'acme-platform/dev', + ]); + expect(discovery.stacks[0].ref).toEqual({ + backendId: 'b1', + engine: 'pulumi', + project: 'acme-infra', + stack: 'prod', + layout: 'project', + }); + expect(discovery.stacks[0].version).not.toBeNull(); + }); + + it('reads a snapshot: resources, stack outputs and metadata', async () => { + const { store, find } = await stacksOf('project-layout'); + const snapshot = await engine.readSnapshot(store, '.pulumi/', find('acme-infra', 'prod'), { + maxBytes: MAX, + }); + expect(snapshot.resources).toHaveLength(49); + expect(snapshot.toolVersion).toBe('v3.276.0'); + expect(snapshot.takenAt).toBe('2026-11-25T11:56:55.792125+01:00'); + expect(snapshot.pendingOperations).toBe(0); + expect(snapshot.outputs).toMatchObject({ + assetsBucketName: 'acme-assets-prod', + redisPort: 6378, + }); + + const service = snapshot.resources.find((r) => r.name === 'enable-apis-dns')!; + expect(service).toMatchObject({ + type: 'gcp:projects/service:Service', + providerType: 'gcp', + managed: true, + parent: 'urn:pulumi:prod::acme-infra::acme:infra:enable-apis::enable-apis', + }); + // provider reference without its trailing :: + expect(service.provider).toMatch( + /^urn:pulumi:prod::acme-infra::pulumi:providers:gcp::default_[\d_]+$/, + ); + // internal provider keys are dropped + expect(Object.keys(service.outputs).some((key) => key.startsWith('__'))).toBe(false); + + const component = snapshot.resources.find((r) => r.type === 'acme:infra:cloud-sql')!; + expect(component.managed).toBe(false); + expect(component.providerType).toBeNull(); + }); + + it('masks every secret and never exposes ciphertexts nor the secrets provider', async () => { + const { store, find } = await stacksOf('project-layout'); + const snapshot = await engine.readSnapshot(store, '.pulumi/', find('acme-infra', 'prod'), { + maxBytes: MAX, + }); + const users = snapshot.resources.filter((r) => r.type === 'gcp:sql/user:User'); + expect(users.length).toBeGreaterThan(0); + for (const user of users) { + expect(user.inputs.password).toEqual({ $iac: 'secret' }); + } + const text = JSON.stringify(snapshot); + expect(text).not.toContain(FAKE_CIPHERTEXT); + expect(text).not.toMatch( + /ciphertext|secrets_providers|"salt"|4dabf18193072939515e22adb298388d/, + ); + }); + + it('turns resource references into links', async () => { + const { store, find } = await stacksOf('project-layout'); + const snapshot = await engine.readSnapshot(store, '.pulumi/', find('acme-infra', 'prod'), { + maxBytes: MAX, + }); + const refs = JSON.stringify(snapshot).match(/"\$iac":"resource-ref"/g) ?? []; + expect(refs.length).toBeGreaterThan(0); + }); + + it('reads gzipped states and empty stacks', async () => { + const { store, find } = await stacksOf('project-layout'); + const staging = await engine.readSnapshot(store, '.pulumi/', find('acme-infra', 'staging'), { + maxBytes: MAX, + }); + expect(staging.resources).toHaveLength(45); + const empty = await engine.readSnapshot(store, '.pulumi/', find('acme-platform', 'dev'), { + maxBytes: MAX, + }); + expect(empty.resources).toEqual([]); + expect(empty.outputs).toEqual({}); + }); + + it('reads the legacy layout', async () => { + const { store, discovery, find } = await stacksOf('legacy-layout'); + expect(discovery.layout).toBe('legacy'); + const prod = find('acme-legacy', 'prod'); + expect(prod.ref.layout).toBe('legacy'); + const snapshot = await engine.readSnapshot(store, '.pulumi/', prod, { maxBytes: MAX }); + expect(snapshot.resources[0].address).toMatch(/^urn:pulumi:prod::acme-legacy::/); + const updates = await engine.listUpdates(store, '.pulumi/', prod, { limit: 10, maxBytes: MAX }); + expect(updates.map((u) => u.id)).toEqual(['1795604216162649000', '1795602803296701000']); + }); + + it('fails cleanly past the size limit', async () => { + const { store, find } = await stacksOf('project-layout'); + await expect( + engine.readSnapshot(store, '.pulumi/', find('acme-infra', 'prod'), { maxBytes: 10_000 }), + ).rejects.toThrow(/larger than/); + }); + + it('lists updates, newest first, with an allow-listed environment', async () => { + const { store, find } = await stacksOf('project-layout'); + const updates = await engine.listUpdates(store, '.pulumi/', find('acme-infra', 'prod'), { + limit: 10, + maxBytes: MAX, + }); + expect(updates.map((u) => [u.id, u.kind, u.result])).toEqual([ + ['1795604216162649000', 'update', 'succeeded'], + ['1795602803296701000', 'update', 'succeeded'], + ['1795602066945844000', 'update', 'succeeded'], + ['1789061079158069310', 'update', 'failed'], + ]); + expect(updates[0]).toMatchObject({ + changes: { same: 146, update: 2 }, + toolVersion: 'v3.276.0', + snapshotAvailable: true, + vcs: { + kind: 'github.com', + owner: 'Acme', + repo: 'acme-infra', + branch: 'main', + author: 'Jane Doe', + }, + }); + expect(updates[0].startedAt).toBe(new Date(1795604139 * 1000).toISOString()); + // secret config values masked; no emails nor local paths + expect(updates[0].config['acme-infra:sqlApiUserPassword']).toEqual({ $iac: 'secret' }); + const text = JSON.stringify(updates); + expect(text).not.toMatch(/jane@example\.com|\/usr\/local|v1:/); + + const limited = await engine.listUpdates(store, '.pulumi/', find('acme-infra', 'prod'), { + limit: 1, + maxBytes: MAX, + }); + expect(limited.map((u) => u.id)).toEqual(['1795604216162649000']); + }); + + it('reads gzipped history and other kinds', async () => { + const { store, find } = await stacksOf('project-layout'); + const updates = await engine.listUpdates(store, '.pulumi/', find('acme-infra', 'staging'), { + limit: 10, + maxBytes: MAX, + }); + expect(updates.map((u) => u.kind).sort()).toEqual(['import', 'refresh']); + }); + + it('reports the lock of an operation in progress, without who holds it', async () => { + const { store, find } = await stacksOf('project-layout'); + expect(await engine.readLock(store, '.pulumi/', find('acme-infra', 'prod'))).toEqual({ + since: '2026-11-25T10:56:00.000000Z', + }); + expect(await engine.readLock(store, '.pulumi/', find('acme-infra', 'staging'))).toBeNull(); + }); +}); + +describe('normalizeValue', () => { + const SIG = '4dabf18193072939515e22adb298388d'; + it('handles every special value', () => { + expect( + normalizeValue({ [SIG]: '1b47061264138c4ac30d75fd1eb44270', ciphertext: 'v1:x' }), + ).toEqual({ + $iac: 'secret', + }); + expect( + normalizeValue({ [SIG]: '1b47061264138c4ac30d75fd1eb44270', plaintext: '"pw"' }), + ).toEqual({ + $iac: 'secret', + }); + expect( + normalizeValue({ [SIG]: 'd0e6a833031e9bbcd3f4e8bde6ca49a4', secret: true, value: 'pw' }), + ).toEqual({ + $iac: 'secret', + }); + expect(normalizeValue({ [SIG]: 'd0e6a833031e9bbcd3f4e8bde6ca49a4', value: 'ok' })).toBe('ok'); + expect( + normalizeValue({ [SIG]: 'c44067f5952c0a294b673a41bacd8c17', path: './index.js' }), + ).toEqual({ + $iac: 'asset', + summary: './index.js', + }); + expect(normalizeValue({ [SIG]: 'unknown-signature', anything: 'secret?' })).toEqual({ + $iac: 'secret', + }); + expect(normalizeValue({ ciphertext: 'v1:x' })).toEqual({ $iac: 'secret' }); + expect(normalizeValue('04da6b54-80e4-46f7-96ec-b56ff0331ba9')).toEqual({ $iac: 'unknown' }); + expect(normalizeValue({ nested: [{ [SIG]: '1b47061264138c4ac30d75fd1eb44270' }] })).toEqual({ + nested: [{ $iac: 'secret' }], + }); + }); + + it('refuses checkpoints newer than it understands', () => { + const ref = { + backendId: 'b', + engine: 'pulumi' as const, + project: 'p', + stack: 's', + layout: 'project' as const, + }; + expect(() => + parseCheckpoint('{"version":4,"checkpoint":{}}', ref, { + source: 'current', + versionId: null, + sizeBytes: 1, + }), + ).toThrow(UnsupportedStateVersionError); + expect(() => + parseCheckpoint('nope', ref, { source: 'current', versionId: null, sizeBytes: 1 }), + ).toThrow(/not valid JSON/); + }); +}); diff --git a/src/modules/state-iac/infrastructure/engines/pulumi/pulumi-state-engine.ts b/src/modules/state-iac/infrastructure/engines/pulumi/pulumi-state-engine.ts new file mode 100644 index 00000000..c19288d5 --- /dev/null +++ b/src/modules/state-iac/infrastructure/engines/pulumi/pulumi-state-engine.ts @@ -0,0 +1,134 @@ +import type { IacLock, IacSnapshot, IacUpdate } from '../../../domain/iac.model'; +import { listAll, readText, type ObjectStore } from '../../object-store/object-store'; +import type { EngineDiscovery, EngineStack, StateEngine } from '../state-engine'; +import { discoverPulumi } from './pulumi-discovery'; +import { parseCheckpoint, parseHistory } from './pulumi-state'; + +const HISTORY_FILE = /-(\d+)\.(history|checkpoint)\.json(?:\.gz|\.zst)?$/; +const MAX_HISTORY_OBJECTS = 20_000; +const READ_CONCURRENCY = 4; + +/** Paths of a stack's bookkeeping files in both layouts (docs/adr/0003-state-iac.md). */ +export function pulumiPaths(root: string, stack: EngineStack) { + const { project, stack: name, layout } = stack.ref; + const scoped = layout === 'project' && project !== null; + return { + history: scoped ? `${root}history/${project}/${name}/` : `${root}history/${name}/`, + // locks are keyed by the fully qualified name, `organization/` included + locks: scoped ? `${root}locks/organization/${project}/${name}/` : `${root}locks/${name}/`, + }; +} + +/** Pulumi DIY backend: `project` and legacy layouts, plain, `.gz` (and, listed only, `.zst`). */ +export class PulumiStateEngine implements StateEngine { + readonly kind = 'pulumi' as const; + + async discoverStacks( + store: ObjectStore, + root: string, + backendId: string, + ): Promise { + const discovery = await discoverPulumi(store, root); + const layout = discovery.layout === 'legacy' ? 'legacy' : 'project'; + return { + layout: discovery.layout, + metaVersion: discovery.metaVersion, + truncated: discovery.truncated, + stacks: discovery.projects.flatMap((project) => + project.stacks.map((stack) => ({ + ref: { + backendId, + engine: 'pulumi' as const, + project: project.name, + stack: stack.name, + layout, + }, + key: stack.key, + size: stack.size, + updatedAt: stack.updatedAt, + version: stack.version, + })), + ), + }; + } + + async readSnapshot( + store: ObjectStore, + _root: string, + stack: EngineStack, + options: { maxBytes: number }, + ): Promise { + const text = await readText(store, stack.key, options.maxBytes); + if (text === null) throw new StackStateMissingError(stack.key); + return parseCheckpoint(text, stack.ref, { + source: 'current', + versionId: stack.version, + sizeBytes: Buffer.byteLength(text), + }); + } + + async listUpdates( + store: ObjectStore, + root: string, + stack: EngineStack, + options: { limit: number; maxBytes: number }, + ): Promise { + const dir = pulumiPaths(root, stack).history; + const { objects } = await listAll(store, dir, { + delimiter: '/', + maxObjects: MAX_HISTORY_OBJECTS, + }); + const entries = new Map(); + for (const object of objects) { + const file = object.key.slice(dir.length); + // `-.…`: the stack name may itself contain `-` + if (!file.startsWith(`${stack.ref.stack}-`)) continue; + const match = file.match(HISTORY_FILE); + if (!match) continue; + const entry = entries.get(match[1]) ?? { checkpoint: false }; + if (match[2] === 'history') entry.history = object.key; + else entry.checkpoint = true; + entries.set(match[1], entry); + } + const ids = [...entries.entries()] + .filter(([, entry]) => entry.history) + // unixnano ids have the same length for centuries: compare as numbers anyway + .sort(([a], [b]) => (BigInt(b) > BigInt(a) ? 1 : BigInt(b) < BigInt(a) ? -1 : 0)) + .slice(0, options.limit); + + const updates: IacUpdate[] = []; + for (let i = 0; i < ids.length; i += READ_CONCURRENCY) { + const batch = await Promise.all( + ids.slice(i, i + READ_CONCURRENCY).map(async ([id, entry]) => { + const text = await readText(store, entry.history!, options.maxBytes); + return text === null ? null : parseHistory(text, id, entry.checkpoint); + }), + ); + updates.push(...batch.filter((update): update is IacUpdate => update !== null)); + } + return updates; + } + + async readLock(store: ObjectStore, root: string, stack: EngineStack): Promise { + const page = await store.list(pulumiPaths(root, stack).locks, { delimiter: '/', maxKeys: 10 }); + const lock = page.objects.find((object) => object.key.endsWith('.json')); + if (!lock) return null; + // only when it was taken: who holds it (user, host, pid) is not exposed + const text = await readText(store, lock.key, 64 * 1024).catch(() => null); + let since: string | null = lock.updatedAt; + try { + const parsed = text ? (JSON.parse(text) as { timestamp?: unknown }) : null; + if (typeof parsed?.timestamp === 'string') since = parsed.timestamp; + } catch { + // a lock we can't read is still a lock + } + return { since }; + } +} + +export class StackStateMissingError extends Error { + constructor(key: string) { + super(`State object disappeared: ${key}`); + this.name = 'StackStateMissingError'; + } +} diff --git a/src/modules/state-iac/infrastructure/engines/pulumi/pulumi-state.ts b/src/modules/state-iac/infrastructure/engines/pulumi/pulumi-state.ts new file mode 100644 index 00000000..dcdfbef3 --- /dev/null +++ b/src/modules/state-iac/infrastructure/engines/pulumi/pulumi-state.ts @@ -0,0 +1,280 @@ +import type { + IacResource, + IacSnapshot, + IacStackRef, + IacUpdate, + IacUpdateKind, + IacValue, +} from '../../../domain/iac.model'; + +/** + * Pulumi checkpoint (`version: 3`) and history entry → normalized model. Secret values are + * replaced by `{ $iac: 'secret' }` while walking the JSON, so neither ciphertexts nor + * `secrets_providers` ever leave this file. Format notes: docs/adr/0003-state-iac.md. + */ + +/** Pulumi tags special values with this key (`sig.Key`). */ +const SIG_KEY = '4dabf18193072939515e22adb298388d'; +const SIG_SECRET = '1b47061264138c4ac30d75fd1eb44270'; +const SIG_RESOURCE_REF = '5cf8f73096256a8f31e491e813e4eb8e'; +const SIG_ASSET = 'c44067f5952c0a294b673a41bacd8c17'; +const SIG_ARCHIVE = '0def7320c3a5731c473e5ecbe6d01bc7'; +const SIG_OUTPUT = 'd0e6a833031e9bbcd3f4e8bde6ca49a4'; +/** Unknown values of a preview. */ +const UNKNOWN = '04da6b54-80e4-46f7-96ec-b56ff0331ba9'; + +export const MAX_CHECKPOINT_VERSION = 3; + +export class UnsupportedStateVersionError extends Error { + constructor(readonly version: number) { + super(`Pulumi checkpoint version ${version} is not supported`); + this.name = 'UnsupportedStateVersionError'; + } +} + +export class InvalidStateError extends Error { + constructor(message = 'The state file is not valid JSON') { + super(message); + this.name = 'InvalidStateError'; + } +} + +type Json = null | boolean | number | string | Json[] | { [key: string]: Json }; + +const isObject = (value: unknown): value is Record => + Boolean(value) && typeof value === 'object' && !Array.isArray(value); + +/** Internal keys of the providers (bridge private state, raw deltas): noise for people. */ +const isInternalKey = (key: string) => key.startsWith('__'); + +/** Pulumi value → `IacValue`, masking every secret. */ +export function normalizeValue(value: unknown): IacValue { + if (value === UNKNOWN) return { $iac: 'unknown' }; + if (Array.isArray(value)) return value.map((item) => normalizeValue(item)); + if (!isObject(value)) { + return typeof value === 'string' || + typeof value === 'number' || + typeof value === 'boolean' || + value === null + ? value + : null; + } + + const sig = value[SIG_KEY]; + if (sig !== undefined) { + switch (sig) { + case SIG_RESOURCE_REF: + return { + $iac: 'resource-ref', + address: typeof value.urn === 'string' ? value.urn : '', + ...(typeof value.id === 'string' && value.id ? { id: value.id } : {}), + }; + case SIG_ASSET: + return { $iac: 'asset', summary: summaryOf(value, ['path', 'uri', 'hash']) }; + case SIG_ARCHIVE: + return { $iac: 'archive', summary: summaryOf(value, ['path', 'uri', 'hash']) }; + case SIG_OUTPUT: + if (value.secret === true) return { $iac: 'secret' }; + return 'value' in value ? normalizeValue(value.value) : { $iac: 'unknown' }; + // SIG_SECRET and any signature we don't know: never show what is inside + case SIG_SECRET: + default: + return { $iac: 'secret' }; + } + } + // defensive: an encrypted value without its signature is still a secret + if ('ciphertext' in value) return { $iac: 'secret' }; + + const out: Record = {}; + for (const [key, item] of Object.entries(value)) { + if (!isInternalKey(key)) out[key] = normalizeValue(item); + } + return out; +} + +function summaryOf(value: Record, keys: string[]): string { + for (const key of keys) { + const item = value[key]; + if (typeof item === 'string' && item) + return key === 'hash' ? `sha256:${item.slice(0, 12)}` : item; + } + return ''; +} + +function normalizeMap(value: unknown): Record { + const normalized = normalizeValue(value ?? {}); + return isObject(normalized) && !('$iac' in normalized) + ? (normalized as Record) + : {}; +} + +/** `urn:pulumi:prod::proj::parent$type::name` → `name`. */ +export function nameFromUrn(urn: string): string { + const index = urn.lastIndexOf('::'); + return index >= 0 ? urn.slice(index + 2) : urn; +} + +/** Package of a type: `gcp:storage/bucket:Bucket` → `gcp`, `pulumi:providers:aws` → `aws`. */ +export function packageOf(type: string): string | null { + if (type.startsWith('pulumi:providers:')) return type.slice('pulumi:providers:'.length) || null; + if (type.startsWith('pulumi:')) return null; + const pkg = type.split(':')[0]; + return pkg || null; +} + +const STACK_TYPE = 'pulumi:pulumi:Stack'; + +function toResource(raw: Record): IacResource { + const urn = typeof raw.urn === 'string' ? raw.urn : ''; + const type = typeof raw.type === 'string' ? raw.type : ''; + const managed = raw.custom === true; + const provider = + typeof raw.provider === 'string' && raw.provider + ? raw.provider.split('::').slice(0, -1).join('::') || raw.provider + : null; + const dependencies = Array.isArray(raw.dependencies) + ? [...new Set(raw.dependencies.filter((d): d is string => typeof d === 'string'))].sort() + : []; + const text = (value: Json | undefined) => (typeof value === 'string' && value ? value : null); + return { + address: urn, + type, + name: nameFromUrn(urn), + parent: text(raw.parent), + provider, + providerType: managed || type.startsWith('pulumi:providers:') ? packageOf(type) : null, + externalId: text(raw.id), + managed, + flags: { + protect: raw.protect === true, + retainOnDelete: raw.retainOnDelete === true, + external: raw.external === true, + pendingReplacement: raw.pendingReplacement === true, + pendingDelete: raw.delete === true, + }, + inputs: normalizeMap(raw.inputs), + outputs: normalizeMap(raw.outputs), + dependencies, + createdAt: text(raw.created), + modifiedAt: text(raw.modified), + }; +} + +export type SnapshotMeta = { + source: IacSnapshot['source']; + versionId: string | null; + sizeBytes: number; +}; + +/** Parses a checkpoint file (`stacks/…json`, `history/…checkpoint.json`, `backups/…`). */ +export function parseCheckpoint(text: string, ref: IacStackRef, meta: SnapshotMeta): IacSnapshot { + let json: unknown; + try { + json = JSON.parse(text); + } catch { + throw new InvalidStateError(); + } + if (!isObject(json)) throw new InvalidStateError('The state file is not an object'); + const version = typeof json.version === 'number' ? json.version : 0; + if (version > MAX_CHECKPOINT_VERSION) throw new UnsupportedStateVersionError(version); + + const latest = + isObject(json.checkpoint) && isObject(json.checkpoint.latest) ? json.checkpoint.latest : {}; + const manifest = isObject(latest.manifest) ? latest.manifest : {}; + const rawResources = Array.isArray(latest.resources) ? latest.resources.filter(isObject) : []; + const resources = rawResources.map(toResource); + const stack = resources.find((resource) => resource.type === STACK_TYPE && !resource.parent); + // `secrets_providers` (salt, KMS key) is deliberately never read + return { + ref, + source: meta.source, + versionId: meta.versionId, + takenAt: typeof manifest.time === 'string' ? manifest.time : null, + toolVersion: typeof manifest.version === 'string' ? manifest.version : null, + resources, + outputs: stack ? stack.outputs : {}, + pendingOperations: Array.isArray(latest.pending_operations) + ? latest.pending_operations.length + : 0, + sizeBytes: meta.sizeBytes, + }; +} + +const KINDS: Record = { + update: 'update', + refresh: 'refresh', + destroy: 'destroy', + import: 'import', + 'resource-import': 'import', + rename: 'rename', +}; + +/** Config values: `{ secure: 'v1:…' }` is a secret config value. */ +function normalizeConfig(value: unknown): IacValue { + if (Array.isArray(value)) return value.map(normalizeConfig); + if (isObject(value)) { + if ('secure' in value) return { $iac: 'secret' }; + const out: Record = {}; + for (const [key, item] of Object.entries(value)) out[key] = normalizeConfig(item); + return out; + } + return normalizeValue(value); +} + +const seconds = (value: Json | undefined) => + typeof value === 'number' && value > 0 ? new Date(value * 1000).toISOString() : null; + +/** + * Parses a `*.history.json`. Only an allow-list of `environment` leaves this function: no emails, + * no local paths, no hostnames. + */ +export function parseHistory(text: string, id: string, snapshotAvailable: boolean): IacUpdate { + let json: unknown; + try { + json = JSON.parse(text); + } catch { + throw new InvalidStateError('The history entry is not valid JSON'); + } + if (!isObject(json)) throw new InvalidStateError('The history entry is not an object'); + const env = isObject(json.environment) ? json.environment : {}; + const envText = (key: string) => + typeof env[key] === 'string' && env[key] ? (env[key] as string) : null; + const result = json.result; + const changes: IacUpdate['changes'] = {}; + if (isObject(json.resourceChanges)) { + for (const [key, count] of Object.entries(json.resourceChanges)) { + if ( + typeof count === 'number' && + ['create', 'update', 'delete', 'replace', 'same', 'import'].includes(key) + ) { + changes[key as keyof IacUpdate['changes']] = count; + } + } + } + const dirty = envText('git.dirty'); + return { + id, + kind: KINDS[String(json.kind)] ?? 'other', + result: + result === 'succeeded' || result === 'failed' || result === 'in-progress' + ? result + : 'unknown', + startedAt: seconds(json.startTime), + endedAt: seconds(json.endTime), + message: typeof json.message === 'string' ? json.message : '', + changes, + toolVersion: envText('pulumi.version'), + vcs: { + kind: envText('vcs.kind'), + owner: envText('vcs.owner'), + repo: envText('vcs.repo'), + commit: envText('git.head'), + branch: envText('git.headName')?.replace(/^refs\/heads\//, '') ?? null, + dirty: dirty === null ? null : dirty === 'true', + author: envText('git.author'), + }, + execKind: envText('exec.kind'), + config: isObject(json.config) ? (normalizeConfig(json.config) as Record) : {}, + snapshotAvailable, + }; +} diff --git a/src/modules/state-iac/infrastructure/engines/state-engine.ts b/src/modules/state-iac/infrastructure/engines/state-engine.ts new file mode 100644 index 00000000..f957f13a --- /dev/null +++ b/src/modules/state-iac/infrastructure/engines/state-engine.ts @@ -0,0 +1,45 @@ +import type { IacLock, IacSnapshot, IacStackRef, IacUpdate } from '../../domain/iac.model'; +import type { ObjectStore } from '../object-store/object-store'; + +/** A stack found in a backend, with what is needed to read it and to cache it. */ +export type EngineStack = { + ref: IacStackRef; + /** Object key of its current state. */ + key: string; + size: number; + updatedAt: string | null; + /** ETag / generation of the state object. */ + version: string | null; +}; + +export type EngineDiscovery = { + layout: 'project' | 'legacy' | 'empty'; + metaVersion: number | null; + stacks: EngineStack[]; + truncated: boolean; +}; + +/** + * Reads one IaC tool's layout and translates it into the normalized model. Pulumi is the only + * engine in v1; a Terraform one implements the same interface (`listUpdates` from object + * versions, as Terraform keeps no history). Engines only read. + */ +export interface StateEngine { + readonly kind: IacStackRef['engine']; + /** `root` is the backend's bookkeeping prefix (`/.pulumi/`). */ + discoverStacks(store: ObjectStore, root: string, backendId: string): Promise; + readSnapshot( + store: ObjectStore, + root: string, + stack: EngineStack, + options: { maxBytes: number }, + ): Promise; + /** Most recent first. */ + listUpdates( + store: ObjectStore, + root: string, + stack: EngineStack, + options: { limit: number; maxBytes: number }, + ): Promise; + readLock(store: ObjectStore, root: string, stack: EngineStack): Promise; +} diff --git a/src/routes/+layout.server.ts b/src/routes/+layout.server.ts index 6334e6b1..bddfb84b 100644 --- a/src/routes/+layout.server.ts +++ b/src/routes/+layout.server.ts @@ -61,6 +61,7 @@ export async function load({ locals, url }) { canReadOrgEvents, canReadOrganizationAlerts, canReadOrgStateIac, + canReadOrgStateIacStacks, ] = await Promise.all([ orgSectionPermission('organization:projects:read'), orgSectionPermission('organization:users:read'), @@ -72,6 +73,7 @@ export async function load({ locals, url }) { orgSectionPermission('organization:events:read'), orgSectionPermission('organization:alerts:read'), orgSectionPermission('organization:stateiac:backends:read'), + orgSectionPermission('organization:stateiac:stacks:read'), ]); const currentProjectSlug = url.pathname.match(/\/projects\/([^/]+)/)?.[1] ?? null; @@ -180,6 +182,7 @@ export async function load({ locals, url }) { canReadOrgEvents, canReadOrganizationAlerts, canReadOrgStateIac, + canReadOrgStateIacStacks, canReadProjectInfo, canReadProjectUsers, canReadProjectRoles, diff --git a/src/routes/api/state-iac/stacks/+server.ts b/src/routes/api/state-iac/stacks/+server.ts new file mode 100644 index 00000000..ca4f8afe --- /dev/null +++ b/src/routes/api/state-iac/stacks/+server.ts @@ -0,0 +1,17 @@ +import { json } from '@sveltejs/kit'; +import { toResponse } from '#lib/server/alerts/http'; +import { listStacks, resolveStackScope } from '#lib/server/state-iac/stacks'; + +// GET /api/state-iac/stacks?projectId=…|organizationId=…[&refresh=1]: from a project, only the +// stacks assigned to it (`project:stateiac:stacks:read`); from the organization, all of them +// (`organization:stateiac:stacks:read`). Backends that can't be read come back with their `error` +export async function GET({ url, locals }) { + const scope = await resolveStackScope({ + projectId: url.searchParams.get('projectId'), + organizationId: url.searchParams.get('organizationId'), + }); + if (!scope.ok) return json({ error: scope.error }, { status: scope.status }); + return toResponse( + await listStacks(locals, scope.data, { refresh: url.searchParams.get('refresh') === '1' }), + ); +} diff --git a/src/routes/api/state-iac/stacks/[backend]/[pulumiProject]/[stack]/+server.ts b/src/routes/api/state-iac/stacks/[backend]/[pulumiProject]/[stack]/+server.ts new file mode 100644 index 00000000..717ec795 --- /dev/null +++ b/src/routes/api/state-iac/stacks/[backend]/[pulumiProject]/[stack]/+server.ts @@ -0,0 +1,24 @@ +import { json } from '@sveltejs/kit'; +import { toResponse } from '#lib/server/alerts/http'; +import { getStack, parseInclude, resolveStackScope } from '#lib/server/state-iac/stacks'; + +// GET /api/state-iac/stacks///?projectId=…|organizationId=… +// [&include=resources,outputs][&refresh=1]. `~` is the project of a legacy stack without +// resources. Secret values come back as { "$iac": "secret" }; a stack not assigned to the project +// answers 404. Resources and outputs need `project:stateiac:states:read` in a project +export async function GET({ params, url, locals }) { + const scope = await resolveStackScope({ + projectId: url.searchParams.get('projectId'), + organizationId: url.searchParams.get('organizationId'), + }); + if (!scope.ok) return json({ error: scope.error }, { status: scope.status }); + return toResponse( + await getStack( + locals, + scope.data, + { backendId: params.backend, project: params.pulumiProject, stack: params.stack }, + parseInclude(url.searchParams.get('include')), + { refresh: url.searchParams.get('refresh') === '1' }, + ), + ); +} diff --git a/src/routes/api/state-iac/stacks/server.test.ts b/src/routes/api/state-iac/stacks/server.test.ts new file mode 100644 index 00000000..a25bf3d7 --- /dev/null +++ b/src/routes/api/state-iac/stacks/server.test.ts @@ -0,0 +1,181 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +// grants per caller (`user:` / `key:`) and context key (`org:` / `project:`) +const grants: Record> = {}; +const keyProjects: Record = {}; + +const contextKey = (context: { scope: string; organizationId?: string; projectId?: string }) => + context.scope === 'project' ? `project:${context.projectId}` : `org:${context.organizationId}`; + +vi.mock('#modules/auth', () => ({ + cancanService: { + canSessionUser: async (user: { id?: string } | null, permission: string, context: never) => + (grants[`user:${user?.id}`]?.[contextKey(context)] ?? []).includes(permission), + canApiKey: ( + key: { id: string }, + permission: string, + context: { scope: string; projectId?: string }, + ) => { + const own = keyProjects[key.id]; + if (own && (context.scope !== 'project' || context.projectId !== own)) return false; + return (grants[`key:${key.id}`]?.[contextKey(context as never)] ?? []).includes(permission); + }, + }, +})); + +vi.mock('#modules/organization', () => ({ + organizationService: { + getOrganization: async (id: string) => (id === 'org-1' ? { id, name: id, slug: id } : null), + }, +})); + +vi.mock('#modules/projects', () => ({ + projectService: { + getProject: async (id: string) => + ['p1', 'p2'].includes(id) ? { id, organization: { id: 'org-1' } } : null, + }, +})); + +vi.mock('#modules/state-iac', async () => { + const { createStateIacFixture } = await import('#modules/state-iac/application/testing'); + const fixture = createStateIacFixture(); + return { stateIacService: fixture.stateIacService, fixture }; +}); + +const { fixture } = (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 list = await import('./+server'); +const item = await import('./[backend]/[pulumiProject]/[stack]/+server'); + +let backendId = ''; + +function get( + handler: (event: never) => Promise, + query: string, + locals: Record, + params: Record = {}, +) { + return handler({ + locals, + params, + url: new URL(`http://localhost/api/state-iac/stacks?${query}`), + } as never); +} + +const user = (id: string) => ({ user: { id } }); +const stackParams = (project: string, stack: string) => ({ + backend: backendId, + pulumiProject: project, + stack, +}); + +describe('/api/state-iac/stacks', () => { + beforeEach(async () => { + fixture.backends.rows = []; + fixture.bindings.rows = []; + const backend = await fixture.backendService.create('org-1', { + name: 'shared', + provider: 'gcs', + bucket: 'shared-state', + }); + backendId = backend.id; + fixture.buckets.set('shared-state', fixtureStore('project-layout')); + await fixture.bindingService.set(backend, 'acme-infra', { projectId: 'p1' }); + await fixture.bindingService.set(backend, 'acme-platform', { projectId: 'p2' }); + for (const key of Object.keys(grants)) delete grants[key]; + grants['user:a'] = { + 'project:p1': ['project:stateiac:stacks:read', 'project:stateiac:states:read'], + }; + grants['user:listOnly'] = { 'project:p1': ['project:stateiac:stacks:read'] }; + grants['user:org'] = { 'org:org-1': ['organization:stateiac:stacks:read'] }; + grants['key:k1'] = { 'project:p1': ['project:stateiac:stacks:read'] }; + keyProjects.k1 = 'p1'; + }); + + it('a project lists only its stacks', async () => { + const response = await get(list.GET, 'projectId=p1', user('a')); + expect(response.status).toBe(200); + const { backends } = await response.json(); + expect(backends[0].stacks.map((s: { ref: { stack: string } }) => s.ref.stack)).toEqual([ + 'prod', + 'staging', + ]); + }); + + it("another project's stack answers 404, also with a resource-level grant", async () => { + for (const [project, stack] of [ + ['acme-platform', 'dev'], + ['acme-infra', 'missing'], + ]) { + const response = await get(item.GET, 'projectId=p1', user('a'), stackParams(project, stack)); + expect(response.status).toBe(404); + } + // without stacks:read in the project it does not even exist + const hidden = await get( + item.GET, + 'projectId=p2', + user('a'), + stackParams('acme-platform', 'dev'), + ); + expect(hidden.status).toBe(404); + }); + + it('resources and outputs need states:read; secrets come back masked', async () => { + const forbidden = await get( + item.GET, + 'projectId=p1&include=resources', + user('listOnly'), + stackParams('acme-infra', 'prod'), + ); + expect(forbidden.status).toBe(403); + const summary = await get( + item.GET, + 'projectId=p1', + user('listOnly'), + stackParams('acme-infra', 'prod'), + ); + expect(summary.status).toBe(200); + expect(await summary.json()).not.toHaveProperty('resources'); + + const full = await get( + item.GET, + 'projectId=p1&include=resources,outputs', + user('a'), + stackParams('acme-infra', 'prod'), + ); + const text = await full.text(); + expect(JSON.parse(text).resources).toHaveLength(49); + expect(text).toContain('{"$iac":"secret"}'); + expect(text).not.toMatch(/ciphertext|secrets_providers/); + }); + + it('the organization view needs organization:stateiac:stacks:read', async () => { + expect((await get(list.GET, 'organizationId=org-1', user('a'))).status).toBe(403); + const response = await get(list.GET, 'organizationId=org-1', user('org')); + const { backends } = await response.json(); + expect(backends[0].stacks).toHaveLength(3); + const detail = await get( + item.GET, + 'organizationId=org-1&include=outputs', + user('org'), + stackParams('acme-infra', 'staging'), + ); + expect(detail.status).toBe(200); + }); + + it('a project API key stays in its project', async () => { + const apiKey = { apiKey: { id: 'k1', projectId: 'p1', userId: null, role: null } }; + expect((await get(list.GET, 'projectId=p1', apiKey)).status).toBe(200); + expect((await get(list.GET, 'projectId=p2', apiKey)).status).toBe(403); + expect((await get(list.GET, 'organizationId=org-1', apiKey)).status).toBe(403); + }); + + it('requires a scope', async () => { + expect((await get(list.GET, '', user('a'))).status).toBe(400); + expect((await get(list.GET, 'projectId=nope', user('a'))).status).toBe(404); + }); +}); diff --git a/src/routes/org/[org]/projects/[slug]/state-iac/+page.server.ts b/src/routes/org/[org]/projects/[slug]/state-iac/+page.server.ts index a383706a..29d899d8 100644 --- a/src/routes/org/[org]/projects/[slug]/state-iac/+page.server.ts +++ b/src/routes/org/[org]/projects/[slug]/state-iac/+page.server.ts @@ -1,37 +1,21 @@ import { error } from '@sveltejs/kit'; -import { cancanService } from '#modules/auth'; -import { projectService } from '#modules/projects'; +import { listStacks, type StackScope } from '#lib/server/state-iac/stacks'; -export async function load({ params, locals }) { - let project; - try { - project = await projectService.getProjectBySlug(params.slug); - } catch { - throw error(404, 'Project not found'); - } - - const organizationId = project.organization?.id; - const [canReadStacks, canReadStates, canReadHistory] = await Promise.all([ - cancanService.canSessionUser(locals.user, 'project:stateiac:stacks:read', { - scope: 'project', - projectId: project.id, - organizationId, - }), - cancanService.canSessionUser(locals.user, 'project:stateiac:states:read', { - scope: 'project', - projectId: project.id, - organizationId, - }), - cancanService.canSessionUser(locals.user, 'project:stateiac:history:read', { - scope: 'project', - projectId: project.id, - organizationId, - }), - ]); - - if (!canReadStacks && !canReadStates && !canReadHistory) { - throw error(403, 'Forbidden'); - } - - return {}; +export async function load({ parent, locals, params, url }) { + const { project } = await parent(); + const scope: StackScope = { + scope: 'project', + projectId: project.id, + organizationId: project.organization?.id ?? '', + }; + // only the stacks assigned to this project (`project:stateiac:stacks:read`) + const result = await listStacks(locals, scope, { + refresh: url.searchParams.get('refresh') === '1', + }); + if (!result.ok) throw error(result.status, result.error); + return { + groups: result.data.backends, + base: `/org/${params.org}/projects/${params.slug}/state-iac`, + organizationSettingsHref: `/org/${params.org}/settings/state-iac`, + }; } diff --git a/src/routes/org/[org]/projects/[slug]/state-iac/+page.svelte b/src/routes/org/[org]/projects/[slug]/state-iac/+page.svelte index f51009bf..9e608d97 100644 --- a/src/routes/org/[org]/projects/[slug]/state-iac/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/state-iac/+page.svelte @@ -1,58 +1,39 @@ - {$_('project.stateIac.title')} - GitOps + {$_('project.stateIac.title')} - {data.project.name}
-
-
-
-
-

GitOps

-

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

-

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

-
- - - {$_('common.comingSoon')} - -
-
- -
-
- -

{$_('project.stateIac.stacks')}

-

{$_('project.stateIac.stacksDescription')}

-
-
- -

{$_('project.stateIac.storageBackends')}

-

{$_('project.stateIac.storageBackendsDescription')}

-
-
- -

{$_('project.stateIac.history')}

-

{$_('project.stateIac.historyDescription')}

-
-
-
+
+

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

+

{$_('stateIac.stacks.projectDescription')}

+
-
-
- + {#if data.groups.length === 0} +
+ +

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

+

+ {$_('stateIac.stacks.emptyDescription')} +

-

{$_('project.stateIac.workingTitle')}

-

{$_('project.stateIac.workingDescription')}

-
+ {:else} + + {/if}
diff --git a/src/routes/org/[org]/projects/[slug]/state-iac/[backend]/[pulumiProject]/[stack]/+page.server.ts b/src/routes/org/[org]/projects/[slug]/state-iac/[backend]/[pulumiProject]/[stack]/+page.server.ts new file mode 100644 index 00000000..bb6d4981 --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/state-iac/[backend]/[pulumiProject]/[stack]/+page.server.ts @@ -0,0 +1,27 @@ +import { error } from '@sveltejs/kit'; +import { canReadStates, getStack, type StackScope } from '#lib/server/state-iac/stacks'; + +export async function load({ parent, locals, params, url }) { + const { project } = await parent(); + const scope: StackScope = { + scope: 'project', + projectId: project.id, + organizationId: project.organization?.id ?? '', + }; + // resources and outputs need `project:stateiac:states:read`; the summary only `stacks:read` + const states = await canReadStates(locals, scope); + const result = await getStack( + locals, + scope, + { backendId: params.backend, project: params.pulumiProject, stack: params.stack }, + states ? ['resources', 'outputs'] : [], + { refresh: url.searchParams.get('refresh') === '1' }, + ); + // a stack that is not assigned to this project is indistinguishable from a missing one + if (!result.ok) throw error(result.status, result.error); + return { + detail: result.data, + canReadStates: states, + backHref: `/org/${params.org}/projects/${params.slug}/state-iac`, + }; +} diff --git a/src/routes/org/[org]/projects/[slug]/state-iac/[backend]/[pulumiProject]/[stack]/+page.svelte b/src/routes/org/[org]/projects/[slug]/state-iac/[backend]/[pulumiProject]/[stack]/+page.svelte new file mode 100644 index 00000000..ff933363 --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/state-iac/[backend]/[pulumiProject]/[stack]/+page.svelte @@ -0,0 +1,20 @@ + + + + {data.detail.summary.ref.stack} · State IaC - {data.project.name} + + + diff --git a/src/routes/org/[org]/state-iac/+page.server.ts b/src/routes/org/[org]/state-iac/+page.server.ts new file mode 100644 index 00000000..afb12342 --- /dev/null +++ b/src/routes/org/[org]/state-iac/+page.server.ts @@ -0,0 +1,23 @@ +import { error } from '@sveltejs/kit'; +import { projectService } from '#modules/projects'; +import { listStacks } from '#lib/server/state-iac/stacks'; + +// every stack of the organization's backends, assigned or not (`organization:stateiac:stacks:read`) +export async function load({ parent, locals, params, url }) { + const { organization } = await parent(); + const result = await listStacks( + locals, + { scope: 'organization', organizationId: organization.id }, + { refresh: url.searchParams.get('refresh') === '1' }, + ); + if (!result.ok) throw error(result.status, result.error); + const projects = await projectService.listProjectsByOrganization(organization.id); + return { + groups: result.data.backends, + base: `/org/${params.org}/state-iac`, + projectNames: Object.fromEntries( + projects.map((project: { id: string; name: string }) => [project.id, project.name]), + ) as Record, + settingsHref: `/org/${params.org}/settings/state-iac`, + }; +} diff --git a/src/routes/org/[org]/state-iac/+page.svelte b/src/routes/org/[org]/state-iac/+page.svelte new file mode 100644 index 00000000..e860b856 --- /dev/null +++ b/src/routes/org/[org]/state-iac/+page.svelte @@ -0,0 +1,48 @@ + + + + {$_('stateIac.stacks.organizationTitle')} · GitOps + + +
+
+
+

{$_('stateIac.stacks.organizationTitle')}

+

+ {$_('stateIac.stacks.organizationDescription')} +

+
+ {#if data.canReadOrgStateIac} + + + {$_('stateIac.stacks.manageBackends')} + + {/if} +
+ + {#if data.groups.length === 0} +
+ +

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

+

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

+
+ {:else} + + {/if} +
diff --git a/src/routes/org/[org]/state-iac/[backend]/[pulumiProject]/[stack]/+page.server.ts b/src/routes/org/[org]/state-iac/[backend]/[pulumiProject]/[stack]/+page.server.ts new file mode 100644 index 00000000..8c5fc356 --- /dev/null +++ b/src/routes/org/[org]/state-iac/[backend]/[pulumiProject]/[stack]/+page.server.ts @@ -0,0 +1,22 @@ +import { error } from '@sveltejs/kit'; +import { projectService } from '#modules/projects'; +import { getStack } from '#lib/server/state-iac/stacks'; + +export async function load({ parent, locals, params, url }) { + const { organization } = await parent(); + const result = await getStack( + locals, + { scope: 'organization', organizationId: organization.id }, + { backendId: params.backend, project: params.pulumiProject, stack: params.stack }, + ['resources', 'outputs'], + { refresh: url.searchParams.get('refresh') === '1' }, + ); + if (!result.ok) throw error(result.status, result.error); + const assigned = result.data.summary.assignedProjectId; + const project = assigned ? await projectService.getProject(assigned).catch(() => null) : null; + return { + detail: result.data, + projectName: project?.name ?? null, + backHref: `/org/${params.org}/state-iac`, + }; +} diff --git a/src/routes/org/[org]/state-iac/[backend]/[pulumiProject]/[stack]/+page.svelte b/src/routes/org/[org]/state-iac/[backend]/[pulumiProject]/[stack]/+page.svelte new file mode 100644 index 00000000..57ba717c --- /dev/null +++ b/src/routes/org/[org]/state-iac/[backend]/[pulumiProject]/[stack]/+page.svelte @@ -0,0 +1,18 @@ + + + + {data.detail.summary.ref.stack} · State IaC · GitOps + + +