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

Merged opened this in answer to

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/16656-apps-can-read-a-printer-job-s-final-stat → main 0 commits fork

  • Merged. scout/16656-apps-can-read-a-printer-job-s-final-stat was merged into main as 6f95d61.

Review

Sign in to review this change.
13 files changed +329 −13
docs/features/devices.md +1
@@ -19,6 +19,7 @@ row: Devices
1919 - 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.
2020 - 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.
2121 - 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`).
2223 - Each print appends `device.printed` (device, app, pages).
2324 - 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`.
2425 - 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";
8787 export { route as getApiV1CrewNow } from "./getApiV1CrewNow.ts";
8888 export { route as getApiV1CrewScorecard } from "./getApiV1CrewScorecard.ts";
8989 export { route as getApiV1CrewWeek } from "./getApiV1CrewWeek.ts";
90 export { route as getApiV1DevicesIdPrintJob } from "./getApiV1DevicesIdPrintJob.ts";
9091 export { route as getApiV1Explore } from "./getApiV1Explore.ts";
9192 export { route as getApiV1Family } from "./getApiV1Family.ts";
9293 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 {
1818 readonly pages: number;
1919 readonly outcome: Outcome;
2020 readonly at: string;
21 readonly job: number | null;
2122 }
2223
2324 export const dayOf = (now: Date): string => now.toISOString().slice(0, 10);
@@ -59,7 +60,7 @@ export const OUTCOME_WORDS: Record<Outcome, string> = {
5960 */
6061 export function logJob(
6162 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 },
6364 now = new Date(),
6465 ): void {
6566 if (
@@ -69,13 +70,14 @@ export function logJob(
6970 .get(job.deviceId, job.appId, dayOf(now))
7071 )
7172 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(
7374 job.deviceId,
7475 job.appId,
7576 job.pages,
7677 job.outcome,
7778 dayOf(now),
7879 now.toISOString(),
80 job.jobId ?? null,
7981 );
8082 if (job.outcome === "printed" || job.outcome === "failed") {
8183 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
108110 export function recentJobs(db: Database, deviceId: number, limit = 10): PrintJobRow[] {
109111 return db
110112 .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
112114 WHERE j.device_id = ?1 ORDER BY j.id DESC LIMIT ?2`,
113115 )
114116 .all(deviceId, limit);
@@ -122,3 +124,14 @@ export function setDailyCap(db: Database, deviceId: number, slug: string, cap: n
122124 .run(deviceId, slug, cap);
123125 return r.changes === 0 ? err("not_found") : ok(true);
124126 }
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 @@
66 */
77
88 const OP_PRINT_JOB = 0x0002; // RFC 8011 §4.2.1
9 const OP_GET_JOB_ATTRIBUTES = 0x0009; // RFC 8011 §4.3.4
910 const OP_GET_PRINTER_ATTRIBUTES = 0x000b; // RFC 8011 §5.2 operation-id registry
1011 const TAG = {
1112 operation: 0x01,
@@ -314,3 +315,45 @@ async function readCapped(res: Response): Promise<Uint8Array | undefined> {
314315 }
315316 return out;
316317 }
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 @@
88 import type { App } from "../app.ts";
99 import { appOfToken, isGranted, type AppRef } from "../core/device_grants.ts";
1010 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";
1212 import { RateLimiter } from "../core/ratelimit.ts";
1313 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";
1515 import { PWG_MAX_BYTES, readPwg, unsupportedBy, type PwgError } from "./pwg.ts";
1616 import { BODY_CAPS } from "../kernel/body_caps.ts";
1717
@@ -22,7 +22,7 @@ export const PDF_MAX_PAGES = 20;
2222 export const PRINTS_PER_MINUTE = 10;
2323 export const PRINTS_AT_ONCE = 2;
2424
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";
2626
2727 export const PRINT_WORDS: Record<PrintError, string> = {
2828 forbidden: "This app is not granted that printer.",
@@ -39,6 +39,7 @@ export const PRINT_WORDS: Record<PrintError, string> = {
3939 raster_type_refused: "The printer says it does not take PWG raster in this colour space and depth.",
4040 printer_unreachable: "The printer did not answer.",
4141 printer_refused: "The printer did not accept the job.",
42 job_unknown: "This app sent no such job to this printer.",
4243 };
4344
4445 const latin = {
@@ -132,7 +133,8 @@ export async function printFor(app: App, permit: Permit, pdf: Uint8Array, kind:
132133 try {
133134 const { caller, device } = permit;
134135 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 });
136138 if (!checked.ok) {
137139 log(0, "refused_document");
138140 return checked;
@@ -155,7 +157,7 @@ export async function printFor(app: App, permit: Permit, pdf: Uint8Array, kind:
155157 }
156158 const jobName = `${caller.slug} (forge)`;
157159 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);
159161 releasePermit(permit);
160162 if (sent.ok) {
161163 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:
166168 releasePermit(permit);
167169 }
168170 }
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 @@
44 * PDF, or PWG raster when the content-type says `image/pwg-raster`. The route takes a device number and nothing that names an address.
55 */
66
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";
88 import { PWG_MAX_BYTES } from "../../devices/pwg.ts";
99 import type { Handler } from "../context.ts";
1010 import { readBounded } from "../limits.ts";
@@ -27,6 +27,7 @@ const STATUS: Record<PrintError, number> = {
2727 raster_unsupported: 422,
2828 raster_resolution_refused: 422,
2929 raster_type_refused: 422,
30 job_unknown: 404,
3031 };
3132
3233 /** 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 {
6263 if (!done.ok) return printRefusal(done.error);
6364 return json({ job: { id: done.value.id, state: done.value.state, reasons: done.value.reasons } });
6465 });
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 });
6578 }
src/tui/screens/devices.ts +1 −1
@@ -124,7 +124,7 @@ export function devicesScreen(f: Session, ctx: Ctx): Screen {
124124 const below = (d: Device): string[] => [
125125 ...(d.probe?.supplies.length ? [d.probe.supplies.map((s) => `${s.name} ${s.percent === null ? "?" : `${s.percent}%`}`).join(" · ")] : []),
126126 ...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}`}`,
128128 ),
129129 ];
130130 const lines = (): ListRow[] =>
test/pages-budget.test.ts +1 −1
@@ -69,7 +69,7 @@ const HEAVIER: Record<string, { statements?: number; git?: number }> = {
6969 };
7070
7171 /** 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)
7373
7474 /** Streams and live fragments: no page. */
7575 const NOT_PAGES = new Set([
test/print.test.ts +142 −2
@@ -7,10 +7,11 @@ import { createApp, type App } from "../src/app.ts";
77 import { mintAppToken, revokeAppToken } from "../src/apps/token.ts";
88 import { grantDevice, isGranted } from "../src/core/device_grants.ts";
99 import { declareDevice } from "../src/core/devices.ts";
10 import { logJob } from "../src/core/print_log.ts";
1011 import { createToken } from "../src/core/tokens.ts";
1112 import { createSession } from "../src/core/sessions.ts";
1213 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";
1415 import { serve, type Servers } from "../src/http/server.ts";
1516 import { adminCookie } from "./helpers/admin.ts";
1617
@@ -30,11 +31,26 @@ const pdf = (pages: number): Uint8Array =>
3031 );
3132
3233 let received: Uint8Array[] = [];
34 let reads: Uint8Array[] = [];
35 let jobState = 9;
3336 const printer = Bun.serve({
3437 port: 0,
3538 hostname: "127.0.0.1",
3639 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);
3854 return new Response(
3955 Uint8Array.from([
4056 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
339355 expect(cap()).toBe(7);
340356 expect(app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM event WHERE kind = 'device.cap_set'").get()!.n).toBe(before + 1);
341357 });
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> = {
104104 "/:owner/:name/waves/:version": WAVE,
105105 "/api/v1/boards/:slug/panels/:id": BOARD,
106106 "/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",
107108 "/api/v1/fleet/ops/:id": FLEET,
108109 "/api/v1/migrate/:job": MIGRATE,
109110 "/api/v1/migrate/:job/stream": MIGRATE,

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs