Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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/<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
11 changes: 11 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,17 @@ and `/api/state-iac/backends/**` check `organization:stateiac:backends:<action>`
`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/<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
Expand Down
95 changes: 95 additions & 0 deletions e2e/fixtures/fake-s3.ts
Original file line number Diff line number Diff line change
@@ -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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');

function notFound(code: 'NoSuchKey' | 'NoSuchBucket') {
return `<?xml version="1.0" encoding="UTF-8"?><Error><Code>${code}</Code><Message>${code}</Message></Error>`;
}

export function startFakeS3(directory: string, port: number): Promise<Server> {
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 = [
'<?xml version="1.0" encoding="UTF-8"?>',
'<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">',
`<Name>${FAKE_S3_BUCKET}</Name><Prefix>${xml(prefix)}</Prefix>`,
`<KeyCount>${page.objects.length + page.prefixes.length}</KeyCount><MaxKeys>${maxKeys}</MaxKeys>`,
delimiter ? `<Delimiter>${delimiter}</Delimiter>` : '',
`<IsTruncated>${page.nextPageToken ? 'true' : 'false'}</IsTruncated>`,
page.nextPageToken
? `<NextContinuationToken>${xml(page.nextPageToken)}</NextContinuationToken>`
: '',
...page.objects.map(
(object) =>
`<Contents><Key>${xml(object.key)}</Key><LastModified>${object.updatedAt}</LastModified><ETag>&quot;${object.version}&quot;</ETag><Size>${object.size}</Size><StorageClass>STANDARD</StorageClass></Contents>`,
),
...page.prefixes.map(
(p) => `<CommonPrefixes><Prefix>${xml(p)}</Prefix></CommonPrefixes>`,
),
'</ListBucketResult>',
].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<Buffer> {
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);
}
59 changes: 59 additions & 0 deletions e2e/fixtures/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -294,6 +303,52 @@ export async function seedAll(): Promise<SeedOutput> {
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',
Expand Down Expand Up @@ -416,6 +471,10 @@ export async function seedAll(): Promise<SeedOutput> {
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,
Expand Down
25 changes: 24 additions & 1 deletion e2e/global-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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<string, string | undefined> {
Expand Down Expand Up @@ -66,6 +78,10 @@ function buildEnv(): Record<string, string | undefined> {
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),
};
}
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -142,5 +164,6 @@ export default async function globalSetup() {
if (!server.killed) {
server.kill();
}
fakeS3.close();
};
}
3 changes: 2 additions & 1 deletion e2e/specs/state-iac-backends.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }) => {
Expand Down
Loading
Loading