Public: anyone can read this; the crew can change it.
Apps can read a printer job's final state, so morning-paper can confirm the 7… #16657
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/16656-apps-can-read-a-printer-job-s-final-stat → main 0 commits fork
13 files
changed +329
−13
- docs/features/devices.md
- src/contract/openapi/routes/getApiV1DevicesIdPrintJob.ts
- src/contract/openapi/routes/index.ts
- src/core/migration-pins/20261129090000-print-job-id.pin
- src/core/migrations/20261129090000-print-job-id.ts
- src/core/print_log.ts
- src/devices/ipp.ts
- src/devices/print.ts
- src/http/api/print.ts
- src/tui/screens/devices.ts
- test/pages-budget.test.ts
- test/print.test.ts
- test/security-floor-routes.test.ts
docs/features/devices.md +1
| @@ -19,6 +19,7 @@ row: Devices | ||
| 19 | 19 | - An app prints with `POST $FORGE_API_URL/devices/<id>/print`, `Authorization: Bearer $FORGE_TOKEN`: the app process's own token, body the PDF (`content-type: application/pdf`). The forge knows the app from `app_token`, which only the runtime writes when it mints that token; a person's token named like an app is not one. A printer that takes only PWG raster is printed to with `content-type: image/pwg-raster` (up to 80 MB, 20 pages; sent as document-format `image/pwg-raster`). Before anything leaves for the LAN the forge checks the `RaS2` sync word, walks every page header (1796 bytes) and its PackBits lines, and takes the page count from them; a truncated, mis-synced, odd-format or 21-page file is 422. Then it asks the printer (Get-Printer-Attributes) for `pwg-raster-document-resolution-supported` and `-type-supported` and refuses a page those lists rule out with 422 (`raster_resolution_refused`, `raster_type_refused`); a printer that lists nothing is not second-guessed. Width and height are not checked against the printer (IPP has no attribute for them). The body is buffered, as the PDF is. The reply is `{"job":{"id","state","reasons"}}` from the printer's IPP Print-Job answer. |
| 20 | 20 | - Checked before anything leaves for the LAN: at most 10 MB and 20 pages, `%PDF-` header and `%%EOF` trailer, otherwise 422. Pages are counted from the plain page tree; a PDF whose tree is in a compressed object stream answers 422 `pages_unknown`. Not granted, or not a declared device: 403. Printer silent or refusing: 502. |
| 21 | 21 | - The route takes a device number only; the job goes to the declared address, so an app reaches no other LAN host through it. Its cell's own egress is unchanged (`src/apps/egress.ts` still opens only granted `host:port`s). |
| 22 | - An app reads how a job it sent ended with `GET $FORGE_API_URL/devices/<id>/print/<job>?within=<seconds>` (the same token and grant; `<job>` is the `job.id` the print answered with, which the forge keeps on the `print_job` row). The forge asks the printer (IPP Get-Job-Attributes) about every half second for up to `within` seconds (default 10, at most 30) and answers `{"job":{"id","state","printer","reasons"}}` with `state` one of `completed`, `failed` (the printer reports canceled, aborted or stopped) or `timed_out` (still pending, held or processing when the time ran out; `printer` says which). Only `completed` means the page came out: an app should say "sent, not confirmed" for anything else. A job this app did not send is 404 `job_unknown`; a printer that never answers is 502; an app may read 60 times a minute and hold 2 reads open at once; past either, 429 `rate_limited`. The terminal door is the Devices screen, which lists each print (`src/tui/screens/devices.ts`). | |
| 22 | 23 | - Each print appends `device.printed` (device, app, pages). |
| 23 | 24 | - The app and grant are checked before the body is read, so a caller without a grant costs a lookup, not 10 MB. An app may start 10 prints a minute and have 2 in flight; past that, 429 `rate_limited`. |
| 24 | 25 | - A PDF containing an object stream (`/ObjStm`) answers 422 `pages_unknown`: the page tree could hide there behind a plain decoy. |
src/contract/openapi/routes/getApiV1DevicesIdPrintJob.ts added +19
| @@ -0,0 +1,19 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "get", | |
| 5 | path: "/api/v1/devices/{id}/print/{job}", | |
| 6 | summary: "Read the final state of a print job the app sent: completed, failed or timed_out", | |
| 7 | detail: "Read a printer job the app (its own token) sent, by the job id the print answered with; waits up to `within` seconds (default 10, at most 30) for the printer to finish, then answers 200 with {job:{id,state,printer,reasons}}, state one of completed, failed (canceled, aborted or stopped) or timed_out (the printer still reports pending, held or processing)", | |
| 8 | auth: true, | |
| 9 | role: "member", | |
| 10 | refusals: { | |
| 11 | forbidden: "403: the app holds no grant on this device", | |
| 12 | job_unknown: "404: this app sent no such job to this device", | |
| 13 | rate_limited: "429: the app read more than 60 jobs in a minute, or holds 2 reads open", | |
| 14 | printer_unreachable: "502: the printer never answered", | |
| 15 | printer_refused: "502: the printer refused the question", | |
| 16 | unauthorized: "no token", | |
| 17 | }, | |
| 18 | refuses: [401], | |
| 19 | }; |
src/contract/openapi/routes/index.ts +1
| @@ -87,6 +87,7 @@ export { route as getApiV1Credit } from "./getApiV1Credit.ts"; | ||
| 87 | 87 | export { route as getApiV1CrewNow } from "./getApiV1CrewNow.ts"; |
| 88 | 88 | export { route as getApiV1CrewScorecard } from "./getApiV1CrewScorecard.ts"; |
| 89 | 89 | export { route as getApiV1CrewWeek } from "./getApiV1CrewWeek.ts"; |
| 90 | export { route as getApiV1DevicesIdPrintJob } from "./getApiV1DevicesIdPrintJob.ts"; | |
| 90 | 91 | export { route as getApiV1Explore } from "./getApiV1Explore.ts"; |
| 91 | 92 | export { route as getApiV1Family } from "./getApiV1Family.ts"; |
| 92 | 93 | export { route as getApiV1Features } from "./getApiV1Features.ts"; |
src/core/migration-pins/20261129090000-print-job-id.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | ccdd6f4422341351874a65355816763ad78b65273ba30c583f200d5f485a1994 |
src/core/migrations/20261129090000-print-job-id.ts added +7
| @@ -0,0 +1,7 @@ | ||
| 1 | // The printer's own job id on each print_job row (#16656), so an app can read | |
| 2 | // back the final state of a job it sent and no other. Null for rows older than | |
| 3 | // this and for refusals. Additive. | |
| 4 | export default ` | |
| 5 | ALTER TABLE print_job ADD COLUMN job_id INTEGER; | |
| 6 | CREATE INDEX print_job_sent ON print_job (device_id, app_id, job_id); | |
| 7 | `; |
src/core/print_log.ts +16 −3
| @@ -18,6 +18,7 @@ export interface PrintJobRow { | ||
| 18 | 18 | readonly pages: number; |
| 19 | 19 | readonly outcome: Outcome; |
| 20 | 20 | readonly at: string; |
| 21 | readonly job: number | null; | |
| 21 | 22 | } |
| 22 | 23 | |
| 23 | 24 | export const dayOf = (now: Date): string => now.toISOString().slice(0, 10); |
| @@ -59,7 +60,7 @@ export const OUTCOME_WORDS: Record<Outcome, string> = { | ||
| 59 | 60 | */ |
| 60 | 61 | export function logJob( |
| 61 | 62 | db: Database, |
| 62 | job: { deviceId: number; appId: string; pages: number; outcome: Outcome }, | |
| 63 | job: { deviceId: number; appId: string; pages: number; outcome: Outcome; jobId?: number | null }, | |
| 63 | 64 | now = new Date(), |
| 64 | 65 | ): void { |
| 65 | 66 | if ( |
| @@ -69,13 +70,14 @@ export function logJob( | ||
| 69 | 70 | .get(job.deviceId, job.appId, dayOf(now)) |
| 70 | 71 | ) |
| 71 | 72 | return; |
| 72 | db.query("INSERT INTO print_job (device_id, app_id, pages, outcome, day, at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)").run( | |
| 73 | db.query("INSERT INTO print_job (device_id, app_id, pages, outcome, day, at, job_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)").run( | |
| 73 | 74 | job.deviceId, |
| 74 | 75 | job.appId, |
| 75 | 76 | job.pages, |
| 76 | 77 | job.outcome, |
| 77 | 78 | dayOf(now), |
| 78 | 79 | now.toISOString(), |
| 80 | job.jobId ?? null, | |
| 79 | 81 | ); |
| 80 | 82 | if (job.outcome === "printed" || job.outcome === "failed") { |
| 81 | 83 | db.query("DELETE FROM print_job WHERE day < ?1").run(dayOf(new Date(now.getTime() - KEEP_DAYS * 86_400_000))); |
| @@ -108,7 +110,7 @@ export function grantLimits(db: Database, deviceId: number, now = new Date()): G | ||
| 108 | 110 | export function recentJobs(db: Database, deviceId: number, limit = 10): PrintJobRow[] { |
| 109 | 111 | return db |
| 110 | 112 | .query<PrintJobRow, [number, number]>( |
| 111 | `SELECT a.slug AS app, j.pages, j.outcome, j.at FROM print_job j JOIN app a ON a.id = j.app_id | |
| 113 | `SELECT a.slug AS app, j.pages, j.outcome, j.at, j.job_id AS job FROM print_job j JOIN app a ON a.id = j.app_id | |
| 112 | 114 | WHERE j.device_id = ?1 ORDER BY j.id DESC LIMIT ?2`, |
| 113 | 115 | ) |
| 114 | 116 | .all(deviceId, limit); |
| @@ -122,3 +124,14 @@ export function setDailyCap(db: Database, deviceId: number, slug: string, cap: n | ||
| 122 | 124 | .run(deviceId, slug, cap); |
| 123 | 125 | return r.changes === 0 ? err("not_found") : ok(true); |
| 124 | 126 | } |
| 127 | ||
| 128 | /** | |
| 129 | * Whether this app sent printer job `jobId` to this device: an app reads only the jobs it started. | |
| 130 | */ | |
| 131 | export function sentJob(db: Database, deviceId: number, appId: string, jobId: number): boolean { | |
| 132 | return ( | |
| 133 | db | |
| 134 | .query("SELECT 1 FROM print_job WHERE device_id = ?1 AND app_id = ?2 AND job_id = ?3 AND outcome = 'printed' LIMIT 1") | |
| 135 | .get(deviceId, appId, jobId) !== null | |
| 136 | ); | |
| 137 | } |
src/devices/ipp.ts +43
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | 8 | const OP_PRINT_JOB = 0x0002; // RFC 8011 §4.2.1 |
| 9 | const OP_GET_JOB_ATTRIBUTES = 0x0009; // RFC 8011 §4.3.4 | |
| 9 | 10 | const OP_GET_PRINTER_ATTRIBUTES = 0x000b; // RFC 8011 §5.2 operation-id registry |
| 10 | 11 | const TAG = { |
| 11 | 12 | operation: 0x01, |
| @@ -314,3 +315,45 @@ async function readCapped(res: Response): Promise<Uint8Array | undefined> { | ||
| 314 | 315 | } |
| 315 | 316 | return out; |
| 316 | 317 | } |
| 318 | ||
| 319 | const intAttr = (tag: number, name: string, value: number): number[] => { | |
| 320 | const n = enc.encode(name); | |
| 321 | return [tag, n.length >> 8, n.length & 255, ...n, 0, 4, (value >>> 24) & 255, (value >>> 16) & 255, (value >>> 8) & 255, value & 255]; | |
| 322 | }; | |
| 323 | ||
| 324 | /** The request body for Get-Job-Attributes on one job of `printerUri`. */ | |
| 325 | export function encodeGetJobAttributes(printerUri: string, jobId: number, requestId = 1): Uint8Array { | |
| 326 | return Uint8Array.from([ | |
| 327 | 1, 1, | |
| 328 | OP_GET_JOB_ATTRIBUTES >> 8, OP_GET_JOB_ATTRIBUTES & 255, | |
| 329 | (requestId >>> 24) & 255, (requestId >>> 16) & 255, (requestId >>> 8) & 255, requestId & 255, | |
| 330 | TAG.operation, | |
| 331 | ...attr(TAG.charset, "attributes-charset", "utf-8"), | |
| 332 | ...attr(TAG.language, "attributes-natural-language", "en"), | |
| 333 | ...attr(TAG.uri, "printer-uri", printerUri), | |
| 334 | ...intAttr(TAG.integer, "job-id", jobId), | |
| 335 | ...attr(TAG.keyword, "requested-attributes", "job-state"), | |
| 336 | ...attr(TAG.keyword, "", "job-state-reasons"), | |
| 337 | TAG.end, | |
| 338 | ]); | |
| 339 | } | |
| 340 | ||
| 341 | export type JobRead = | |
| 342 | | { readonly ok: true; readonly job: PrintJob } | |
| 343 | | { readonly ok: false; readonly error: "unreachable" | "refused" | "bad_answer" }; | |
| 344 | ||
| 345 | /** Ask the printer at `url` (already validated and granted) for one job's current state. */ | |
| 346 | export async function readJob(url: string, jobId: number, timeoutMs = 5000): Promise<JobRead> { | |
| 347 | const answer = await exchange(url, encodeGetJobAttributes(url, jobId), timeoutMs); | |
| 348 | if (!answer.ok) return answer; | |
| 349 | const a = answer.response.attributes; | |
| 350 | const state = a.get("job-state")?.[0]; | |
| 351 | return { | |
| 352 | ok: true, | |
| 353 | job: { | |
| 354 | id: jobId, | |
| 355 | state: typeof state === "number" ? (JOB_STATES[state] ?? "unknown") : "unknown", | |
| 356 | reasons: str(a, "job-state-reasons").filter((r) => r !== "none"), | |
| 357 | }, | |
| 358 | }; | |
| 359 | } |
src/devices/print.ts +82 −5
| @@ -8,10 +8,10 @@ | ||
| 8 | 8 | import type { App } from "../app.ts"; |
| 9 | 9 | import { appOfToken, isGranted, type AppRef } from "../core/device_grants.ts"; |
| 10 | 10 | import { getDevice, type Device } from "../core/devices.ts"; |
| 11 | import { dailyCap, logJob, printedToday, type Outcome } from "../core/print_log.ts"; | |
| 11 | import { dailyCap, logJob, printedToday, sentJob, type Outcome } from "../core/print_log.ts"; | |
| 12 | 12 | import { RateLimiter } from "../core/ratelimit.ts"; |
| 13 | 13 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 14 | import { printDocument, printPdf, probeRasterSupport, type PrintJob } from "./ipp.ts"; | |
| 14 | import { printDocument, printPdf, probeRasterSupport, readJob, type PrintJob } from "./ipp.ts"; | |
| 15 | 15 | import { PWG_MAX_BYTES, readPwg, unsupportedBy, type PwgError } from "./pwg.ts"; |
| 16 | 16 | import { BODY_CAPS } from "../kernel/body_caps.ts"; |
| 17 | 17 | |
| @@ -22,7 +22,7 @@ export const PDF_MAX_PAGES = 20; | ||
| 22 | 22 | export const PRINTS_PER_MINUTE = 10; |
| 23 | 23 | export const PRINTS_AT_ONCE = 2; |
| 24 | 24 | |
| 25 | export type PrintError = "forbidden" | "rate_limited" | "daily_cap" | "not_pdf" | "too_large" | "too_many_pages" | "pages_unknown" | "printer_unreachable" | "printer_refused" | PwgError | "raster_resolution_refused" | "raster_type_refused"; | |
| 25 | export type PrintError = "forbidden" | "rate_limited" | "daily_cap" | "not_pdf" | "too_large" | "too_many_pages" | "pages_unknown" | "printer_unreachable" | "printer_refused" | PwgError | "raster_resolution_refused" | "raster_type_refused" | "job_unknown"; | |
| 26 | 26 | |
| 27 | 27 | export const PRINT_WORDS: Record<PrintError, string> = { |
| 28 | 28 | forbidden: "This app is not granted that printer.", |
| @@ -39,6 +39,7 @@ export const PRINT_WORDS: Record<PrintError, string> = { | ||
| 39 | 39 | raster_type_refused: "The printer says it does not take PWG raster in this colour space and depth.", |
| 40 | 40 | printer_unreachable: "The printer did not answer.", |
| 41 | 41 | printer_refused: "The printer did not accept the job.", |
| 42 | job_unknown: "This app sent no such job to this printer.", | |
| 42 | 43 | }; |
| 43 | 44 | |
| 44 | 45 | const latin = { |
| @@ -132,7 +133,8 @@ export async function printFor(app: App, permit: Permit, pdf: Uint8Array, kind: | ||
| 132 | 133 | try { |
| 133 | 134 | const { caller, device } = permit; |
| 134 | 135 | const checked = kind === "raster" ? checkRaster(pdf) : checkPdf(pdf); |
| 135 | const log = (pages: number, outcome: Outcome): void => logJob(app.db, { deviceId: device.id, appId: caller.id, pages, outcome }); | |
| 136 | const log = (pages: number, outcome: Outcome, jobId: number | null = null): void => | |
| 137 | logJob(app.db, { deviceId: device.id, appId: caller.id, pages, outcome, jobId }); | |
| 136 | 138 | if (!checked.ok) { |
| 137 | 139 | log(0, "refused_document"); |
| 138 | 140 | return checked; |
| @@ -155,7 +157,7 @@ export async function printFor(app: App, permit: Permit, pdf: Uint8Array, kind: | ||
| 155 | 157 | } |
| 156 | 158 | const jobName = `${caller.slug} (forge)`; |
| 157 | 159 | const sent = kind === "raster" ? await printDocument(device.url, pdf, jobName, "image/pwg-raster") : await printPdf(device.url, pdf, jobName); |
| 158 | log(checked.value, sent.ok ? "printed" : "failed"); | |
| 160 | log(checked.value, sent.ok ? "printed" : "failed", sent.ok ? sent.job.id : null); | |
| 159 | 161 | releasePermit(permit); |
| 160 | 162 | if (sent.ok) { |
| 161 | 163 | app.bus.append({ kind: "device.printed", payload: { device: device.name, app: caller.slug, pages: checked.value } }); |
| @@ -166,3 +168,78 @@ export async function printFor(app: App, permit: Permit, pdf: Uint8Array, kind: | ||
| 166 | 168 | releasePermit(permit); |
| 167 | 169 | } |
| 168 | 170 | } |
| 171 | ||
| 172 | /** | |
| 173 | * What an app is told of a job it sent: `timed_out` means the printer had not finished within the | |
| 174 | * limit asked. | |
| 175 | */ | |
| 176 | export type JobOutcome = "completed" | "failed" | "timed_out"; | |
| 177 | ||
| 178 | export const WITHIN_DEFAULT_S = 10; | |
| 179 | export const WITHIN_MAX_S = 30; | |
| 180 | const POLL_MS = 500; | |
| 181 | const reads = new RateLimiter({ perMinute: 60, adminPerMinute: 60, enabled: true }); | |
| 182 | /** | |
| 183 | * Reads one app may hold open at once: each polls the printer twice a second for up to | |
| 184 | * WITHIN_MAX_S. | |
| 185 | */ | |
| 186 | export const READS_AT_ONCE = 2; | |
| 187 | const readsOf = new WeakMap<object, Map<string, number>>(); | |
| 188 | ||
| 189 | /** `?within=` seconds, a whole number from 0 to WITHIN_MAX_S; anything else is the default. */ | |
| 190 | export function withinOf(raw: string | null): number { | |
| 191 | if (raw === null || !/^\d{1,3}$/.test(raw)) return WITHIN_DEFAULT_S; | |
| 192 | return Math.min(Number(raw), WITHIN_MAX_S); | |
| 193 | } | |
| 194 | ||
| 195 | /** | |
| 196 | * completed is done; canceled, aborted and stopped will not finish by themselves; the rest is still | |
| 197 | * on its way. | |
| 198 | */ | |
| 199 | const FINAL: Partial<Record<PrintJob["state"], JobOutcome>> = { completed: "completed", canceled: "failed", aborted: "failed", stopped: "failed" }; | |
| 200 | ||
| 201 | /** | |
| 202 | * The final state of printer job `jobId`, which the app holding `secret` sent | |
| 203 | * to device `deviceId`: `completed`, `failed`, or `timed_out` once `withinS` | |
| 204 | * seconds pass with the printer still working. The same grant checks as a | |
| 205 | * print, and a job this app did not send is `job_unknown`, so one app never | |
| 206 | * reads another's. A printer that never answers is `printer_unreachable`. | |
| 207 | */ | |
| 208 | export async function jobOutcome(app: App, secret: string, deviceId: number, jobId: number, withinS: number): Promise<Result<{ state: JobOutcome; printer: PrintJob["state"]; reasons: readonly string[] }, PrintError>> { | |
| 209 | const caller = appOfToken(app.db, secret); | |
| 210 | if (!caller || !Number.isSafeInteger(deviceId)) return err("forbidden"); | |
| 211 | const device = getDevice(app.db, deviceId); | |
| 212 | if (!device || device.kind !== "printer" || !isGranted(app.db, device.id, caller.id)) return err("forbidden"); | |
| 213 | if (!Number.isSafeInteger(jobId) || !sentJob(app.db, device.id, caller.id, jobId)) return err("job_unknown"); | |
| 214 | const readsInFlight = readsOf.get(app) ?? new Map<string, number>(); | |
| 215 | readsOf.set(app, readsInFlight); | |
| 216 | const held = readsInFlight.get(caller.id) ?? 0; | |
| 217 | if (held >= READS_AT_ONCE || !reads.take(caller.id, "ro").allowed) return err("rate_limited"); | |
| 218 | readsInFlight.set(caller.id, held + 1); | |
| 219 | try { | |
| 220 | return await waitForJob(device.url, jobId, withinS); | |
| 221 | } finally { | |
| 222 | const left = (readsInFlight.get(caller.id) ?? 1) - 1; | |
| 223 | if (left <= 0) readsInFlight.delete(caller.id); | |
| 224 | else readsInFlight.set(caller.id, left); | |
| 225 | } | |
| 226 | } | |
| 227 | ||
| 228 | /** Poll the printer until the job is final or `withinS` seconds pass. */ | |
| 229 | async function waitForJob(url: string, jobId: number, withinS: number): Promise<Result<{ state: JobOutcome; printer: PrintJob["state"]; reasons: readonly string[] }, PrintError>> { | |
| 230 | const deadline = Date.now() + withinS * 1000; | |
| 231 | let last: PrintJob | undefined; | |
| 232 | let failure: "unreachable" | "refused" | "bad_answer" = "unreachable"; | |
| 233 | for (;;) { | |
| 234 | const read = await readJob(url, jobId, Math.max(500, Math.min(5000, deadline - Date.now()))); | |
| 235 | if (read.ok) { | |
| 236 | last = read.job; | |
| 237 | const done = FINAL[read.job.state]; | |
| 238 | if (done !== undefined) return ok({ state: done, printer: read.job.state, reasons: read.job.reasons }); | |
| 239 | } else failure = read.error; | |
| 240 | if (Date.now() + POLL_MS >= deadline) break; | |
| 241 | await Bun.sleep(POLL_MS); | |
| 242 | } | |
| 243 | if (last === undefined) return err(failure === "unreachable" ? "printer_unreachable" : "printer_refused"); | |
| 244 | return ok({ state: "timed_out", printer: last.state, reasons: last.reasons }); | |
| 245 | } |
src/http/api/print.ts +14 −1
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | * PDF, or PWG raster when the content-type says `image/pwg-raster`. The route takes a device number and nothing that names an address. |
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | import { PRINT_WORDS, PDF_MAX_BYTES, permitPrint, printFor, releasePermit, type PrintError } from "../../devices/print.ts"; | |
| 7 | import { PRINT_WORDS, PDF_MAX_BYTES, jobOutcome, permitPrint, printFor, releasePermit, withinOf, type PrintError } from "../../devices/print.ts"; | |
| 8 | 8 | import { PWG_MAX_BYTES } from "../../devices/pwg.ts"; |
| 9 | 9 | import type { Handler } from "../context.ts"; |
| 10 | 10 | import { readBounded } from "../limits.ts"; |
| @@ -27,6 +27,7 @@ const STATUS: Record<PrintError, number> = { | ||
| 27 | 27 | raster_unsupported: 422, |
| 28 | 28 | raster_resolution_refused: 422, |
| 29 | 29 | raster_type_refused: 422, |
| 30 | job_unknown: 404, | |
| 30 | 31 | }; |
| 31 | 32 | |
| 32 | 33 | /** A print refusal; the two 429s say when: the minute's window, or the next UTC day for the daily cap. */ |
| @@ -62,4 +63,16 @@ export function printRoutes(router: Router<Handler>): void { | ||
| 62 | 63 | if (!done.ok) return printRefusal(done.error); |
| 63 | 64 | return json({ job: { id: done.value.id, state: done.value.state, reasons: done.value.reasons } }); |
| 64 | 65 | }); |
| 66 | // The final state of a job this app sent: waits up to ?within= seconds (default 10, at most 30) | |
| 67 | // for the printer to finish. | |
| 68 | router.add("GET", "/api/v1/devices/:id/print/:job", async (ctx) => { | |
| 69 | const secret = tokenSecret(ctx.request.headers.get("authorization") ?? ""); | |
| 70 | if (secret === null) return unauthorized(); | |
| 71 | const number = (v: string | undefined): number => (/^\d{1,9}$/.test(v ?? "") ? Number(v) : Number.NaN); | |
| 72 | const url = new URL(ctx.request.url); | |
| 73 | const jobId = number(ctx.params["job"]); | |
| 74 | const done = await jobOutcome(ctx.app, secret, number(ctx.params["id"]), jobId, withinOf(url.searchParams.get("within"))); | |
| 75 | if (!done.ok) return printRefusal(done.error); | |
| 76 | return json({ job: { id: jobId, state: done.value.state, printer: done.value.printer, reasons: done.value.reasons } }); | |
| 77 | }); | |
| 65 | 78 | } |
src/tui/screens/devices.ts +1 −1
| @@ -124,7 +124,7 @@ export function devicesScreen(f: Session, ctx: Ctx): Screen { | ||
| 124 | 124 | const below = (d: Device): string[] => [ |
| 125 | 125 | ...(d.probe?.supplies.length ? [d.probe.supplies.map((s) => `${s.name} ${s.percent === null ? "?" : `${s.percent}%`}`).join(" · ")] : []), |
| 126 | 126 | ...recentJobs(f.db, d.id, 5).map( |
| 127 | (j) => `${j.at.slice(0, 16).replace("T", " ")} ${j.app} · ${j.pages} ${j.pages === 1 ? "page" : "pages"} · ${OUTCOME_WORDS[j.outcome]}`, | |
| 127 | (j) => `${j.at.slice(0, 16).replace("T", " ")} ${j.app} · ${j.pages} ${j.pages === 1 ? "page" : "pages"} · ${OUTCOME_WORDS[j.outcome]}${j.job === null ? "" : ` · job ${j.job}`}`, | |
| 128 | 128 | ), |
| 129 | 129 | ]; |
| 130 | 130 | const lines = (): ListRow[] => |
test/pages-budget.test.ts +1 −1
| @@ -69,7 +69,7 @@ const HEAVIER: Record<string, { statements?: number; git?: number }> = { | ||
| 69 | 69 | }; |
| 70 | 70 | |
| 71 | 71 | /** Patterns with no fixture today: lower this as fixtures are added, never raise it silently. */ |
| 72 | const MAX_UNFIXTURED = 157; // +1: /:owner/:name/large/:oid, a redirect to a presigned URL with no large blob in the fixture (#4490) // +1: /:owner/:name/bets/:id/walk/:walk, a journey walk of a closed bet scope the fixture has not run (#8715) // +2: /status/:token and /api/v1/status/:token, an outsider status link the fixture has not been handed (#15768); // +1: /tell/share/:id, a receipt of a share the fixture has not sent; +1: /docs/features/:file, a static reference note with no fixture (#12069); +1: /:owner/:name/pulls/:number/check.txt, plain text with no page to fixture (#12165) // +1: /:owner/:name/data/:file, a CSV download with no app data in the fixture (#12684) // +1: /api/v1/repos/:owner/:name/drop/:file, a private file with no drop in the fixture (#645) // +1: /:owner/:name/stl/:ref/*path, an .stl download with no model file in the fixture (#15856) | |
| 72 | const MAX_UNFIXTURED = 158; // +1: /:owner/:name/large/:oid, a redirect to a presigned URL with no large blob in the fixture (#4490) // +1: /:owner/:name/bets/:id/walk/:walk, a journey walk of a closed bet scope the fixture has not run (#8715) // +2: /status/:token and /api/v1/status/:token, an outsider status link the fixture has not been handed (#15768); // +1: /tell/share/:id, a receipt of a share the fixture has not sent; +1: /docs/features/:file, a static reference note with no fixture (#12069); +1: /:owner/:name/pulls/:number/check.txt, plain text with no page to fixture (#12165) // +1: /:owner/:name/data/:file, a CSV download with no app data in the fixture (#12684) // +1: /api/v1/repos/:owner/:name/drop/:file, a private file with no drop in the fixture (#645) // +1: /:owner/:name/stl/:ref/*path, an .stl download with no model file in the fixture (#15856) // +1: /api/v1/devices/:id/print/:job, a printer job the fixture has not sent (#16656) | |
| 73 | 73 | |
| 74 | 74 | /** Streams and live fragments: no page. */ |
| 75 | 75 | const NOT_PAGES = new Set([ |
test/print.test.ts +142 −2
| @@ -7,10 +7,11 @@ import { createApp, type App } from "../src/app.ts"; | ||
| 7 | 7 | import { mintAppToken, revokeAppToken } from "../src/apps/token.ts"; |
| 8 | 8 | import { grantDevice, isGranted } from "../src/core/device_grants.ts"; |
| 9 | 9 | import { declareDevice } from "../src/core/devices.ts"; |
| 10 | import { logJob } from "../src/core/print_log.ts"; | |
| 10 | 11 | import { createToken } from "../src/core/tokens.ts"; |
| 11 | 12 | import { createSession } from "../src/core/sessions.ts"; |
| 12 | 13 | import { getUserByName } from "../src/core/users.ts"; |
| 13 | import { PDF_MAX_BYTES, PRINTS_PER_MINUTE, checkPdf, pageCount } from "../src/devices/print.ts"; | |
| 14 | import { PDF_MAX_BYTES, PRINTS_PER_MINUTE, READS_AT_ONCE, WITHIN_DEFAULT_S, WITHIN_MAX_S, checkPdf, pageCount, withinOf } from "../src/devices/print.ts"; | |
| 14 | 15 | import { serve, type Servers } from "../src/http/server.ts"; |
| 15 | 16 | import { adminCookie } from "./helpers/admin.ts"; |
| 16 | 17 | |
| @@ -30,11 +31,26 @@ const pdf = (pages: number): Uint8Array => | ||
| 30 | 31 | ); |
| 31 | 32 | |
| 32 | 33 | let received: Uint8Array[] = []; |
| 34 | let reads: Uint8Array[] = []; | |
| 35 | let jobState = 9; | |
| 33 | 36 | const printer = Bun.serve({ |
| 34 | 37 | port: 0, |
| 35 | 38 | hostname: "127.0.0.1", |
| 36 | 39 | async fetch(req) { |
| 37 | received.push(new Uint8Array(await req.arrayBuffer())); | |
| 40 | const body = new Uint8Array(await req.arrayBuffer()); | |
| 41 | if (body[3] === 9) { | |
| 42 | reads.push(body); | |
| 43 | return new Response( | |
| 44 | Uint8Array.from([ | |
| 45 | 1, 1, 0, 0, 0, 0, 0, 1, | |
| 46 | 0x01, ...attr(0x47, "attributes-charset", "utf-8"), | |
| 47 | 0x05, ...attr(0x23, "job-state", jobState), | |
| 48 | 0x03, | |
| 49 | ]), | |
| 50 | { headers: { "content-type": "application/ipp" } }, | |
| 51 | ); | |
| 52 | } | |
| 53 | received.push(body); | |
| 38 | 54 | return new Response( |
| 39 | 55 | Uint8Array.from([ |
| 40 | 56 | 1, 1, 0, 0, 0, 0, 0, 1, |
| @@ -339,3 +355,127 @@ test("only an admin sets the cap, and setting it appends device.cap_set", async | ||
| 339 | 355 | expect(cap()).toBe(7); |
| 340 | 356 | expect(app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM event WHERE kind = 'device.cap_set'").get()!.n).toBe(before + 1); |
| 341 | 357 | }); |
| 358 | ||
| 359 | const readJob = (path: string, token: string | undefined) => | |
| 360 | fetch(`${servers.url}${path}`, { headers: { connection: "close", ...(token ? { authorization: `Bearer ${token}` } : {}) } }); | |
| 361 | ||
| 362 | test("an app reads a job it sent as completed", async () => { | |
| 363 | jobState = 9; | |
| 364 | reads = []; | |
| 365 | const res = await readJob(`/api/v1/devices/${deviceId}/print/42`, granted); | |
| 366 | expect(res.status).toBe(200); | |
| 367 | expect(await res.json()).toEqual({ job: { id: 42, state: "completed", printer: "completed", reasons: [] } }); | |
| 368 | expect([...reads[0]!.slice(0, 4)]).toEqual([1, 1, 0, 9]); // Get-Job-Attributes | |
| 369 | expect(Buffer.from(reads[0]!).toString("latin1")).toContain("job-id"); | |
| 370 | }); | |
| 371 | ||
| 372 | test("a canceled, aborted or stopped job reads as failed", async () => { | |
| 373 | for (const code of [6, 7, 8]) { | |
| 374 | jobState = code; | |
| 375 | const body = (await (await readJob(`/api/v1/devices/${deviceId}/print/42`, granted)).json()) as { job: { state: string } }; | |
| 376 | expect(body.job.state).toBe("failed"); | |
| 377 | } | |
| 378 | }); | |
| 379 | ||
| 380 | test("a job still processing reads as timed_out after the time limit, never completed", async () => { | |
| 381 | jobState = 5; | |
| 382 | const t0 = Date.now(); | |
| 383 | const res = await readJob(`/api/v1/devices/${deviceId}/print/42?within=1`, granted); | |
| 384 | expect(res.status).toBe(200); | |
| 385 | expect(await res.json()).toEqual({ job: { id: 42, state: "timed_out", printer: "processing", reasons: [] } }); | |
| 386 | expect(Date.now() - t0).toBeLessThan(5000); | |
| 387 | jobState = 9; | |
| 388 | }); | |
| 389 | ||
| 390 | test("a job that finishes while the app waits reads as completed", async () => { | |
| 391 | jobState = 5; | |
| 392 | setTimeout(() => (jobState = 9), 700); | |
| 393 | const res = await readJob(`/api/v1/devices/${deviceId}/print/42?within=10`, granted); | |
| 394 | expect(((await res.json()) as { job: { state: string } }).job.state).toBe("completed"); | |
| 395 | }); | |
| 396 | ||
| 397 | test("an app cannot read a job it did not send, or one on a device it was not granted", async () => { | |
| 398 | reads = []; | |
| 399 | expect((await readJob(`/api/v1/devices/${deviceId}/print/7`, granted)).status).toBe(404); | |
| 400 | // `ungranted` has no grant here (the earlier test revoked it). | |
| 401 | expect((await readJob(`/api/v1/devices/${deviceId}/print/42`, ungranted)).status).toBe(403); | |
| 402 | expect((await readJob(`/api/v1/devices/${otherId}/print/42`, granted)).status).toBe(403); | |
| 403 | expect((await readJob(`/api/v1/devices/${deviceId}/print/42`, plainToken)).status).toBe(403); | |
| 404 | expect((await readJob(`/api/v1/devices/${deviceId}/print/42`, undefined)).status).toBe(401); | |
| 405 | expect((await readJob(`/api/v1/devices/${deviceId}/print/abc`, granted)).status).toBe(404); | |
| 406 | expect(reads.length).toBe(0); // nothing reached the printer | |
| 407 | }); | |
| 408 | ||
| 409 | test("withinOf: a non-number is the default, a big one is clamped, 0 is kept", () => { | |
| 410 | expect(withinOf(null)).toBe(WITHIN_DEFAULT_S); | |
| 411 | expect(withinOf("abc")).toBe(WITHIN_DEFAULT_S); | |
| 412 | expect(withinOf("-1")).toBe(WITHIN_DEFAULT_S); | |
| 413 | expect(withinOf("1.5")).toBe(WITHIN_DEFAULT_S); | |
| 414 | expect(withinOf("99")).toBe(WITHIN_MAX_S); | |
| 415 | expect(withinOf("0")).toBe(0); | |
| 416 | expect(withinOf("7")).toBe(7); | |
| 417 | }); | |
| 418 | ||
| 419 | test("within=0 reads the printer once and answers", async () => { | |
| 420 | jobState = 5; | |
| 421 | reads = []; | |
| 422 | const res = await readJob(`/api/v1/devices/${deviceId}/print/42?within=0`, granted); | |
| 423 | expect(((await res.json()) as { job: { state: string } }).job.state).toBe("timed_out"); | |
| 424 | expect(reads.length).toBe(1); | |
| 425 | jobState = 9; | |
| 426 | }); | |
| 427 | ||
| 428 | /** | |
| 429 | * A fresh app with a grant on `url` and a job 5 it "sent", so reads get past the ownership check. | |
| 430 | */ | |
| 431 | function readerOn(slug: string, url: string): { token: string; path: string } { | |
| 432 | const owner = getUserByName(app.db, "alice")!; | |
| 433 | addApp(`id-${slug}`, slug); | |
| 434 | const d = declareDevice(app.db, { name: `Dev ${slug}`, kind: "printer", url }); | |
| 435 | if (!d.ok) throw new Error("declare"); | |
| 436 | expect(grantDevice(app.db, d.value.id, slug, owner.id).ok).toBe(true); | |
| 437 | logJob(app.db, { deviceId: d.value.id, appId: `id-${slug}`, pages: 1, outcome: "printed", jobId: 5 }); | |
| 438 | return { token: mintAppToken(app.db, owner.id, slug, "production").token, path: `/api/v1/devices/${d.value.id}/print/5` }; | |
| 439 | } | |
| 440 | ||
| 441 | test("the 61st read in a minute is 429 rate_limited", async () => { | |
| 442 | const r = readerOn("minuter", `ipp://127.0.0.1:${printer.port}/ipp/print`); | |
| 443 | jobState = 9; | |
| 444 | for (let i = 0; i < 60; i++) expect((await readJob(`${r.path}?within=0`, r.token)).status).toBe(200); | |
| 445 | const res = await readJob(`${r.path}?within=0`, r.token); | |
| 446 | expect(res.status).toBe(429); | |
| 447 | expect(((await res.json()) as { error: string }).error).toBe("rate_limited"); | |
| 448 | }); | |
| 449 | ||
| 450 | test("reads held open past the in-flight cap are 429, and a finished read gives its place back", async () => { | |
| 451 | const r = readerOn("holder", `ipp://127.0.0.1:${printer.port}/ipp/print`); | |
| 452 | jobState = 5; | |
| 453 | reads = []; | |
| 454 | const held = Array.from({ length: READS_AT_ONCE }, () => readJob(`${r.path}?within=3`, r.token)); | |
| 455 | // Both reads are in the forge once the printer has been asked twice. | |
| 456 | while (reads.length < READS_AT_ONCE) await new Promise((done) => setImmediate(done)); | |
| 457 | const over = await readJob(`${r.path}?within=3`, r.token); | |
| 458 | expect(over.status).toBe(429); | |
| 459 | expect(((await over.json()) as { error: string }).error).toBe("rate_limited"); | |
| 460 | jobState = 9; | |
| 461 | for (const h of await Promise.all(held)) expect(h.status).toBe(200); | |
| 462 | expect((await readJob(`${r.path}?within=0`, r.token)).status).toBe(200); | |
| 463 | }); | |
| 464 | ||
| 465 | test("a printer that never answers is 502 printer_unreachable; one that refuses is printer_refused", async () => { | |
| 466 | const silent = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => new Promise<Response>(() => {}) }); | |
| 467 | const refusing = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => new Response("no", { status: 500 }) }); | |
| 468 | try { | |
| 469 | const a = readerOn("mute", `ipp://127.0.0.1:${silent.port}/ipp/print`); | |
| 470 | const res = await readJob(`${a.path}?within=0`, a.token); | |
| 471 | expect(res.status).toBe(502); | |
| 472 | expect(((await res.json()) as { error: string }).error).toBe("printer_unreachable"); | |
| 473 | const b = readerOn("refuser", `ipp://127.0.0.1:${refusing.port}/ipp/print`); | |
| 474 | const no = await readJob(`${b.path}?within=0`, b.token); | |
| 475 | expect(no.status).toBe(502); | |
| 476 | expect(((await no.json()) as { error: string }).error).toBe("printer_refused"); | |
| 477 | } finally { | |
| 478 | silent.stop(true); | |
| 479 | refusing.stop(true); | |
| 480 | } | |
| 481 | }); |
test/security-floor-routes.test.ts +1
| @@ -104,6 +104,7 @@ const UNSEEDED: Record<string, string> = { | ||
| 104 | 104 | "/:owner/:name/waves/:version": WAVE, |
| 105 | 105 | "/api/v1/boards/:slug/panels/:id": BOARD, |
| 106 | 106 | "/api/v1/conversation/files/:id": "an attachment id exists only once its owner uploads a file; the seed holds none", |
| 107 | "/api/v1/devices/:id/print/:job": "a printer job exists only once an app sends one to a device; the seed holds none", | |
| 107 | 108 | "/api/v1/fleet/ops/:id": FLEET, |
| 108 | 109 | "/api/v1/migrate/:job": MIGRATE, |
| 109 | 110 | "/api/v1/migrate/:job/stream": MIGRATE, |
new above
offline