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
17 changes: 16 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ Domain layers include entity classes (e.g., `*.domain.ts`) and centralized data
`*.data.ts`) for configuration constants: role permissions, default project settings, risk weights,
and tool policy mappings.

Current modules include `auth`, `config`, `organization`, `projects`, `storage`,
Current modules include `auth`, `config`, `organization`, `projects`, `state-iac`,
`code-report`, `vault`, `audit`, `alerts`, `monitoring`, and `notifications`. The `notifications`
module handles external email recipients of alerts (allowed domains, verification tokens,
unsubscribe tracking). Shared infrastructure lives in `src/lib/`. Routes should import module APIs from
Expand All @@ -194,6 +194,21 @@ origin of the absolute links in emails (`absoluteUrl()`); only under `vite dev`
the origin of the requests the dev server receives instead (`rememberDevOrigin()` in
`hooks.server.ts`), so they work on port 5173 whatever `ORIGIN` says.

## State IaC

`$modules/state-iac` reads IaC state from the buckets where teams keep it; design and Pulumi DIY
layout in `docs/adr/0003-state-iac.md`, anonymized real buckets in `test/fixtures/state-iac/`
(load them with `fixtureStore()` from `application/testing.ts`). GitDB only stores configuration:
`state_backends` (one bucket/prefix per row, per organization; credentials AES-GCM encrypted with
the backend id as AAD, never returned, only `hasCredentials`) and `state_bindings` (one per Pulumi
project of a backend → a GitOps project of the same organization; `stacks` empty = all). Bindings
go with their backend and with their GitOps project (`registerStateIac()` listens to
`project.deleted`). Buckets are only read through `ObjectStore` (`GcsObjectStore`, `S3ObjectStore`,
`InMemoryObjectStore` in tests): never add a write. Org settings page `/org/<org>/settings/state-iac`
and `/api/state-iac/backends/**` check `organization:stateiac:backends:<action>` (actions include
`test`); a backend of another organization answers 404. Read failures are stored as short codes in
`lastError` (`access_denied`, `bucket_not_found`…), never the provider message.

## Domain events

Services announce what happened on an in-process event bus in `#lib/server/events`; the design is
Expand Down
21 changes: 21 additions & 0 deletions e2e/fixtures/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export type PersonaKey =
| 'orgOutsider'
| 'orgNone'
| 'orgProjectsReadOnly'
| 'orgStateIacReader'
| 'projectAdmin'
| 'projectDeveloper'
| 'projectViewer'
Expand Down Expand Up @@ -146,6 +147,22 @@ export async function seedAll(): Promise<SeedOutput> {
email: 'org-projects-read-only@e2e.test',
});

// sees the State IaC backends and their assignments, can't change them
const orgStateIacReaderRole = await roleService.createRole({
name: 'E2E Org State IaC Reader',
slug: 'e2e-org-stateiac-reader',
scope: 'organization',
organizationId: primaryOrg.id,
permissions: ['organization:stateiac:backends:read'],
});
const orgStateIacReader = await userAccessService.createOrganizationUser({
organizationId: primaryOrg.id,
username: 'e2e-org-stateiac-reader',
password: E2E_PASSWORD,
roleId: orgStateIacReaderRole.id,
email: 'org-stateiac-reader@e2e.test',
});

// --- primary project under the primary org ----------------------------------------------
const primaryProject = await projectService.createProject({
organizationId: primaryOrg.id,
Expand Down Expand Up @@ -353,6 +370,10 @@ export async function seedAll(): Promise<SeedOutput> {
userId: orgProjectsReadOnly.userId,
username: orgProjectsReadOnly.username,
},
orgStateIacReader: {
userId: orgStateIacReader.userId,
username: orgStateIacReader.username,
},
projectAdmin: { userId: projectAdminUser.userId, username: projectAdminUser.username },
projectDeveloper: {
userId: projectDeveloperUser.userId,
Expand Down
1 change: 1 addition & 0 deletions e2e/specs/organization-settings.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const settingsRoutes = [
`/org/${org}/settings/audit`,
`/org/${org}/settings/events`,
`/org/${org}/settings/alerts`,
`/org/${org}/settings/state-iac`,
];

test.describe('organization settings — org admin', () => {
Expand Down
31 changes: 23 additions & 8 deletions e2e/specs/project-settings.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,7 @@ test.describe('server access keys — real revoke mutation', () => {
// client-side hydration, which is unrelated to what this test cares about — whether the
// server actually revokes the key for a role with delete permission, not whether the click
// wiring works.
test('a role with delete permission can actually revoke a key', async ({
page,
loginAs,
}) => {
test('a role with delete permission can actually revoke a key', async ({ page, loginAs }) => {
await loginAs('projectAdmin');
await page.goto(`${base}/settings/server-access-keys`);
const before = await page.getByRole('button', { name: /revocar/i }).count();
Expand Down Expand Up @@ -145,10 +142,7 @@ test.describe('project users — role-change control (canUpdate)', () => {
});

test.describe('project roles — real create mutation', () => {
test('project admin can create a role and see it in the list', async ({
page,
loginAs,
}) => {
test('project admin can create a role and see it in the list', async ({ page, loginAs }) => {
await loginAs('projectAdmin');
const response = await page.request.post(`${base}/settings/roles-permissions/new?/createRole`, {
form: {
Expand Down Expand Up @@ -183,3 +177,24 @@ test.describe('project roles — real create mutation', () => {
expect(body.status).toBe(403);
});
});

test.describe('project settings — State IaC module', () => {
test('a project admin can turn the State IaC module off and on', async ({ page, loginAs }) => {
await loginAs('projectAdmin');
await page.goto(`${base}/settings/overview`);
await page.waitForLoadState('networkidle');
const toggle = page.getByRole('switch', { name: 'State IaC' });
const sidebar = page.locator('aside').first();
const save = page.getByRole('button', { name: 'Guardar cambios' });

await expect(toggle).toBeEnabled();
await expect(toggle).toBeChecked();
await toggle.click();
await save.click();
await expect(sidebar.locator(`a[href^="${base}/state-iac"]`)).toHaveCount(0);

await toggle.click();
await save.click();
await expect(sidebar.locator(`a[href^="${base}/state-iac"]`).first()).toBeVisible();
});
});
15 changes: 4 additions & 11 deletions e2e/specs/sidebar-visibility.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,7 @@ const seed = getSeed();
const org = seed.primaryOrgSlug;
const project = seed.primaryProjectSlug;

test('org developer only has a link into "Proyectos", nothing else', async ({
page,
loginAs,
}) => {
test('org developer only has a link into "Proyectos", nothing else', async ({ page, loginAs }) => {
await loginAs('orgDeveloper');
await page.goto(`/org/${org}/settings/projects`);
const sidebar = page.locator('aside').first();
Expand All @@ -20,10 +17,7 @@ test('org developer only has a link into "Proyectos", nothing else', async ({
await expect(page.locator('#section-nav')).toHaveCount(0);
});

test('org admin has links into every organization settings resource', async ({
page,
loginAs,
}) => {
test('org admin has links into every organization settings resource', async ({ page, loginAs }) => {
await loginAs('orgAdmin');
await page.goto(`/org/${org}/settings/projects`);
// el sidebar enlaza el módulo; cada recurso está en las pestañas de sección
Expand Down Expand Up @@ -60,8 +54,7 @@ test('project admin has a sidebar link into Code Report', async ({ page, loginAs
const sidebar = page.locator('aside').first();
const base = `/org/${org}/projects/${project}`;
await expect(sidebar.getByText('Code Report', { exact: true })).toBeVisible();
// Vault is enabled for the seeded project, so the admin gets it too. State IaC is "coming soon":
// the service forces it off, so it never reaches the sidebar regardless of permissions.
// Vault and State IaC are enabled for the seeded project, so the admin gets them too
await expect(sidebar.locator(`a[href="${base}/vault"]`)).toBeVisible();
await expect(sidebar.locator(`a[href^="${base}/state-iac"]`)).toHaveCount(0);
await expect(sidebar.locator(`a[href^="${base}/state-iac"]`).first()).toBeVisible();
});
97 changes: 97 additions & 0 deletions e2e/specs/state-iac-backends.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { test, expect, getSeed } from '../fixtures/auth';
import { expectAllowed, expectDenied } from '../fixtures/expect-access';
import { E2E_BASE_URL } from '../global-setup';

const seed = getSeed();
const pageUrl = `/org/${seed.primaryOrgSlug}/settings/state-iac`;
const api = `${E2E_BASE_URL}/api/state-iac/backends`;

const backendBody = (name: string) => ({
organizationId: seed.primaryOrgId,
name,
provider: 's3',
bucket: 'e2e-state',
endpoint: 'https://minio.example.com',
auth: 'credentials',
credentials: { accessKeyId: 'AKIAE2E', secretAccessKey: 'e2e-very-secret' },
});

test.describe.configure({ mode: 'serial' });

test.describe('state iac backends — org admin', () => {
test('creates a backend from the modal and deletes it typing its name', async ({
page,
loginAs,
}) => {
await loginAs('orgAdmin');
await expectAllowed(page, pageUrl);
await page.waitForLoadState('networkidle');

await page.getByRole('button', { name: 'Nuevo backend' }).click();
const modal = page.getByRole('dialog', { name: 'Nuevo backend' });
await modal.getByLabel('Nombre').fill('e2e-gcs');
await modal.getByLabel('Bucket').fill('e2e-pulumi-state');
await modal.getByLabel('Prefijo').fill('infra');
await modal.getByRole('button', { name: 'Nuevo backend' }).click();

const card = page.getByTestId('state-backends').locator('li', { hasText: 'e2e-gcs' });
await expect(card).toBeVisible();
await expect(card.getByText('gs://e2e-pulumi-state/infra')).toBeVisible();

await card.getByRole('button', { name: 'Eliminar: e2e-gcs' }).click();
const confirm = page.getByRole('alertdialog', { name: '¿Eliminar backend?' });
const submit = confirm.getByRole('button', { name: 'Eliminar' });
await expect(submit).toBeDisabled();
await confirm.getByLabel('Escribe e2e-gcs para confirmar').fill('e2e-gcs');
await submit.click();
await expect(page.getByTestId('state-backends-empty')).toBeVisible();
});

test('the API never returns the credentials', async ({ page, loginAs }) => {
await loginAs('orgAdmin');
const created = await page.request.post(api, { data: backendBody('e2e-s3') });
expect(created.status()).toBe(201);
const { id } = (await created.json()) as { id: string };
const listed = await page.request.get(`${api}?organizationId=${seed.primaryOrgId}`);
const text = await listed.text();
expect(text).toContain('"hasCredentials":true');
expect(text).not.toContain('e2e-very-secret');
expect(text).not.toContain('AKIAE2E');
expect((await page.request.delete(`${api}/${id}`)).status()).toBe(200);
});
});

test.describe('state iac backends — read only', () => {
test('organization:stateiac:backends:read sees the page but cannot configure', async ({
page,
loginAs,
}) => {
await loginAs('orgStateIacReader');
await expectAllowed(page, pageUrl);
await expect(page.getByRole('heading', { name: 'State IaC', level: 1 })).toBeVisible();
await expect(page.getByRole('button', { name: 'Nuevo backend' })).toHaveCount(0);

expect((await page.request.post(api, { data: backendBody('nope') })).status()).toBe(403);
expect((await page.request.get(`${api}?organizationId=${seed.primaryOrgId}`)).status()).toBe(
200,
);
});
});

test.describe('state iac backends — no stateiac grant', () => {
test('an org developer is denied the page and the API', async ({ page, loginAs }) => {
await loginAs('orgDeveloper');
await expectDenied(page, pageUrl);
expect((await page.request.get(`${api}?organizationId=${seed.primaryOrgId}`)).status()).toBe(
403,
);
expect((await page.request.post(api, { data: backendBody('nope') })).status()).toBe(403);
});

test('a member of another organization is denied', async ({ page, loginAs }) => {
await loginAs('orgOutsider');
expect((await page.request.get(`${api}?organizationId=${seed.primaryOrgId}`)).status()).toBe(
403,
);
});
});
3 changes: 3 additions & 0 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { apiKeysService, authService, cancanService, ensureAuthReady } from '#mo
import { organizationService } from '#modules/organization';
import { projectService } from '#modules/projects';
import { registerAlertEngine } from '#modules/alerts';
import { registerStateIac } from '#modules/state-iac';
import { getMonitoringConfig, startMonitoring } from '#modules/monitoring';
import {
isInternalMonitoringRequest,
Expand All @@ -25,6 +26,8 @@ const serverReady = (async () => {
await ensureAuthReady();
// once per process (HMR-safe): system notifications and alerts on every published event
registerAlertEngine();
// State IaC bindings follow the projects they point at
registerStateIac();
await refreshBootstrapState();
markServerReady();
// monitoring needs GitDB; if its repository or runtime can't start, the rest of the app still does
Expand Down
2 changes: 1 addition & 1 deletion src/lib/components/AppSidebar.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@
{#if !isConfigured}
<a
href={organizationSlug
? `/org/${organizationSlug}/settings/storage`
? `/org/${organizationSlug}/settings/state-iac`
: '/gitops-settings/orgs'}
class="mt-3 flex items-center gap-2.5 rounded-xl border border-warn/30 bg-warn/8 p-2.5 text-sm font-medium text-amber-200 transition-colors hover:border-warn/50 {collapsed
? 'justify-center'
Expand Down
18 changes: 18 additions & 0 deletions src/lib/config/permissions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,24 @@ const permissions = {
resource: 'notifications',
permissions: grantsFor('organization', 'notifications'),
},
// State IaC (/org/<org>/settings/state-iac): the buckets with the IaC state and which
// GitOps project sees each Pulumi project. `stacks:read` sees every stack, assigned or not
stateiac: {
resource: 'stateiac',
sections: {
backends: {
resource: 'backends',
permissions: grantsFor('organization:stateiac', 'backends', ['test']),
},
stacks: {
resource: 'stacks',
permissions: [
'organization:stateiac:stacks:read',
'organization:stateiac:stacks:all',
],
},
},
},
},
},
project: {
Expand Down
43 changes: 43 additions & 0 deletions src/lib/database/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,49 @@ export const NotificationChannelEntity = entity('notification_channels', {
lastError: text(),
});

// State IaC (docs/adr/0003-state-iac.md): only configuration, the states stay in the buckets
export const StateBackendEntity = entity('state_backends', {
id: uuid().primaryKey(),
organizationId: uuid().notNull(),
name: text().notNull(),
engine: text().notNull().default('pulumi'),
provider: text().notNull(),
bucket: text().notNull(),
prefix: text(),
region: text(),
endpoint: text(),
forcePathStyle: bool().notNull().default(false),
auth: text().notNull().default('ambient'),
// encrypted JSON (GITDB_ENCRYPTION_KEY, AAD = backend id): never returned by the API
credentials: text(),
enabled: bool().notNull().default(true),
lastScanAt: timestamp(),
lastError: text(),
createdAt: timestamp()
.notNull()
.$defaultFn(() => new Date().toISOString()),
updatedAt: timestamp()
.notNull()
.$defaultFn(() => new Date().toISOString()),
});

export const StateBindingEntity = entity('state_bindings', {
id: uuid().primaryKey(),
organizationId: uuid().notNull(),
backendId: uuid().notNull(),
pulumiProject: text().notNull(),
stacks: json()
.notNull()
.$defaultFn(() => []),
projectId: uuid().notNull(),
createdAt: timestamp()
.notNull()
.$defaultFn(() => new Date().toISOString()),
updatedAt: timestamp()
.notNull()
.$defaultFn(() => new Date().toISOString()),
});

relations.for(ProjectEntity, ({ one, many }) => ({
roles: many(RoleEntity, { fields: ['id'], references: ['projectId'] }),
organization: one(OrganizationEntity, { fields: ['organizationId'], references: ['id'] }),
Expand Down
3 changes: 3 additions & 0 deletions src/lib/events/catalog/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { projectEvents } from './projects.events';
import { organizationEvents } from './organization.events';
import { accessEvents } from './access.events';
import { monitoringEvents } from './monitoring.events';
import { stateIacEvents } from './state-iac.events';
import type {
EventCatalog,
EventDefinition,
Expand All @@ -21,6 +22,7 @@ export { PROJECT_CHANGED_FIELDS } from './projects.events';
export { ORGANIZATION_CHANGED_FIELDS } from './organization.events';
export { ACCESS_SCOPES } from './access.events';
export { MONITORING_CAUSES } from './monitoring.events';
export { STATE_IAC_BACKEND_CHANGED_FIELDS, STATE_IAC_PROVIDERS } from './state-iac.events';
export {
PROJECT_SCOPE_FIELD,
isScopeField,
Expand Down Expand Up @@ -53,6 +55,7 @@ export const EVENT_CATALOG: EventCatalog = defineEventCatalog({
...organizationEvents,
...accessEvents,
...monitoringEvents,
...stateIacEvents,
});

export function isEventType(value: string): value is EventType {
Expand Down
Loading
Loading