diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 9f1ff6e8..1d15a26b 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -130,3 +130,14 @@ Usar los patrones existentes (`*.domain.ts`, `*.service.ts`, `*.repository.ts`, inyeccion de dependencias y fakes en memoria. Los handlers API validan permisos primero y normalizan errores. Ejecutar `bun run check`, `bun run lint`, `bun run test` y `bun run format:check` antes de terminar cambios relevantes. + +## Comportamiento conocido + +**Startup y readiness del servidor:** El auth guard en `hooks.server.ts` verifica readiness via +`getServerReadyState()` antes de procesar cualquier request. Durante startup, los navegadores +reciben una página de landing "GitOps is starting" que se recarga automáticamente, mientras que +API requests reciben 503 con header `retry-after: 3`. Si startup falla, ambos reciben 503 +(página HTML para navegadores, JSON con "Server failed to start" para APIs). El endpoint `/health` +(usado por e2e e infraestructura) devuelve 200 solo tras completar startup. Aplica tanto en dev +(Vite carga en la primera request) como en producción. La bootstrap state es válida solo después +que startup termina. diff --git a/CLAUDE.md b/CLAUDE.md index a6f7e76e..139df673 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -313,3 +313,15 @@ permission-first and normalize errors consistently. Before finishing a change, run the relevant checks. Do not silently fix unrelated bugs or rewrite generated files. Update `README.md`, `CONTRIBUTING.md`, and this file when architecture or public commands change. + +## Known behavior + +**Server startup and readiness:** The auth guard in `hooks.server.ts` checks readiness via +`getServerReadyState()` before processing any request. During startup, browsers receive a +self-reloading "GitOps is starting" landing page, while API requests get a 503 response with +`retry-after: 3` header. If startup fails, both receive 503 Service Unavailable (HTML landing +page for browsers, JSON for APIs with "Server failed to start" message). The `/health` endpoint +(used by e2e and infrastructure probes) returns 200 only after startup completes. This applies +in both development (where Vite loads the module on the first request) and production (where no +infrastructure probe guarantees traffic is held back during startup). The bootstrap state is only +meaningful after startup completes. diff --git a/README.md b/README.md index d6a87575..0edcac19 100644 --- a/README.md +++ b/README.md @@ -215,3 +215,5 @@ pull request. ## License GitOps is released under the [Elastic License 2.0](license.md). + + diff --git a/e2e/global-setup.ts b/e2e/global-setup.ts index eec93581..fb9579ff 100644 --- a/e2e/global-setup.ts +++ b/e2e/global-setup.ts @@ -68,9 +68,10 @@ async function waitForServer(url: string, timeoutMs: number) { while (Date.now() < deadline) { try { const response = await fetch(url, { redirect: 'manual' }); - // any HTTP response (even a redirect to /bootstrap) means the process - // is up; we only need "port is listening and hooks.server.ts responded". - if (response.status > 0) return; + // /health only answers 200 once startup (GitDB clone, auth, bootstrap detection) has + // finished; until then every page gets the 503 "GitOps is starting" landing + if (response.ok) return; + lastError = `HTTP ${response.status}`; } catch (error) { lastError = error; } @@ -115,7 +116,7 @@ export default async function globalSetup() { serverExited = true; }); - await waitForServer(`${E2E_BASE_URL}/auth/login`, 60_000); + await waitForServer(`${E2E_BASE_URL}/health`, 120_000); if (serverExited) { throw new Error('Dev server exited before becoming ready'); } diff --git a/eslint.config.js b/eslint.config.js index d8cc6609..c539e1a3 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -31,7 +31,11 @@ export default [ ...tseslint.configs.recommended.rules, '@typescript-eslint/no-explicit-any': 'off', 'no-unused-vars': 'off', - '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }], + 'no-undef': 'off', + '@typescript-eslint/no-unused-vars': [ + 'error', + { argsIgnorePattern: '^_', ignoreRestSiblings: true }, + ], }, }, { @@ -55,6 +59,7 @@ export default [ 'svelte/require-each-key': 'off', 'svelte/prefer-svelte-reactivity': 'off', 'no-useless-assignment': 'off', + 'svelte/no-useless-mustaches': ['error', { ignoreStringEscape: true }], }, }, prettier, diff --git a/src/hooks.server.ts b/src/hooks.server.ts index 05e54309..b5555e6f 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -6,7 +6,12 @@ import { projectService } from '#modules/projects'; import { registerAlertEngine } from '#modules/alerts'; import { isBootstrapCompleted, refreshBootstrapState } from '#lib/server/bootstrap'; import { startGitDb } from '#lib/server/gitdb'; -import { markServerFailed, markServerReady } from '#lib/server/server-ready'; +import { + getServerReadyState, + markServerFailed, + markServerReady, +} from '#lib/server/server-ready'; +import { renderStartingPage } from '#lib/server/starting-page'; import { runWithActor } from '#lib/server/request-context'; import { createLogger, createRequestLogger, logHttpRequest, logger } from '#lib/server/logger'; @@ -61,8 +66,31 @@ const authGuard: Handle = async ({ event, resolve }) => { return resolve(event); } - // readiness gating happens at the infrastructure level: Cloud Run's startup probe - // polls /health and only routes traffic once the server reports ready + // the bootstrap state is only meaningful once startup has finished: before that it reads as + // "pending" and every request would be sent to (and allowed into) the unauthenticated wizard. + // Vite dev loads this module on the first request, and in production nothing guarantees an + // infrastructure probe holds traffic back, so nothing past this point runs until startup is + // done: pages get a "GitOps is starting" landing that reloads itself, APIs get a 503. + const readiness = getServerReadyState(); + if (readiness.status !== 'ready') { + const state = readiness.status === 'error' ? 'failed' : 'starting'; + if (isApiRequest) { + return new Response( + JSON.stringify({ + error: state === 'failed' ? 'Server failed to start' : 'Server is starting', + }), + { + status: 503, + headers: { + 'content-type': 'application/json', + ...(state === 'starting' ? { 'retry-after': '3' } : {}), + }, + }, + ); + } + return renderStartingPage(state, event.request.headers.get('accept-language')); + } + if (pathname.startsWith('/bootstrap')) { if (isBootstrapCompleted()) { return new Response(null, { status: 302, headers: { location: '/' } }); diff --git a/src/lib/code-report/vulnerability-format.test.ts b/src/lib/code-report/vulnerability-format.test.ts index b0a02233..eab7c795 100644 --- a/src/lib/code-report/vulnerability-format.test.ts +++ b/src/lib/code-report/vulnerability-format.test.ts @@ -25,4 +25,20 @@ describe('vulnerability format', () => { expect(rendered).not.toContain('` + : ''; + + const html = ` + + + + + +${title} +${poll} + + + +
+
GitOps
+ ${starting ? '' : ''} +

${title}

+

${body}

+
+ +`; + + return new Response(html, { + status: 503, + headers: { + 'content-type': 'text/html; charset=utf-8', + 'cache-control': 'no-store', + ...(starting ? { 'retry-after': String(RETRY_AFTER_SECONDS) } : {}), + }, + }); +} diff --git a/src/modules/vault/infrastructure/crypto/secret-cipher.test.ts b/src/modules/vault/infrastructure/crypto/secret-cipher.test.ts index 338549ed..930481ee 100644 --- a/src/modules/vault/infrastructure/crypto/secret-cipher.test.ts +++ b/src/modules/vault/infrastructure/crypto/secret-cipher.test.ts @@ -38,7 +38,7 @@ describe('vault secret cipher', () => { }); it('rejects a tampered ciphertext', () => { - const [version, iv, tag, payload] = encryptSecretValue('secret-1', 'prod', 'value').split(':'); + const [version, iv, tag] = encryptSecretValue('secret-1', 'prod', 'value').split(':'); const tampered = [version, iv, tag, Buffer.from('hacked').toString('base64')].join(':'); expect(() => decryptSecretValue('secret-1', 'prod', tampered)).toThrow(/descifrar/);