diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 48a54b5..d61afbc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,11 +19,10 @@ # # That exclusion got more expensive on 2026-08-28. Android's suite went from 22 # tests to 50: the printed-rule port added ten, PageNormalizer's newly-testable -# internals fourteen, and the cv2 dilation fixture four. Six of those fifty are the -# fixture tests, and they are the only automated check that this app's segmenter and -# its page normaliser still agree with web and iOS, the two ports CI does run. The -# three shared fixtures below are verified on every push, but nothing here verifies -# that the Kotlin side still matches them. +# internals fourteen, and the cv2 dilation fixture four. Some of those are the +# fixture tests, the only automated check that this app's segmenter and page +# normaliser still agree with web and iOS. The `android` job now runs them on every +# push, alongside the web and iOS fixture checks. # # iOS is no longer excluded, but only its pure logic. `apps/ios/MonOcrCore` is a # Swift package over the Foundation-only files, so `swift test` needs no @@ -785,6 +784,28 @@ jobs: done echo "charsets identical ($(wc -c < "$ref") bytes)" + - name: The bundled models are the pinned bytes + # Web checks the download against MODEL_SHA256 and Android checks its + # asset at load, but nothing checked the committed files themselves: a + # re-export or a bad merge could replace them and every test would still + # pass. Android's asset must match the hash both engines pin, read from the + # source so this list cannot drift from it. iOS pins no hash in its own + # source, so its Core ML files are pinned here to the bytes committed on + # 2026-11-10: changing the export means changing these lines with it. + run: | + set -euo pipefail + kt=apps/android/app/src/main/java/dev/janakhpon/monocr/engine/MonOcrEngine.kt + pinned="$(sed -n 's/.*MODEL_SHA256 = "\([0-9a-f]\{64\}\)".*/\1/p' "$kt")" + [ -n "$pinned" ] || { echo "::error file=$kt::no MODEL_SHA256 found"; exit 1; } + grep -q "MODEL_SHA256 = '$pinned'" apps/web/src/lib/monocr-onnx.ts \ + || { echo "::error::web MODEL_SHA256 differs from Android's"; exit 1; } + sha256sum -c - < + + + + + diff --git a/apps/android/app/src/main/res/xml/backup_rules.xml b/apps/android/app/src/main/res/xml/backup_rules.xml index e7bc4fc..48525cd 100644 --- a/apps/android/app/src/main/res/xml/backup_rules.xml +++ b/apps/android/app/src/main/res/xml/backup_rules.xml @@ -1,7 +1,14 @@ + - - - diff --git a/apps/android/app/src/test/java/dev/janakhpon/monocr/ui/BackupRulesTest.kt b/apps/android/app/src/test/java/dev/janakhpon/monocr/ui/BackupRulesTest.kt new file mode 100644 index 0000000..3b9f648 --- /dev/null +++ b/apps/android/app/src/test/java/dev/janakhpon/monocr/ui/BackupRulesTest.kt @@ -0,0 +1,55 @@ +package dev.janakhpon.monocr.ui + +import java.io.File +import javax.xml.parsers.DocumentBuilderFactory +import org.junit.Assert.assertEquals +import org.junit.Test +import org.w3c.dom.Element + +/** + * Cloud backup takes the same data on every Android version, and a + * device-to-device transfer takes scan history wherever Android can tell the + * two apart. + * + * `data_extraction_rules.xml` (Android 12+) limited cloud backup to shared + * preferences while `backup_rules.xml` (Android 11 and older) still sent the + * database and files, so scan history left the device on older phones only. + * `requireFlags="deviceToDeviceTransfer"` exists from API 28, so Android 9 to + * 11 (`xml-v28`) keep the history transfer; Android 7 and 8 cannot without + * also sending it to cloud backup, so they transfer settings only. + */ +class BackupRulesTest { + private fun includes(path: String, parentTag: String? = null): List { + val doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(File(path)) + val root: Element = if (parentTag == null) doc.documentElement + else doc.getElementsByTagName(parentTag).item(0) as Element + val nodes = root.getElementsByTagName("include") + return (0 until nodes.length).map { nodes.item(it) as Element } + } + + /** Domains every backup takes: includes with no `requireFlags`. */ + private fun unflagged(path: String) = + includes(path).filter { !it.hasAttribute("requireFlags") }.map { it.getAttribute("domain") }.toSet() + + private fun deviceTransferOnly(path: String) = + includes(path).filter { it.getAttribute("requireFlags") == "deviceToDeviceTransfer" } + .map { it.getAttribute("domain") }.toSet() + + private val cloud = includes("src/main/res/xml/data_extraction_rules.xml", "cloud-backup") + .map { it.getAttribute("domain") }.toSet() + private val transfer = includes("src/main/res/xml/data_extraction_rules.xml", "device-transfer") + .map { it.getAttribute("domain") }.toSet() + + @Test fun `older Android backs up only what Android 12 cloud backup does`() { + assertEquals(setOf("sharedpref"), cloud) + // API 24 to 27 ignore requireFlags, so any include there reaches cloud backup. + assertEquals(emptyList(), includes("src/main/res/xml/backup_rules.xml").filter { it.hasAttribute("requireFlags") }) + assertEquals(cloud, unflagged("src/main/res/xml/backup_rules.xml")) + assertEquals(cloud, unflagged("src/main/res/xml-v28/backup_rules.xml")) + } + + @Test fun `Android 9 to 11 transfer to a new device what Android 12 does`() { + assertEquals(setOf("root"), transfer) + assertEquals(transfer, deviceTransferOnly("src/main/res/xml-v28/backup_rules.xml")) + } +} diff --git a/apps/ios/MonOcrCore/Tests/MonOcrCoreTests/CtcDecoderTests.swift b/apps/ios/MonOcrCore/Tests/MonOcrCoreTests/CtcDecoderTests.swift index 97f8a93..a7eeddc 100644 --- a/apps/ios/MonOcrCore/Tests/MonOcrCoreTests/CtcDecoderTests.swift +++ b/apps/ios/MonOcrCore/Tests/MonOcrCoreTests/CtcDecoderTests.swift @@ -1,3 +1,4 @@ +import Foundation import Testing @testable import MonOcrCore @@ -66,4 +67,22 @@ struct CtcDecoderTests { try CtcDecoder.decode(logits: logits, timeSteps: 2, numClasses: 4, charset: "AB") } } + + /// The decoded text must never reach the log file: "Export Debug Logs" on the + /// About screen shares that file, and release builds used to append every + /// recognised line to it. Tests run as a DEBUG build, where debug and info lines + /// do reach the file, so this catches a decoder that logs its result at any level. + @Test func decodedTextIsNeverWrittenToTheLogFile() throws { + // Only what this decode appends is checked: the file outlives the run, so + // a line from an earlier build must not fail this one. + let before = (try? Data(contentsOf: MonLogger.logFileURL))?.count ?? 0 + let charset = "QJXZVK" + let logits = buildLogits(timeSteps: 6, numClasses: 7, argmaxes: [1, 2, 3, 4, 5, 6]) + let result = try CtcDecoder.decode(logits: logits, timeSteps: 6, numClasses: 7, charset: charset) + #expect(result == charset) + let data = (try? Data(contentsOf: MonLogger.logFileURL)) ?? Data() + let appended = String(decoding: data.dropFirst(data.count >= before ? before : 0), as: UTF8.self) + #expect(!appended.contains(charset)) + #expect(!appended.contains("[1:Q]")) + } } diff --git a/apps/ios/monocr-ios/CtcDecoder.swift b/apps/ios/monocr-ios/CtcDecoder.swift index 5bb8977..bfe5228 100644 --- a/apps/ios/monocr-ios/CtcDecoder.swift +++ b/apps/ios/monocr-ios/CtcDecoder.swift @@ -77,7 +77,6 @@ nonisolated enum CtcDecoder { // Step 2 & 3: CTC collapse — remove blanks (0) and consecutive duplicates let decoded = NSMutableString() var prevIdx = -1 - var pathDescription = "" for idx in predictions { if idx != 0 && idx != prevIdx { @@ -95,14 +94,14 @@ nonisolated enum CtcDecoder { } let char = String(Character(scalar)) decoded.append(char) - pathDescription += "[\(idx):\(char)] " } prevIdx = idx } let result = decoded as String - MonLogger.d("CTC Path: \(pathDescription)") - MonLogger.i("CTC Result: '\(result)'") + // A count, never the text: the log file can be exported from the About + // screen, and what a person scanned is theirs, not diagnostics. + MonLogger.d("CTC decoded \(result.count) characters") return result } } diff --git a/apps/ios/monocr-ios/Logger.swift b/apps/ios/monocr-ios/Logger.swift index 205cf63..f916fc2 100644 --- a/apps/ios/monocr-ios/Logger.swift +++ b/apps/ios/monocr-ios/Logger.swift @@ -4,16 +4,40 @@ import os.log /** * A lightweight, structured logging utility for MonOCR iOS. * Utilizes Apple's os.log for performance and system integration. + * + * The log file is the one "Export Debug Logs" on the About screen shares, so it + * must never hold what a person scanned. Two rules keep it that way: debug and + * info lines reach the file only in DEBUG builds, and os_log marks every message + * private, so a release build's unified log redacts it unless a debugger is + * attached. Callers still log counts and sizes, never recognised text. */ nonisolated enum MonLogger { private static let log = OSLog(subsystem: "mondevhub.monocr", category: "App") private static let maxFileSize: UInt64 = 1 * 1024 * 1024 // 1 MB - + + #if DEBUG + static let writesVerboseLinesToFile = true + #else + static let writesVerboseLinesToFile = false + #endif + static var logFileURL: URL { + _ = legacyLogRemoved + return cachesDirectory.appendingPathComponent("monocr_diagnostics.txt") + } + + private static var cachesDirectory: URL { FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] - .appendingPathComponent("monocr_logs.txt") } + /// Builds before this file name logged every recognised line to + /// `monocr_logs.txt` in release builds too. Delete it once per launch so an + /// export can never carry that text. + private static let legacyLogRemoved: Void = { + try? FileManager.default.removeItem( + at: cachesDirectory.appendingPathComponent("monocr_logs.txt")) + }() + private static let dateFormatter: DateFormatter = { let df = DateFormatter() df.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" @@ -47,23 +71,23 @@ nonisolated enum MonLogger { } nonisolated static func d(_ message: String) { - os_log("%{public}@", log: log, type: .debug, message) - appendToFile(level: "D", message: message) + os_log("%{private}@", log: log, type: .debug, message) + if writesVerboseLinesToFile { appendToFile(level: "D", message: message) } } nonisolated static func i(_ message: String) { - os_log("%{public}@", log: log, type: .info, message) - appendToFile(level: "I", message: message) + os_log("%{private}@", log: log, type: .info, message) + if writesVerboseLinesToFile { appendToFile(level: "I", message: message) } } nonisolated static func w(_ message: String) { - os_log("%{public}@", log: log, type: .default, "[W] " + message) + os_log("%{private}@", log: log, type: .default, "[W] " + message) appendToFile(level: "W", message: message) } nonisolated static func e(_ message: String, error: Error? = nil) { let errorMessage = error != nil ? "\(message) | Error: \(error!.localizedDescription)" : message - os_log("%{public}@", log: log, type: .error, "[E] " + errorMessage) + os_log("%{private}@", log: log, type: .error, "[E] " + errorMessage) appendToFile(level: "E", message: errorMessage) } } diff --git a/apps/web/README.md b/apps/web/README.md index c9e8e17..4b98e01 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -78,7 +78,9 @@ curl -L -o static/monocr.onnx \ falls back to the pinned URL otherwise, printing which one it chose; production never reads it. Fetch exactly that revision and keep it equal to `CONFIG.MODELS.RECOGNITION`: `static/charset.txt` is 276 characters, and the app refuses a model that does not match it with a `ModelContractError` -at load rather than returning wrong text. +at load rather than returning wrong text. Before that, every model download, local or remote, must +hash to `MODEL_SHA256` in `src/lib/monocr-onnx.ts` or it is refused with a `ModelIntegrityError` +and not cached. ## Test and check diff --git a/apps/web/eslint.config.js b/apps/web/eslint.config.js index 373d724..c58b1eb 100644 --- a/apps/web/eslint.config.js +++ b/apps/web/eslint.config.js @@ -38,7 +38,6 @@ export default ts.config( 'src/lib/utils/use-intersection.svelte.ts', // Vendored quiet-ds: linted in its own repository, with its own rules. 'src/lib/quiet/', - 'functions/', // Generated by `paraglide-js compile`. .prettierignore already skips // these; eslint did not, so regenerating them produced 114 warnings // on code nobody writes. A linter that reports on generated output diff --git a/apps/web/functions/monocr.onnx.js b/apps/web/functions/monocr.onnx.js deleted file mode 100644 index 7f3c660..0000000 --- a/apps/web/functions/monocr.onnx.js +++ /dev/null @@ -1,43 +0,0 @@ -export async function onRequest(context) { - // Pinned to a revision, not `main`. The four SDKs in monocr-onnx all pin; this - // proxy and src/lib/config.ts were the only consumers tracking a moving branch, - // which also made the `immutable` header below a promise this could not keep. - // A revision here means a new model reaches users when someone changes this - // line, not when someone pushes to the model repository. - const MODEL_URL = 'https://huggingface.co/janakhpon/monocr/resolve/d3d9d5e/onnx/monocr.onnx'; - - try { - // Fetch with redirect following (default behavior) - const response = await fetch(MODEL_URL, { - headers: { - 'User-Agent': 'MonOCR-Web-Proxy' - }, - redirect: 'follow' // Explicitly follow redirects - }); - - if (!response.ok) { - return new Response(`Failed to fetch model: ${response.status} ${response.statusText}`, { - status: 502, - headers: { 'Content-Type': 'text/plain' } - }); - } - - // Stream the response body directly rather than buffering. The file is - // 46,247,040 bytes at revision d3d9d5e; this comment read "55MB" until - // 2026-08-15, which was the size of an earlier revision. - return new Response(response.body, { - status: 200, - headers: { - 'Content-Type': 'application/octet-stream', - 'Access-Control-Allow-Origin': '*', - 'Cache-Control': 'public, max-age=31536000, immutable', - 'Content-Length': response.headers.get('Content-Length') || '' - } - }); - } catch (error) { - return new Response(`Proxy error: ${error.message}`, { - status: 500, - headers: { 'Content-Type': 'text/plain' } - }); - } -} diff --git a/apps/web/src/lib/config.ts b/apps/web/src/lib/config.ts index 7733189..1878c3b 100644 --- a/apps/web/src/lib/config.ts +++ b/apps/web/src/lib/config.ts @@ -12,9 +12,7 @@ export const CONFIG = { // Local override for development. Put the model at `static/monocr.onnx` // and every reload reads it off disk instead of pulling 46.2 MB from // Hugging Face. Gitignored — see the README for the fetch command. - // - // The path is the same one `functions/monocr.onnx.js` proxies in - // production, so nothing about the request shape changes between the two. + // It is checked against the same MODEL_SHA256 as the pinned download. RECOGNITION_LOCAL: '/monocr.onnx', CHARSET: '/charset.txt' diff --git a/apps/web/src/lib/monocr-onnx.test.ts b/apps/web/src/lib/monocr-onnx.test.ts index e07afbe..0273739 100644 --- a/apps/web/src/lib/monocr-onnx.test.ts +++ b/apps/web/src/lib/monocr-onnx.test.ts @@ -1,7 +1,9 @@ import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { createHash } from 'node:crypto'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; // onnxruntime-web is imported at module scope and pulls in WASM binaries. None of // it is exercised here: these tests drive the contract check against a stubbed @@ -30,8 +32,14 @@ vi.mock('./segmentation', async (importOriginal) => { return { ...actual, segmentLines: vi.fn(actual.segmentLines) }; }); -const { MonOcrOnnx, ModelContractError, ModelOutputError, readLine } = - await import('./monocr-onnx'); +const { + MonOcrOnnx, + ModelContractError, + ModelIntegrityError, + ModelOutputError, + MODEL_SHA256, + readLine +} = await import('./monocr-onnx'); const { assemblePage } = await import('./reading'); const { CONFIG, resolveRecognitionModel } = await import('./config'); const { segmentLines } = await import('./segmentation'); @@ -673,3 +681,115 @@ describe('reading the model body', () => { expect(seen.at(-1)).toBe(200_000); }); }); + +describe('model integrity', () => { + type Fetcher = { + fetchAsset(u: string, p?: unknown, sha?: string): Promise; + }; + const URL_ = 'https://example.test/monocr.onnx'; + const GOOD = new Uint8Array([7, 7, 7, 7]); + const BAD = new Uint8Array([6, 6, 6, 6]); + const GOOD_SHA = createHash('sha256').update(GOOD).digest('hex'); + + function fetchReturning(...bodies: Uint8Array[]) { + const fn = vi.fn(); + for (const body of bodies) { + fn.mockResolvedValueOnce(new Response(body.slice().buffer as ArrayBuffer, { status: 200 })); + } + vi.stubGlobal('fetch', fn); + return fn; + } + + /** A one-entry Cache API, enough for fetchAsset's match/put/delete. */ + function installCache(initial?: Uint8Array) { + const store = new Map(); + if (initial) store.set(URL_, initial); + const cache = { + match: vi.fn(async (u: string) => { + const body = store.get(u); + return body ? new Response(body.slice().buffer as ArrayBuffer) : undefined; + }), + put: vi.fn(async (u: string, r: Response) => { + store.set(u, new Uint8Array(await r.arrayBuffer())); + }), + delete: vi.fn(async (u: string) => store.delete(u)) + }; + (globalThis as unknown as { caches: unknown }).caches = { open: async () => cache }; + return { cache, store }; + } + + afterEach(() => { + delete (globalThis as unknown as { caches?: unknown }).caches; + }); + + it('pins the same bytes Android bundles', () => { + const kotlin = readFileSync( + fileURLToPath( + new URL( + '../../../android/app/src/main/java/dev/janakhpon/monocr/engine/MonOcrEngine.kt', + import.meta.url + ) + ), + 'utf-8' + ); + expect(kotlin).toContain(`MODEL_SHA256 = "${MODEL_SHA256}"`); + }); + + it('asks for the model to be checked against the pinned hash', async () => { + const engine = new MonOcrOnnx(); + const fetchAsset = vi + .spyOn(engine as unknown as Fetcher, 'fetchAsset') + .mockImplementation(async (url: string) => + url.endsWith('charset.txt') ? new TextEncoder().encode(CHARSET) : new Uint8Array([1]) + ); + createSession.mockResolvedValueOnce(fakeSession(V35.height, V35.classes)); + await engine.initialize('/model.onnx', '/charset.txt'); + expect(fetchAsset).toHaveBeenCalledWith('/model.onnx', undefined, MODEL_SHA256); + }); + + it('refuses a download that does not match, and caches nothing', async () => { + const { cache, store } = installCache(); + const fetch = fetchReturning(BAD); + await expect( + (new MonOcrOnnx() as unknown as Fetcher).fetchAsset(URL_, undefined, GOOD_SHA) + ).rejects.toThrow(ModelIntegrityError); + expect(cache.put).not.toHaveBeenCalled(); + expect(store.has(URL_)).toBe(false); + // Not retried by the direct-fetch fallback. + expect(fetch).toHaveBeenCalledTimes(1); + }); + + it('refuses a mismatch on the no-cache path too, without a second download', async () => { + const fetch = fetchReturning(BAD, BAD); + await expect( + (new MonOcrOnnx() as unknown as Fetcher).fetchAsset(URL_, undefined, GOOD_SHA) + ).rejects.toThrow(ModelIntegrityError); + expect(fetch).toHaveBeenCalledTimes(1); + }); + + it('evicts a cached copy that does not match and fetches the real one', async () => { + const { cache, store } = installCache(BAD); + const fetch = fetchReturning(GOOD); + const bytes = await (new MonOcrOnnx() as unknown as Fetcher).fetchAsset( + URL_, + undefined, + GOOD_SHA + ); + expect(Array.from(bytes)).toEqual(Array.from(GOOD)); + expect(cache.delete).toHaveBeenCalledWith(URL_); + expect(fetch).toHaveBeenCalledTimes(1); + expect(Array.from(store.get(URL_) ?? [])).toEqual(Array.from(GOOD)); + }); + + it('serves a cached copy that matches without touching the network', async () => { + installCache(GOOD); + const fetch = fetchReturning(); + const bytes = await (new MonOcrOnnx() as unknown as Fetcher).fetchAsset( + URL_, + undefined, + GOOD_SHA + ); + expect(Array.from(bytes)).toEqual(Array.from(GOOD)); + expect(fetch).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/src/lib/monocr-onnx.ts b/apps/web/src/lib/monocr-onnx.ts index 4c2faa5..c576758 100644 --- a/apps/web/src/lib/monocr-onnx.ts +++ b/apps/web/src/lib/monocr-onnx.ts @@ -18,6 +18,44 @@ import { looksLikeALine, normalizePagePolarity, segmentLines, tileLine } from '. // Bump this in the same change that bumps those, or it stops being an answer. export const MODEL_VERSION = 'v3.5@d3d9d5e'; +/** + * SHA-256 of `onnx/monocr.onnx` at revision `d3d9d5e`: the same bytes Android + * bundles and checks against its own `MODEL_SHA256`. Bump it with the revision. + * + * A revision pin names the file, it does not prove what arrived. Without this the + * app cached whatever the network returned — a truncated body, a captive portal's + * page, a tampered copy — and served it from the cache on every reload after. + */ +export const MODEL_SHA256 = 'b95de1ea0e3dc99a5c31bea32e220835da801f683ed17091eaec9954c80a4c04'; + +/** + * The downloaded model is not the pinned file. Never cached, never retried by + * the fallback fetch: a second download from the same source is no more + * trustworthy than the first. + */ +export class ModelIntegrityError extends Error { + constructor(message: string) { + super(message); + this.name = 'ModelIntegrityError'; + } +} + +async function sha256Hex(bytes: Uint8Array): Promise { + const digest = await crypto.subtle.digest('SHA-256', bytes as Uint8Array); + return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join(''); +} + +/** Throw unless `bytes` hashes to `expected`; a no-op when nothing is expected. */ +async function assertSha256(url: string, bytes: Uint8Array, expected?: string): Promise { + if (!expected) return; + const actual = await sha256Hex(bytes); + if (actual !== expected) { + throw new ModelIntegrityError( + `${url} has SHA-256 ${actual}, expected ${expected}; refusing to load it` + ); + } +} + /** * The model and the charset disagree about what this model is. * @@ -152,7 +190,7 @@ export class MonOcrOnnx { // Load ONNX model with Caching strategy. The charset above is 556 bytes and // needs no progress; this is the 46 MB one. - const modelBuffer = await this.fetchAsset(modelPath, onProgress); + const modelBuffer = await this.fetchAsset(modelPath, onProgress, MODEL_SHA256); // Init session with buffer, with automatic fallback mapping try { @@ -198,10 +236,16 @@ export class MonOcrOnnx { * Fetch asset with caching (Cache API) for offline robustness. * Cache name matches the Workbox SW runtime cache so both paths * share a single store: Cache API reads → SW writes, and vice-versa. + * + * With `expectedSha256`, bytes are checked before they are used or cached. A + * cached entry that fails is deleted and fetched again, since the service + * worker writes this cache too and checks nothing; a download that fails is + * refused with a ModelIntegrityError. */ private async fetchAsset( url: string, - onProgress?: (received: number, total: number) => void + onProgress?: (received: number, total: number) => void, + expectedSha256?: string ): Promise { const CACHE_NAME = 'monocr-models'; let cacheError: Error | null = null; @@ -212,14 +256,27 @@ export class MonOcrOnnx { const cachedResponse = await cache.match(url); if (cachedResponse) { - const buffer = await cachedResponse.arrayBuffer(); - return new Uint8Array(buffer); + const cached = new Uint8Array(await cachedResponse.arrayBuffer()); + try { + await assertSha256(url, cached, expectedSha256); + return cached; + } catch (e) { + console.warn('[monocr-onnx] cached model failed its hash check; fetching again', e); + await cache.delete(url); + } } const response = await fetch(url); if (!response.ok) throw new Error(`Failed to fetch ${url}: ${response.statusText}`); const bytes = await this.readWithProgress(response, onProgress); + try { + await assertSha256(url, bytes, expectedSha256); + } catch (e) { + // The service worker may already have stored this response. + await cache.delete(url).catch(() => false); + throw e; + } // Cache the bytes we already have rather than a second copy of the // stream. `cache.put(url, response.clone())` used to run before the @@ -238,6 +295,7 @@ export class MonOcrOnnx { return bytes; } } catch (e) { + if (e instanceof ModelIntegrityError) throw e; cacheError = e instanceof Error ? e : new Error(String(e)); } @@ -245,8 +303,11 @@ export class MonOcrOnnx { try { const response = await fetch(url); if (!response.ok) throw new Error(`Failed to fetch ${url}: ${response.statusText}`); - return await this.readWithProgress(response, onProgress); + const bytes = await this.readWithProgress(response, onProgress); + await assertSha256(url, bytes, expectedSha256); + return bytes; } catch (networkError) { + if (networkError instanceof ModelIntegrityError) throw networkError; if (cacheError) { throw new Error( `Offline — cache unavailable and network failed. Cache error: ${cacheError.message}. Network: ${networkError}`, diff --git a/docs/architecture/platform/android.md b/docs/architecture/platform/android.md index ef8af5d..b8f7533 100644 --- a/docs/architecture/platform/android.md +++ b/docs/architecture/platform/android.md @@ -99,18 +99,19 @@ When adding a new column: ## Testing -| Layer | Test Type | Location | -| --------------------------------- | --------------------------------------------- | ---------------------------------------------- | -| `CtcDecoder` | Unit | `src/test/.../engine/CtcDecoderTest.kt` | -| `PageNormalizer` | Unit | `src/test/.../engine/PageNormalizerTest.kt` | -| `PageNormalizer.dilate` | Parity, against a cv2-generated fixture | `src/test/.../engine/DilateFixtureTest.kt` | -| `LineSegmenter` | Unit | `src/test/.../engine/LineSegmenterTest.kt` | -| `LineSegmenter.suppressPageRules` | Unit, paired line for line with the iOS suite | `src/test/.../engine/RuleSuppressionTest.kt` | -| `LineSegmenter.suppressPageRules` | Cross-platform parity | `src/test/.../engine/RuleFixtureTest.kt` | -| `LineTiler` | Unit, cross-platform parity | `src/test/.../engine/LineTilerFixtureTest.kt` | -| `SegmentationMode` | Unit | `src/test/.../engine/SegmentationModeTest.kt` | -| ViewModels | Unit (TODO) | Use `TestCoroutineDispatcher` + in-memory Room | -| Screens | UI (TODO) | Compose test rules | +| Layer | Test Type | Location | +| --------------------------------- | --------------------------------------------- | ------------------------------------------------------------------------------ | +| `CtcDecoder` | Unit | `src/test/.../engine/CtcDecoderTest.kt` | +| `PageNormalizer` | Unit | `src/test/.../engine/PageNormalizerTest.kt` | +| `PageNormalizer.dilate` | Parity, against a cv2-generated fixture | `src/test/.../engine/DilateFixtureTest.kt` | +| `LineSegmenter` | Unit | `src/test/.../engine/LineSegmenterTest.kt` | +| `LineSegmenter.suppressPageRules` | Unit, paired line for line with the iOS suite | `src/test/.../engine/RuleSuppressionTest.kt` | +| `LineSegmenter.suppressPageRules` | Cross-platform parity | `src/test/.../engine/RuleFixtureTest.kt` | +| `LineTiler` | Unit, cross-platform parity | `src/test/.../engine/LineTilerFixtureTest.kt` | +| `SegmentationMode` | Unit | `src/test/.../engine/SegmentationModeTest.kt` | +| `MainViewModel` | Robolectric, against a fake pipeline | `src/test/.../ui/OcrFailureTest.kt`, `ProgressTest.kt`, `ResultActionsTest.kt` | +| Screens | Compose UI on Robolectric | `src/test/.../ui/` (navigation, consent, accessibility, share intent and more) | +| Backup rules | Unit, legacy against Android 12+ cloud backup | `src/test/.../ui/BackupRulesTest.kt` | --- diff --git a/docs/architecture/platform/line-segmentation-parity.md b/docs/architecture/platform/line-segmentation-parity.md index f7e9027..b4a2e74 100644 --- a/docs/architecture/platform/line-segmentation-parity.md +++ b/docs/architecture/platform/line-segmentation-parity.md @@ -56,10 +56,17 @@ surface at once. | Mode selection | **none** | provenance + shape | provenance + shape | `--mode`, `auto`, `inspect` | | Polarity normalised before segmenting | yes | yes | yes | yes | | Printed-rule suppression | yes | yes | yes | yes | +| Background levelled before segmenting | **no** | yes | yes | **no** | The first three rows are all Android against the others; the fourth is web against the others. So no surface is the reference, and no two agree completely. +The last row is `PageNormalizer`, which Android and iOS run before the segmenter +(see the sixth divergence below). Web inverts a dark page and stops there: +`normalizePagePolarity` in `segmentation.ts` says background levelling was not +ported. The CLI's crate, `monocr` 0.5.0, likewise only corrects polarity before +segmenting. + Printed-rule suppression is on all four surfaces; see the fifth-divergence section for what the three ports (iOS, Android, and the CLI's via Rust) pinned. @@ -87,9 +94,9 @@ line mode gets the same probe per crop in `preprocess_line`. **Web has no mode at all**, which is worth stating beside the rest: it is the one surface where a fused-block reading cannot be retried, because there is no other -parameter set to retry with. Its `lineShaped` flag also stops at -`console.warn`, because the worker posts a bare string, so a user sees fused text -as ordinary output. +parameter set to retry with. Its `lineShaped` flag does reach the user: the worker +returns a `PageReading` carrying `fusedBandCount`, and `pageWarnings` in `reading.ts` +turns it into a warning that `+page.svelte` shows beside the text. **Why it matters more than the numbers suggest.** The smoothing kernel is applied to the row-ink profile before bands are detected, so it decides directly @@ -424,23 +431,23 @@ this model reads. Horizontal agrees at 11 everywhere. The ports agree with each other. -### Capture quality exists in three different states +### Capture quality: computed and shown on all three apps -| surface | computed? | reaches the user? | -| ------- | --------------------------- | ------------------------------------- | -| web | yes, sharpness and no-lines | no: `console.warn` inside the worker | -| iOS | yes, sharpness only | no: `isSoft` has no caller in the app | -| Android | no | n/a | +| surface | computed? | reaches the user? | +| ------- | --------------------------- | ----------------------------------------------------------------------- | +| web | yes, sharpness and no-lines | yes: `pageWarnings` in `reading.ts`, shown by `+page.svelte` | +| iOS | yes, sharpness and no-lines | yes: `MonOcrEngine` calls `isSoft`; `ResultCardView` shows the warnings | +| Android | yes, sharpness and no-lines | yes: `OcrRepository` calls `isSoft`; `HomeScreen` shows the warnings | -The one shared threshold matches exactly where both compute it. iOS's is dead code -reached only by its own tests, and Android has no equivalent at all: it folds the -zero-lines case into a whole-page fallback, so the case web reports as its -highest-priority warning is the one Android cannot report. +All three surfaces compute the warning and show it to the person. iOS and +Android report the no-lines case as "no regions detected" alongside their +whole-page fallback, rather than as a capture warning, but the user sees it on +every surface. -The fused-block warning is a separate flag and is in better shape than the above: -Android surfaces it in `HomeScreen` and iOS in `ResultCardView`. Only web stops at a -`console.warn` the user never sees. The difference between "computed" and "reaches a -user" is exactly what this table is for: check it before recording a surface as silent. +The fused-block warning is a separate flag and also reaches the user everywhere: +Android in `HomeScreen`, iOS in `ResultCardView`, web through `fusedBandCount`. The +difference between "computed" and "reaches a user" is exactly what this table is +for: check it before recording a surface as silent. ## What would close it diff --git a/services/feedback/Dockerfile b/services/feedback/Dockerfile index 1f7e5f2..e3e0c6d 100644 --- a/services/feedback/Dockerfile +++ b/services/feedback/Dockerfile @@ -1,5 +1,8 @@ # https://hub.docker.com/_/golang -FROM golang:1.26-alpine AS builder +# The official image sets GOTOOLCHAIN=local, so the toolchain line in go.mod does +# not apply here: the binary is compiled by whatever Go this tag carries. Keep the +# patch equal to that toolchain line and bump the two together. +FROM golang:1.26.11-alpine AS builder # Create and change to the app directory. WORKDIR /app diff --git a/services/feedback/go.mod b/services/feedback/go.mod index 764e8e4..cec6710 100644 --- a/services/feedback/go.mod +++ b/services/feedback/go.mod @@ -3,9 +3,10 @@ module ocr-feedback-service go 1.26.0 // Pinned to the patch that carries the stdlib fixes govulncheck requires; -// go1.26.5 is affected by 7 called vulnerabilities. Bump this with the scan, -// not on a schedule. -toolchain go1.26.9 +// go1.26.9 is affected by 2 called vulnerabilities (GO-2026-6859 in net/http, +// GO-2026-6809 in crypto/x509), both fixed by go1.26.11. Bump this with the +// scan, not on a schedule. +toolchain go1.26.11 require ( github.com/aws/aws-sdk-go-v2 v1.47.3 diff --git a/services/feedback/internal/auth/middleware.go b/services/feedback/internal/auth/middleware.go index 5a61ab3..3f1f4f2 100644 --- a/services/feedback/internal/auth/middleware.go +++ b/services/feedback/internal/auth/middleware.go @@ -1,6 +1,7 @@ package auth import ( + "crypto/subtle" "log/slog" "net/http" "os" @@ -19,7 +20,10 @@ func APIKeyMiddleware() gin.HandlerFunc { return } - if apiKey != expectedKey { + // Constant time, so response timing does not reveal how much of a guess + // matched. ConstantTimeCompare returns early only on a length mismatch, + // which leaks the key's length and nothing else. + if subtle.ConstantTimeCompare([]byte(apiKey), []byte(expectedKey)) != 1 { slog.Warn("Unauthorized access attempt", "client_ip", c.ClientIP(), "user_agent", c.Request.UserAgent()) c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: Invalid API Key"}) return diff --git a/services/feedback/internal/auth/middleware_test.go b/services/feedback/internal/auth/middleware_test.go new file mode 100644 index 0000000..d90c7fa --- /dev/null +++ b/services/feedback/internal/auth/middleware_test.go @@ -0,0 +1,54 @@ +package auth + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" +) + +func serve(t *testing.T, header string, set bool) int { + t.Helper() + gin.SetMode(gin.TestMode) + r := gin.New() + r.GET("/", APIKeyMiddleware(), func(c *gin.Context) { c.Status(http.StatusOK) }) + req := httptest.NewRequest(http.MethodGet, "/", nil) + if set { + req.Header.Set("X-API-Key", header) + } + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + return w.Code +} + +func TestAPIKeyMiddleware(t *testing.T) { + t.Setenv("API_KEY", "expected-key") + cases := []struct { + name string + header string + set bool + want int + }{ + {"matching key", "expected-key", true, http.StatusOK}, + {"wrong key", "unexpected-k", true, http.StatusUnauthorized}, + {"prefix of the key", "expected", true, http.StatusUnauthorized}, + {"key plus suffix", "expected-key2", true, http.StatusUnauthorized}, + {"empty header", "", true, http.StatusUnauthorized}, + {"no header", "", false, http.StatusUnauthorized}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := serve(t, tc.header, tc.set); got != tc.want { + t.Fatalf("status %d, want %d", got, tc.want) + } + }) + } +} + +func TestAPIKeyMiddlewareRefusesWhenUnconfigured(t *testing.T) { + t.Setenv("API_KEY", "") + if got := serve(t, "", true); got != http.StatusInternalServerError { + t.Fatalf("status %d, want %d", got, http.StatusInternalServerError) + } +}