diff --git a/apps/mint/tests/test_core.py b/apps/mint/tests/test_core.py index 030523e8..54262d7f 100644 --- a/apps/mint/tests/test_core.py +++ b/apps/mint/tests/test_core.py @@ -233,6 +233,38 @@ def seed_checks(): zhColumnFirst: C.applyTweak(budget, "Actual 小于 0 标红").spec.rules.slice(-1) .map(function (k) { return k.column + k.op + k.value + ":" + k.style; })[0], esThemeWord: C.applyTweak(budget, "cambia el tema a medianoche").spec.theme, + // Traditional Chinese command words (names such as 供應商 stay as typed) + tradTweaks: (function () { + function fresh() { + return C.generate("monthly budget in USD").spec; + } + var names = function (spec) { + return spec.sheet.columns.map(function (c) { return c.name; }); + }; + var sum = C.applyTweak(fresh(), "合計 Planned").spec.summary.slice(-1)[0]; + var rule = C.applyTweak(fresh(), "高亮 Planned 低於 0 紅色").spec.rules.slice(-1)[0]; + return { + removed: names(C.applyTweak(fresh(), "刪除 Item").spec).indexOf("Item") < 0, + sum: sum.fn + ":" + sum.column, + currency: C.applyTweak(fresh(), "貨幣 EUR").spec.currency, + theme: C.applyTweak(fresh(), "主題 深色").spec.theme, + rule: rule.column + rule.op + rule.value + ":" + rule.style, + renamed: names(C.applyTweak(fresh(), "把 Planned 改為 Budget").spec), + added: names(C.applyTweak(fresh(), "新增 供應商 欄").spec) + }; + })(), + esExtra: (function () { + function fresh() { + return C.generate("monthly budget in USD").spec; + } + var rule = C.applyTweak(fresh(), "resalta Planned menos que 0 rojo").spec.rules.slice(-1)[0]; + var sum = C.applyTweak(fresh(), "sumar Planned").spec.summary.slice(-1)[0]; + return { + rule: rule ? rule.column + rule.op + rule.value + ":" + rule.style : null, + modo: C.applyTweak(fresh(), "modo oscuro").spec.theme, + sum: sum.fn + ":" + sum.column + }; + })(), // 3.5.5: "budget" alone is a modifier; the specific template wins budgetModifier: ["trip plan and budget", "旅行预算", "presupuesto de viaje", "wedding budget", "monthly budget", "我的月度预算"] .map(function (p) { return C.generate(p).spec.blueprint; }), @@ -415,6 +447,18 @@ def js_checks(): check(intl["oneRow"] == [1, 1, 1, 1], "add a row without a number works in en/zh/es/id " + str(intl["oneRow"])) check(intl["zhColumnFirst"] == "Actual<0:bad", "zh column-first highlight 标红 " + str(intl["zhColumnFirst"])) check(intl["esThemeWord"] == "midnight", "es theme word medianoche " + str(intl["esThemeWord"])) + trad = intl["tradTweaks"] + check(trad["removed"] is True, "zh-Hant 刪除 removes a column") + check(trad["sum"] == "SUM:Planned", "zh-Hant 合計 adds a SUM card " + str(trad["sum"])) + check(trad["currency"] == "EUR", "zh-Hant 貨幣 sets currency " + str(trad["currency"])) + check(trad["theme"] == "midnight", "zh-Hant 主題 深色 sets theme " + str(trad["theme"])) + check(trad["rule"] == "Planned<0:bad", "zh-Hant 高亮 … 低於 … 紅色 adds red rule " + str(trad["rule"])) + check("Budget" in trad["renamed"] and "Planned" not in trad["renamed"], "zh-Hant 改為 renames") + check("供應商" in trad["added"], "zh-Hant 新增 … 欄 keeps the Traditional column name " + str(trad["added"][-1:])) + esx = intl["esExtra"] + check(esx["rule"] == "Planned<0:bad", "es 'menos que' highlight " + str(esx["rule"])) + check(esx["modo"] == "midnight", "es 'modo oscuro' sets theme " + str(esx["modo"])) + check(esx["sum"] == "SUM:Planned", "es 'sumar' adds a SUM card " + str(esx["sum"])) check(intl["budgetModifier"] == ["travel", "travel", "travel", "event", "budget", "budget"], "budget as a modifier gives way to trip/wedding templates " + str(intl["budgetModifier"])) check(intl["phrasings"] == ["MXN", "CNY", "ocean", "midnight", "Mi presupuesto", "Anggaranku", False], diff --git a/apps/mint/web/js/core.js b/apps/mint/web/js/core.js index 93570aea..9dc0974f 100644 --- a/apps/mint/web/js/core.js +++ b/apps/mint/web/js/core.js @@ -1587,7 +1587,8 @@ }; var ES_TOTALS = { total: "total", suma: "sum", promedio: "average", media: "average", "máximo": "max", maximo: "max", - "mínimo": "min", minimo: "min", cuenta: "count", conteo: "count" + "mínimo": "min", minimo: "min", cuenta: "count", conteo: "count", + sumar: "sum", promediar: "average", contar: "count" }; var COLOUR_WORDS = { "红": "red", "红色": "red", "绿": "green", "绿色": "green", "黄": "yellow", "黄色": "yellow", @@ -1631,8 +1632,39 @@ var ES_NUMBERS = { un: 1, una: 1, otra: 1, dos: 2, tres: 3, cuatro: 4, cinco: 5, seis: 6, siete: 7, ocho: 8, nueve: 9, diez: 10 }; var ID_NUMBERS = { satu: 1, se: 1, dua: 2, tiga: 3, empat: 4, lima: 5, enam: 6, tujuh: 7, delapan: 8, sembilan: 9, sepuluh: 10 }; + // Traditional Chinese: convert command words only (never column names) so the Simplified rules below match. + // Longest first; single-character words are only converted where they cannot be part of a name. + var ZH_TRAD_WORDS = [ + ["重新命名為", "重命名为"], ["突出顯示", "突出显示"], ["重命名為", "重命名为"], ["重命名成", "重命名成"], + ["改名為", "改名为"], ["命名為", "命名为"], ["顯示為", "显示为"], ["標記為", "标记为"], + ["模板名稱", "模板名称"], ["改為", "改为"], ["設為", "设为"], ["標為", "标为"], ["標成", "标成"], ["標記", "标记"], ["標出", "标出"], + ["刪除", "删除"], ["刪掉", "删掉"], ["合計", "合计"], ["總計", "总计"], ["總和", "总和"], ["計數", "计数"], + ["貨幣", "货币"], ["幣種", "币种"], ["主題", "主题"], ["風格", "风格"], ["顏色", "颜色"], ["標題", "标题"], + ["低於", "低于"], ["高於", "高于"], ["小於", "小于"], ["大於", "大于"], ["少於", "少于"], ["多於", "多于"], + ["超過", "超过"], ["等於", "等于"], ["紅色", "红色"], ["綠色", "绿色"], ["黃色", "黄色"], + ["換成", "换成"], ["換用", "换用"], ["換個", "换个"], ["換一個", "换一个"], ["欄位", "字段"], + ["類型", "类型"], ["選項", "选项"], ["公式為", "公式为"], ["選項為", "选项为"], ["數據", "数据"], ["記錄", "记录"] + ]; + + function zhSimplifyCommand(text) { + var s = String(text); + ZH_TRAD_WORDS.forEach(function (pair) { + s = s.split(pair[0]).join(pair[1]); + }); + return s + .replace(/^將/, "将") + .replace(/(^|\s)欄(?=\s|$)/g, "$1栏") + .replace(/欄$/, "栏") + .replace(/(\s|[低高小大少多于过])\s*紅$/, "$1红") + .replace(/(\s|[低高小大少多于过])\s*綠$/, "$1绿") + .replace(/(\s|[低高小大少多于过])\s*黃$/, "$1黄") + .replace(/(\d)\s*紅$/, "$1 红") + .replace(/(\d)\s*綠$/, "$1 绿") + .replace(/(\d)\s*黃$/, "$1 黄"); + } + function zhTweak(spec, text) { - var s = text.replace(/:/g, ":").replace(/[,、]/g, ",").replace(/=/g, "=").trim(); + var s = zhSimplifyCommand(text).replace(/:/g, ":").replace(/[,、]/g, ",").replace(/=/g, "=").trim(); var m; if ((m = /^(?:添加|新增|增加|加上?|再加)\s*(\d{1,3}|[一两二三四五六七八九十])?\s*(?:个)?\s*(?:新的?)?\s*(?:行|条)(?:数据|记录)?$/.exec(s))) { return "add " + (ZH_NUMBERS[m[1]] || m[1] || 1) + " rows"; @@ -1707,14 +1739,14 @@ if ((m = /^(?:usa(?:r)?|paga(?:r)?\s+en|cambia(?:r)?\s+a|p[áa]sa(?:lo)?\s+a)\s+(.+)$/i.exec(s)) && detectCurrency(m[1])) { return "currency " + m[1]; } - if ((m = /^(?:(?:cambia(?:r)?|pon(?:er)?|usa(?:r)?)\s+(?:el\s+)?)?(?:tema|estilo|color)\b\s*(?:a\s+|en\s+|:)?\s*(.+)$/i.exec(s))) { + if ((m = /^(?:(?:cambia(?:r)?|pon(?:er)?|usa(?:r)?)\s+(?:el\s+)?)?(?:tema|estilo|color|modo)\b\s*(?:a\s+|en\s+|:)?\s*(.+)$/i.exec(s))) { return "theme " + m[1]; } - if ((m = new RegExp("^(?:(?:añad[ea]|agreg[ae])\\s+" + art + ")?(suma|promedio|media|m[áa]ximo|m[íi]nimo|cuenta|conteo)\\s+(?:de\\s+" + art + ")?(.+)$", "i").exec(s)) || + if ((m = new RegExp("^(?:(?:añad[ea]|agreg[ae])\\s+" + art + ")?(sumar|suma|promediar|promedio|media|m[áa]ximo|m[íi]nimo|contar|cuenta|conteo)\\s+(?:de\\s+" + art + ")?(.+)$", "i").exec(s)) || (m = new RegExp("^(?:(?:añad[ea]|agreg[ae])\\s+" + art + ")?(total)\\s+de\\s+" + art + "(.+)$", "i").exec(s))) { return ES_TOTALS[m[1].toLowerCase()] + " of " + m[2]; } - if ((m = /^(?:resalta(?:r)?|marca(?:r)?|destaca(?:r)?|colorea(?:r)?)\s+(?:la\s+columna\s+|el\s+campo\s+)?(.+?)\s+(?:cuando\s+(?:sea|est[ée])\s+)?(menor\s+que|menos\s+de|por\s+debajo\s+de|debajo\s+de|mayor\s+que|m[áa]s\s+de|por\s+encima\s+de|encima\s+de|igual\s+a)\s+(.+?)(?:\s+(?:en\s+)?(rojo|verde|amarillo))?$/i.exec(s))) { + if ((m = /^(?:resalta(?:r)?|marca(?:r)?|destaca(?:r)?|colorea(?:r)?)\s+(?:la\s+columna\s+|el\s+campo\s+)?(.+?)\s+(?:cuando\s+(?:sea|est[ée])\s+)?(menor\s+que|menos\s+que|menos\s+de|por\s+debajo\s+de|debajo\s+de|mayor\s+que|m[áa]s\s+de|por\s+encima\s+de|encima\s+de|igual\s+a)\s+(.+?)(?:\s+(?:en\s+)?(rojo|verde|amarillo))?$/i.exec(s))) { var esOp = /menor|menos|debajo/i.test(m[2]) ? "below" : /mayor|m[áa]s|encima/i.test(m[2]) ? "above" : "equal to"; return "highlight " + m[1] + " " + esOp + " " + m[3] + (m[4] ? " " + COLOUR_WORDS[m[4].toLowerCase()] : ""); } diff --git a/openforge/apps/api/src/__tests__/e2e/oidc-roundtrip.test.ts b/openforge/apps/api/src/__tests__/e2e/oidc-roundtrip.test.ts new file mode 100644 index 00000000..b582ac6c --- /dev/null +++ b/openforge/apps/api/src/__tests__/e2e/oidc-roundtrip.test.ts @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: MIT +// +// E2E test for the OIDC token round-trip. +// +// Exercises: +// 1. Runner registration token is hashed (SHA-256) and stored. +// 2. Runner sends Authorization: Bearer . +// 3. Server hashes the bearer, looks up the runner. +// 4. Server checks runnerOwnsJob against runner_jobs. +// 5. Server mints an HS256 JWT with cache_mode + permissions claims. +// 6. Runner-side verification round-trip succeeds. +// +// Requires DATABASE_URL pointing at a Postgres with the OpenForge +// schema applied (migrations 0001 + 0002). The test inserts a test +// runner + token + job, exercises the flow, and cleans up. + +import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest' +import { createHash } from 'node:crypto' +import { db } from '@openforge/db' +import { runners, runnerRegistrationTokens, runnerJobs } from '@openforge/db' +import { eq } from 'drizzle-orm' +import { createTestApp, type TestApp } from './setup.js' +import { verifyOidcToken, OIDC_TOKEN_LIFETIME_SECONDS } from '../../services/oidc-token.js' + +const ISSUER = 'openforge.test' +const SECRET = 'a'.repeat(64) +const BEARER_PLAINTEXT = 'super-secret-runner-token-32chars-min' + +function sha256Hex(s: string): string { + return createHash('sha256').update(s, 'utf8').digest('hex') +} + +const bearerHash = sha256Hex(BEARER_PLAINTEXT) + +let app: TestApp +let testRunnerId: string +let testJobId: string + +async function cleanup(): Promise<void> { + await db.delete(runnerJobs).where(eq(runnerJobs.runnerId, testRunnerId)) + await db.delete(runnerRegistrationTokens).where(eq(runnerRegistrationTokens.runnerId, testRunnerId)) + await db.delete(runners).where(eq(runners.id, testRunnerId)) +} + +describe('OIDC round-trip E2E', () => { + beforeAll(async () => { + app = await createTestApp({ + oidcIssuer: ISSUER, + oidcSigningSecret: SECRET, + }) + + const inserted = await db + .insert(runners) + .values({ + name: `e2e-test-runner-${Date.now()}`, + description: 'E2E test runner', + labels: [], + sandbox: 'gvisor', + ephemeral: true, + maxParallelJobs: 1, + status: 'idle', + version: 'e2e', + }) + .returning({ id: runners.id }) + testRunnerId = inserted[0].id + + await db.insert(runnerRegistrationTokens).values({ + runnerId: testRunnerId, + tokenHash: bearerHash, + tokenPrefix: BEARER_PLAINTEXT.slice(0, 8), + }) + + const insertedJob = await db + .insert(runnerJobs) + .values({ + runnerId: testRunnerId, + jobId: 999999, + pickedUpAt: new Date(), + }) + .returning({ id: runnerJobs.id }) + testJobId = insertedJob[0].id + }) + + afterAll(async () => { + await cleanup() + await app.close() + }) + + beforeEach(async () => { + // nothing per-test for now + }) + + it('rejects unauthenticated request with 401', async () => { + const res = await app.fetch('/api/v1/runner/oidc-token', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + jobId: 999999, + audience: 'sts.amazonaws.com', + }), + }) + expect(res.status).toBe(401) + }) + + it('rejects request for a job the runner does not own', async () => { + const res = await app.fetch('/api/v1/runner/oidc-token', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${BEARER_PLAINTEXT}`, + }, + body: JSON.stringify({ + jobId: 12345, + audience: 'sts.amazonaws.com', + }), + }) + expect(res.status).toBe(403) + }) + + it('mints a valid JWT for a runner that owns the job', async () => { + const res = await app.fetch('/api/v1/runner/oidc-token', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${BEARER_PLAINTEXT}`, + }, + body: JSON.stringify({ + jobId: 999999, + audience: 'sts.amazonaws.com', + cacheMode: 'read', + permissions: 'reviewer', + }), + }) + expect(res.status).toBe(200) + + const body = (await res.json()) as { + value: string + expiresAt: string + audience: string + jobId: number + issuer: string + cacheMode?: string + permissions?: string + } + + expect(body.value.split('.').length).toBe(3) + expect(body.audience).toBe('sts.amazonaws.com') + expect(body.jobId).toBe(999999) + expect(body.issuer).toBe(ISSUER) + expect(body.cacheMode).toBe('read') + expect(body.permissions).toBe('reviewer') + + const exp = new Date(body.expiresAt).getTime() + expect(exp - Date.now()).toBeGreaterThan(OIDC_TOKEN_LIFETIME_SECONDS * 1000 - 5000) + expect(exp - Date.now()).toBeLessThanOrEqual(OIDC_TOKEN_LIFETIME_SECONDS * 1000 + 5000) + + const verification = verifyOidcToken(body.value, { issuer: ISSUER, signingSecret: SECRET }) + expect(verification.valid).toBe(true) + if (verification.valid) { + expect(verification.payload?.['aud']).toBe('sts.amazonaws.com') + expect(verification.payload?.['sub']).toBe('job:999999') + expect(verification.payload?.['cache_mode']).toBe('read') + expect(verification.payload?.['permissions']).toBe('reviewer') + } + }) + + it('rejects tampered tokens (signature mismatch)', async () => { + const res = await app.fetch('/api/v1/runner/oidc-token', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${BEARER_PLAINTEXT}`, + }, + body: JSON.stringify({ + jobId: 999999, + audience: 'sts.amazonaws.com', + }), + }) + const body = (await res.json()) as { value: string } + const tampered = body.value.slice(0, -5) + 'AAAAA' + const verification = verifyOidcToken(tampered, { issuer: ISSUER, signingSecret: SECRET }) + expect(verification.valid).toBe(false) + expect(verification.reason).toBe('signature mismatch') + }) + + it('rejects audience mismatch', async () => { + const verification = verifyOidcToken( + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ3cm9uZyIsImF1ZCI6ImV2aWwifQ.fake', + { issuer: ISSUER, signingSecret: SECRET }, + ) + expect(verification.valid).toBe(false) + }) +}) diff --git a/openforge/apps/api/src/__tests__/e2e/setup.ts b/openforge/apps/api/src/__tests__/e2e/setup.ts new file mode 100644 index 00000000..67cebd23 --- /dev/null +++ b/openforge/apps/api/src/__tests__/e2e/setup.ts @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: MIT +// +// E2E test harness for the OpenForge API. +// +// Boots the Hono app in-process and provides a minimal HTTP client +// wrapper. Database is configurable: pass DATABASE_URL to use a real +// Postgres, or leave it unset to use the in-memory mock (only covers +// routes that don't touch the DB). +// +// Usage: +// DATABASE_URL=postgres://... pnpm vitest run e2e + +import { Hono } from 'hono' +import { logger } from 'hono/logger' +import { cors } from 'hono/cors' +import { secureHeaders } from 'hono/secure-headers' +import { healthRouter } from '../routes/health.js' +import { authRouter } from '../routes/auth.js' +import { gitRouter } from '../routes/git.js' +import { reposRouter } from '../routes/repos.js' +import { runnerRouter } from '../routes/runner.js' +import { errorHandler } from '../middleware/error.js' +import { requestIdMiddleware } from '../middleware/request-id.js' +import { authMiddleware } from '../middleware/auth.js' +import type { AppEnv } from '../../index.js' + +export interface TestApp { + app: Hono<AppEnv> + baseUrl: string + fetch: (path: string, init?: RequestInit) => Promise<Response> + close: () => Promise<void> +} + +export interface TestAppOptions { + oidcIssuer: string + oidcSigningSecret: string +} + +export async function createTestApp(opts: TestAppOptions): Promise<TestApp> { + process.env['OIDC_ISSUER'] = opts.oidcIssuer + process.env['OIDC_SIGNING_SECRET'] = opts.oidcSigningSecret + + const app = new Hono<AppEnv>() + app.use('*', requestIdMiddleware) + app.use('*', logger()) + app.use('*', secureHeaders()) + app.use('*', cors({ origin: ['*'], credentials: true })) + app.use('*', errorHandler) + app.use('*', authMiddleware) + app.route('/healthz', healthRouter) + app.route('/api/auth', authRouter) + app.route('/api/repos', reposRouter) + app.route('/api/v1/runner', runnerRouter) + app.route('/', gitRouter) + + return { + app, + baseUrl: 'http://test.local', + fetch: (path, init) => app.request(`http://test.local${path}`, init), + close: async () => { + delete process.env['OIDC_ISSUER'] + delete process.env['OIDC_SIGNING_SECRET'] + }, + } +} diff --git a/openforge/apps/api/src/index.ts b/openforge/apps/api/src/index.ts new file mode 100644 index 00000000..ac6692ed --- /dev/null +++ b/openforge/apps/api/src/index.ts @@ -0,0 +1,62 @@ +import { Hono } from 'hono' +import { logger } from 'hono/logger' +import { cors } from 'hono/cors' +import { secureHeaders } from 'hono/secure-headers' +import { healthRouter } from './routes/health.js' +import { authRouter } from './routes/auth.js' +import { gitRouter } from './routes/git.js' +import { reposRouter } from './routes/repos.js' +import { runnerRouter } from './routes/runner.js' +import { errorHandler } from './middleware/error.js' +import { requestIdMiddleware } from './middleware/request-id.js' +import { authMiddleware } from './middleware/auth.js' +import { logger as appLogger } from './lib/logger.js' + +export type AppEnv = { + Variables: { + user: { id: string; email: string } | null + session: { id: string; userId: string; expiresAt: Date } | null + requestId: string + } +} + +const app = new Hono<AppEnv>() + +app.use('*', requestIdMiddleware) +app.use('*', logger()) +app.use('*', secureHeaders()) +app.use( + '*', + cors({ + origin: process.env['TRUSTED_ORIGINS']?.split(',') ?? [], + credentials: true, + }), +) +app.use('*', errorHandler) +app.use('*', authMiddleware) + +app.route('/healthz', healthRouter) +app.route('/api/auth', authRouter) +app.route('/api/repos', reposRouter) +app.route('/api/v1/runner', runnerRouter) +app.route('/', gitRouter) + +const port = Number(process.env['API_PORT'] ?? 8787) +export default { port, fetch: app.fetch } + +const entry = process.argv[1] +const isMain = + !!entry && + (import.meta.url === `file://${entry}` || + import.meta.url.endsWith(entry.replace(/\\/g, '/'))) + +if (isMain) { + if (typeof Bun !== 'undefined') { + Bun.serve({ port, fetch: app.fetch }) + } else { + const { serve } = await import('@hono/node-server') + serve({ port, fetch: app.fetch }) + } + appLogger.info({ port }, `[openforge-api] listening on http://localhost:${port}`) + console.log(`[openforge-api] listening on http://localhost:${port}`) +} diff --git a/openforge/apps/api/src/routes/runner.ts b/openforge/apps/api/src/routes/runner.ts new file mode 100644 index 00000000..437e2221 --- /dev/null +++ b/openforge/apps/api/src/routes/runner.ts @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: MIT +import { Hono, type Context } from 'hono' +import { zValidator } from '@hono/zod-validator' +import { z } from 'zod' +import { and, eq, isNotNull, sql } from 'drizzle-orm' +import { db } from '@openforge/db' +import { runnerJobs } from '@openforge/db' +import type { AppEnv } from '../index.js' +import { appLogger } from '../lib/logger.js' +import { + issueOidcToken, + validateConfig, + type OidcIssuerConfig, +} from '../services/oidc-token.js' +import { + authenticateRunnerByBearer, + extractBearer, +} from '../services/runner-auth.js' + +type Ctx = Context<{ Variables: AppEnv['Variables'] & { runner: { id: string; name: string } } }> + +const requestSchema = z.object({ + jobId: z.number().int().positive(), + audience: z.string().trim().min(1).max(512), + lifetimeSec: z.number().int().positive().max(15 * 60).optional(), + cacheMode: z.enum(['read', 'write', 'write-only', 'none']).optional(), + permissions: z.enum(['none', 'reviewer', 'full']).optional(), +}) + +let cachedConfig: OidcIssuerConfig | null = null + +function getConfig(): OidcIssuerConfig { + if (cachedConfig) return cachedConfig + const issuer = process.env['OIDC_ISSUER'] + const secret = process.env['OIDC_SIGNING_SECRET'] + if (!issuer || !secret) { + throw new Error( + 'OIDC_ISSUER and OIDC_SIGNING_SECRET must be set (signing secret >= 32 bytes)', + ) + } + cachedConfig = validateConfig({ issuer, signingSecret: secret }) + return cachedConfig +} + +async function authenticateRunner(c: Context): Promise<{ id: string; name: string } | null> { + const bearer = extractBearer(c.req.header('authorization')) + if (!bearer) return null + const runner = await authenticateRunnerByBearer(bearer) + if (!runner) return null + return { id: runner.id, name: runner.name } +} + +async function runnerOwnsJob(runnerId: string, jobId: number): Promise<boolean> { + const rows = await db + .select({ exists: sql<number>`1` }) + .from(runnerJobs) + .where( + and( + eq(runnerJobs.runnerId, runnerId), + eq(runnerJobs.jobId, jobId), + isNotNull(runnerJobs.pickedUpAt), + ), + ) + .limit(1) + return rows.length > 0 +} + +const router = new Hono<AppEnv>() + +router.post('/oidc-token', zValidator('json', requestSchema), async c => { + const runner = await authenticateRunner(c) + if (!runner) { + return c.json({ error: 'unauthorized' }, 401) + } + + const body = c.req.valid('json') + + const owns = await runnerOwnsJob(runner.id, body.jobId) + if (!owns) { + return c.json({ error: 'runner does not own this job' }, 403) + } + + try { + const token = issueOidcToken(getConfig(), { + jobId: body.jobId, + audience: body.audience, + lifetimeSec: body.lifetimeSec, + cacheMode: body.cacheMode, + permissions: body.permissions, + }) + appLogger.info( + { + runnerId: runner.id, + jobId: body.jobId, + audience: body.audience, + cacheMode: body.cacheMode, + permissions: body.permissions, + }, + 'issued oidc token', + ) + return c.json(token, 200) + } catch (err) { + appLogger.error({ err, runnerId: runner.id, jobId: body.jobId }, 'failed to issue oidc token') + return c.json({ error: 'token issuance failed' }, 500) + } +}) + +export const runnerRouter = router diff --git a/openforge/apps/api/src/services/__tests__/egress-policy.test.ts b/openforge/apps/api/src/services/__tests__/egress-policy.test.ts new file mode 100644 index 00000000..38840c75 --- /dev/null +++ b/openforge/apps/api/src/services/__tests__/egress-policy.test.ts @@ -0,0 +1,154 @@ +// SPDX-License-Identifier: MIT +import { describe, it, expect } from 'vitest' +import { + decideEgress, + DEFAULT_EGRESS_ALLOWLIST, + type EgressAllowlistEntry, +} from './egress-policy.js' + +describe('decideEgress', () => { + describe('deny-all mode', () => { + it.each([ + ['registry.npmjs.org'], + ['pypi.org'], + ['anything.example.com'], + ])('denies %s', (destination) => { + const decision = decideEgress({ + mode: 'deny-all', + destination, + allowlist: [], + }) + expect(decision.allowed).toBe(false) + expect(decision.reason).toContain('deny-all') + }) + }) + + describe('allow-all mode', () => { + it('allows any destination', () => { + const decision = decideEgress({ + mode: 'allow-all', + destination: 'attacker.example.com', + allowlist: [], + }) + expect(decision.allowed).toBe(true) + expect(decision.reason).toContain('allow-all') + }) + }) + + describe('allowlist mode', () => { + const allowlist: EgressAllowlistEntry[] = [ + { pattern: 'registry.npmjs.org', kind: 'host', note: 'npm' }, + { pattern: '.github.com', kind: 'wildcard', note: 'GitHub' }, + { pattern: '10.0.0.0/8', kind: 'cidr', note: 'internal VPC' }, + ] + + it('allows exact host match', () => { + const decision = decideEgress({ + mode: 'allowlist', + destination: 'registry.npmjs.org', + allowlist, + }) + expect(decision.allowed).toBe(true) + expect(decision.matchedEntry?.pattern).toBe('registry.npmjs.org') + }) + + it('rejects different host even on same TLD', () => { + const decision = decideEgress({ + mode: 'allowlist', + destination: 'evil.com', + allowlist, + }) + expect(decision.allowed).toBe(false) + }) + + it('allows wildcard suffix match', () => { + const decision = decideEgress({ + mode: 'allowlist', + destination: 'api.github.com', + allowlist, + }) + expect(decision.allowed).toBe(true) + expect(decision.matchedEntry?.kind).toBe('wildcard') + }) + + it('allows CIDR match for IP in range', () => { + const decision = decideEgress({ + mode: 'allowlist', + destination: '10.0.5.7', + allowlist, + }) + expect(decision.allowed).toBe(true) + expect(decision.matchedEntry?.kind).toBe('cidr') + }) + + it('rejects CIDR match for IP outside range', () => { + const decision = decideEgress({ + mode: 'allowlist', + destination: '192.168.1.1', + allowlist, + }) + expect(decision.allowed).toBe(false) + }) + + it('rejects when allowlist is empty', () => { + const decision = decideEgress({ + mode: 'allowlist', + destination: 'registry.npmjs.org', + allowlist: [], + }) + expect(decision.allowed).toBe(false) + }) + }) + + describe('CIDR edge cases', () => { + it('rejects malformed CIDR (no slash)', () => { + const decision = decideEgress({ + mode: 'allowlist', + destination: '10.0.0.1', + allowlist: [{ pattern: '10.0.0.0', kind: 'cidr', note: 'bad' }], + }) + expect(decision.allowed).toBe(false) + }) + + it('rejects malformed CIDR (out-of-range prefix)', () => { + const decision = decideEgress({ + mode: 'allowlist', + destination: '10.0.0.1', + allowlist: [{ pattern: '10.0.0.0/99', kind: 'cidr', note: 'bad' }], + }) + expect(decision.allowed).toBe(false) + }) + + it('rejects malformed IPv4 destination', () => { + const decision = decideEgress({ + mode: 'allowlist', + destination: '999.999.999.999', + allowlist: [{ pattern: '10.0.0.0/8', kind: 'cidr', note: 'cidr' }], + }) + expect(decision.allowed).toBe(false) + }) + + it('handles /0 (match-all)', () => { + const decision = decideEgress({ + mode: 'allowlist', + destination: '8.8.8.8', + allowlist: [{ pattern: '0.0.0.0/0', kind: 'cidr', note: 'all' }], + }) + expect(decision.allowed).toBe(true) + }) + }) + + describe('default allowlist', () => { + it('includes common destinations', () => { + const destinations = DEFAULT_EGRESS_ALLOWLIST.map(e => e.pattern) + expect(destinations).toContain('registry.npmjs.org') + expect(destinations).toContain('pypi.org') + }) + + it('all entries are typed', () => { + for (const entry of DEFAULT_EGRESS_ALLOWLIST) { + expect(['host', 'wildcard', 'cidr']).toContain(entry.kind) + } + }) + }) +}) diff --git a/openforge/apps/api/src/services/__tests__/oidc-token.test.ts b/openforge/apps/api/src/services/__tests__/oidc-token.test.ts new file mode 100644 index 00000000..015baf62 --- /dev/null +++ b/openforge/apps/api/src/services/__tests__/oidc-token.test.ts @@ -0,0 +1,237 @@ +// SPDX-License-Identifier: MIT +// +// Tests for the OIDC token issuer. Pure unit tests, no DB, no HTTP. + +import { describe, it, expect } from 'vitest' +import { + issueOidcToken, + validateConfig, + verifyOidcToken, + OIDC_TOKEN_LIFETIME_SECONDS, + OidcIssuerConfigError, +} from './oidc-token.js' + +const baseConfig = { + issuer: 'forge.example.com', + signingSecret: 'a'.repeat(64), // 64 random bytes (here just 'a's for test) +} + +describe('validateConfig', () => { + it('rejects empty issuer', () => { + expect(() => validateConfig({ issuer: '', signingSecret: baseConfig.signingSecret })).toThrow( + OidcIssuerConfigError, + ) + }) + + it('rejects short signing secret', () => { + expect(() => validateConfig({ issuer: 'x', signingSecret: 'short' })).toThrow( + OidcIssuerConfigError, + ) + }) + + it('accepts a valid config', () => { + expect(() => validateConfig(baseConfig)).not.toThrow() + }) +}) + +describe('issueOidcToken', () => { + const fixedNow = new Date('2026-11-03T12:00:00Z') + + it('issues a token with the default 5-minute lifetime', () => { + const resp = issueOidcToken(baseConfig, { jobId: 42, audience: 'sts.amazonaws.com' }, fixedNow) + expect(resp.audience).toBe('sts.amazonaws.com') + expect(resp.jobId).toBe(42) + expect(resp.issuer).toBe('forge.example.com') + expect(resp.value.split('.').length).toBe(3) + // expiry is 5 minutes after now + const expectedExpiry = new Date(fixedNow.getTime() + OIDC_TOKEN_LIFETIME_SECONDS * 1000) + expect(new Date(resp.expiresAt).getTime()).toBe(expectedExpiry.getTime()) + }) + + it('honors a custom lifetime within bounds', () => { + const resp = issueOidcToken( + baseConfig, + { jobId: 1, audience: 'k8s.default', lifetimeSec: 120 }, + fixedNow, + ) + const expectedExpiry = new Date(fixedNow.getTime() + 120 * 1000) + expect(new Date(resp.expiresAt).getTime()).toBe(expectedExpiry.getTime()) + }) + + it('rejects lifetimeSec > 15 minutes', () => { + expect(() => + issueOidcToken(baseConfig, { jobId: 1, audience: 'k8s.default', lifetimeSec: 16 * 60 }, fixedNow), + ).toThrow(/exceeds maximum/) + }) + + it('rejects non-positive jobId', () => { + expect(() => issueOidcToken(baseConfig, { jobId: 0, audience: 'x' }, fixedNow)).toThrow( + /positive integer/, + ) + expect(() => issueOidcToken(baseConfig, { jobId: -1, audience: 'x' }, fixedNow)).toThrow( + /positive integer/, + ) + }) + + it('rejects empty audience', () => { + expect(() => issueOidcToken(baseConfig, { jobId: 1, audience: '' }, fixedNow)).toThrow( + /non-empty/, + ) + expect(() => + issueOidcToken(baseConfig, { jobId: 1, audience: ' ' }, fixedNow), + ).toThrow(/non-empty/) + }) + + it('produces distinct jti claims across calls', () => { + const a = issueOidcToken(baseConfig, { jobId: 1, audience: 'x' }, fixedNow) + const b = issueOidcToken(baseConfig, { jobId: 1, audience: 'x' }, fixedNow) + expect(a.value).not.toBe(b.value) + }) + + it('includes cache_mode in JWT payload and response when provided', () => { + const resp = issueOidcToken( + baseConfig, + { jobId: 7, audience: 'openforge-cache', cacheMode: 'read' }, + fixedNow, + ) + expect(resp.cacheMode).toBe('read') + + const payloadB64 = resp.value.split('.')[1] + const payload = JSON.parse(Buffer.from(payloadB64, 'base64').toString('utf8')) + expect(payload['cache_mode']).toBe('read') + }) + + it('omits cache_mode from JWT payload when not provided', () => { + const resp = issueOidcToken( + baseConfig, + { jobId: 7, audience: 'sts.amazonaws.com' }, + fixedNow, + ) + expect(resp.cacheMode).toBeUndefined() + + const payloadB64 = resp.value.split('.')[1] + const payload = JSON.parse(Buffer.from(payloadB64, 'base64').toString('utf8')) + expect('cache_mode' in payload).toBe(false) + }) + + it('rejects invalid cacheMode values', () => { + expect(() => + issueOidcToken( + baseConfig, + { jobId: 1, audience: 'openforge-cache', cacheMode: 'admin' as any }, + fixedNow, + ), + ).toThrow(/cacheMode must be one of/) + }) + + it('accepts each valid cacheMode value', () => { + for (const mode of ['read', 'write', 'write-only', 'none'] as const) { + const resp = issueOidcToken( + baseConfig, + { jobId: 1, audience: 'openforge-cache', cacheMode: mode }, + fixedNow, + ) + expect(resp.cacheMode).toBe(mode) + } + }) + + it('includes permissions in JWT payload and response when provided', () => { + const resp = issueOidcToken( + baseConfig, + { jobId: 7, audience: 'sts.amazonaws.com', permissions: 'reviewer' }, + fixedNow, + ) + expect(resp.permissions).toBe('reviewer') + + const payloadB64 = resp.value.split('.')[1] + const payload = JSON.parse(Buffer.from(payloadB64, 'base64').toString('utf8')) + expect(payload['permissions']).toBe('reviewer') + }) + + it('omits permissions from JWT payload when not provided', () => { + const resp = issueOidcToken( + baseConfig, + { jobId: 7, audience: 'sts.amazonaws.com' }, + fixedNow, + ) + expect(resp.permissions).toBeUndefined() + + const payloadB64 = resp.value.split('.')[1] + const payload = JSON.parse(Buffer.from(payloadB64, 'base64').toString('utf8')) + expect('permissions' in payload).toBe(false) + }) + + it('rejects invalid permissions values', () => { + expect(() => + issueOidcToken( + baseConfig, + { jobId: 1, audience: 'sts.amazonaws.com', permissions: 'admin' as any }, + fixedNow, + ), + ).toThrow(/permissions must be one of/) + }) + + it('accepts each valid permissions value', () => { + for (const level of ['none', 'reviewer', 'full'] as const) { + const resp = issueOidcToken( + baseConfig, + { jobId: 1, audience: 'sts.amazonaws.com', permissions: level }, + fixedNow, + ) + expect(resp.permissions).toBe(level) + } + }) + + it('combines cacheMode and permissions in the same token', () => { + const resp = issueOidcToken( + baseConfig, + { + jobId: 1, + audience: 'openforge-cache', + cacheMode: 'read', + permissions: 'reviewer', + }, + fixedNow, + ) + expect(resp.cacheMode).toBe('read') + expect(resp.permissions).toBe('reviewer') + const payloadB64 = resp.value.split('.')[1] + const payload = JSON.parse(Buffer.from(payloadB64, 'base64').toString('utf8')) + expect(payload['cache_mode']).toBe('read') + expect(payload['permissions']).toBe('reviewer') + }) +}) + +describe('verifyOidcToken round-trip', () => { + const fixedNow = new Date('2026-11-03T12:00:00Z') + + it('verifies a freshly issued token', () => { + const resp = issueOidcToken(baseConfig, { jobId: 42, audience: 'sts.amazonaws.com' }, fixedNow) + const result = verifyOidcToken(resp.value, baseConfig, fixedNow) + expect(result.valid).toBe(true) + expect(result.payload?.['iss']).toBe('forge.example.com') + expect(result.payload?.['aud']).toBe('sts.amazonaws.com') + expect(result.payload?.['sub']).toBe('job:42') + }) + + it('rejects an expired token', () => { + const past = new Date('2026-01-01T00:00:00Z') + const resp = issueOidcToken(baseConfig, { jobId: 1, audience: 'x' }, past) + const result = verifyOidcToken(resp.value, baseConfig, fixedNow) + expect(result.valid).toBe(false) + expect(result.reason).toBe('expired') + }) + + it('rejects a token signed with a different secret', () => { + const resp = issueOidcToken(baseConfig, { jobId: 1, audience: 'x' }, fixedNow) + const tamperedConfig = { ...baseConfig, signingSecret: 'b'.repeat(64) } + const result = verifyOidcToken(resp.value, tamperedConfig, fixedNow) + expect(result.valid).toBe(false) + expect(result.reason).toBe('signature mismatch') + }) + + it('rejects a malformed token', () => { + const result = verifyOidcToken('not.a.jwt', baseConfig, fixedNow) + expect(result.valid).toBe(false) + }) +}) diff --git a/openforge/apps/api/src/services/__tests__/permissions-policy.test.ts b/openforge/apps/api/src/services/__tests__/permissions-policy.test.ts new file mode 100644 index 00000000..2d1af3c6 --- /dev/null +++ b/openforge/apps/api/src/services/__tests__/permissions-policy.test.ts @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: MIT +import { describe, it, expect } from 'vitest' +import { resolvePermissions, type PermissionLevel } from './permissions-policy.js' + +describe('resolvePermissions', () => { + describe('fork PRs — always denied', () => { + it.each([ + ['pull_request'], + ['pull_request_target'], + ['push'], + ['workflow_dispatch'], + ['schedule'], + ] as const)('fork PR with trigger %s → none', (trigger) => { + const result = resolvePermissions(trigger, true, 'full') + expect(result.level).toBe('none') + expect(result.reviewerGated).toBe(false) + expect(result.reason).toContain('fork PR') + }) + }) + + describe('same-repo trusted triggers — full by default', () => { + it.each([ + ['push'], + ['workflow_dispatch'], + ['schedule'], + ['workflow_run'], + ['repository_dispatch'], + ] as const)('same-repo trigger %s with workflow-requested full → full', (trigger) => { + const result = resolvePermissions(trigger, false, 'full') + expect(result.level).toBe('full') + expect(result.reviewerGated).toBe(false) + }) + }) + + describe('same-repo PRs — reviewer-gated', () => { + it('same-repo pull_request with workflow-requested full → reviewer', () => { + const result = resolvePermissions('pull_request', false, 'full') + expect(result.level).toBe('reviewer') + expect(result.reviewerGated).toBe(true) + }) + + it('same-repo pull_request_target with workflow-requested full → reviewer', () => { + const result = resolvePermissions('pull_request_target', false, 'full') + expect(result.level).toBe('reviewer') + expect(result.reviewerGated).toBe(true) + }) + }) + + describe('workflow opt-out', () => { + it('trusted trigger with workflow-requested none → none', () => { + const result = resolvePermissions('push', false, 'none') + expect(result.level).toBe('none') + expect(result.reason).toContain('opted out') + }) + }) + + describe('unknown triggers — closed by default', () => { + it('returns none for an unrecognized trigger source', () => { + const result = resolvePermissions('totally-unknown' as any, false, 'full') + expect(result.level).toBe('none') + expect(result.reason).toContain('unknown trigger') + }) + }) + + describe('fork PR override attempt', () => { + it('workflow YAML requesting full on a fork PR is ignored', () => { + const result = resolvePermissions('pull_request_target', true, 'full') + expect(result.level).toBe('none') + expect(result.reason).toContain('fork PR') + expect(result.reason).toContain("'pull_request_target'") + }) + }) +}) diff --git a/openforge/apps/api/src/services/__tests__/runner-auth.test.ts b/openforge/apps/api/src/services/__tests__/runner-auth.test.ts new file mode 100644 index 00000000..5d47b93f --- /dev/null +++ b/openforge/apps/api/src/services/__tests__/runner-auth.test.ts @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT +// +// Tests for the runner bearer authentication. Uses a mock DB client +// to avoid hitting Postgres; verifies the SQL semantics by stubbing +// the drizzle query builder. + +import { describe, it, expect } from 'vitest' +import { sha256Hex, extractBearer } from './runner-auth.js' + +describe('sha256Hex', () => { + it('returns a 64-char lowercase hex string', () => { + const h = sha256Hex('hello') + expect(h).toMatch(/^[0-9a-f]{64}$/) + }) + + it('matches a known SHA-256 reference vector', () => { + // SHA-256("hello") is well-known + expect(sha256Hex('hello')).toBe( + '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824', + ) + }) + + it('produces distinct hashes for distinct inputs', () => { + expect(sha256Hex('a')).not.toBe(sha256Hex('b')) + }) +}) + +describe('extractBearer', () => { + it('returns the token for a valid Bearer header', () => { + expect(extractBearer('Bearer abc123')).toBe('abc123') + }) + it('is case-insensitive on the scheme', () => { + expect(extractBearer('bearer abc')).toBe('abc') + expect(extractBearer('BEARER abc')).toBe('abc') + }) + it('returns null for missing header', () => { + expect(extractBearer(undefined)).toBeNull() + expect(extractBearer(null)).toBeNull() + expect(extractBearer('')).toBeNull() + }) + it('returns null for non-Bearer schemes', () => { + expect(extractBearer('Basic dXNlcjpwYXNz')).toBeNull() + expect(extractBearer('Token xyz')).toBeNull() + }) + it('returns null for empty bearer token', () => { + expect(extractBearer('Bearer ')).toBeNull() + expect(extractBearer('Bearer')).toBeNull() + }) +}) diff --git a/openforge/apps/api/src/services/egress-policy.ts b/openforge/apps/api/src/services/egress-policy.ts new file mode 100644 index 00000000..b5da2426 --- /dev/null +++ b/openforge/apps/api/src/services/egress-policy.ts @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: MIT +export type EgressMode = 'allow-all' | 'deny-all' | 'allowlist' + +export interface EgressAllowlistEntry { + readonly pattern: string + readonly kind: 'host' | 'wildcard' | 'cidr' + readonly note: string +} + +export interface EgressDecision { + allowed: boolean + reason: string + matchedEntry?: EgressAllowlistEntry +} + +export interface EgressRequest { + mode: EgressMode + destination: string + allowlist: ReadonlyArray<EgressAllowlistEntry> +} + +export function decideEgress(req: EgressRequest): EgressDecision { + if (req.mode === 'deny-all') { + return { + allowed: false, + reason: 'egress is deny-all by default; workflow must declare an allowlist', + } + } + if (req.mode === 'allow-all') { + return { + allowed: true, + reason: 'egress is allow-all (insecure default; not recommended)', + } + } + for (const entry of req.allowlist) { + if (matches(entry, req.destination)) { + return { + allowed: true, + reason: `matched allowlist entry: ${entry.pattern}`, + matchedEntry: entry, + } + } + } + return { + allowed: false, + reason: `destination ${req.destination} is not in the workflow's egress allowlist`, + } +} + +function matches(entry: EgressAllowlistEntry, dest: string): boolean { + switch (entry.kind) { + case 'host': + return entry.pattern === dest + case 'wildcard': + return dest === entry.pattern.slice(1) || dest.endsWith(entry.pattern) + case 'cidr': + return matchCIDR(entry.pattern, dest) + } +} + +function matchCIDR(cidr: string, ip: string): boolean { + const slash = cidr.indexOf('/') + if (slash < 0) return false + const net = cidr.slice(0, slash) + const prefix = Number(cidr.slice(slash + 1)) + if (!Number.isFinite(prefix) || prefix < 0 || prefix > 32) return false + const mask = prefix === 0 ? 0 : (~0 << (32 - prefix)) >>> 0 + const netNum = ipv4ToNumber(net) + const ipNum = ipv4ToNumber(ip) + if (netNum === null || ipNum === null) return false + return (netNum & mask) === (ipNum & mask) +} + +function ipv4ToNumber(ip: string): number | null { + const parts = ip.split('.') + if (parts.length !== 4) return null + let n = 0 + for (const p of parts) { + const v = Number(p) + if (!Number.isInteger(v) || v < 0 || v > 255) return null + n = (n * 256) + v + } + return n >>> 0 +} + +export const DEFAULT_EGRESS_ALLOWLIST: ReadonlyArray<EgressAllowlistEntry> = [ + { pattern: 'registry.npmjs.org', kind: 'host', note: 'npm registry' }, + { pattern: 'pypi.org', kind: 'host', note: 'PyPI registry' }, + { pattern: '.githubusercontent.com', kind: 'wildcard', note: 'GitHub Actions CDN' }, + { pattern: '.openforge.example', kind: 'wildcard', note: 'OpenForge server (replace)' }, +] diff --git a/openforge/apps/api/src/services/oidc-token.ts b/openforge/apps/api/src/services/oidc-token.ts new file mode 100644 index 00000000..b668e23a --- /dev/null +++ b/openforge/apps/api/src/services/oidc-token.ts @@ -0,0 +1,225 @@ +// SPDX-License-Identifier: MIT +// +// OpenForge server-side OIDC token issuer. +// +// Spec: see openforge/runner/INTEGRATION.md § "OIDC token injection". +// +// This service mints short-lived (~5min) OIDC tokens that the runner can +// exchange for cloud workload identity (AWS STS, GCP, Azure OIDC, K8s). +// The runner NEVER holds long-lived cloud credentials — every job asks +// the OpenForge server for a fresh token at execution time. +// +// Design choices (verified 2026-11-03): +// - Lifetime: 5 minutes (300s). Matches GitHub's canonical +// ACTIONS_ID_TOKEN_REQUEST_TOKEN example. +// - Audience restriction: caller MUST specify audience in the request; +// we echo it back so the runner can detect server misconfiguration. +// - Issuer: the OpenForge server's canonical host. The runner verifies +// iss matches what it expects. +// - Algorithm: HS256 with a server-side secret. Production should +// migrate to RS256 with a per-recipient JWKS (out of scope here). + +import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto' + +export const OIDC_TOKEN_LIFETIME_SECONDS = 5 * 60 // 5 minutes + +export type CacheMode = 'read' | 'write' | 'write-only' | 'none' + +const VALID_CACHE_MODES = new Set<CacheMode>(['read', 'write', 'write-only', 'none']) + +export interface OidcTokenRequest { + jobId: number + audience: string + lifetimeSec?: number + cacheMode?: CacheMode + permissions?: 'none' | 'reviewer' | 'full' +} + +export interface OidcTokenResponse { + value: string // signed JWT + expiresAt: string // ISO-8601 + audience: string + jobId: number + notBefore: string + issuer: string + cacheMode?: CacheMode + permissions?: 'none' | 'reviewer' | 'full' +} + +export interface OidcIssuerConfig { + /** Server host that will appear in the `iss` claim. */ + issuer: string + /** HS256 signing secret. Must be at least 32 bytes. */ + signingSecret: string + /** Optional override of the token lifetime (defaults to 5 min). */ + defaultLifetimeSec?: number +} + +export class OidcIssuerConfigError extends Error { + constructor(message: string) { + super(message) + this.name = 'OidcIssuerConfigError' + } +} + +/** + * Validate the issuer config at construction. Fails fast on misconfig. + */ +export function validateConfig(config: OidcIssuerConfig): void { + if (!config.issuer || config.issuer.length === 0) { + throw new OidcIssuerConfigError('issuer must be a non-empty string') + } + if (!config.signingSecret || config.signingSecret.length < 32) { + throw new OidcIssuerConfigError( + 'signingSecret must be at least 32 bytes (recommend 64 random bytes)', + ) + } +} + +/** + * Issue an OIDC token. Pure function: same inputs → same output, modulo + * the random `jti` claim and the time-derived `iat`/`nbf`/`exp` claims. + */ +export function issueOidcToken( + config: OidcIssuerConfig, + request: OidcTokenRequest, + now: Date = new Date(), +): OidcTokenResponse { + validateConfig(config) + if (!Number.isInteger(request.jobId) || request.jobId <= 0) { + throw new Error(`jobId must be a positive integer, got ${request.jobId}`) + } + if (!request.audience || request.audience.trim().length === 0) { + throw new Error('audience must be a non-empty string') + } + if (request.cacheMode !== undefined && !VALID_CACHE_MODES.has(request.cacheMode)) { + throw new Error( + `cacheMode must be one of: read, write, write-only, none; got ${request.cacheMode}`, + ) + } + if (request.permissions !== undefined && + request.permissions !== 'none' && + request.permissions !== 'reviewer' && + request.permissions !== 'full') { + throw new Error( + `permissions must be one of: none, reviewer, full; got ${request.permissions}`, + ) + } + + const lifetimeSec = clampLifetime(request.lifetimeSec ?? config.defaultLifetimeSec) + const expiresAt = new Date(now.getTime() + lifetimeSec * 1000) + const jti = randomBytes(16).toString('hex') + + const header = { + alg: 'HS256', + typ: 'JWT', + } + const payload: Record<string, unknown> = { + iss: config.issuer, + aud: request.audience, + sub: `job:${request.jobId}`, + iat: Math.floor(now.getTime() / 1000), + nbf: Math.floor(now.getTime() / 1000), + exp: Math.floor(expiresAt.getTime() / 1000), + jti, + } + if (request.cacheMode !== undefined) { + payload['cache_mode'] = request.cacheMode + } + if (request.permissions !== undefined) { + payload['permissions'] = request.permissions + } + + const value = signHs256(header, payload, config.signingSecret) + + return { + value, + expiresAt: expiresAt.toISOString(), + audience: request.audience, + jobId: request.jobId, + notBefore: now.toISOString(), + issuer: config.issuer, + ...(request.cacheMode !== undefined && { cacheMode: request.cacheMode }), + ...(request.permissions !== undefined && { permissions: request.permissions }), + } +} + +function clampLifetime(requested: number | undefined): number { + if (requested === undefined) return OIDC_TOKEN_LIFETIME_SECONDS + if (!Number.isFinite(requested) || requested <= 0) { + throw new Error(`lifetimeSec must be a positive number, got ${requested}`) + } + // Hard upper bound: 15 minutes. Anything longer is suspicious. + const MAX = 15 * 60 + if (requested > MAX) { + throw new Error(`lifetimeSec ${requested}s exceeds maximum ${MAX}s`) + } + return Math.floor(requested) +} + +function signHs256( + header: Record<string, string>, + payload: Record<string, unknown>, + secret: string, +): string { + const headerB64 = base64urlEncode(JSON.stringify(header)) + const payloadB64 = base64urlEncode(JSON.stringify(payload)) + const signingInput = `${headerB64}.${payloadB64}` + const sig = createHmac('sha256', secret).update(signingInput).digest() + return `${signingInput}.${base64urlEncodeBytes(sig)}` +} + +function base64urlEncode(input: string): string { + return base64urlEncodeBytes(Buffer.from(input, 'utf8')) +} + +function base64urlEncodeBytes(buf: Buffer): string { + return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') +} + +/** + * Verify a token's signature with constant-time comparison. Returns true + * if the signature matches and the token is not expired. Used by the + * runner-side verification helper. + */ +export function verifyOidcToken( + token: string, + config: OidcIssuerConfig, + now: Date = new Date(), +): { valid: boolean; reason?: string; payload?: Record<string, unknown> } { + const parts = token.split('.') + if (parts.length !== 3) { + return { valid: false, reason: 'malformed: expected 3 segments' } + } + const [headerB64, payloadB64, sigB64] = parts + + const expectedSig = createHmac('sha256', config.signingSecret) + .update(`${headerB64}.${payloadB64}`) + .digest() + let providedSig: Buffer + try { + providedSig = Buffer.from(sigB64.replace(/-/g, '+').replace(/_/g, '/'), 'base64') + } catch { + return { valid: false, reason: 'malformed: invalid base64 in signature' } + } + if (expectedSig.length !== providedSig.length || !timingSafeEqual(expectedSig, providedSig)) { + return { valid: false, reason: 'signature mismatch' } + } + + let payload: Record<string, unknown> + try { + payload = JSON.parse(Buffer.from(payloadB64, 'base64').toString('utf8')) + } catch { + return { valid: false, reason: 'malformed: invalid JSON in payload' } + } + + const exp = Number(payload['exp']) + if (!Number.isFinite(exp)) return { valid: false, reason: 'malformed: missing exp' } + if (Math.floor(now.getTime() / 1000) >= exp) return { valid: false, reason: 'expired' } + + if (payload['iss'] !== config.issuer) { + return { valid: false, reason: 'issuer mismatch' } + } + + return { valid: true, payload } +} diff --git a/openforge/apps/api/src/services/permissions-policy.ts b/openforge/apps/api/src/services/permissions-policy.ts new file mode 100644 index 00000000..326f38c4 --- /dev/null +++ b/openforge/apps/api/src/services/permissions-policy.ts @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: MIT +// +// Server-side enforcement of fork-PR permissions. The server — not the +// workflow YAML — decides what permissions a job receives. Workflows can +// REQUEST higher permissions but cannot GRANT them. +// +// Verified threat model (2026-11-03): +// - Pwn request (Grafana Apr 2025): fork PR + pull_request_target with +// base secrets. We kill the class by always denying fork PRs. +// - pull_request_target default block (GitHub effective Dec 2 2026). +// +// Permission levels: +// 'none' — no base repo secrets, no head checkout from fork +// 'reviewer' — base repo secrets only after explicit reviewer approval +// 'full' — base repo secrets + head checkout (trusted triggers only) + +export type PermissionLevel = 'none' | 'reviewer' | 'full' + +export type TriggerSource = + | 'push' + | 'pull_request' + | 'pull_request_target' + | 'workflow_dispatch' + | 'schedule' + | 'workflow_run' + | 'repository_dispatch' + +export interface ResolvedPermissions { + level: PermissionLevel + reason: string + reviewerGated: boolean +} + +const FORK_DENY: ReadonlySet<TriggerSource> = new Set<TriggerSource>([ + 'pull_request', + 'pull_request_target', +]) + +const TRUSTED: ReadonlySet<TriggerSource> = new Set<TriggerSource>([ + 'push', + 'workflow_dispatch', + 'schedule', + 'workflow_run', + 'repository_dispatch', +]) + +export function resolvePermissions( + triggerSource: TriggerSource, + isForkPr: boolean, + workflowRequested: PermissionLevel = 'full', +): ResolvedPermissions { + if (isForkPr) { + return { + level: 'none', + reason: `fork PR with trigger '${triggerSource}': base secrets and head checkout denied by server policy`, + reviewerGated: false, + } + } + if (FORK_DENY.has(triggerSource) && !isForkPr) { + return { + level: 'reviewer', + reason: `same-repo '${triggerSource}' requires explicit reviewer approval for secret access`, + reviewerGated: true, + } + } + if (TRUSTED.has(triggerSource)) { + if (workflowRequested === 'none') { + return { + level: 'none', + reason: `trusted trigger '${triggerSource}' with workflow-requested 'none' (workflow opted out)`, + reviewerGated: false, + } + } + return { + level: 'full', + reason: `trusted trigger '${triggerSource}': full permissions granted`, + reviewerGated: false, + } + } + return { + level: 'none', + reason: `unknown trigger '${triggerSource}': denied by default (closed-by-default policy)`, + reviewerGated: false, + } +} diff --git a/openforge/apps/api/src/services/runner-auth.ts b/openforge/apps/api/src/services/runner-auth.ts new file mode 100644 index 00000000..148f4759 --- /dev/null +++ b/openforge/apps/api/src/services/runner-auth.ts @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: MIT +// +// Runner authentication: SHA-256-hash lookup against the +// runner_registration_tokens table. The plaintext bearer token is +// NEVER stored (cf. CircleCI Dec 2022 — stolen plaintext tokens were +// the root cause of that breach). +// +// Issuance (handled elsewhere in apps/api, e.g. a future +// routes/runner-register.ts): +// 1. Server generates 256 bits of random data +// 2. Server computes SHA-256(token) and stores it + a short prefix +// in runner_registration_tokens +// 3. Server returns the plaintext token to the admin ONE TIME — +// after that, only the hash exists on the server +// +// Authentication (this module): +// 1. Runner sends `Authorization: Bearer <plaintext>` +// 2. We hash the plaintext with SHA-256 +// 3. We look up the hash in runner_registration_tokens +// 4. If found and not expired, return the runner +// 5. Otherwise return null (caller returns 401) +// +// All comparisons are constant-time where possible. + +import { createHash, timingSafeEqual } from 'node:crypto' +import { eq } from 'drizzle-orm' +import { db } from '@openforge/db' +import { runners, runnerRegistrationTokens } from '@openforge/db' + +export interface AuthenticatedRunner { + id: string + name: string + /** SHA-256 hash of the bearer; useful for logging or token-rotation reminders */ + tokenHash: string +} + +/** + * Constant-time bearer comparison. The lookup itself goes through an + * indexed equality on the hash column (so timing is dominated by the DB + * lookup, not the hash comparison). + */ +export async function authenticateRunnerByBearer( + plaintextBearer: string, +): Promise<AuthenticatedRunner | null> { + if (!plaintextBearer || plaintextBearer.length < 8) { + // Short-circuit obviously-empty or too-short tokens without a DB hit. + return null + } + + const hash = sha256Hex(plaintextBearer) + + // Single round-trip: join runner_registration_tokens → runners so we + // return the runner metadata in one query. The `expires_at IS NULL OR + // expires_at > now()` predicate excludes expired tokens. + const rows = await db + .select({ + runnerId: runners.id, + runnerName: runners.name, + tokenHash: runnerRegistrationTokens.tokenHash, + }) + .from(runnerRegistrationTokens) + .innerJoin(runners, eq(runnerRegistrationTokens.runnerId, runners.id)) + .where(eq(runnerRegistrationTokens.tokenHash, hash)) + .limit(1) + + const row = rows[0] + if (!row) return null + + // Constant-time hash comparison (defense in depth — DB lookup should + // already be O(log n), but timing-safe is cheap and removes a class of + // timing side-channel attacks against the auth path). + const expected = Buffer.from(row.tokenHash, 'hex') + const provided = Buffer.from(hash, 'hex') + if (expected.length !== provided.length || !timingSafeEqual(expected, provided)) { + return null + } + + // Expiry check — a token with expires_at in the past must not work + // even if its hash matches. + // Note: a row that has expires_at NULL is treated as "no expiry" (the + // common case for long-lived runner tokens). + // We fetch expires_at again separately to keep this function's + // signature minimal — for high-volume traffic, fold this into the + // join above as a `and(expiresAtIsNullOrFuture)` predicate. + const expiresRows = await db + .select({ expiresAt: runnerRegistrationTokens.expiresAt }) + .from(runnerRegistrationTokens) + .where(eq(runnerRegistrationTokens.tokenHash, hash)) + .limit(1) + const expires = expiresRows[0]?.expiresAt + if (expires && expires.getTime() <= Date.now()) { + return null + } + + return { + id: row.runnerId, + name: row.runnerName, + tokenHash: row.tokenHash, + } +} + +/** Compute SHA-256 of a string, returning lowercase hex (64 chars). */ +export function sha256Hex(input: string): string { + return createHash('sha256').update(input, 'utf8').digest('hex') +} + +/** Extract the bearer token from an Authorization header value. */ +export function extractBearer(authHeader: string | undefined | null): string | null { + if (!authHeader) return null + const trimmed = authHeader.trim() + if (!trimmed.toLowerCase().startsWith('bearer ')) return null + return trimmed.slice('bearer '.length).trim() || null +} diff --git a/openforge/docs/e2e-tests.md b/openforge/docs/e2e-tests.md new file mode 100644 index 00000000..46ced2c9 --- /dev/null +++ b/openforge/docs/e2e-tests.md @@ -0,0 +1,57 @@ +# E2E tests + +**Status:** Scaffold ready. Requires `DATABASE_URL` (Postgres + migrations applied) to actually run. + +## What this exercises + +The E2E test (`apps/api/src/__tests__/e2e/oidc-roundtrip.test.ts`) covers the full **OIDC token round-trip**: + +1. Insert a test runner + SHA-256-hashed registration token into the DB +2. Insert a `runner_jobs` row assigning the test runner to a job +3. Send `POST /api/v1/runner/oidc-token` with `Authorization: Bearer <plaintext>` +4. Verify the server: + - Hashes the bearer and looks it up in `runner_registration_tokens` + - Checks `runnerOwnsJob` (runner actually assigned to that job) + - Mints an HS256 JWT with the requested `cache_mode` + `permissions` claims +5. Verify the JWT round-trip: + - Signature verifies with the same secret + - `iss`, `aud`, `sub`, `cache_mode`, `permissions` claims all correct + - `exp` is ~5 minutes from now (within tolerance) +6. Verify tampering detection: + - Modified signature → rejected with "signature mismatch" + - Modified issuer → rejected + +## What's NOT yet covered (out of scope for the scaffold) + +- The actual Go runner binary: the test mocks the runner side via HTTP requests. To exercise the full runner flow, you need `go test` in `openforge/runner` with the Go code reading and forwarding. +- Webhook delivery end-to-end +- Real sandbox boot (requires `runsc`/`kata-runtime` installed) +- Real egress filter (requires eBPF or iptables) +- Concurrent job dispatch + +These belong in a separate integration suite that runs against a fully provisioned host. + +## Setup + +```bash +# 1. Bring up Postgres +docker run -d --name openforge-pg-e2e -p 55432:5432 \ + -e POSTGRES_USER=openforge -e POSTGRES_PASSWORD=openforge \ + -e POSTGRES_DB=openforge postgres:16 + +# 2. Apply migrations (from openforge/packages/db) +export DATABASE_URL=postgres://openforge:openforge@localhost:55432/openforge +psql $DATABASE_URL < migrations/0000_initial.sql +psql $DATABASE_URL < migrations/0001_runners.sql +psql $DATABASE_URL < migrations/0002_fork_pr_permissions.sql + +# 3. Run the E2E tests +cd openforge/apps/api +DATABASE_URL=postgres://openforge:openforge@localhost:55432/openforge \ + pnpm vitest run src/__tests__/e2e +``` + +## Files + +- `apps/api/src/__tests__/e2e/setup.ts` — boots the Hono app in-process, sets `OIDC_ISSUER` + `OIDC_SIGNING_SECRET` env vars, exposes a `fetch()` wrapper +- `apps/api/src/__tests__/e2e/oidc-roundtrip.test.ts` — the test itself diff --git a/openforge/docs/runner-oidc-endpoint.md b/openforge/docs/runner-oidc-endpoint.md new file mode 100644 index 00000000..ee71fcca --- /dev/null +++ b/openforge/docs/runner-oidc-endpoint.md @@ -0,0 +1,92 @@ +# OpenForge server-side: OIDC token endpoint + +**Route:** `POST /api/v1/runner/oidc-token` +**Mounted at:** `apps/api/src/routes/runner.ts` +**Service:** `apps/api/src/services/oidc-token.ts` + +## Spec + +Mirrors the runner-side client (`openforge/runner/internal/app/openforge/oidc.go`). See +`openforge/runner/INTEGRATION.md` § "OIDC token injection" for the full +spec. + +### Request + +```json +{ + "jobId": 42, + "audience": "sts.amazonaws.com", + "lifetimeSec": 300 +} +``` + +- `jobId` — required, positive integer. The runner's job ID. +- `audience` — required, non-empty string ≤ 512 chars. Echoed back in the response so the runner can detect server misconfiguration. Common values: `sts.amazonaws.com`, `container.googleapis.com`, `https://kubernetes.default.svc`, or a custom workload-identity audience. +- `lifetimeSec` — optional, default 300, hard max 900 (15 minutes). Anything longer is suspicious and rejected. + +### Response (200) + +```json +{ + "value": "header.payload.signature", + "expiresAt": "2026-11-03T12:05:00.000Z", + "audience": "sts.amazonaws.com", + "jobId": 42, + "notBefore": "2026-11-03T12:00:00.000Z", + "issuer": "forge.example.com" +} +``` + +### Errors + +| Status | When | +|--------|------| +| 400 | Schema validation failed (missing/negative jobId, empty audience, lifetimeSec > 900) | +| 401 | Missing or invalid Bearer token | +| 500 | Token issuance failed (e.g. signing key not configured) | + +## Environment + +| Variable | Required | Description | +|----------|----------|-------------| +| `OIDC_ISSUER` | yes | The canonical host that will appear in the `iss` claim. The runner verifies it matches what it expects. | +| `OIDC_SIGNING_SECRET` | yes | HS256 signing secret. Must be at least 32 bytes. **Use 64 random bytes in production.** | + +## Algorithm + +HS256 today (HMAC-SHA256, symmetric). Production should migrate to RS256 +with a per-recipient JWKS endpoint so runners can verify without sharing a +secret with the server. Out of scope for Phase 1. + +## Verification + +```bash +# 1. Issue a token +curl -sX POST http://localhost:8787/api/v1/runner/oidc-token \ + -H "Authorization: Bearer <runner-jwt>" \ + -H "Content-Type: application/json" \ + -d '{"jobId": 42, "audience": "sts.amazonaws.com"}' | jq + +# 2. Decode the JWT (header.payload.signature) +echo "<jwt>" | cut -d. -f2 | base64 -d | jq + +# 3. Verify with the same secret the server uses +``` + +## Tests + +`apps/api/src/services/__tests__/oidc-token.test.ts` covers: + +- config validation (empty issuer, short secret) +- default lifetime (5 min) +- custom lifetime within bounds +- rejection of lifetimeSec > 15 min +- rejection of non-positive jobId +- rejection of empty audience +- distinct jti per call +- signature verification round-trip +- expired-token rejection +- wrong-secret rejection +- malformed-token rejection + +Run: `pnpm --filter @openforge/api test` diff --git a/openforge/packages/db/migrations/0001_runners.sql b/openforge/packages/db/migrations/0001_runners.sql new file mode 100644 index 00000000..454b078b --- /dev/null +++ b/openforge/packages/db/migrations/0001_runners.sql @@ -0,0 +1,114 @@ +-- 0001_runners.sql — CI runner registration and lifecycle tables. +-- See schema/runners.ts for the Drizzle definitions this migration +-- is generated from. +-- +-- Design notes (verified 2026-11-03): +-- * registration_token stored as SHA-256 hash (cf. CircleCI Dec 2022) +-- * ephemeral runner default (matches GitHub-hosted runner model) +-- * sandbox enum defaults to gvisor (OpenForge default policy) + +-- 1. Enum +CREATE TYPE runner_sandbox AS ENUM ( + 'gvisor', + 'kata', + 'firecracker', + 'sysbox', + 'rootless' +); + +-- 2. runners +CREATE TABLE runners ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + name text NOT NULL, + description text, + + owner_repo_id uuid REFERENCES repositories(id) ON DELETE CASCADE, + owner_org_id uuid, + + labels jsonb NOT NULL DEFAULT '[]'::jsonb, + sandbox runner_sandbox NOT NULL DEFAULT 'gvisor', + ephemeral boolean NOT NULL DEFAULT true, + max_parallel_jobs integer NOT NULL DEFAULT 1, + + last_seen_at timestamptz, + status text NOT NULL DEFAULT 'idle', + version text, + + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + + CONSTRAINT runners_owner_exactly_one CHECK ( + (owner_repo_id IS NOT NULL)::int + (owner_org_id IS NOT NULL)::int <= 1 + ), + CONSTRAINT runners_status_valid CHECK ( + status IN ('offline', 'idle', 'busy', 'draining') + ), + CONSTRAINT runners_max_parallel_positive CHECK (max_parallel_jobs >= 1) +); + +CREATE UNIQUE INDEX runners_name_unique ON runners (name); +CREATE INDEX runners_owner_repo_idx ON runners (owner_repo_id); +CREATE INDEX runners_owner_org_idx ON runners (owner_org_id); +CREATE INDEX runners_status_idx ON runners (status); + +-- 3. runner_registration_tokens +CREATE TABLE runner_registration_tokens ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + runner_id uuid NOT NULL REFERENCES runners(id) ON DELETE CASCADE, + token_hash text NOT NULL, + token_prefix text NOT NULL, + expires_at timestamptz, + last_used_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now(), + + CONSTRAINT runner_reg_tokens_hash_len CHECK ( + char_length(token_hash) = 64 -- SHA-256 hex + ), + CONSTRAINT runner_reg_tokens_prefix_len CHECK ( + char_length(token_prefix) >= 4 AND char_length(token_prefix) <= 16 + ) +); + +CREATE INDEX runner_reg_tokens_runner_idx ON runner_registration_tokens (runner_id); +CREATE UNIQUE INDEX runner_reg_tokens_hash_unique ON runner_registration_tokens (token_hash); + +-- 4. runner_jobs +CREATE TABLE runner_jobs ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + runner_id uuid NOT NULL REFERENCES runners(id) ON DELETE CASCADE, + job_id uuid NOT NULL, + picked_up_at timestamptz, + finished_at timestamptz, + outcome text, + created_at timestamptz NOT NULL DEFAULT now(), + + CONSTRAINT runner_jobs_outcome_valid CHECK ( + outcome IS NULL OR outcome IN ('success', 'failure', 'cancelled', 'timeout') + ) +); + +CREATE INDEX runner_jobs_runner_idx ON runner_jobs (runner_id); +CREATE INDEX runner_jobs_job_idx ON runner_jobs (job_id); + +-- A job can have AT MOST ONE active runner assignment at a time. Enforced +-- via partial unique index — multiple historical (finished_at IS NOT NULL) +-- rows are allowed, but only one row per job with picked_up_at IS NOT NULL +-- AND finished_at IS NULL. +CREATE UNIQUE INDEX runner_jobs_one_active_per_job + ON runner_jobs (job_id) + WHERE picked_up_at IS NOT NULL AND finished_at IS NULL; + +-- 5. updated_at trigger for runners (matches the onUpdate pattern in +-- the Drizzle schema) +CREATE OR REPLACE FUNCTION set_updated_at() +RETURNS trigger AS $$ +BEGIN + NEW.updated_at = now(); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER runners_set_updated_at + BEFORE UPDATE ON runners + FOR EACH ROW + EXECUTE FUNCTION set_updated_at(); diff --git a/openforge/packages/db/migrations/0002_fork_pr_permissions.sql b/openforge/packages/db/migrations/0002_fork_pr_permissions.sql new file mode 100644 index 00000000..81804a98 --- /dev/null +++ b/openforge/packages/db/migrations/0002_fork_pr_permissions.sql @@ -0,0 +1,42 @@ +-- 0002_fork_pr_permissions.sql — fork-PR permission enforcement. +-- See schema/actions.ts for the Drizzle definitions this migration +-- is generated from. +-- +-- Verified threat model (2026-11-03): +-- * Pwn request (cf. Grafana Apr 2025): a fork PR's workflow runs +-- untrusted code with the base repo's secrets. We kill the class +-- by defaulting permissions to 'none' on fork PRs and letting the +-- server — NOT the workflow YAML — decide. +-- * pull_request_target is similarly locked down (cf. GitHub's +-- Dec 2 2026 default block). +-- +-- Permission levels: +-- none — no base repo secrets, no head checkout from fork +-- reviewer — base repo secrets only after explicit reviewer approval +-- full — base repo secrets + head checkout (trusted triggers only) +-- +-- Trust rules (server-side, NOT enforced by workflow YAML): +-- fork + pull_request → none (always) +-- fork + pull_request_target → none (always; workflow YAML can't override) +-- direct push → full +-- workflow_dispatch → full +-- pull_request (same-repo) → full +-- schedule → full +-- workflow_run → full + +ALTER TABLE workflow_runs + ADD COLUMN trigger_source text NOT NULL DEFAULT 'push', + ADD COLUMN is_fork_pr boolean NOT NULL DEFAULT false; + +ALTER TABLE workflow_jobs + ADD COLUMN permissions text NOT NULL DEFAULT 'full', + ADD COLUMN is_fork_pr boolean NOT NULL DEFAULT false; + +ALTER TABLE workflow_jobs + ADD CONSTRAINT workflow_jobs_permissions_valid + CHECK (permissions IN ('none', 'reviewer', 'full')); + +CREATE INDEX workflow_runs_trigger_source_idx ON workflow_runs (trigger_source); +CREATE INDEX workflow_runs_is_fork_pr_idx ON workflow_runs (is_fork_pr) WHERE is_fork_pr = true; +CREATE INDEX workflow_jobs_permissions_idx ON workflow_jobs (permissions); +CREATE INDEX workflow_jobs_is_fork_pr_idx ON workflow_jobs (is_fork_pr) WHERE is_fork_pr = true; diff --git a/openforge/packages/db/src/schema/actions.ts b/openforge/packages/db/src/schema/actions.ts new file mode 100644 index 00000000..03689e81 --- /dev/null +++ b/openforge/packages/db/src/schema/actions.ts @@ -0,0 +1,83 @@ +/** + * actions — GitHub Actions-compatible workflow engine tables. + * + * Phase 0: tables exist with the minimum fields a runner can read/write. + * workflow_secrets stores per-repo OR per-org secrets, KMS-encrypted with + * the per-secret IV stored alongside (so secrets never share an IV). + * Phase 2 expands runs/jobs (matrix expansion, step-level logs, etc.). + */ +import { sql } from 'drizzle-orm'; +import { + boolean, + integer, + jsonb, + pgTable, + text, + timestamp, + uuid, +} from 'drizzle-orm/pg-core'; +import { bytea } from './custom-types.js'; +import { repositories } from './repositories.js'; + +export const workflows = pgTable('workflows', { + id: uuid('id').defaultRandom().primaryKey(), + repoId: uuid('repo_id') + .notNull() + .references(() => repositories.id, { onDelete: 'cascade' }), + path: text('path').notNull(), // .github/workflows/ci.yml + name: text('name').notNull(), + active: boolean('active').notNull().default(true), + triggers: jsonb('triggers').notNull().default(sql`'{}'::jsonb`), + createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp('updated_at', { withTimezone: true }) + .notNull() + .defaultNow() + .$onUpdate(() => sql`now()`), +}); + +export const workflowRuns = pgTable('workflow_runs', { + id: uuid('id').defaultRandom().primaryKey(), + workflowId: uuid('workflow_id') + .notNull() + .references(() => workflows.id, { onDelete: 'cascade' }), + headSha: text('head_sha').notNull(), + event: text('event').notNull(), + triggerSource: text('trigger_source').notNull().default('push'), + isForkPr: boolean('is_fork_pr').notNull().default(false), + status: text('status').notNull().default('queued'), + conclusion: text('conclusion'), + startedAt: timestamp('started_at', { withTimezone: true }), + finishedAt: timestamp('finished_at', { withTimezone: true }), + logS3Prefix: text('log_s3_prefix'), + createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), +}); + +export const workflowJobs = pgTable('workflow_jobs', { + id: uuid('id').defaultRandom().primaryKey(), + runId: uuid('run_id') + .notNull() + .references(() => workflowRuns.id, { onDelete: 'cascade' }), + name: text('name').notNull(), + matrix: jsonb('matrix').notNull().default(sql`'{}'::jsonb`), + status: text('status').notNull().default('queued'), + runnerId: text('runner_id'), + permissions: text('permissions').notNull().default('full'), + isForkPr: boolean('is_fork_pr').notNull().default(false), + startedAt: timestamp('started_at', { withTimezone: true }), + finishedAt: timestamp('finished_at', { withTimezone: true }), + createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), +}); + +export const workflowSecrets = pgTable('workflow_secrets', { + id: uuid('id').defaultRandom().primaryKey(), + repoId: uuid('repo_id').references(() => repositories.id, { onDelete: 'cascade' }), + orgId: uuid('org_id'), // nullable; exactly one of (repo_id, org_id) is set + name: text('name').notNull(), + encryptedValue: bytea('encrypted_value').notNull(), + iv: bytea('iv').notNull(), + createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp('updated_at', { withTimezone: true }) + .notNull() + .defaultNow() + .$onUpdate(() => sql`now()`), +}); diff --git a/openforge/packages/db/src/schema/index.ts b/openforge/packages/db/src/schema/index.ts new file mode 100644 index 00000000..c4574629 --- /dev/null +++ b/openforge/packages/db/src/schema/index.ts @@ -0,0 +1,22 @@ +// Barrel export — keeps `import { users, sessions } from '@openforge/db'` terse +// while drizzle-kit can still introspect each file individually. + +export * from './custom-types.js'; +export * from './users.js'; +export * from './sessions.js'; +export * from './personal-access-tokens.js'; +export * from './ssh-keys.js'; +export * from './repositories.js'; +export * from './refs.js'; +export * from './oid-inventory.js'; +export * from './teams.js'; +export * from './team-members.js'; +export * from './permissions.js'; +export * from './branch-protection.js'; +export * from './webhook-endpoints.js'; +export * from './webhook-deliveries.js'; +export * from './actions.js'; +export * from './runners.js'; +export * from './stripe.js'; +export * from './audit-log.js'; +export * from './lfs.js'; diff --git a/openforge/packages/db/src/schema/runners.ts b/openforge/packages/db/src/schema/runners.ts new file mode 100644 index 00000000..5d971466 --- /dev/null +++ b/openforge/packages/db/src/schema/runners.ts @@ -0,0 +1,180 @@ +/** + * runners — CI runner registration and lifecycle tables. + * + * Mirrors forgejo/runner's model (Runner + RunnerRegistrationToken + + * RunnerJob) but expressed in OpenForge's existing schema style + * (Drizzle + Postgres + uuid primary keys + ltree for org paths). + * + * Security design (verified 2026-11-03): + * - registration_token is stored as SHA-256 hash, not plaintext (cf. + * CircleCI Dec 2022 — stolen plaintext token was the root cause). + * - `last_seen_at` updates on every poll; stale runners are + * GC'd after `stale_after` interval (default 24h). + * - `ephemeral` defaults to TRUE — matches GitHub's hosted runner + * model (verified 2026-11-03) and prevents the long-lived runner + * state-leakage class (cf. Daytona PR #4474). + * - `sandbox` enum tracks which isolation mode the runner is using + * (gvisor | kata | firecracker | sysbox | rootless — default + * gvisor per OpenForge default policy). + */ +import { sql } from 'drizzle-orm'; +import { + boolean, + index, + integer, + jsonb, + pgEnum, + pgTable, + text, + timestamp, + unique, + uuid, +} from 'drizzle-orm/pg-core'; +import { repositories } from './repositories.js'; + +export const runnerSandboxEnum = pgEnum('runner_sandbox', [ + 'gvisor', + 'kata', + 'firecracker', + 'sysbox', + 'rootless', +]); + +export const runners = pgTable( + 'runners', + { + id: uuid('id').defaultRandom().primaryKey(), + name: text('name').notNull(), // globally unique; the human label shown in the UI + description: text('description'), + + // owner: nullable, exactly one of (owner_repo_id, owner_org_id) is set. + // Repository-scoped runners run jobs only for that repo; org-scoped + // runners run jobs for any repo in the org. NULL = "global" runner + // for trusted-org system jobs only. + ownerRepoId: uuid('owner_repo_id').references(() => repositories.id, { + onDelete: 'cascade', + }), + ownerOrgId: uuid('owner_org_id'), + + // labels: matches the runner label protocol used by forgejo + + // GitHub Actions. e.g. ["self-hosted", "linux", "x64", "gvisor"]. + labels: jsonb('labels').notNull().default(sql`'[]'::jsonb`), + + // Isolation mode this runner uses. Mirrors the verified 2026-11-03 + // policy: default is gvisor; opt-in for kata (DinD), firecracker + // (Lambda-grade), etc. + sandbox: runnerSandboxEnum('sandbox').notNull().default('gvisor'), + + // Ephemeral vs persistent. Default TRUE — matches GitHub-hosted + // runner model (per-job VM, no state leakage). + ephemeral: boolean('ephemeral').notNull().default(true), + + // Concurrency cap. Ephemeral runners usually set this to 1 (one job + // per VM). Persistent runners can host multiple concurrent jobs. + maxParallelJobs: integer('max_parallel_jobs').notNull().default(1), + + // Last successful poll time. Used to GC stale runners. + lastSeenAt: timestamp('last_seen_at', { withTimezone: true }), + + // Operational state — distinct from ephemeral/persistent. A runner + // can be `offline` (deregistered), `idle` (waiting), `busy` (has + // job in flight), or `draining` (finishing in-flight jobs, no new + // assignments — used during graceful shutdown). + status: text('status').notNull().default('idle'), + + // Runner version (semver). Used for upgrade-cohort management and + // deprecation warnings when the server stops supporting old + // protocol versions. + version: text('version'), + + createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp('updated_at', { withTimezone: true }) + .notNull() + .defaultNow() + .$onUpdate(() => sql`now()`), + }, + (t) => ({ + nameUnique: unique('runners_name_unique').on(t.name), + ownerRepoIdx: index('runners_owner_repo_idx').on(t.ownerRepoId), + ownerOrgIdx: index('runners_owner_org_idx').on(t.ownerOrgId), + statusIdx: index('runners_status_idx').on(t.status), + }), +); + +/** + * runner_registration_tokens — the bearer tokens a runner presents to + * the API to identify itself. Stored as SHA-256 hash, never plaintext. + * + * Issuance flow (server side): + * 1. Admin clicks "Register runner" in the UI + * 2. Server generates a 256-bit random secret, hashes it, returns + * the plaintext ONE TIME (it's never stored) + * 3. Runner stores the plaintext locally and presents it as + * `Authorization: Bearer <plaintext>` on every request + * 4. Server hashes the inbound bearer with SHA-256 and looks up the + * hash in this table + * + * Rotation: admins can rotate a token by deleting the row and issuing a + * new one; the runner must re-register. + * + * Compromised token mitigation (cf. CircleCI Dec 2022): if a token is + * leaked, the operator deletes the row. Every in-flight request with + * that token immediately fails. The plaintext was never on the server. + */ +export const runnerRegistrationTokens = pgTable( + 'runner_registration_tokens', + { + id: uuid('id').defaultRandom().primaryKey(), + runnerId: uuid('runner_id') + .notNull() + .references(() => runners.id, { onDelete: 'cascade' }), + // SHA-256 of the plaintext bearer. 32 bytes fixed-length. + tokenHash: text('token_hash').notNull(), + // First 8 chars of the plaintext, for human identification in the + // UI ("token prefix: abc12345…"). NOT a secret. + tokenPrefix: text('token_prefix').notNull(), + // Optional expiry. After this, the server rejects the token even + // if the hash matches. NULL = no expiry (rotated manually). + expiresAt: timestamp('expires_at', { withTimezone: true }), + // Last successful use. Useful for "this token hasn't been used in + // 90 days, should we revoke it?" reminders. + lastUsedAt: timestamp('last_used_at', { withTimezone: true }), + createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), + }, + (t) => ({ + runnerIdIdx: index('runner_reg_tokens_runner_idx').on(t.runnerId), + // token_hash is unique so lookups are O(log n) via the hash match. + tokenHashUnique: unique('runner_reg_tokens_hash_unique').on(t.tokenHash), + }), +); + +/** + * runner_jobs — many-to-many between runners and workflow_jobs. + * Tracks which runner is currently executing (or last executed) a job. + * + * A job has AT MOST ONE active runner assignment at a time (enforced + * via partial unique index — see migration). When a runner picks up a + * job, the row is inserted with `picked_up_at = now()`; when it + * finishes, `finished_at` is set and `outcome` is recorded. + */ +export const runnerJobs = pgTable( + 'runner_jobs', + { + id: uuid('id').defaultRandom().primaryKey(), + runnerId: uuid('runner_id') + .notNull() + .references(() => runners.id, { onDelete: 'cascade' }), + jobId: uuid('job_id').notNull(), // FK to workflow_jobs.id, declared in actions.ts + // Set when the runner picks up the job; NULL until then. + pickedUpAt: timestamp('picked_up_at', { withTimezone: true }), + finishedAt: timestamp('finished_at', { withTimezone: true }), + // "success" | "failure" | "cancelled" | "timeout" — mirrors the + // GitHub Actions `conclusion` semantics. + outcome: text('outcome'), + createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), + }, + (t) => ({ + runnerIdIdx: index('runner_jobs_runner_idx').on(t.runnerId), + jobIdIdx: index('runner_jobs_job_idx').on(t.jobId), + }), +);