diff --git a/CLAUDE.md b/CLAUDE.md index 5ccfb4a..9553910 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -219,6 +219,13 @@ for `STATE_IAC_CACHE_SECONDS` and states by object version, so an unchanged stat `?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). +History and diff: `stateIacService.history()` pages `*.history.json` (`project:stateiac:history:read`); +`diff()` compares two snapshot sources (`current`, `history:`, `backup:`, `retained:`, +`previous`, `version:` from `ObjectStore.listVersions`) with `diffSnapshots()` in +`application/state-diff.service.ts` (`project:stateiac:states:read`), by default the last update +against the one before. Two secrets always compare equal (Pulumi re-encrypts them on every write); +provider-only changes are flagged `providerOnly`. Past sources are cached for good, the current one +by object version. Periodic scans and `state_iac.stack.*` events are not built (ADR 0003, deferred). ## Domain events diff --git a/e2e/specs/state-iac-stacks.spec.ts b/e2e/specs/state-iac-stacks.spec.ts index 7f38d0a..cfd3172 100644 --- a/e2e/specs/state-iac-stacks.spec.ts +++ b/e2e/specs/state-iac-stacks.spec.ts @@ -142,3 +142,60 @@ test.describe('state iac stacks — organization view', () => { await expectDenied(page, `/org/${org}/state-iac`); }); }); + +test.describe('state iac stacks — history and changes', () => { + test('the history lists the updates and opens what changed in one', async ({ page, loginAs }) => { + await loginAs('projectAdmin'); + await expectAllowed(page, `${projectA}/${backend}/acme-infra/prod`); + await page.waitForLoadState('networkidle'); + const tabs = page.getByRole('tablist', { name: 'Contenido del stack' }); + + await tabs.getByRole('tab', { name: 'Historial' }).click(); + const history = page.getByTestId('stack-history'); + await expect(history.locator('li[data-update-id]')).toHaveCount(4); + await expect(history.locator('li[data-update-id="1789061079158069310"]')).toContainText( + 'fallido', + ); + // allow-listed environment: commit and author, never the email + await expect(history).toContainText('Jane Doe'); + await expect(history).not.toContainText('jane@example.com'); + + await history + .locator('li[data-update-id="1795604216162649000"]') + .getByRole('button', { name: 'Ver cambios' }) + .click(); + const diff = page.getByTestId('stack-diff'); + await expect(diff.getByTestId('diff-summary')).toContainText('Cambios 2'); + const sql = diff.locator('li[data-resource="cloud-sql-acme-prod"]'); + await expect(sql).toHaveAttribute('data-change', 'update'); + await sql.getByRole('button').first().click(); + await expect(sql).toContainText('inputs.publicIp'); + }); + + test('a replace between two chosen versions', async ({ page, loginAs }) => { + await loginAs('projectAdmin'); + await expectAllowed(page, `${projectA}/${backend}/acme-infra/prod`); + await page.waitForLoadState('networkidle'); + await page + .getByRole('tablist', { name: 'Contenido del stack' }) + .getByRole('tab', { name: 'Cambios' }) + .click(); + const diff = page.getByTestId('stack-diff'); + await expect(diff.getByTestId('diff-summary')).toBeVisible(); + await diff.getByLabel('Hasta').selectOption('history:1795602803296701000'); + await expect(diff.locator('li[data-resource="lb-prod-cert"]')).toHaveAttribute( + 'data-change', + 'replace', + ); + }); + + test('without history:read nor states:read there is no history nor diff', async ({ + page, + loginAs, + }) => { + await loginAs('stateiacStacksOnly'); + await expectAllowed(page, `${projectA}/${backend}/acme-infra/prod`); + await expect(page.getByRole('tab', { name: 'Historial' })).toHaveCount(0); + await expect(page.getByRole('tab', { name: 'Cambios' })).toHaveCount(0); + }); +}); diff --git a/src/lib/components/state-iac/StackDetail.svelte b/src/lib/components/state-iac/StackDetail.svelte index d863519..20b7916 100644 --- a/src/lib/components/state-iac/StackDetail.svelte +++ b/src/lib/components/state-iac/StackDetail.svelte @@ -9,22 +9,45 @@ import { Drawer, Tabs } from '#lib/components/ui'; import { _ } from '#lib/i18n'; import type { IacResourceView, StackDetailView } from '#lib/state-iac/types'; + import { untrack } from 'svelte'; import IacValue from './IacValue.svelte'; + import StackDiff from './StackDiff.svelte'; + import StackHistory from './StackHistory.svelte'; type Props = { detail: StackDetailView; /** Sin `project:stateiac:states:read` solo se ve el resumen. */ canReadStates: boolean; + /** Historial de updates (`project:stateiac:history:read`). */ + canReadHistory?: boolean; backHref: string; projectName?: string | null; + /** `/api/state-iac/stacks///` y `projectId=…|organizationId=…` */ + apiBase: string; + scopeQuery: string; }; - let { detail, canReadStates, backHref, projectName = null }: Props = $props(); + let { + detail, + canReadStates, + canReadHistory = false, + backHref, + projectName = null, + apiBase, + scopeQuery, + }: Props = $props(); const STACK_TYPE = 'pulumi:pulumi:Stack'; const resources = $derived(detail.resources ?? []); const byAddress = $derived(new Map(resources.map((r) => [r.address, r]))); - let tab = $state('resources'); + let tab = $state(untrack(() => (canReadStates ? 'resources' : 'history'))); + /** Version picked in the history for the changes tab. */ + let changesTo = $state(null); + + function showChanges(updateId: string) { + changesTo = `history:${updateId}`; + tab = 'changes'; + } let query = $state(''); let typeFilter = $state(''); let providerFilter = $state(''); @@ -81,6 +104,18 @@ }); const outputs = $derived(Object.entries(detail.outputs ?? {})); + // what this viewer may open: resources/outputs/changes need states:read, the history its own grant + const tabs = $derived([ + ...(canReadStates + ? [ + { value: 'resources', label: $_('stateIac.stacks.resources'), count: resources.length }, + { value: 'outputs', label: $_('stateIac.detail.outputs'), count: outputs.length }, + ] + : []), + ...(canReadHistory ? [{ value: 'history', label: $_('stateIac.history.title') }] : []), + ...(canReadStates ? [{ value: 'changes', label: $_('stateIac.diff.title') }] : []), + ]); + function select(address: string) { const resource = byAddress.get(address); if (!resource) return; @@ -170,7 +205,7 @@ - {:else if !canReadStates} + {:else if tabs.length === 0}

{:else} - + {#if tab === 'resources'}

{/each} + {:else if tab === 'history'} +
+ +
+ {:else if tab === 'changes'} +
+ +
{:else}
+ + +
+ {#if outcome && outcome.sources.length > 1} +
+ + + {#if loading}{/if} +
+ {/if} + + {#if !outcome && loading} +

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

+ {:else if outcome && !diff} +
+

+ + {onlyCurrent ? $_('stateIac.diff.noSources') : $_('stateIac.diff.unavailable')} +

+ {#if lastChanges && Object.keys(lastChanges).length > 0} +

+ {$_('stateIac.diff.lastUpdateChanges')} + {#each Object.entries(lastChanges) as [key, count] (key)} + {$_(`stateIac.changes.${key}`)} {count} + {/each} +

+ {/if} +
+ {:else if diff} +

+ {#each SUMMARY as key (key)} + + {$_(`stateIac.changes.${key}`)} + {diff.summary[key]} + + {/each} + {$_('stateIac.changes.same')} {diff.summary.same} +

+

+ {$_('stateIac.diff.secretsNotice')} +

+ + {#if changes.length === 0 && providerOnly.length === 0 && diff.outputs.length === 0} +

+ {$_('stateIac.diff.noChanges')} +

+ {/if} + + {#if changes.length > 0} +
    + {#each changes as resource (resource.address)} + {@const expandable = resource.fields.length > 0} +
  • + + {#if open[resource.address]} +
    + + + + + + + + + + {#each resource.fields as field (field.path)} + + + + + + {/each} + +
    {$_('stateIac.diff.property')}{$_('stateIac.diff.before')}{$_('stateIac.diff.after')}
    {field.path} + {#if field.before === undefined}—{:else}{/if} + + {#if field.after === undefined}—{:else}{/if} +
    +
    + {/if} +
  • + {/each} +
+ {/if} + + {#if providerOnly.length > 0} +
+ + {#if showProviderOnly} +
    + {#each providerOnly as resource (resource.address)}
  • {resource.name}
  • {/each} +
+ {/if} +
+ {/if} + + {#if diff.outputs.length > 0} +
+

{$_('stateIac.diff.outputs')}

+ + + {#each diff.outputs as field (field.path)} + + + + + + {/each} + +
{field.path}{#if field.before === undefined}—{:else}{/if}{#if field.after === undefined}—{:else}{/if}
+
+ {/if} + {/if} +
diff --git a/src/lib/components/state-iac/StackHistory.svelte b/src/lib/components/state-iac/StackHistory.svelte new file mode 100644 index 0000000..605af04 --- /dev/null +++ b/src/lib/components/state-iac/StackHistory.svelte @@ -0,0 +1,157 @@ + + + +
+ {#if !loaded && loading} +

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

+ {:else if loaded && updates.length === 0} +

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

+ {:else} +
    + {#each updates as update (update.id)} + {@const took = duration(update.startedAt, update.endedAt)} +
  1. +
    + {#if update.result === 'succeeded'} + {:else if update.result === 'failed'} + {:else}{/if} +
    +

    + {$_(`stateIac.kinds.${update.kind}`)} + + {$_(`stateIac.results.${update.result}`)} + + {#if update.message}{update.message}{/if} +

    +

    + {date(update.startedAt)}{#if took} + · {$_('stateIac.history.took', { values: { duration: took } })}{/if} + {#if update.toolVersion} + · Pulumi {update.toolVersion}{/if} + {#if update.execKind} + · {update.execKind}{/if} +

    + {#if update.vcs.commit || update.vcs.author} +

    + + {#if update.vcs.commit}{update.vcs.commit.slice(0, 8)}{/if} + {#if update.vcs.branch}· {update.vcs.branch}{/if} + {#if update.vcs.owner && update.vcs.repo}· {update.vcs.owner}/{update.vcs.repo}{/if} + {#if update.vcs.dirty}{$_('stateIac.history.dirty')}{/if} + {#if update.vcs.author}· {update.vcs.author}{/if} +

    + {/if} +

    + {#each CHANGE_ORDER.filter((key) => update.changes[key]) as key (key)} + + {$_(`stateIac.changes.${key}`)} + {update.changes[key]} + + {/each} +

    +
    + {#if canDiff && update.snapshotAvailable} + + {/if} +
    +
  2. + {/each} +
+ {#if cursor} + + {/if} + {/if} +
diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index 024982b..1f07195 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -2464,6 +2464,50 @@ "resourceTabs": "Resource data", "inputs": "Inputs", "dependencies": "Dependencies" + }, + "history": { + "title": "History", + "loading": "Reading the history…", + "loadFailed": "The history could not be loaded", + "empty": "This stack has no update history.", + "took": "took {duration}", + "dirty": "uncommitted changes", + "showChanges": "Show changes", + "loadMore": "Load more" + }, + "changes": { + "create": "Created", + "update": "Updated", + "replace": "Replaced", + "delete": "Deleted", + "import": "Imported", + "same": "Unchanged" + }, + "diff": { + "title": "Changes", + "loading": "Comparing versions…", + "loadFailed": "The diff could not be computed", + "from": "From", + "to": "To", + "noSources": "There are no previous versions of this state to compare. Pulumi keeps a copy in the history on every update; if it was deleted, turn on bucket versioning (GCS Object Versioning or S3 Versioning) or PULUMI_RETAIN_CHECKPOINTS.", + "unavailable": "That version is no longer in the bucket.", + "lastUpdateChanges": "According to the last update:", + "secretsNotice": "Secrets are compared without being revealed. Pulumi re-encrypts them on every write, so whether a secret value changed can't be known; only whether a value became or stopped being secret.", + "noChanges": "There are no changes between these two versions.", + "fields": "{count} properties", + "property": "Property", + "before": "Before", + "after": "After", + "providerOnly": "{count} resources only changed provider (version upgrade)", + "outputs": "Stack outputs", + "sources": { + "current": "Current state", + "history": "Update", + "backup": "Backup", + "retained": "Retained checkpoint", + "previous": "Previous state (.bak)", + "object-version": "Object version" + } } } } diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index 8395db4..c2f62d5 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -2464,6 +2464,50 @@ "resourceTabs": "Datos del recurso", "inputs": "Inputs", "dependencies": "Dependencias" + }, + "history": { + "title": "Historial", + "loading": "Leyendo el historial…", + "loadFailed": "No se pudo cargar el historial", + "empty": "Este stack no tiene historial de updates.", + "took": "duró {duration}", + "dirty": "cambios sin commit", + "showChanges": "Ver cambios", + "loadMore": "Cargar más" + }, + "changes": { + "create": "Altas", + "update": "Cambios", + "replace": "Reemplazos", + "delete": "Bajas", + "import": "Importados", + "same": "Sin cambios" + }, + "diff": { + "title": "Cambios", + "loading": "Comparando versiones…", + "loadFailed": "No se pudo calcular el diff", + "from": "Desde", + "to": "Hasta", + "noSources": "No hay versiones anteriores de este estado que comparar. Pulumi guarda una copia en el historial con cada update; si se borró, activa el versionado del bucket (GCS Object Versioning o S3 Versioning) o PULUMI_RETAIN_CHECKPOINTS.", + "unavailable": "Esa versión ya no está disponible en el bucket.", + "lastUpdateChanges": "Según el último update:", + "secretsNotice": "Los secretos se comparan sin revelarse. Pulumi los vuelve a cifrar en cada escritura, así que no se puede saber si un valor secreto cambió; solo si pasó a ser secreto o dejó de serlo.", + "noChanges": "No hay cambios entre estas dos versiones.", + "fields": "{count} propiedades", + "property": "Propiedad", + "before": "Antes", + "after": "Después", + "providerOnly": "{count} recursos solo cambiaron de provider (subida de versión)", + "outputs": "Outputs del stack", + "sources": { + "current": "Estado actual", + "history": "Update", + "backup": "Backup", + "retained": "Checkpoint retenido", + "previous": "Estado anterior (.bak)", + "object-version": "Versión del objeto" + } } } } diff --git a/src/lib/server/state-iac/stacks.ts b/src/lib/server/state-iac/stacks.ts index dfeb505..ad138ec 100644 --- a/src/lib/server/state-iac/stacks.ts +++ b/src/lib/server/state-iac/stacks.ts @@ -1,6 +1,8 @@ import { stateIacService, type BackendStacks, + type DiffOutcome, + type IacHistoryPage, type IacResource, type IacValue, type StackListItem, @@ -25,7 +27,7 @@ export type StackScope = 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') { +function can(locals: AlertLocals, scope: StackScope, permission: 'stacks' | 'states' | 'history') { if (scope.scope === 'project') { return callerCan(locals, `project:stateiac:${permission}:read`, { scope: 'project', @@ -143,3 +145,58 @@ export function parseInclude(value: string | null): StackInclude[] { ), ]; } + +type StackRef = { backendId: string; project: string; stack: string }; + +/** The stack if the scope may see it at all (any State IaC read grant), else 404. */ +async function locateFor(locals: AlertLocals, scope: StackScope, ref: StackRef, refresh = false) { + const [stacks, history, states] = await Promise.all([ + can(locals, scope, 'stacks'), + can(locals, scope, 'history'), + can(locals, scope, 'states'), + ]); + if (!stacks && !history && !states) return null; + const viewer = + scope.scope === 'project' + ? { projectId: scope.projectId } + : { organizationId: scope.organizationId }; + return stateIacService.locate(viewer, ref.backendId, ref.project, ref.stack, { refresh }); +} + +/** Update history, newest first: `project:stateiac:history:read` in a project. */ +export async function getStackHistory( + locals: AlertLocals, + scope: StackScope, + ref: StackRef, + page: { cursor?: string | null; limit?: number }, +): Promise> { + const located = await locateFor(locals, scope, ref); + if (!located) return notFound; + if (!(await can(locals, scope, 'history'))) return forbidden; + const cursor = page.cursor && /^\d+$/.test(page.cursor) ? page.cursor : null; + return { + ok: true, + status: 200, + data: await stateIacService.history(located, { ...page, cursor }), + }; +} + +/** + * Diff between two versions of the state (`project:stateiac:states:read` in a project): by default + * the last update against the one before. `sources` lists what can be compared. + */ +export async function getStackDiff( + locals: AlertLocals, + scope: StackScope, + ref: StackRef, + ids: { from?: string | null; to?: string | null }, +): Promise> { + const located = await locateFor(locals, scope, ref); + if (!located) return notFound; + if (!(await can(locals, scope, 'states'))) return forbidden; + return { ok: true, status: 200, data: await stateIacService.diff(located, ids) }; +} + +export async function canReadHistory(locals: AlertLocals, scope: StackScope): Promise { + return can(locals, scope, 'history'); +} diff --git a/src/lib/state-iac/types.ts b/src/lib/state-iac/types.ts index 8af962a..41345ab 100644 --- a/src/lib/state-iac/types.ts +++ b/src/lib/state-iac/types.ts @@ -57,6 +57,52 @@ export type IacUpdateView = { }; }; +export type IacHistoryPageView = { + updates: (IacUpdateView & { + snapshotAvailable: boolean; + config: Record; + execKind: string | null; + })[]; + nextCursor: string | null; +}; + +export type IacSnapshotSourceView = { + id: string; + source: 'current' | 'history' | 'backup' | 'retained' | 'previous' | 'object-version'; + takenAt: string | null; + sizeBytes: number; + updateId: string | null; +}; + +export type IacFieldChangeView = { + path: string; + before?: IacValue; + after?: IacValue; + secret: boolean; +}; + +export type IacResourceChangeView = { + address: string; + type: string; + name: string; + change: 'create' | 'delete' | 'update' | 'replace'; + providerOnly: boolean; + fields: IacFieldChangeView[]; +}; + +export type DiffOutcomeView = { + diff: { + from: { sourceId: string | null; takenAt: string | null }; + to: { sourceId: string | null; takenAt: string | null }; + summary: Record<'create' | 'delete' | 'update' | 'replace' | 'same' | 'providerOnly', number>; + resources: IacResourceChangeView[]; + outputs: IacFieldChangeView[]; + } | null; + sources: IacSnapshotSourceView[]; + from: string | null; + to: string | null; +}; + export type StackSummaryView = { ref: { backendId: string; diff --git a/src/modules/state-iac/application/state-diff.service.test.ts b/src/modules/state-iac/application/state-diff.service.test.ts new file mode 100644 index 0000000..90f3d14 --- /dev/null +++ b/src/modules/state-iac/application/state-diff.service.test.ts @@ -0,0 +1,169 @@ +import { describe, expect, it } from 'vitest'; +import type { IacResource, IacSnapshot } from '../domain/iac.model'; +import { PulumiStateEngine } from '../infrastructure/engines/pulumi/pulumi-state-engine'; +import type { EngineStack } from '../infrastructure/engines/state-engine'; +import { diffSnapshots, sameValue } from './state-diff.service'; +import { fixtureStore } from './testing'; + +const engine = new PulumiStateEngine(); +const MAX = 50 * 1024 * 1024; + +async function prodHistory() { + const store = fixtureStore('project-layout'); + const discovery = await engine.discoverStacks(store, '.pulumi/', 'b1'); + const prod = discovery.stacks.find((s) => s.ref.stack === 'prod') as EngineStack; + const read = async (id: string) => + (await engine.readSnapshotSource(store, '.pulumi/', prod, id, { maxBytes: MAX }))!; + return { store, prod, read }; +} + +const byChange = (diff: ReturnType, change: string) => + diff.resources.filter((r) => r.change === change).map((r) => r.name); + +describe('diffSnapshots on real consecutive states', () => { + it('a replace: same URN, new cloud id (the managed certificate)', async () => { + const { read } = await prodHistory(); + const diff = diffSnapshots( + await read('history:1795602066945844000'), + await read('history:1795602803296701000'), + ); + expect(diff.summary).toMatchObject({ create: 0, delete: 0, replace: 1 }); + expect(byChange(diff, 'replace')).toEqual(['lb-prod-cert']); + const cert = diff.resources.find((r) => r.name === 'lb-prod-cert')!; + expect(cert.fields.map((f) => f.path)).toContain('externalId'); + // the history entry says: replace 1, update 3; the raw JSON comparison flags ~30 + expect(diff.summary.replace + diff.summary.update).toBe(4); + }); + + it('a 2-resource update with property-level changes', async () => { + const { read } = await prodHistory(); + const diff = diffSnapshots( + await read('history:1795602803296701000'), + await read('history:1795604216162649000'), + ); + expect(diff.summary).toMatchObject({ create: 0, delete: 0, replace: 0, update: 2 }); + expect(byChange(diff, 'update').sort()).toEqual(['acme-prod', 'cloud-sql-acme-prod']); + const component = diff.resources.find((r) => r.name === 'cloud-sql-acme-prod')!; + expect(component.fields).toEqual([ + expect.objectContaining({ path: 'inputs.publicIp', secret: false }), + ]); + }); + + it('re-encrypted secrets are not changes (Pulumi uses a fresh nonce on every write)', async () => { + const { read } = await prodHistory(); + const diff = diffSnapshots( + await read('history:1795602803296701000'), + await read('history:1795604216162649000'), + ); + // every fixture ciphertext differs between both files, yet no secret field shows up + expect(diff.resources.flatMap((r) => r.fields).some((f) => f.secret)).toBe(false); + expect(JSON.stringify(diff)).not.toMatch(/ciphertext|v1:/); + }); + + it('creates, deletes and a provider upgrade shown as provider-only changes', async () => { + const { read } = await prodHistory(); + const diff = diffSnapshots( + await read('history:1789061079158069310'), + await read('history:1795602066945844000'), + ); + expect(diff.summary.create).toBe(6); + expect(diff.summary.delete).toBe(1); + expect(diff.summary.providerOnly).toBeGreaterThan(0); + const providerOnly = diff.resources.filter((r) => r.providerOnly); + expect(providerOnly.every((r) => r.fields.every((f) => f.path === 'provider'))).toBe(true); + // ordered: replace, create, delete, update + const order = diff.resources.map((r) => r.change); + expect(order.indexOf('create')).toBeLessThan(order.lastIndexOf('update')); + expect(diff.outputs.map((o) => o.path)).toContain('pulseThemeTokenSecretId'); + }); + + it('the current state against itself has no changes', async () => { + const { read } = await prodHistory(); + const current = await read('current'); + expect(diffSnapshots(current, current).summary).toMatchObject({ + create: 0, + delete: 0, + update: 0, + replace: 0, + same: current.resources.length, + }); + }); +}); + +describe('diffSnapshots rules', () => { + const resource = (overrides: Partial = {}): IacResource => ({ + address: 'urn:pulumi:dev::p::aws:s3/bucket:Bucket::logs', + type: 'aws:s3/bucket:Bucket', + name: 'logs', + parent: null, + provider: 'urn:pulumi:dev::p::pulumi:providers:aws::default', + providerType: 'aws', + externalId: 'logs-123', + managed: true, + flags: { + protect: false, + retainOnDelete: false, + external: false, + pendingReplacement: false, + pendingDelete: false, + }, + inputs: {}, + outputs: {}, + dependencies: [], + createdAt: null, + modifiedAt: null, + ...overrides, + }); + const snapshot = (resources: IacResource[], outputs = {}): IacSnapshot => ({ + ref: { backendId: 'b', engine: 'pulumi', project: 'p', stack: 'dev', layout: 'project' }, + source: 'history', + versionId: null, + takenAt: null, + toolVersion: null, + resources, + outputs, + pendingOperations: 0, + sizeBytes: 0, + }); + + it('never reveals a secret, and says when a value became or stopped being secret', () => { + const before = resource({ inputs: { password: { $iac: 'secret' }, user: 'admin' } }); + const after = resource({ inputs: { password: 'plain-now', user: { $iac: 'secret' } } }); + const diff = diffSnapshots(snapshot([before]), snapshot([after])); + const fields = diff.resources[0].fields; + expect(fields).toEqual([ + { path: 'inputs.password', before: { $iac: 'secret' }, after: 'plain-now', secret: true }, + { path: 'inputs.user', before: 'admin', after: { $iac: 'secret' }, secret: true }, + ]); + // secret → secret is "same" + const same = diffSnapshots(snapshot([before]), snapshot([resource({ inputs: before.inputs })])); + expect(same.summary.same).toBe(1); + }); + + it('dependencies compare as sets and nested values down to the leaves', () => { + const dep = (n: string) => `urn:pulumi:dev::p::aws:iam/role:Role::${n}`; + const before = resource({ + dependencies: [dep('a'), dep('b')], + inputs: { tags: { env: 'dev', team: 'x' }, ports: [80, 443] }, + }); + const reordered = resource({ ...before, dependencies: [dep('b'), dep('a')] }); + expect(diffSnapshots(snapshot([before]), snapshot([reordered])).summary.same).toBe(1); + + const after = resource({ + dependencies: [dep('b'), dep('c')], + inputs: { tags: { env: 'prod', team: 'x' }, ports: [80, 8443] }, + }); + const fields = diffSnapshots(snapshot([before]), snapshot([after])).resources[0].fields; + expect(fields).toEqual([ + { path: 'inputs.ports[1]', before: 443, after: 8443, secret: false }, + { path: 'inputs.tags.env', before: 'dev', after: 'prod', secret: false }, + { path: 'dependencies', before: [dep('a')], after: [dep('c')], secret: false }, + ]); + }); + + it('sameValue treats every secret as equal', () => { + expect(sameValue({ $iac: 'secret' }, { $iac: 'secret' })).toBe(true); + expect(sameValue({ a: [1, { b: 2 }] }, { a: [1, { b: 2 }] })).toBe(true); + expect(sameValue({ a: 1 }, { a: 1, b: 2 })).toBe(false); + }); +}); diff --git a/src/modules/state-iac/application/state-diff.service.ts b/src/modules/state-iac/application/state-diff.service.ts new file mode 100644 index 0000000..def59fa --- /dev/null +++ b/src/modules/state-iac/application/state-diff.service.ts @@ -0,0 +1,219 @@ +import { + isSpecialValue, + type IacResource, + type IacSnapshot, + type IacValue, +} from '../domain/iac.model'; + +/** + * Compares two snapshots of a stack (docs/adr/0003-state-iac.md, "Diff normalization"): + * - resources are matched by address; same address with another cloud id is a `replace`; + * - dependencies compare as sets and the provider without its id (both already normalized); + * - secrets are never revealed: two secrets compare equal (Pulumi re-encrypts them on every + * write, so a different ciphertext means nothing), and a field that is or was secret says so; + * - a resource whose only change is its provider (a provider upgrade touches every resource) is + * flagged `providerOnly`, so it can be shown as one change instead of N updates. + */ + +export type IacFieldChange = { + /** `inputs.settings.tier`, `outputs.ipAddresses[0]`, `dependencies`, `provider`… */ + path: string; + before?: IacValue; + after?: IacValue; + /** The value is, or was, a secret: neither side is shown in clear. */ + secret: boolean; +}; + +export type IacResourceChange = { + address: string; + type: string; + name: string; + change: 'create' | 'delete' | 'update' | 'replace'; + providerOnly: boolean; + fields: IacFieldChange[]; +}; + +export type IacDiffSummary = { + create: number; + delete: number; + update: number; + replace: number; + same: number; + /** Updates whose only change is the provider (included in `update`). */ + providerOnly: number; +}; + +export type IacDiff = { + from: { sourceId: string | null; takenAt: string | null }; + to: { sourceId: string | null; takenAt: string | null }; + summary: IacDiffSummary; + resources: IacResourceChange[]; + /** Changes of the stack outputs. */ + outputs: IacFieldChange[]; +}; + +const MAX_DEPTH = 8; +const MAX_FIELDS = 200; +const ORDER = { replace: 0, create: 1, delete: 2, update: 3 } as const; + +const isSecret = (value: IacValue | undefined) => + isSpecialValue(value) && (value as { $iac: string }).$iac === 'secret'; + +/** Deep equality where every secret equals every secret. */ +export function sameValue(a: IacValue | undefined, b: IacValue | undefined): boolean { + if (isSecret(a) && isSecret(b)) return true; + if (a === b) return true; + if (a === null || b === null || a === undefined || b === undefined) return false; + if (typeof a !== 'object' || typeof b !== 'object') return false; + if (Array.isArray(a) !== Array.isArray(b)) return false; + if (Array.isArray(a) && Array.isArray(b)) { + return a.length === b.length && a.every((item, i) => sameValue(item, b[i])); + } + const left = a as Record; + const right = b as Record; + const keys = new Set([...Object.keys(left), ...Object.keys(right)]); + for (const key of keys) if (!sameValue(left[key], right[key])) return false; + return true; +} + +const isPlainObject = (value: IacValue | undefined): value is Record => + Boolean(value) && typeof value === 'object' && !Array.isArray(value) && !isSpecialValue(value); + +/** Field-level differences between two values, down to the leaves. */ +function diffValues( + path: string, + before: IacValue | undefined, + after: IacValue | undefined, + out: IacFieldChange[], + depth = 0, +) { + if (out.length >= MAX_FIELDS || sameValue(before, after)) return; + if (depth < MAX_DEPTH && isPlainObject(before) && isPlainObject(after)) { + const left = before as Record; + const right = after as Record; + const keys = [...new Set([...Object.keys(left), ...Object.keys(right)])].sort(); + for (const key of keys) diffValues(`${path}.${key}`, left[key], right[key], out, depth + 1); + return; + } + if ( + depth < MAX_DEPTH && + Array.isArray(before) && + Array.isArray(after) && + before.length === after.length + ) { + before.forEach((item, i) => diffValues(`${path}[${i}]`, item, after[i], out, depth + 1)); + return; + } + const secret = isSecret(before) || isSecret(after); + out.push({ + path, + ...(before !== undefined ? { before: isSecret(before) ? { $iac: 'secret' } : before } : {}), + ...(after !== undefined ? { after: isSecret(after) ? { $iac: 'secret' } : after } : {}), + secret, + }); +} + +function diffResource(before: IacResource, after: IacResource): IacFieldChange[] { + const fields: IacFieldChange[] = []; + for (const key of [ + ...new Set([...Object.keys(before.inputs), ...Object.keys(after.inputs)]), + ].sort()) { + diffValues(`inputs.${key}`, before.inputs[key], after.inputs[key], fields); + } + for (const key of [ + ...new Set([...Object.keys(before.outputs), ...Object.keys(after.outputs)]), + ].sort()) { + diffValues(`outputs.${key}`, before.outputs[key], after.outputs[key], fields); + } + const scalar = (path: string, a: IacValue, b: IacValue) => { + if (!sameValue(a, b)) fields.push({ path, before: a, after: b, secret: false }); + }; + scalar('externalId', before.externalId, after.externalId); + scalar('parent', before.parent, after.parent); + scalar('provider', before.provider, after.provider); + // dependencies are sets (Pulumi reorders them between writes) + const removed = before.dependencies.filter((d) => !after.dependencies.includes(d)); + const added = after.dependencies.filter((d) => !before.dependencies.includes(d)); + if (removed.length > 0 || added.length > 0) { + fields.push({ path: 'dependencies', before: removed, after: added, secret: false }); + } + for (const flag of Object.keys(before.flags) as (keyof IacResource['flags'])[]) { + scalar(`flags.${flag}`, before.flags[flag], after.flags[flag]); + } + return fields.slice(0, MAX_FIELDS); +} + +export function diffSnapshots(from: IacSnapshot, to: IacSnapshot): IacDiff { + const before = new Map(from.resources.map((r) => [r.address, r])); + const after = new Map(to.resources.map((r) => [r.address, r])); + const resources: IacResourceChange[] = []; + const summary: IacDiffSummary = { + create: 0, + delete: 0, + update: 0, + replace: 0, + same: 0, + providerOnly: 0, + }; + const entry = ( + r: IacResource, + change: IacResourceChange['change'], + fields: IacFieldChange[] = [], + ) => ({ + address: r.address, + type: r.type, + name: r.name, + change, + providerOnly: false, + fields, + }); + + for (const [address, next] of after) { + const previous = before.get(address); + if (!previous) { + summary.create++; + resources.push(entry(next, 'create')); + continue; + } + const fields = diffResource(previous, next); + if (fields.length === 0) { + summary.same++; + continue; + } + const replaced = + previous.externalId !== null && + next.externalId !== null && + previous.externalId !== next.externalId; + if (replaced) { + summary.replace++; + resources.push(entry(next, 'replace', fields)); + continue; + } + summary.update++; + const change = entry(next, 'update', fields); + change.providerOnly = fields.every((field) => field.path === 'provider'); + if (change.providerOnly) summary.providerOnly++; + resources.push(change); + } + for (const [address, previous] of before) { + if (after.has(address)) continue; + summary.delete++; + resources.push(entry(previous, 'delete')); + } + resources.sort((a, b) => ORDER[a.change] - ORDER[b.change] || a.address.localeCompare(b.address)); + + const outputs: IacFieldChange[] = []; + for (const key of [ + ...new Set([...Object.keys(from.outputs), ...Object.keys(to.outputs)]), + ].sort()) { + diffValues(key, from.outputs[key], to.outputs[key], outputs); + } + + return { + from: { sourceId: from.versionId, takenAt: from.takenAt }, + to: { sourceId: to.versionId, takenAt: to.takenAt }, + summary, + resources, + outputs, + }; +} diff --git a/src/modules/state-iac/application/state-iac.service.test.ts b/src/modules/state-iac/application/state-iac.service.test.ts index 827f08a..b76a2a1 100644 --- a/src/modules/state-iac/application/state-iac.service.test.ts +++ b/src/modules/state-iac/application/state-iac.service.test.ts @@ -181,4 +181,128 @@ describe('StateIacService', () => { expect(group.stacks[0].resourceCount).toBe(0); }); }); + + describe('history and diff', () => { + const locate = (fx: ReturnType, id: string, stack = 'prod') => + fx.stateIacService.locate({ projectId: 'p1' }, id, 'acme-infra', stack); + + it('locate follows the same visibility as the detail', async () => { + expect(await locate(fx, shared.id)).not.toBeNull(); + expect(await locate(fx, shared.id, 'staging')).toBeNull(); + expect( + await fx.stateIacService.locate( + { organizationId: 'org-2' }, + shared.id, + 'acme-infra', + 'prod', + ), + ).toBeNull(); + }); + + it('pages the history, newest first', async () => { + const located = (await locate(fx, shared.id))!; + const first = await fx.stateIacService.history(located, { limit: 3 }); + expect(first.updates.map((u) => u.id)).toEqual([ + '1795604216162649000', + '1795602803296701000', + '1795602066945844000', + ]); + expect(first.nextCursor).toBe('1795602066945844000'); + const second = await fx.stateIacService.history(located, { + limit: 3, + cursor: first.nextCursor, + }); + expect(second.updates.map((u) => [u.id, u.result])).toEqual([ + ['1789061079158069310', 'failed'], + ]); + expect(second.nextCursor).toBeNull(); + }); + + it('lists every source: current, history, backups, retained copies and the .bak', async () => { + const sources = await fx.stateIacService.snapshotSources((await locate(fx, shared.id))!); + expect(sources[0].id).toBe('current'); + expect(sources.map((source) => source.source).sort()).toEqual( + [ + 'backup', + 'current', + 'history', + 'history', + 'history', + 'history', + 'previous', + 'retained', + ].sort(), + ); + expect(sources.find((s) => s.id === 'history:1795604216162649000')).toMatchObject({ + updateId: '1795604216162649000', + takenAt: new Date(1795604216162).toISOString(), + }); + }); + + it('by default compares the last update with the one before', async () => { + const outcome = await fx.stateIacService.diff((await locate(fx, shared.id))!); + expect(outcome.to).toBe('history:1795604216162649000'); + expect(outcome.from).toBe('history:1795602803296701000'); + expect(outcome.diff?.summary).toMatchObject({ update: 2, create: 0, delete: 0, replace: 0 }); + expect(outcome.diff?.from.sourceId).toBe('history:1795602803296701000'); + }); + + it('compares any two sources, and refuses unknown ones', async () => { + const located = (await locate(fx, shared.id))!; + const outcome = await fx.stateIacService.diff(located, { + from: 'history:1795602066945844000', + to: 'current', + }); + expect(outcome.diff?.summary.replace).toBe(1); + const unknown = await fx.stateIacService.diff(located, { from: 'history:1', to: 'current' }); + expect(unknown.diff).toBeNull(); + const traversal = await fx.stateIacService.diff(located, { + from: 'backup:../../x', + to: 'current', + }); + expect(traversal.diff).toBeNull(); + }); + + it('uses object versions when the bucket keeps them', async () => { + const store = fixtureStore('project-layout'); + store.versioning = true; + const key = '.pulumi/stacks/acme-platform/dev.json'; + const empty = + '{"version":3,"checkpoint":{"stack":"organization/acme-platform/dev","latest":{}}}'; + store.put(key, empty, '2026-11-01T00:00:00Z'); + store.put( + key, + '{"version":3,"checkpoint":{"stack":"organization/acme-platform/dev","latest":{"resources":[{"urn":"urn:pulumi:dev::acme-platform::aws:s3/bucket:Bucket::logs","type":"aws:s3/bucket:Bucket","custom":true,"id":"logs"}]}}}', + '2026-11-02T00:00:00Z', + ); + fx.buckets.set('shared-state', store); + fx.stateIacService.invalidate(shared.id); + const located = (await fx.stateIacService.locate( + { projectId: 'p2' }, + shared.id, + 'acme-platform', + 'dev', + ))!; + const sources = await fx.stateIacService.snapshotSources(located); + // the fixture's dev.json was version 1 (before versioning), then 2 and 3 (live) + expect(sources.map((s) => s.id).sort()).toEqual(['current', 'previous', 'version:2']); + const outcome = await fx.stateIacService.diff(located, { from: 'version:2', to: 'current' }); + expect(outcome.diff?.summary.create).toBe(1); + // no history: by default, current against the newest other source + const byDefault = await fx.stateIacService.diff(located); + expect(byDefault.to).toBe('current'); + expect(byDefault.diff).not.toBeNull(); + }); + + it('with only the current state there is nothing to compare', async () => { + const located = (await fx.stateIacService.locate( + { projectId: 'p2' }, + shared.id, + 'acme-platform', + 'dev', + ))!; + const outcome = await fx.stateIacService.diff(located, { from: 'version:9', to: 'current' }); + expect(outcome.diff).toBeNull(); + }); + }); }); diff --git a/src/modules/state-iac/application/state-iac.service.ts b/src/modules/state-iac/application/state-iac.service.ts index ac2a028..fde17e8 100644 --- a/src/modules/state-iac/application/state-iac.service.ts +++ b/src/modules/state-iac/application/state-iac.service.ts @@ -1,5 +1,12 @@ import type { Logger } from 'pino'; -import type { IacLock, IacSnapshot, IacStackSummary, IacUpdate } from '../domain/iac.model'; +import type { + IacHistoryPage, + IacLock, + IacSnapshot, + IacSnapshotSource, + IacStackSummary, + IacUpdate, +} from '../domain/iac.model'; import type { StateBackendDomain } from '../domain/state-backend.domain'; import type { StateBindingDomain } from '../domain/state-binding.domain'; import type { @@ -9,6 +16,7 @@ import type { } from '../infrastructure/engines/state-engine'; import type { StateBindingRepositoryPort } from '../infrastructure/repositories/state-binding.repository'; import type { StateIacConfig } from '../infrastructure/config'; +import { diffSnapshots, type IacDiff } from './state-diff.service'; import { readErrorCode, type BackendErrorCode, @@ -41,6 +49,23 @@ export type BackendStacks = { export type StackDetail = { summary: StackListItem; snapshot: IacSnapshot }; +/** Who is looking: a GitOps project (its bindings) or an organization (everything). */ +export type StackViewer = { projectId: string } | { organizationId: string }; + +export type LocatedStack = { + backend: StateBackendDomain; + stack: EngineStack; + assignedProjectId: string | null; +}; + +export type DiffOutcome = { + /** `null`: nothing to compare with (only the current state, or a source that is gone). */ + diff: IacDiff | null; + sources: IacSnapshotSource[]; + from: string | null; + to: string | null; +}; + export type StateIacServiceOptions = { now?: () => number; logger?: Pick; @@ -66,6 +91,8 @@ export class StateIacService { private readonly snapshots = new Map(); private snapshotBytes = 0; private readonly extras = new Map(); + private readonly pages = new Map(); + private readonly sources = new Map(); private readonly now: () => number; private readonly log: Pick; private readonly maxCacheBytes: number; @@ -129,17 +156,7 @@ export class StateIacService { 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); + return this.detail(await this.locate({ projectId }, backendId, project, stack, options)); } /** A stack seen from its organization: any stack of its backends. */ @@ -150,17 +167,130 @@ export class StateIacService { 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); + return this.detail(await this.locate({ organizationId }, backendId, project, stack, options)); + } + + /** + * Finds a stack the viewer may see: from a project, only if one of its bindings covers it; + * from an organization, any stack of its backends. `null` means 404. + */ + async locate( + viewer: StackViewer, + backendId: string, + project: string, + stackName: string, + options: { refresh?: boolean } = {}, + ): Promise { const projectName = project === UNKNOWN_PROJECT ? null : project; - return this.detail( - backend, - project, - stack, - assignedTo(bindings, projectName, stack) ?? null, - options, + let assignedProjectId: string | null; + if ('projectId' in viewer) { + const bindings = await this.bindings.listByProject(viewer.projectId); + const visible = bindings.some( + (binding) => + binding.backendId === backendId && + binding.pulumiProject === projectName && + binding.covers(stackName), + ); + if (!visible) return null; + assignedProjectId = viewer.projectId; + } else { + assignedProjectId = null; + } + const backend = await this.backends.get(backendId).catch(() => null); + if (!backend || !backend.enabled) return null; + if ('organizationId' in viewer) { + if (backend.organizationId !== viewer.organizationId) return null; + const bindings = await this.bindings.listByBackend(backend.id); + assignedProjectId = assignedTo(bindings, projectName, stackName) ?? null; + } + const discovery = await this.discover(backend, options); + if ('error' in discovery) return null; + const stack = discovery.stacks.find( + (candidate) => candidate.ref.project === projectName && candidate.ref.stack === stackName, + ); + return stack ? { backend, stack, assignedProjectId } : null; + } + + /** One page of the stack's history, newest first. */ + async history( + located: LocatedStack, + options: { cursor?: string | null; limit?: number } = {}, + ): Promise { + const limit = Math.min(Math.max(options.limit ?? 20, 1), 100); + const key = `${located.backend.id}|history|${located.stack.key}|${located.stack.version ?? ''}|${options.cursor ?? ''}|${limit}`; + const cached = this.pages.get(key); + if (cached && cached.expires > this.now()) return cached.value; + const value = await this.engine.listHistory( + this.backends.storeFor(located.backend), + located.backend.pulumiRoot, + located.stack, + { limit, before: options.cursor ?? null, maxBytes: this.config().maxStateBytes }, ); + this.pages.set(key, { expires: this.now() + this.config().cacheTtlMs, value }); + this.trimPages(); + return value; + } + + /** Versions of the state that can be compared, newest first. */ + async snapshotSources(located: LocatedStack): Promise { + const key = `${located.backend.id}|sources|${located.stack.key}|${located.stack.version ?? ''}`; + const cached = this.sources.get(key); + if (cached && cached.expires > this.now()) return cached.value; + const value = await this.engine.listSnapshotSources( + this.backends.storeFor(located.backend), + located.backend.pulumiRoot, + located.stack, + ); + this.sources.set(key, { expires: this.now() + this.config().cacheTtlMs, value }); + return value; + } + + /** + * Diff between two versions of the state. Without `from`/`to`: the state after the last update + * against the one before it. `null` sources when there is nothing to compare with. + */ + async diff( + located: LocatedStack, + ids: { from?: string | null; to?: string | null } = {}, + ): Promise { + const sources = await this.snapshotSources(located); + const known = new Set(sources.map((source) => source.id)); + const history = sources.filter((source) => source.source === 'history'); + const others = sources.filter((source) => source.id !== 'current'); + const toId = ids.to ?? history[0]?.id ?? 'current'; + const fromId = + ids.from ?? + (toId === history[0]?.id ? history[1]?.id : undefined) ?? + others.find((source) => source.id !== toId)?.id ?? + null; + if (!fromId || !known.has(fromId) || !known.has(toId)) { + return { diff: null, sources, from: fromId, to: toId }; + } + const [from, to] = await Promise.all([ + this.sourceSnapshot(located, fromId), + this.sourceSnapshot(located, toId), + ]); + if (!from || !to) return { diff: null, sources, from: fromId, to: toId }; + const diff = diffSnapshots({ ...from, versionId: fromId }, { ...to, versionId: toId }); + return { diff, sources, from: fromId, to: toId }; + } + + private async sourceSnapshot(located: LocatedStack, sourceId: string) { + if (sourceId === 'current') return this.snapshot(located.backend, located.stack); + // past versions never change; `previous` (the .bak) changes with every write + const version = sourceId === 'previous' ? (located.stack.version ?? '') : ''; + const key = `${located.backend.id}|${located.stack.key}|src:${sourceId}|${version}`; + const cached = this.snapshots.get(key); + if (cached) return cached; + const snapshot = await this.engine.readSnapshotSource( + this.backends.storeFor(located.backend), + located.backend.pulumiRoot, + located.stack, + sourceId, + { maxBytes: this.config().maxStateBytes }, + ); + if (snapshot) this.remember(key, snapshot); + return snapshot; } /** Name and location of a backend, for headings. */ @@ -175,27 +305,16 @@ export class StateIacService { 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); + for (const cache of [this.extras, this.pages, this.sources]) { + for (const key of cache.keys()) if (key.startsWith(`${backendId}|`)) cache.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); + private async detail(located: LocatedStack | null): Promise { + if (!located) return null; + const summary = await this.summarize(located.backend, located.stack, located.assignedProjectId); + if (summary.error) return { summary, snapshot: emptySnapshot(located.stack) }; + const snapshot = await this.snapshot(located.backend, located.stack); return { summary, snapshot }; } @@ -291,6 +410,12 @@ export class StateIacService { maxBytes: this.config().maxStateBytes, }, ); + this.remember(key, snapshot); + return snapshot; + } + + /** LRU bounded by the raw size of the states. */ + private remember(key: string, snapshot: IacSnapshot) { this.snapshots.set(key, snapshot); this.snapshotBytes += snapshot.sizeBytes; for (const [oldKey, old] of this.snapshots) { @@ -298,7 +423,11 @@ export class StateIacService { this.snapshots.delete(oldKey); this.snapshotBytes -= old.sizeBytes; } - return snapshot; + } + + private trimPages() { + // history pages are small; keep the newest few thousand + while (this.pages.size > 2_000) this.pages.delete(this.pages.keys().next().value!); } private async summarize( diff --git a/src/modules/state-iac/domain/iac.model.ts b/src/modules/state-iac/domain/iac.model.ts index bbaae07..a365c46 100644 --- a/src/modules/state-iac/domain/iac.model.ts +++ b/src/modules/state-iac/domain/iac.model.ts @@ -113,3 +113,19 @@ export type IacStackSummary = { pendingOperations: number; sizeBytes: number; }; + +/** + * A version of a stack's state that can be read and compared. `id` is stable and opaque: + * `current`, `history:`, `backup:`, `retained:`, `previous` (the + * `.bak`) or `version:`. + */ +export type IacSnapshotSource = { + id: string; + source: IacSnapshot['source']; + takenAt: string | null; + sizeBytes: number; + /** The history entry this state comes after (`history:` sources). */ + updateId: string | null; +}; + +export type IacHistoryPage = { updates: IacUpdate[]; nextCursor: string | null }; diff --git a/src/modules/state-iac/index.ts b/src/modules/state-iac/index.ts index 47add62..4617ba9 100644 --- a/src/modules/state-iac/index.ts +++ b/src/modules/state-iac/index.ts @@ -78,7 +78,16 @@ export type { PulumiLayout } from './infrastructure/engines/pulumi/pulumi-discov export { UNKNOWN_PROJECT, type BackendStacks, + type DiffOutcome, + type LocatedStack, + type StackViewer, type StackDetail, type StackListItem, } from './application/state-iac.service'; export type * from './domain/iac.model'; +export type { + IacDiff, + IacDiffSummary, + IacFieldChange, + IacResourceChange, +} from './application/state-diff.service'; 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 index c19288d..ced5407 100644 --- a/src/modules/state-iac/infrastructure/engines/pulumi/pulumi-state-engine.ts +++ b/src/modules/state-iac/infrastructure/engines/pulumi/pulumi-state-engine.ts @@ -1,10 +1,18 @@ -import type { IacLock, IacSnapshot, IacUpdate } from '../../../domain/iac.model'; +import type { + IacHistoryPage, + IacLock, + IacSnapshot, + IacSnapshotSource, + 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)?$/; +/** `..json(.gz)` in backups/ */ +const BACKUP_FILE = /\.(\d+)\.json(?:\.gz|\.zst)?$/; const MAX_HISTORY_OBJECTS = 20_000; const READ_CONCURRENCY = 4; @@ -16,9 +24,22 @@ export function pulumiPaths(root: string, stack: EngineStack) { 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}/`, + backups: scoped ? `${root}backups/${project}/${name}/` : `${root}backups/${name}/`, }; } +/** `` → ISO date. */ +export function nanosToIso(nanos: string): string | null { + try { + return new Date(Number(BigInt(nanos) / 1_000_000n)).toISOString(); + } catch { + return null; + } +} + +const byNanosDesc = (a: string, b: string) => + BigInt(b) > BigInt(a) ? 1 : BigInt(b) < BigInt(a) ? -1 : 0; + /** Pulumi DIY backend: `project` and legacy layouts, plain, `.gz` (and, listed only, `.zst`). */ export class PulumiStateEngine implements StateEngine { readonly kind = 'pulumi' as const; @@ -73,40 +94,197 @@ export class PulumiStateEngine implements StateEngine { stack: EngineStack, options: { limit: number; maxBytes: number }, ): Promise { + return (await this.listHistory(store, root, stack, options)).updates; + } + + async listHistory( + store: ObjectStore, + root: string, + stack: EngineStack, + options: { limit: number; before?: string | null; maxBytes: number }, + ): Promise { + const entries = await this.historyEntries(store, root, stack); + const ids = [...entries.keys()] + .filter((id) => entries.get(id)!.history) + .filter((id) => !options.before || BigInt(id) < BigInt(options.before)) + .sort(byNanosDesc); + const page = ids.slice(0, options.limit); + + const updates: IacUpdate[] = []; + for (let i = 0; i < page.length; i += READ_CONCURRENCY) { + const batch = await Promise.all( + page.slice(i, i + READ_CONCURRENCY).map(async (id) => { + const entry = entries.get(id)!; + const text = await readText(store, entry.history!, options.maxBytes); + return text === null ? null : parseHistory(text, id, Boolean(entry.checkpoint)); + }), + ); + updates.push(...batch.filter((update): update is IacUpdate => update !== null)); + } + return { updates, nextCursor: ids.length > page.length ? page[page.length - 1] : null }; + } + + /** `` → its `.history.json` and `.checkpoint.json` keys. */ + private async historyEntries(store: ObjectStore, root: string, stack: EngineStack) { const dir = pulumiPaths(root, stack).history; const { objects } = await listAll(store, dir, { delimiter: '/', maxObjects: MAX_HISTORY_OBJECTS, }); - const entries = new Map(); + 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 }; + const entry = entries.get(match[1]) ?? { size: 0 }; if (match[2] === 'history') entry.history = object.key; - else entry.checkpoint = true; + else { + entry.checkpoint = object.key; + entry.size = object.size; + } 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); + return entries; + } - 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)); + async listSnapshotSources( + store: ObjectStore, + root: string, + stack: EngineStack, + ): Promise { + const paths = pulumiPaths(root, stack); + const [entries, backups, siblings, versions] = await Promise.all([ + this.historyEntries(store, root, stack), + listAll(store, paths.backups, { delimiter: '/', maxObjects: MAX_HISTORY_OBJECTS }), + // retained copies (`.`) and the `.bak` sit next to the live file + listAll(store, stack.key, { maxObjects: MAX_HISTORY_OBJECTS }), + store.listVersions(stack.key), + ]); + const sources: IacSnapshotSource[] = [ + { + id: 'current', + source: 'current', + takenAt: stack.updatedAt, + sizeBytes: stack.size, + updateId: null, + }, + ]; + for (const [id, entry] of entries) { + if (!entry.checkpoint) continue; + sources.push({ + id: `history:${id}`, + source: 'history', + takenAt: nanosToIso(id), + sizeBytes: entry.size, + updateId: entry.history ? id : null, + }); + } + for (const object of backups.objects) { + const match = object.key.slice(paths.backups.length).match(BACKUP_FILE); + if (!match) continue; + sources.push({ + id: `backup:${match[1]}`, + source: 'backup', + takenAt: nanosToIso(match[1]), + sizeBytes: object.size, + updateId: null, + }); + } + for (const object of siblings.objects) { + const suffix = object.key.slice(stack.key.length); + const retained = suffix.match(/^\.(\d+)$/); + if (retained) { + sources.push({ + id: `retained:${retained[1]}`, + source: 'retained', + takenAt: nanosToIso(retained[1]), + sizeBytes: object.size, + updateId: null, + }); + } else if (suffix === '.bak') { + sources.push({ + id: 'previous', + source: 'previous', + takenAt: object.updatedAt, + sizeBytes: object.size, + updateId: null, + }); + } + } + for (const version of versions) { + if (version.latest) continue; + sources.push({ + id: `version:${version.versionId}`, + source: 'object-version', + takenAt: version.updatedAt, + sizeBytes: version.size, + updateId: null, + }); + } + return sources.sort((a, b) => + a.id === 'current' + ? -1 + : b.id === 'current' + ? 1 + : (b.takenAt ?? '').localeCompare(a.takenAt ?? ''), + ); + } + + async readSnapshotSource( + store: ObjectStore, + root: string, + stack: EngineStack, + sourceId: string, + options: { maxBytes: number }, + ): Promise { + if (sourceId === 'current') return this.readSnapshot(store, root, stack, options); + const [kind, id] = splitSource(sourceId); + if (!id && kind !== 'previous') return null; + const paths = pulumiPaths(root, stack); + let key: string | null; + let versionId: string | undefined; + let source: IacSnapshot['source']; + switch (kind) { + case 'history': { + if (!/^\d+$/.test(id)) return null; + key = (await this.historyEntries(store, root, stack)).get(id)?.checkpoint ?? null; + source = 'history'; + break; + } + case 'backup': { + if (!/^\d+$/.test(id)) return null; + const { objects } = await listAll(store, `${paths.backups}${stack.ref.stack}.${id}.json`); + key = objects[0]?.key ?? null; + source = 'backup'; + break; + } + case 'retained': + if (!/^\d+$/.test(id)) return null; + key = `${stack.key}.${id}`; + source = 'retained'; + break; + case 'previous': + key = `${stack.key}.bak`; + source = 'previous'; + break; + case 'version': + key = stack.key; + versionId = id; + source = 'object-version'; + break; + default: + return null; } - return updates; + if (!key) return null; + const text = await readText(store, key, options.maxBytes, versionId); + if (text === null) return null; + return parseCheckpoint(text, stack.ref, { + source, + versionId: sourceId, + sizeBytes: Buffer.byteLength(text), + }); } async readLock(store: ObjectStore, root: string, stack: EngineStack): Promise { @@ -126,6 +304,11 @@ export class PulumiStateEngine implements StateEngine { } } +function splitSource(sourceId: string): [string, string] { + const index = sourceId.indexOf(':'); + return index < 0 ? [sourceId, ''] : [sourceId.slice(0, index), sourceId.slice(index + 1)]; +} + export class StackStateMissingError extends Error { constructor(key: string) { super(`State object disappeared: ${key}`); diff --git a/src/modules/state-iac/infrastructure/engines/state-engine.ts b/src/modules/state-iac/infrastructure/engines/state-engine.ts index f957f13..cea2466 100644 --- a/src/modules/state-iac/infrastructure/engines/state-engine.ts +++ b/src/modules/state-iac/infrastructure/engines/state-engine.ts @@ -1,4 +1,11 @@ -import type { IacLock, IacSnapshot, IacStackRef, IacUpdate } from '../../domain/iac.model'; +import type { + IacHistoryPage, + IacLock, + IacSnapshot, + IacSnapshotSource, + 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. */ @@ -41,5 +48,26 @@ export interface StateEngine { stack: EngineStack, options: { limit: number; maxBytes: number }, ): Promise; + /** One page of history, newest first; `before` is the `nextCursor` of the previous page. */ + listHistory( + store: ObjectStore, + root: string, + stack: EngineStack, + options: { limit: number; before?: string | null; maxBytes: number }, + ): Promise; readLock(store: ObjectStore, root: string, stack: EngineStack): Promise; + /** Every readable version of the state, newest first (sources in docs/adr/0003-state-iac.md). */ + listSnapshotSources( + store: ObjectStore, + root: string, + stack: EngineStack, + ): Promise; + /** `null` when the source does not exist (any more). */ + readSnapshotSource( + store: ObjectStore, + root: string, + stack: EngineStack, + sourceId: string, + options: { maxBytes: number }, + ): Promise; } diff --git a/src/modules/state-iac/infrastructure/object-store/gcs-object-store.ts b/src/modules/state-iac/infrastructure/object-store/gcs-object-store.ts index d3e6e3e..b3bbd0d 100644 --- a/src/modules/state-iac/infrastructure/object-store/gcs-object-store.ts +++ b/src/modules/state-iac/infrastructure/object-store/gcs-object-store.ts @@ -6,6 +6,7 @@ import { type ListPage, type ObjectInfo, type ObjectStore, + type ObjectVersion, } from './object-store'; export type GcsObjectStoreConfig = { @@ -71,6 +72,37 @@ export class GcsObjectStore implements ObjectStore { throw error; } } + + /** `storage.objects.list` with `versions=true` (Object Versioning): no extra permission. */ + async listVersions(key: string): Promise { + try { + const [files] = await this.bucket.getFiles({ prefix: key, versions: true }); + return files + .filter((file) => file.name === key && file.metadata.generation !== undefined) + .map((file) => ({ + versionId: String(file.metadata.generation), + updatedAt: (file.metadata.updated as string | undefined) ?? null, + size: Number(file.metadata.size ?? 0), + // noncurrent versions carry the time they stopped being live + latest: !file.metadata.timeDeleted, + })) + .sort((a, b) => (BigInt(b.versionId) > BigInt(a.versionId) ? 1 : -1)); + } catch { + // no versioning or no permission: the diff falls back to the other sources + return []; + } + } + + async openReadVersion(key: string, versionId: string): Promise { + try { + return await primeStream( + this.bucket.file(key, { generation: Number(versionId) }).createReadStream(), + ); + } catch (error) { + if (isNotFound(error)) return null; + throw error; + } + } } function toInfo( diff --git a/src/modules/state-iac/infrastructure/object-store/in-memory-object-store.ts b/src/modules/state-iac/infrastructure/object-store/in-memory-object-store.ts index 0a6882b..d9dc071 100644 --- a/src/modules/state-iac/infrastructure/object-store/in-memory-object-store.ts +++ b/src/modules/state-iac/infrastructure/object-store/in-memory-object-store.ts @@ -1,13 +1,16 @@ import { readdirSync, readFileSync, statSync } from 'node:fs'; import { join, relative, sep } from 'node:path'; import { Readable } from 'node:stream'; -import type { ListOptions, ListPage, ObjectInfo, ObjectStore } from './object-store'; +import type { ListOptions, ListPage, ObjectInfo, ObjectStore, ObjectVersion } from './object-store'; type StoredObject = { body: Buffer; updatedAt: string; version: number }; /** Bucket in memory for tests: same listing semantics as GCS/S3 (sorted keys, delimiter, pages). */ export class InMemoryObjectStore implements ObjectStore { private readonly objects = new Map(); + /** Every version ever put, when `versioning` is on (like a versioned bucket). */ + private readonly history = new Map(); + versioning = false; /** Every call, to assert that nothing lists the whole bucket or writes. */ readonly calls: Array<{ op: 'list' | 'head' | 'get'; key: string }> = []; /** Makes every call fail with this error (simulates a denied or missing bucket). */ @@ -31,11 +34,13 @@ export class InMemoryObjectStore implements ObjectStore { put(key: string, body: string | Buffer, updatedAt = new Date().toISOString()): void { const previous = this.objects.get(key); - this.objects.set(key, { + const object = { body: typeof body === 'string' ? Buffer.from(body) : body, updatedAt, version: (previous?.version ?? 0) + 1, - }); + }; + this.objects.set(key, object); + if (this.versioning) this.history.set(key, [...(this.history.get(key) ?? []), object]); } private check() { @@ -106,4 +111,23 @@ export class InMemoryObjectStore implements ObjectStore { })(), ); } + + async listVersions(key: string): Promise { + this.calls.push({ op: 'list', key: `${key}#versions` }); + this.check(); + const current = this.objects.get(key); + return [...(this.history.get(key) ?? [])].reverse().map((object) => ({ + versionId: String(object.version), + updatedAt: object.updatedAt, + size: object.body.length, + latest: object === current, + })); + } + + async openReadVersion(key: string, versionId: string): Promise { + this.calls.push({ op: 'get', key: `${key}#${versionId}` }); + this.check(); + const object = (this.history.get(key) ?? []).find((o) => String(o.version) === versionId); + return object ? Readable.from([object.body]) : null; + } } diff --git a/src/modules/state-iac/infrastructure/object-store/object-store.ts b/src/modules/state-iac/infrastructure/object-store/object-store.ts index 54981cc..5bfaf89 100644 --- a/src/modules/state-iac/infrastructure/object-store/object-store.ts +++ b/src/modules/state-iac/infrastructure/object-store/object-store.ts @@ -15,8 +15,22 @@ export interface ObjectStore { head(key: string): Promise; /** Raw object stream, or `null` when it does not exist. */ openRead(key: string): Promise; + /** + * Previous versions of one object (GCS Object Versioning / S3 Versioning), newest first. Empty + * when the bucket keeps none or the credentials can't list them. + */ + listVersions(key: string): Promise; + /** One version of an object, or `null` when it does not exist (any more). */ + openReadVersion(key: string, versionId: string): Promise; } +export type ObjectVersion = { + versionId: string; + updatedAt: string | null; + size: number; + latest: boolean; +}; + export type ListOptions = { delimiter?: '/'; pageToken?: string; maxKeys?: number }; export type ObjectInfo = { @@ -75,8 +89,11 @@ export async function readObject( store: ObjectStore, key: string, maxBytes = DEFAULT_MAX_OBJECT_BYTES, + versionId?: string, ): Promise { - const stream = await store.openRead(key); + const stream = versionId + ? await store.openReadVersion(key, versionId) + : await store.openRead(key); if (!stream) return null; const iterator = stream[Symbol.asyncIterator](); @@ -113,8 +130,9 @@ export async function readText( store: ObjectStore, key: string, maxBytes?: number, + versionId?: string, ): Promise { - const buffer = await readObject(store, key, maxBytes); + const buffer = await readObject(store, key, maxBytes, versionId); return buffer ? buffer.toString('utf8') : null; } diff --git a/src/modules/state-iac/infrastructure/object-store/s3-object-store.ts b/src/modules/state-iac/infrastructure/object-store/s3-object-store.ts index c023db5..cd48201 100644 --- a/src/modules/state-iac/infrastructure/object-store/s3-object-store.ts +++ b/src/modules/state-iac/infrastructure/object-store/s3-object-store.ts @@ -2,11 +2,12 @@ import { Readable } from 'node:stream'; import { GetObjectCommand, HeadObjectCommand, + ListObjectVersionsCommand, ListObjectsV2Command, S3Client, type S3ClientConfig, } from '@aws-sdk/client-s3'; -import type { ListOptions, ListPage, ObjectInfo, ObjectStore } from './object-store'; +import type { ListOptions, ListPage, ObjectInfo, ObjectStore, ObjectVersion } from './object-store'; export type S3ObjectStoreConfig = { bucket: string; @@ -81,10 +82,53 @@ export class S3ObjectStore implements ObjectStore { } } - async openRead(key: string): Promise { + /** Needs `s3:ListBucketVersions`; empty without versioning or permission. */ + async listVersions(key: string): Promise { + try { + const versions: ObjectVersion[] = []; + let keyMarker: string | undefined; + let versionIdMarker: string | undefined; + do { + const response = await this.client.send( + new ListObjectVersionsCommand({ + Bucket: this.bucket, + Prefix: key, + KeyMarker: keyMarker, + VersionIdMarker: versionIdMarker, + }), + ); + for (const version of response.Versions ?? []) { + // unversioned objects report the version id "null" + if (version.Key !== key || !version.VersionId || version.VersionId === 'null') continue; + versions.push({ + versionId: version.VersionId, + updatedAt: version.LastModified?.toISOString() ?? null, + size: version.Size ?? 0, + latest: version.IsLatest === true, + }); + } + keyMarker = response.IsTruncated ? response.NextKeyMarker : undefined; + versionIdMarker = response.IsTruncated ? response.NextVersionIdMarker : undefined; + } while (keyMarker && versions.length < 5_000); + return versions.sort((a, b) => (b.updatedAt ?? '').localeCompare(a.updatedAt ?? '')); + } catch { + return []; + } + } + + openReadVersion(key: string, versionId: string): Promise { + return this.get(key, versionId); + } + + openRead(key: string): Promise { + return this.get(key); + } + + /** Needs `s3:GetObject` (and `s3:GetObjectVersion` with a version). */ + private async get(key: string, versionId?: string): Promise { try { const response = await this.client.send( - new GetObjectCommand({ Bucket: this.bucket, Key: key }), + new GetObjectCommand({ Bucket: this.bucket, Key: key, VersionId: versionId }), ); const body = response.Body; if (!body) return Readable.from([]); diff --git a/src/routes/api/state-iac/stacks/[backend]/[pulumiProject]/[stack]/diff/+server.ts b/src/routes/api/state-iac/stacks/[backend]/[pulumiProject]/[stack]/diff/+server.ts new file mode 100644 index 0000000..40c1cef --- /dev/null +++ b/src/routes/api/state-iac/stacks/[backend]/[pulumiProject]/[stack]/diff/+server.ts @@ -0,0 +1,23 @@ +import { json } from '@sveltejs/kit'; +import { toResponse } from '#lib/server/alerts/http'; +import { getStackDiff, resolveStackScope } from '#lib/server/state-iac/stacks'; + +// GET …/stacks////diff?projectId=…|organizationId=…[&from=&to=]: +// `from`/`to` are source ids (`current`, `history:`, `backup:`, `retained:`, +// `previous`, `version:`); by default the last update against the one before. Needs +// `project:stateiac:states:read`. Secrets are compared without being revealed +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 getStackDiff( + locals, + scope.data, + { backendId: params.backend, project: params.pulumiProject, stack: params.stack }, + { from: url.searchParams.get('from'), to: url.searchParams.get('to') }, + ), + ); +} diff --git a/src/routes/api/state-iac/stacks/[backend]/[pulumiProject]/[stack]/history/+server.ts b/src/routes/api/state-iac/stacks/[backend]/[pulumiProject]/[stack]/history/+server.ts new file mode 100644 index 0000000..14a19e5 --- /dev/null +++ b/src/routes/api/state-iac/stacks/[backend]/[pulumiProject]/[stack]/history/+server.ts @@ -0,0 +1,23 @@ +import { json } from '@sveltejs/kit'; +import { toResponse } from '#lib/server/alerts/http'; +import { getStackHistory, resolveStackScope } from '#lib/server/state-iac/stacks'; + +// GET …/stacks////history?projectId=…|organizationId=… +// [&cursor=][&limit=20]: updates newest first (`project:stateiac:history:read`). +// Config secrets come back masked; the environment is an allow-list (no emails nor paths) +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 }); + const limit = Number(url.searchParams.get('limit') ?? 20); + return toResponse( + await getStackHistory( + locals, + scope.data, + { backendId: params.backend, project: params.pulumiProject, stack: params.stack }, + { cursor: url.searchParams.get('cursor'), limit: Number.isFinite(limit) ? limit : 20 }, + ), + ); +} diff --git a/src/routes/api/state-iac/stacks/server.test.ts b/src/routes/api/state-iac/stacks/server.test.ts index a25bf3d..bb04051 100644 --- a/src/routes/api/state-iac/stacks/server.test.ts +++ b/src/routes/api/state-iac/stacks/server.test.ts @@ -50,6 +50,8 @@ const { fixture } = (await import('#modules/state-iac')) as unknown as { const { fixtureStore } = await import('#modules/state-iac/application/testing'); const list = await import('./+server'); const item = await import('./[backend]/[pulumiProject]/[stack]/+server'); +const historyRoute = await import('./[backend]/[pulumiProject]/[stack]/history/+server'); +const diffRoute = await import('./[backend]/[pulumiProject]/[stack]/diff/+server'); let backendId = ''; @@ -91,6 +93,7 @@ describe('/api/state-iac/stacks', () => { 'project:p1': ['project:stateiac:stacks:read', 'project:stateiac:states:read'], }; grants['user:listOnly'] = { 'project:p1': ['project:stateiac:stacks:read'] }; + grants['user:historian'] = { 'project:p1': ['project:stateiac:history:read'] }; grants['user:org'] = { 'org:org-1': ['organization:stateiac:stacks:read'] }; grants['key:k1'] = { 'project:p1': ['project:stateiac:stacks:read'] }; keyProjects.k1 = 'p1'; @@ -178,4 +181,51 @@ describe('/api/state-iac/stacks', () => { expect((await get(list.GET, '', user('a'))).status).toBe(400); expect((await get(list.GET, 'projectId=nope', user('a'))).status).toBe(404); }); + + it('history needs history:read and pages newest first', async () => { + const params = stackParams('acme-infra', 'prod'); + expect((await get(historyRoute.GET, 'projectId=p1', user('a'), params)).status).toBe(403); + const page = await get(historyRoute.GET, 'projectId=p1&limit=2', user('historian'), params); + expect(page.status).toBe(200); + const body = await page.json(); + expect(body.updates.map((u: { id: string }) => u.id)).toEqual([ + '1795604216162649000', + '1795602803296701000', + ]); + const next = await get( + historyRoute.GET, + `projectId=p1&limit=2&cursor=${body.nextCursor}`, + user('historian'), + params, + ); + expect((await next.json()).updates).toHaveLength(2); + // another project's stack: not found, whatever the grant + const other = await get( + historyRoute.GET, + 'projectId=p1', + user('historian'), + stackParams('acme-platform', 'dev'), + ); + expect(other.status).toBe(404); + }); + + it('diff needs states:read and compares the last update with the previous one', async () => { + const params = stackParams('acme-infra', 'prod'); + expect((await get(diffRoute.GET, 'projectId=p1', user('historian'), params)).status).toBe(403); + const response = await get(diffRoute.GET, 'projectId=p1', user('a'), params); + expect(response.status).toBe(200); + const body = await response.json(); + expect(body.to).toBe('history:1795604216162649000'); + expect(body.diff.summary.update).toBe(2); + const text = JSON.stringify(body); + expect(text).not.toMatch(/ciphertext|v1:/); + + const explicit = await get( + diffRoute.GET, + 'projectId=p1&from=history:1795602066945844000&to=history:1795602803296701000', + user('a'), + params, + ); + expect((await explicit.json()).diff.summary.replace).toBe(1); + }); }); 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 index bb6d498..66c9c66 100644 --- 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 @@ -1,5 +1,10 @@ import { error } from '@sveltejs/kit'; -import { canReadStates, getStack, type StackScope } from '#lib/server/state-iac/stacks'; +import { + canReadHistory, + canReadStates, + getStack, + type StackScope, +} from '#lib/server/state-iac/stacks'; export async function load({ parent, locals, params, url }) { const { project } = await parent(); @@ -9,7 +14,10 @@ export async function load({ parent, locals, params, url }) { organizationId: project.organization?.id ?? '', }; // resources and outputs need `project:stateiac:states:read`; the summary only `stacks:read` - const states = await canReadStates(locals, scope); + const [states, history] = await Promise.all([ + canReadStates(locals, scope), + canReadHistory(locals, scope), + ]); const result = await getStack( locals, scope, @@ -22,6 +30,14 @@ export async function load({ parent, locals, params, url }) { return { detail: result.data, canReadStates: states, + canReadHistory: history, + apiBase: apiBaseOf(params), + scopeQuery: `projectId=${encodeURIComponent(project.id)}`, backHref: `/org/${params.org}/projects/${params.slug}/state-iac`, }; } + +function apiBaseOf(params: { backend: string; pulumiProject: string; stack: string }) { + const part = encodeURIComponent; + return `/api/state-iac/stacks/${part(params.backend)}/${part(params.pulumiProject)}/${part(params.stack)}`; +} 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 index ff93336..4c1d73d 100644 --- 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 @@ -7,6 +7,9 @@ detail: StackDetailView; canReadStates: boolean; backHref: string; + apiBase: string; + scopeQuery: string; + canReadHistory?: boolean; project: { name: string }; }; }; @@ -17,4 +20,11 @@ {data.detail.summary.ref.stack} · State IaC - {data.project.name} - + 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 index 8c5fc35..0e9d810 100644 --- 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 @@ -18,5 +18,7 @@ export async function load({ parent, locals, params, url }) { detail: result.data, projectName: project?.name ?? null, backHref: `/org/${params.org}/state-iac`, + apiBase: `/api/state-iac/stacks/${encodeURIComponent(params.backend)}/${encodeURIComponent(params.pulumiProject)}/${encodeURIComponent(params.stack)}`, + scopeQuery: `organizationId=${encodeURIComponent(organization.id)}`, }; } 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 index 57ba717..9e9ea30 100644 --- a/src/routes/org/[org]/state-iac/[backend]/[pulumiProject]/[stack]/+page.svelte +++ b/src/routes/org/[org]/state-iac/[backend]/[pulumiProject]/[stack]/+page.svelte @@ -2,7 +2,15 @@ import StackDetail from '#lib/components/state-iac/StackDetail.svelte'; import type { StackDetailView } from '#lib/state-iac/types'; - type Props = { data: { detail: StackDetailView; projectName: string | null; backHref: string } }; + type Props = { + data: { + detail: StackDetailView; + projectName: string | null; + backHref: string; + apiBase: string; + scopeQuery: string; + }; + }; let { data }: Props = $props(); @@ -11,6 +19,9 @@