Skip to content
44 changes: 44 additions & 0 deletions apps/mint/tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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; }),
Expand Down Expand Up @@ -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],
Expand Down
42 changes: 37 additions & 5 deletions apps/mint/web/js/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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";
Expand Down Expand Up @@ -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()] : "");
}
Expand Down
193 changes: 193 additions & 0 deletions openforge/apps/api/src/__tests__/e2e/oidc-roundtrip.test.ts
Original file line number Diff line number Diff line change
@@ -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 <plaintext>.
// 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)
})
})
65 changes: 65 additions & 0 deletions openforge/apps/api/src/__tests__/e2e/setup.ts
Original file line number Diff line number Diff line change
@@ -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']
},
}
}
Loading
Loading