Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,11 @@ curl 'http://localhost:8080/api/v1/openapi.json'
registers — `GET /api/v1/jobs` and this route. The document lives in
`src/api/openapi.ts`, and `test/openapi.test.ts` fails in both directions: a
registered route missing from the contract, and a contract path with no route.
The check reads every registration verb and either quote style, through the
reader it shares with the endpoint-table check (`test/apiDocReader.ts`), so a
`POST` or a double-quoted registration cannot slip past it. It counts path
declarations in the contract's source too, because a duplicate key inside the
`paths` literal collapses before the served document could show it.
- Session-only routes, the console pages and callbacks are not in it. The
OpenAI-compatible `/v1/*` gateway keeps its own shape and is also absent.
- When a status code or a field changes, `src/api/openapi.ts` changes in the same
Expand Down
80 changes: 80 additions & 0 deletions test/apiDocReader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { readFileSync } from 'node:fs'

// The route reader both checks share: `test/apiDocRoutes.test.ts` (#1289) checks
// that `docs/api.md` carries no row the app does not serve, and
// `test/openapi.test.ts` (#1243, #1293) checks that the OpenAPI contract
// describes every route the app registers. One definition of "a route the app
// registers" keeps the two checks from disagreeing about what a route is — and
// keeps a second, weaker scanner out of the tree.

const API_DOC = readFileSync(new URL('../docs/api.md', import.meta.url), 'utf8')
const APP_SOURCE = readFileSync(new URL('../src/app.ts', import.meta.url), 'utf8')

const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] as const
const VERB_FORMS = new Set(METHODS.map((method) => method.toLowerCase()))

// Comments are removed before the scan: the app's own explanations quote route
// shapes, and a commented-out registration is not a route.
function withoutComments(source: string): string {
return source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^[ \t]*\/\/.*$/gm, '')
}

// `/repos/:id/instance` and `/repos/:repo/instance` are the same route: the
// parameter name is documentation, not contract. A trailing slash is not a
// different route either.
export function normalisePath(path: string): string {
const trimmed = path.trim().replace(/\/+$/, '')
const segments = trimmed
.split('/')
.map((segment) => (segment.startsWith(':') ? ':' : segment))
return segments.join('/') || '/'
}

/** Every route `src/app.ts` registers, as `METHOD /normalised/path`. */
export function registeredRoutes(source = APP_SOURCE): Set<string> {
const text = withoutComments(source)
// `app.route({ method, url })` keeps the method in an object, which this
// reader cannot read; refuse it instead of skipping a route silently.
if (/app\.route\s*\(/.test(text)) throw new Error('the checker cannot read app.route(...); teach registeredRoutes or register with a verb')

const routes = new Set<string>()
// Both quote styles are read: a route is a route whichever quote the author
// used, and a reader that only understands one style reports the other as
// "not a route" (#1293).
for (const match of text.matchAll(/app\.([A-Za-z]+)\(\s*['"]([^'"]*)['"]/g)) {
const form = (match[1] ?? '').toLowerCase()
const path = match[2] ?? ''
if (form === 'all') {
// `app.all` answers every method, so a document row for any of them is served.
for (const method of METHODS) routes.add(`${method} ${normalisePath(path)}`)
continue
}
if (!VERB_FORMS.has(form)) {
// `app.addHook('onResponse', …)` is not a route; a route-shaped form this
// reader does not know is refused rather than skipped.
if (path.startsWith('/')) throw new Error(`the checker cannot read app.${form}('${path}'); teach registeredRoutes or drop the form`)
continue
}
routes.add(`${form.toUpperCase()} ${normalisePath(path)}`)
}
return routes
}

/** The `| METHOD | \`path\` |` rows of the endpoint table. */
export function documentedRoutes(markdown = API_DOC): Array<{ method: string; path: string }> {
const rows: Array<{ method: string; path: string }> = []
for (const line of markdown.split('\n')) {
const match = /^\|\s*(GET|POST|PUT|PATCH|DELETE)\s*\|\s*`([^`]+)`\s*\|/.exec(line)
if (match === null) continue
rows.push({ method: match[1] as string, path: (match[2] as string).trim() })
}
return rows
}

/** One line per row the app does not serve: `undocumented-route: METHOD path`. */
export function undocumentedRoutes(markdown = API_DOC, source = APP_SOURCE): string[] {
const registered = registeredRoutes(source)
return documentedRoutes(markdown)
.filter((row) => !registered.has(`${row.method} ${normalisePath(row.path)}`))
.map((row) => `undocumented-route: ${row.method} ${row.path}`)
}
92 changes: 14 additions & 78 deletions test/apiDocRoutes.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { documentedRoutes, registeredRoutes, undocumentedRoutes } from './apiDocReader.js'

// #1289: `docs/api.md` is the reference an integrator follows, so a row for a
// route the app does not serve is worse than a missing row — the reader posts
Expand All @@ -9,89 +9,17 @@ import { readFileSync } from 'node:fs'
// `src/app.ts` answers.
//
// This checker reads the two things that can disagree — the `| METHOD | path |`
// rows of the document and the `app.<verb>('...')` registrations of the app —
// and names every row that has no registration. It reads the registrations out
// of the source on purpose: importing a route list would let the document agree
// with itself instead of with the server.
// rows of the document and the `app.<verb>(...)` registrations of the app — and
// names every row that has no registration. It reads the registrations out of
// the source on purpose: importing a route list would let the document agree
// with itself instead of with the server. The reader itself lives in
// `test/apiDocReader.ts` so the contract check (#1243, #1293) uses the same one.
//
// The second half is the part that keeps a fix honest: the same checker, run on
// a fixture table, still reports a fake route and still resolves a known-good
// one. A "fix" that empties the table or deletes the checker passes the first
// half and fails here.

const API_DOC = readFileSync(new URL('../docs/api.md', import.meta.url), 'utf8')
const APP_SOURCE = readFileSync(new URL('../src/app.ts', import.meta.url), 'utf8')

const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] as const
const VERB_FORMS = new Set(METHODS.map((method) => method.toLowerCase()))

// Comments are removed before the scan: this file's own explanations quote route
// shapes, and a commented-out registration is not a route.
function withoutComments(source: string): string {
return source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^[ \t]*\/\/.*$/gm, '')
}

// `/repos/:id/instance` and `/repos/:repo/instance` are the same route: the
// parameter name is documentation, not contract. A trailing slash is not a
// different route either.
function normalisePath(path: string): string {
const trimmed = path.trim().replace(/\/+$/, '')
const segments = trimmed
.split('/')
.map((segment) => (segment.startsWith(':') ? ':' : segment))
return segments.join('/') || '/'
}

/** Every route `src/app.ts` registers, as `METHOD /normalised/path`. */
export function registeredRoutes(source = APP_SOURCE): Set<string> {
const text = withoutComments(source)
// `app.route({ method, url })` keeps the method in an object, which this
// reader cannot read; refuse it instead of skipping a route silently.
if (/app\.route\s*\(/.test(text)) throw new Error('the checker cannot read app.route(...); teach registeredRoutes or register with a verb')
// The reader below reads single quotes because that is the file's style, so a
// double-quoted registration would look like "not a route".
const doubleQuoted = /app\.([A-Za-z]+)\(\s*"/.exec(text)
if (doubleQuoted !== null) throw new Error(`the checker cannot read app.${doubleQuoted[1]}("..."); register with single quotes or teach registeredRoutes`)

const routes = new Set<string>()
for (const match of text.matchAll(/app\.([A-Za-z]+)\(\s*'([^']*)'/g)) {
const form = (match[1] ?? '').toLowerCase()
const path = match[2] ?? ''
if (form === 'all') {
// `app.all` answers every method, so a document row for any of them is served.
for (const method of METHODS) routes.add(`${method} ${normalisePath(path)}`)
continue
}
if (!VERB_FORMS.has(form)) {
// `app.addHook('onResponse', …)` is not a route; a route-shaped form this
// reader does not know is refused rather than skipped.
if (path.startsWith('/')) throw new Error(`the checker cannot read app.${form}('${path}'); teach registeredRoutes or drop the form`)
continue
}
routes.add(`${form.toUpperCase()} ${normalisePath(path)}`)
}
return routes
}

/** The `| METHOD | \`path\` |` rows of the endpoint table. */
export function documentedRoutes(markdown = API_DOC): Array<{ method: string; path: string }> {
const rows: Array<{ method: string; path: string }> = []
for (const line of markdown.split('\n')) {
const match = /^\|\s*(GET|POST|PUT|PATCH|DELETE)\s*\|\s*`([^`]+)`\s*\|/.exec(line)
if (match === null) continue
rows.push({ method: match[1] as string, path: (match[2] as string).trim() })
}
return rows
}

/** One line per row the app does not serve: `undocumented-route: METHOD path`. */
export function undocumentedRoutes(markdown = API_DOC, source = APP_SOURCE): string[] {
const registered = registeredRoutes(source)
return documentedRoutes(markdown)
.filter((row) => !registered.has(`${row.method} ${normalisePath(row.path)}`))
.map((row) => `undocumented-route: ${row.method} ${row.path}`)
}

test('#1289 every route in the API table is declared by the app', () => {
const undocumented = undocumentedRoutes()
assert.deepEqual(undocumented, [], `${undocumented.length} table row(s) name a route src/app.ts does not register: ${undocumented.join(', ')}`)
Expand All @@ -115,3 +43,11 @@ test('#1289 the checker reports an unmatched row and still resolves a served one
const fixtureSource = "app.post('/repos/:id/instance', async () => {})"
assert.deepEqual(undocumentedRoutes(fixtureTable, fixtureSource), ['undocumented-route: POST /fixture/nowhere'])
})

// #1293: a reader that understands one quote style reads the other as "not a
// route", so a double-quoted registration would make the checker green on a
// document that omits it. The reader sees the route whichever quote was used.
test('#1289 the reader sees a registration in either quote style', () => {
const routes = registeredRoutes(['app.get("/api/v1/quoted", async () => {})', "app.post('/api/v1/single', async () => {})"].join('\n'))
assert.deepEqual([...routes].sort(), ['GET /api/v1/quoted', 'POST /api/v1/single'])
})
51 changes: 45 additions & 6 deletions test/openapi.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { registeredRoutes } from './apiDocReader.js'
import { buildApp } from '../src/app.js'
import { Store } from '../src/db.js'
import { randomToken, sha256Hex } from '../src/lib/secrets.js'
Expand All @@ -14,12 +15,19 @@ import { makeUser, MemoryMailer, testConfig } from './helpers.js'
//
// The route list is read out of the app source on purpose. Importing the
// document module would let the test agree with itself; reading the registration
// calls is what makes "an undocumented route fails" true.
// calls is what makes "an undocumented route fails" true. The reader is
// `test/apiDocReader.ts`, shared with the `docs/api.md` checker (#1289): one
// definition of "a route the app registers", every verb, either quote style.

const APP_SOURCE = readFileSync(new URL('../src/app.ts', import.meta.url), 'utf8')
const CONTRACT_SOURCE = readFileSync(new URL('../src/api/openapi.ts', import.meta.url), 'utf8')

function registeredApiRoutes(): string[] {
return [...APP_SOURCE.matchAll(/\bapp\.get\('(\/api\/v1\/[^']*)'/g)].map((match) => match[1] as string)
// `paths` in the contract is an object literal, so a duplicate key is already
// gone from the document the route serves; the declaration is counted in the
// source text instead. In that file a `/api/v1/*` string appears only as a key.
function pathDeclarationCount(path: string, source: string): number {
const quoted = path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
return [...source.matchAll(new RegExp(`['"]${quoted}['"]\\s*:`, 'g'))].length
}

async function serveContract(): Promise<{ app: Awaited<ReturnType<typeof buildApp>>['app']; status: number; document: Record<string, unknown> }> {
Expand All @@ -41,23 +49,54 @@ test('the contract is served at GET /api/v1/openapi.json as OpenAPI 3.1', async
}
})

// `paths` is flattened to `METHOD /path` entries, so the assertions below hold
// per method: a `POST /api/v1/x` registered in `src/app.ts` fails unless the
// contract describes that same verb, and a documented verb with no registration
// fails the other way.
test('every /api/v1 route src/app.ts registers appears exactly once in the contract', async () => {
const { app, document } = await serveContract()
try {
const paths = Object.keys((document.paths ?? {}) as Record<string, unknown>)
const registered = registeredApiRoutes()
const paths = Object.entries((document.paths ?? {}) as Record<string, Record<string, unknown>>).flatMap(([path, item]) =>
Object.keys(item).map((method) => `${method.toUpperCase()} ${path}`),
)
const registered = [...registeredRoutes(APP_SOURCE)].filter((route) => route.slice(route.indexOf(' ') + 1).startsWith('/api/v1/'))
assert.ok(registered.length > 0, 'the app registers at least one public API route')
for (const route of registered) {
assert.equal(paths.filter((path) => path === route).length, 1, `${route} is registered in src/app.ts but is not declared exactly once in the contract`)
}
for (const path of paths.filter((entry) => entry.startsWith('/api/v1/'))) {
for (const path of paths.filter((entry) => entry.slice(entry.indexOf(' ') + 1).startsWith('/api/v1/'))) {
assert.ok(registered.includes(path), `the contract declares ${path}, but src/app.ts registers no such route`)
}
} finally {
await app.close()
}
})

// A duplicate path key collapses inside the literal, so "declared exactly once"
// can only be checked against the source text; counting the served object would
// count the survivor and always pass (#1293).
test('every path is declared exactly once in the contract source', async () => {
const { app, document } = await serveContract()
try {
const paths = Object.keys((document.paths ?? {}) as Record<string, unknown>)
assert.ok(paths.length > 0, 'the contract declares at least one path')
for (const path of paths) {
const declared = pathDeclarationCount(path, CONTRACT_SOURCE)
assert.equal(declared, 1, `${path} is declared ${declared} time(s) in src/api/openapi.ts; a duplicate key collapses before the served document can show it`)
}
} finally {
await app.close()
}
})

// The counter is the only thing that makes the assertion above able to fail, so
// it is tested on source the contract does not contain.
test('the declaration counter sees a path declared twice', () => {
const source = ['const paths = {', " '/api/v1/jobs': { get: {} },", " '/api/v1/jobs': { get: {} },", '}'].join('\n')
assert.equal(pathDeclarationCount('/api/v1/jobs', source), 2)
assert.equal(pathDeclarationCount('/api/v1/openapi.json', source), 0)
})

test('the contract carries no session-only, console or callback route', async () => {
const { app, document } = await serveContract()
try {
Expand Down
Loading