Skip to content
Merged
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
11 changes: 11 additions & 0 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
12 changes: 12 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -215,3 +215,5 @@ pull request.
## License

GitOps is released under the [Elastic License 2.0](license.md).


9 changes: 5 additions & 4 deletions e2e/global-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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');
}
Expand Down
7 changes: 6 additions & 1 deletion eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
],
},
},
{
Expand All @@ -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,
Expand Down
34 changes: 31 additions & 3 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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: '/' } });
Expand Down
16 changes: 16 additions & 0 deletions src/lib/code-report/vulnerability-format.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,20 @@ describe('vulnerability format', () => {
expect(rendered).not.toContain('<script>');
expect(rendered).not.toContain('javascript:');
});

it('never renders remote images, degrading them to a link with the alt text', () => {
const rendered = renderVulnerabilityDescription('![diagram](https://evil.example/pixel.png)');

expect(rendered).not.toContain('<img');
expect(rendered).toContain('href="https://evil.example/pixel.png"');
expect(rendered).toContain('>diagram</a>');
});

it('drops images with unsafe URLs and escapes their alt text', () => {
const rendered = renderVulnerabilityDescription('![x" onerror="alert(1)](javascript:alert(1))');

expect(rendered).not.toContain('<img');
expect(rendered).not.toContain('javascript:');
expect(rendered).not.toContain('"alert(1)');
});
});
7 changes: 7 additions & 0 deletions src/lib/code-report/vulnerability-format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,13 @@ export function renderVulnerabilityDescription(value: string) {
const titleAttribute = title ? ` title="${escapeHtml(title)}"` : '';
return `<a href="${escapeHtml(href)}"${titleAttribute} target="_blank" rel="noreferrer noopener">${text}</a>`;
};
// advisories are third-party content: never let them load remote resources (tracking pixels
// would leak who viewed which CVE), so an image degrades to a plain link with its alt text
renderer.image = ({ href, text }) => {
const label = escapeHtml(text || href);
if (!/^https?:/i.test(href)) return label;
return `<a href="${escapeHtml(href)}" target="_blank" rel="noreferrer noopener">${label}</a>`;
};

return marked.parse(value, { renderer, async: false });
}
1 change: 1 addition & 0 deletions src/lib/components/code-report/CveDetailView.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@
<section class="rounded-[28px] border border-slate-200 bg-white p-6 shadow-sm sm:p-8">
<h2 class="text-sm font-semibold uppercase tracking-wide text-slate-500">Overview</h2>
{#if renderedDescription}
<!-- eslint-disable-next-line svelte/no-at-html-tags -- sanitized by renderVulnerabilityDescription -->
<div class="cve-description mt-2 text-sm text-slate-600">{@html renderedDescription}</div>
{:else}
<p class="mt-2 text-sm text-slate-600">Sin descripcion disponible.</p>
Expand Down
17 changes: 15 additions & 2 deletions src/lib/page-store.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
import { page } from '$app/state';
import { toStore } from 'svelte/store';

// `page` is a single long-lived object whose fields are reactive getters. Returning it as-is
// (`toStore(() => page)`) reads none of those getters, so the store never re-emits after a
// client-side navigation and `$page.url` stays frozen at the first page that was rendered.
// Reading each field here registers them as dependencies and yields a fresh snapshot per change.
export function createPageStore() {
return toStore(() => page);
}
return toStore(() => ({
url: page.url,
params: page.params,
route: page.route,
status: page.status,
error: page.error,
data: page.data,
form: page.form,
state: page.state,
}));
}
108 changes: 108 additions & 0 deletions src/lib/server/starting-page.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
// Served straight from hooks.server.ts while startup (GitDB clone, auth, bootstrap detection) is
// still running or has failed. It is deliberately self-contained HTML: the root layout loads
// organizations, projects and permissions from GitDB, which is exactly what isn't available yet.

export type StartingPageState = 'starting' | 'failed';

type Locale = 'es' | 'en';

const COPY: Record<Locale, Record<StartingPageState, { title: string; body: string }>> = {
es: {
starting: {
title: 'GitOps está arrancando',
body: 'Estamos sincronizando el repositorio de datos. La página se recargará sola en cuanto esté lista.',
},
failed: {
title: 'GitOps no ha podido arrancar',
body: 'El servidor no ha completado el arranque. Revisa los logs o contacta con un administrador del cluster.',
},
},
en: {
starting: {
title: 'GitOps is starting',
body: 'We are syncing the data repository. This page will reload on its own as soon as it is ready.',
},
failed: {
title: 'GitOps failed to start',
body: 'The server did not finish starting up. Check the logs or contact a cluster administrator.',
},
},
};

const RETRY_AFTER_SECONDS = 3;

function pickLocale(acceptLanguage: string | null): Locale {
const first = (acceptLanguage ?? '').split(',')[0]?.trim().toLowerCase() ?? '';
return first.startsWith('en') ? 'en' : 'es';
}

export function renderStartingPage(state: StartingPageState, acceptLanguage: string | null) {
const locale = pickLocale(acceptLanguage);
const { title, body } = COPY[locale][state];
const starting = state === 'starting';

// while starting, poll /health (200 once ready) and reload the original URL; <noscript> falls
// back to a meta refresh. A failed startup won't recover on its own, so it doesn't poll.
const poll = starting
? `<noscript><meta http-equiv="refresh" content="${RETRY_AFTER_SECONDS}"></noscript>
<script>
(function poll() {
fetch('/health', { cache: 'no-store' })
.then(function (r) { if (r.ok) location.reload(); else setTimeout(poll, 1500); })
.catch(function () { setTimeout(poll, 1500); });
})();
</script>`
: '';

const html = `<!doctype html>
<html lang="${locale}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>${title}</title>
${poll}
<style>
:root { color-scheme: dark; }
* { box-sizing: border-box; }
body {
margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 16px;
background: #020813; color: #e2e8f0;
font-family: ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif;
}
main {
width: 100%; max-width: 420px; text-align: center; padding: 40px 28px;
border: 1px solid #142236; border-radius: 20px; background: #06101f;
}
.brand { font-size: 12px; font-weight: 600; letter-spacing: 0.24em; text-transform: uppercase; color: #647189; }
h1 { margin: 20px 0 8px; font-size: 20px; font-weight: 600; color: #fff; }
p { margin: 0; font-size: 14px; line-height: 1.6; color: #94a3b8; }
.spinner {
width: 36px; height: 36px; margin: 28px auto 0; border-radius: 50%;
border: 3px solid #142236; border-top-color: #38bdf8; animation: spin 0.9s linear infinite;
}
.error { width: 36px; height: 36px; margin: 28px auto 0; border-radius: 50%; background: #7f1d1d;
color: #fecaca; font-weight: 700; line-height: 36px; }
@keyframes spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) { .spinner { animation-duration: 3s; } }
</style>
</head>
<body>
<main role="status" aria-live="polite">
<div class="brand">GitOps</div>
${starting ? '<div class="spinner" aria-hidden="true"></div>' : '<div class="error" aria-hidden="true">!</div>'}
<h1>${title}</h1>
<p>${body}</p>
</main>
</body>
</html>`;

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) } : {}),
},
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -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/);
Expand Down
Loading