SPB Git

Repository Public

security.md 22.4 KB 216 lines markdown

1<!--2ORIX Docs3File: docs/security.md4Description: Threat model for untrusted documents in ORIX Docs 1.0.0, what the code does about each threat, the tests that exercise it, and the residual risks.5Author: Simon-Pierre Boucher6Contact: contact@spboucher.ai7-->8# Security910A word processor opens files written by other people. This document states what ORIX Docs 1.0.0 assumes about those files, what the code does, which tests exercise it, and what remains at risk. The requirements were set before the importers were written ([technology-evaluation.md, section 13](research/technology-evaluation.md#13-security-requirements-for-opening-untrusted-files)); this document describes the code as it is.1112## Threat model1314**Assets.** The user's documents and other files, the integrity of the document being edited, and the user's privacy (no content leaves the Mac).1516**Untrusted input.** Any file opened or imported: `.orixdoc`, DOCX (also `.docm` and `.dotx`), RTF, Markdown, HTML, plain text, PDF; bibliography files (BibTeX, RIS, CSL-JSON); workflow JSON files; pasted and dropped content; LaTeX strings inside documents.1718**Adversary.** Someone who can get a crafted file opened — by e-mail, download or a shared folder — and wants to crash the application, exhaust memory or CPU, read or write files the user did not choose, make the application contact a server, or run code.1920**Out of scope.** An attacker who already runs code as the user; physical access; malicious fonts installed on the system; flaws in macOS frameworks themselves (they are listed under residual risks because the application depends on them).2122## Summary2324| Threat | What the code does | Tests |25|---|---|---|26| Decompression bombs, oversized archives | Limits on entry count, entry size, total size and compression ratio | `ZipTests.detectsCorruptionAndBombs`, `decompressionBombIsRefused` |27| Path traversal in archives | Unsafe entry names refused; entries are never extracted to disk | `ZipTests.rejectsTraversalAndGarbage`, `pathTraversalEntryNamesAreRefused` |28| XML entity attacks (XXE, billion laughs) | Any part containing `<!DOCTYPE` or `<!ENTITY` is refused; external entities never resolved | `doctypeAndEntitiesAreRefused` |29| Stack or memory exhaustion by nesting | Depth, size and node limits; dedicated large stacks | `hugeNestingIsRefusedNotOverflowed`, `tenThousandNestedQuotesAndLists` |30| Macros and active content | Never executed, never preserved | `macrosOleAndActiveXAreDroppedNeverPreserved` |31| Remote resources (tracking, data exfiltration) | Nothing is ever fetched; external targets are inert strings | `externalTargetsAreKeptAsTextNeverFetched`, `imagesComeOnlyFromDataURIsAndTheLoader` |32| Script in HTML and Markdown | Own parsers, no web engine; script content skipped, script schemes removed | `scriptSchemesNeverReachTheOutput`, `scriptLinksAreRemoved` |33| Crashing the math typesetter | Guard before typesetting; fuzz tests | `MathRobustnessTests` |34| Corrupted native files | SHA-256 manifest, strict reader, bounded recovery | `NativeContainerTests`, `malformedContainersNeverTrap` |35| Workflow files that run code or write anywhere | Closed step vocabulary; output path confinement | `unknownStepTypesAreRejected`, `pathsLeavingTheOutputFolderAreRejected` |36| Malformed input in general | Importers throw or warn, never trap | `truncatedAndCorruptedPackagesNeverCrash`, `mutatedXmlNeverCrashes`, `fuzzedMarkupNeverTrapsAndKeepsModelInvariants` |3738The engine test run that contains these tests is recorded as 582 tests, passed, 0 issues, in [test-results.json](reports/test-results.json). The report records totals, not individual test outcomes.3940## ZIP archives4142Code: `Packages/ORIXDocsKit/Sources/DocContainer/ZipArchive.swift`. Both `.orixdoc` and DOCX are ZIP files and go through the same reader, written for this project.4344`ZipLimits.standard`:4546| Limit | Value |47|---|---|48| Entries | 20,000 |49| One entry, uncompressed | 256 MiB |50| All entries, uncompressed | 1 GiB |51| Compression ratio | Entries larger than 1 MB whose uncompressed/compressed ratio exceeds 1,000 are refused |5253Checks made while reading the central directory, before any data is decompressed:5455* ZIP64 archives, encrypted entries and compression methods other than stored and deflate are refused (`unsupported`);56* the central directory and every entry must lie inside the file (`corrupted`);57* **duplicate entry names** are refused;58* **unsafe entry names** are refused: empty, starting with `/`, containing a backslash, a NUL, a colon, or a `..` component.5960When an entry is read: the local header must match the directory (signature and name), the data must lie inside the file, a stored entry must have equal sizes, the inflated data must have exactly the declared size, and the CRC-32 must match.6162The archive is held in memory and entries are decompressed on demand. **Nothing is ever extracted to the file system**, so a path in an archive cannot become a path on disk; the name checks are defence in depth.6364Tests: `Tests/DocContainerTests/ZipTests.swift` (`rejectsTraversalAndGarbage`, `detectsCorruptionAndBombs`, plus interoperability with the system `zip` and `unzip`); `Tests/DocDOCXTests/SecurityTests.swift` (`notAnArchive`, `decompressionBombIsRefused`, `pathTraversalEntryNamesAreRefused`). DocContainer line coverage is 100.0 % ([coverage.json](reports/coverage.json)).6566## XML in DOCX6768Code: `Packages/ORIXDocsKit/Sources/DocDOCX/XML.swift` (`XMLTree.parse`), on Foundation's `XMLParser`.6970* **No DTD at all.** A part whose bytes contain `<!DOCTYPE` or `<!ENTITY` is refused before parsing. UTF-16 parts are transcoded first so that the scan sees them. OOXML never needs a DTD, so nothing legitimate is lost; entity expansion and external entities are therefore impossible.71* `shouldResolveExternalEntities` is set to `false` explicitly.72* `XMLLimits.standard`: 96 MiB per part, depth 256, 4,000,000 elements. Custom XML and the ORIX extras payload are size-capped before parsing (32 MiB for the extras payload).73* Import and export run on a thread with a 32 MB stack (`DocxStack`), so nesting up to the depth limit cannot overflow a small concurrency-thread stack.74* Numbers read from XML are range-checked before conversion.7576Tests: `doctypeAndEntitiesAreRefused`, `hugeNestingIsRefusedNotOverflowed`, `absurdValuesDoNotCrash`, `mutatedXmlNeverCrashes` (200 structurally mutated documents), `truncatedAndCorruptedPackagesNeverCrash` (198 corrupted archives) — counts as stated in [compatibility/docx.md](compatibility/docx.md#security-behaviour).7778## Macros, OLE and other active content7980* A `.docm` is imported for its text; VBA projects, OLE embeddings, ActiveX controls and custom UI parts are **never interpreted, never executed and never kept**. The user gets a warning that names what was dropped.81* Uninterpreted parts of a DOCX (theme, font table, custom XML…) are preserved through an **allow-list** of part names; each must be well-formed XML and its relationships must stay inside the preserved set.82* The exporter validates preserved parts again, because a model can also come from an untrusted `.orixdoc` that claims to carry preserved parts.83* The model's field type is a closed set (page number, page count, date, title, sequence, heading text…); there is no field that reads files, the environment or the network. Unknown DOCX fields keep their displayed text and raise a warning.84* ORIX Docs never writes a macro-enabled file.8586Tests: `macrosOleAndActiveXAreDroppedNeverPreserved`, `preservedPartsFromAnUntrustedModelAreRevalidatedOnExport`.8788## External relationships and links8990* `OPC.resolve` maps a relationship target to a part inside the archive or to nothing. A target that is absolute, has a scheme, or climbs above the package root is ignored with a warning.91* External targets (linked pictures, remote templates, `INCLUDEPICTURE`) are kept as strings or dropped with a warning. **Nothing is read from the file system or fetched from the network.**92* Hyperlinks are inert data. In the editor a link is followed only on an explicit ⌘-click, and only `http`, `https` and `mailto` URLs are handed to the system; `#name` jumps inside the document ([text-engine.md](architecture/text-engine.md#11-mouse)).9394Tests: `relationshipTargetsCannotLeaveThePackage`, `externalTargetsAreKeptAsTextNeverFetched`.9596## HTML and Markdown9798Code: `Packages/ORIXDocsKit/Sources/DocFormats/HTMLTokenizer.swift`, `HTMLImporter.swift`, `MarkdownImporter.swift`, `MarkdownInline.swift`.99100* **No web engine.** HTML is read by a tolerant tokeniser and tree builder written for this project; WebKit and `NSAttributedString(html:)` are not used. There is nothing that could execute a script.101* The content of `<script>` and `<style>` is skipped as raw text; scripts, frames and event handlers are reported as dropped.102* Links whose scheme can carry script (`javascript:`, `vbscript:`, `data:`, `livescript:`) are removed and their text kept, in HTML and in Markdown.103* **Images** come only from data URIs or from the **resource loader** supplied by the caller. The loader built in `DocAutomation/DocumentConverter.swift` refuses any path that contains `://`, resolves the path against the folder of the source file, requires the result to stay under that folder, and refuses files of 64 MiB or more. Remote images are never fetched.104* Limits: 64 MiB of source, 256 open HTML elements, 32 nested Markdown containers, 9 list levels, 256 columns and 1,000,000 cells per table; the recursive Markdown parser runs on its own 16 MiB stack ([formats.md](compatibility/formats.md#safety-limits)).105106Tests: `Tests/DocFormatsTests/HTMLTests.swift` (`scriptSchemesNeverReachTheOutput`), `MarkdownTests.swift` (`scriptLinksAreRemoved`, `imagesComeOnlyFromDataURIsAndTheLoader`), `FacadeAndRobustnessTests.swift` (`HostileInputTests`: `tenThousandNestedQuotesAndLists`, `pathologicalInlineInputIsLinearEnough`, `hugeTables`, `brokenMarkdownTables`, `malformedContainersNeverTrap`, `fuzzedMarkupNeverTrapsAndKeepsModelInvariants`; `UnicodeTortureTests`).107108The loader (`DocumentConverter.confinedResource`) resolves symbolic links and compares whole path components, so neither a sibling folder with a similar name nor a link pointing outside is read; `Tests/DocAutomationTests/ResourceConfinementTests.swift` checks both.109110## RTF, plain text and PDF import111112* **RTF** goes through AppKit's `NSAttributedString` RTF codec, which is local (no network, no WebKit). Pictures are lifted out of the bytes and handled by this project's code; WMF, EMF and PICT pictures are dropped with a warning. RTFD is refused. Limit: 128 MiB.113* **Plain text**: encoding detection with repair, control characters removed. Limit: 64 MiB.114* **PDF**: text extraction through PDFKit only. Password-protected PDFs and PDFs whose owner forbids extraction are refused. Limits: 512 MiB, 20,000 pages.115116Details and what was verified: [formats.md](compatibility/formats.md).117118## Mathematics119120Equations are LaTeX strings that arrive from untrusted documents and are given to a third-party typesetter, SwiftMath, which recurses on nesting and can trap on some malformed input.121122`MathGuard` (`Packages/ORIXDocsKit/Sources/DocMath/MathRenderer.swift`) refuses an expression **before** it reaches the library when it:123124* is longer than 4,000 UTF-16 units (`maxLength`);125* contains control characters or the object-replacement character;126* has an unmatched closing brace, an unclosed group, or ends with an incomplete command;127* has two script operators in a row (`^^`, `__`);128* nests deeper than 24 levels (`maxDepth`), counting braces, `\left` and `\begin`;129* contains more than 60 fraction, root or binomial commands;130* has more than 400 cells (`maxCells`), counting `&` and `\\`.131132A refused or unparsable expression is shown as its source in red monospaced text with an error message; it never disappears and never stops the layout. Drawing is serialised by a lock.133134Tests: `Tests/DocLayoutTests/MathRobustnessTests.swift` — `hostileLatexNeverCrashes` (a list of about a hundred malformed and extreme expressions, each typeset inline and in display style, then drawn), `randomTokenSoupNeverCrashes` (3,000 pseudo-random token sequences from a fixed seed), `validEquationsTypesetWithoutError`.135136## The native container137138Code: `Packages/ORIXDocsKit/Sources/DocFormats/NativeContainer.swift`; description in [persistence.md](architecture/persistence.md).139140* A hostile `.orixdoc` is as untrusted as a hostile DOCX: it goes through the same ZIP reader and limits, plus a 1 GiB file limit.141* The manifest lists every entry with its size and SHA-256; the strict reader verifies them before decoding `document.json`. A container or schema version newer than the build is refused.142* Recovery of a damaged file keeps only entries whose data is complete, reports everything it skipped, and refuses to open a file whose `document.json` cannot be recovered.143144**What the checksum is for.** It detects corruption — a bad disk, a truncated download, a careless tool. It does **not** detect tampering: whoever can rewrite the file can rewrite the manifest. The format has no digital signature and no encryption.145146Tests: `Tests/DocFormatsTests/NativeContainerTests.swift` (byte flips in each kind of entry, tampered asset, truncation, wrong or misplaced mimetype, missing manifest, future versions, recovery).147148## Workflows149150Code: `Packages/ORIXDocsKit/Sources/DocAutomation/Workflow.swift`, `WorkflowRunner.swift`; description in [automation.md](development/automation.md#security). A workflow is a JSON file, possibly received from someone else.151152* **Closed vocabulary.** The step types are a fixed list of document operations. Any other `type` is rejected when the file is loaded, before any input is read. There is no step that runs a script, starts a process or opens a connection.153* **Values are validated before anything runs**: theme, template, paper, citation style, audit profile, export format, margins and levels. The file must be smaller than 1 MB.154* **Path confinement.** An output name that is absolute, starts with `~`, or contains `..`, `.` or empty components is rejected at load time. At run time the destination is resolved again with symbolic links followed and refused if it lands outside the output folder; the `{name}` placeholder is sanitised.155* Existing files are not overwritten unless asked, and a workflow can never replace its own input.156157Tests: `Tests/DocAutomationTests/WorkflowRunnerTests.swift` — `unknownStepTypesAreRejected` (`runScript`, `shell`, `exec`, `appleScript`, `download`), `pathsLeavingTheOutputFolderAreRejected`, `invalidValuesAreRejectedBeforeAnythingRuns`.158159## No network code160161The application, the engines and the command-line tool contain no networking calls.162163* **Tests.** `OnDeviceOnlyTests.noNetworkCodeInAutomationOrIntelligence` (`Tests/DocAutomationTests/IntelligenceTests.swift`) reads every Swift file under `DocAutomation`, `orixdocs`, `App/Sources/Intelligence`, `App/Sources/Automation` and `App/Sources/Inspector` and fails if one contains `URLSession`, `URLRequest`, `NWConnection`, `import Network`, `CFNetwork`, `NSURLConnection`, `Process()`, `NSTask`, `NSAppleScript` or `/bin/sh`. `OnDeviceOnlyTests.noServerBackedModelTypeInTheSources` reads every Swift file of the application and of the package and fails if one names the server-backed language-model type.164* **By inspection.** The first test covers five folders, not the whole code base. A search of all of `App/Sources` and `Packages/ORIXDocsKit/Sources` for the same networking APIs and for WebKit, made on 2026-11-21, found none. This is an observation, not a standing test.165* What does leave the process, on the user's action only: a ⌘-clicked `http`, `https` or `mailto` URL, handed to the system; and revealing an output folder in the Finder after a workflow.166* macOS services the application calls (spelling, NaturalLanguage, the on-device model) are system components; the system may download assets for them on its own account ([technology-evaluation.md, section 9](research/technology-evaluation.md#9-local-ai)).167168## The process169170* **Hardened runtime, no entitlements.** The Release build is signed with the hardened runtime and an empty entitlements file: no JIT, no unsigned executable memory, no DYLD environment variables, no disabled library validation, no debugger attachment, no `get-task-allow` ([signing.md](release/signing.md)). The release script fails if `get-task-allow` is present.171* **Notarized** by Apple and stapled ([notarization.md](release/notarization.md)).172* **Not sandboxed.** This is the weak point of the design. The application runs with the user's full file permissions (subject to the system's privacy prompts for folders such as Documents and Desktop) and, like any unsandboxed process, could open network connections if code to do so were injected. If a parser flaw allowed code execution, nothing in the process would confine the damage. The technology evaluation recommended the sandbox for the GUI application ([section 12](research/technology-evaluation.md#12-distribution)); it is not adopted in 1.0.0, which is why the parser rules above carry the weight.173* **Foreign files are never written back.** A DOCX, RTF, Markdown, HTML, text or PDF file opens as an untitled copy ([persistence.md](architecture/persistence.md#foreign-files-open-as-untitled-documents)).174* **No updater.** There is no code that downloads and installs anything. The other side of that coin is under residual risks.175176## Third-party code177178One dependency: **SwiftMath** (`https://github.com/mgriebling/SwiftMath`, MIT), pinned in `Packages/ORIXDocsKit/Package.swift` **by revision**, `0b0222e102ba415b352cd29f334075622bd4e6aa`, and recorded in `Package.resolved`.179180* **Why a revision and not a version.** In the checkout this revision is described by git as `1.7.3-111-g0b0222e`: 111 commits after the last tagged release, 1.7.3, dated 2026-10-28. The technology evaluation found that release 1.7.3 contained input-triggered traps whose fixes existed only on the upstream main branch, together with commonly used commands, and listed "pin a specific main revision after review" as an option ([section 6](research/technology-evaluation.md#6-math)). `Package.swift` itself carries no comment giving the reason; this is the reason the evaluation supports.181* **Why pinned at all.** A revision pin means a build cannot silently pick up different upstream code: the same sources are fetched every time, and moving the pin is a deliberate, reviewable change.182* **Cost.** An unreleased revision has no upstream release notes and no version to compare against advisories. Updating it is manual, and must be followed by the math robustness tests.183* The library is treated as untrusted with respect to input: `MathGuard` and the fuzz tests above exist because of it.184185Everything else — ZIP, DOCX, Markdown, HTML, citations, layout — is written in this repository and has no other dependency than Apple's frameworks.186187## Hostile-input tests188189| File | Suite or tests |190|---|---|191| `Tests/DocContainerTests/ZipTests.swift` | `rejectsTraversalAndGarbage`, `detectsCorruptionAndBombs` |192| `Tests/DocDOCXTests/SecurityTests.swift` | Suite "DOCX import — hostile input": `notAnArchive`, `archiveWithoutDocument`, `decompressionBombIsRefused`, `pathTraversalEntryNamesAreRefused`, `relationshipTargetsCannotLeaveThePackage`, `doctypeAndEntitiesAreRefused`, `hugeNestingIsRefusedNotOverflowed`, `macrosOleAndActiveXAreDroppedNeverPreserved`, `preservedPartsFromAnUntrustedModelAreRevalidatedOnExport`, `externalTargetsAreKeptAsTextNeverFetched`, `absurdValuesDoNotCrash`, `truncatedAndCorruptedPackagesNeverCrash`, `mutatedXmlNeverCrashes` |193| `Tests/DocFormatsTests/FacadeAndRobustnessTests.swift` | `HostileInputTests`, `UnicodeTortureTests` |194| `Tests/DocFormatsTests/HTMLTests.swift`, `MarkdownTests.swift` | `scriptSchemesNeverReachTheOutput`, `scriptLinksAreRemoved`, `imagesComeOnlyFromDataURIsAndTheLoader` |195| `Tests/DocFormatsTests/NativeContainerTests.swift` | Corruption, tampering, truncation, versions, recovery |196| `Tests/DocLayoutTests/MathRobustnessTests.swift` | `hostileLatexNeverCrashes`, `randomTokenSoupNeverCrashes` |197| `Tests/DocAutomationTests/WorkflowRunnerTests.swift` | `unknownStepTypesAreRejected`, `pathsLeavingTheOutputFolderAreRejected`, `invalidValuesAreRejectedBeforeAnythingRuns` |198| `Tests/DocAutomationTests/IntelligenceTests.swift` | `OnDeviceOnlyTests` |199200## Residual risks201202Stated plainly.2032041. **No sandbox.** A memory-safety or logic flaw that led to code execution would act with the user's permissions. Swift's memory safety makes this unlikely in this project's own code; it does not cover the system frameworks listed next.2052. **System parsers run in-process on untrusted bytes**: ImageIO (every embedded image), PDFKit (PDF import, PDF assets), AppKit's RTF codec, Foundation's `XMLParser` and `JSONDecoder`, Core Text. Their flaws are outside this project's control, and no size limit removes that exposure.2063. **SwiftMath** can still trap on an input that `MathGuard` does not anticipate. The fuzz tests cover a fixed list and a fixed random seed; they are evidence, not proof. A trap would terminate the application; autosave limits the loss to the autosave delay for a saved document.2074. **Fuzzing is modest**: hundreds to thousands of generated cases per importer, run as unit tests. There is no coverage-guided fuzzing and no continuous fuzzing.2085. **Denial of service within the limits.** A file inside every limit can still be slow or memory-hungry to open (up to 1 GiB of uncompressed entries is accepted). Layout runs on the main thread, so a pathological document can make the window unresponsive.2096. **Image loading from the document's folder.** Markdown and HTML may reference local images; they are read only from inside the source file's own folder (symbolic links resolved, whole path components compared, 64 MB cap — `DocumentConverter.confinedResource`, tested in `ResourceConfinementTests`). A hostile document can still make the app read any image-like file placed in that same folder; nothing is sent anywhere.2107. **Integrity is not authenticity.** The native container's checksums do not protect against deliberate modification; documents are neither signed nor encrypted.2118. **No automatic updates.** A parser fix reaches users only when they install a new version by hand. The technology evaluation called this out as the main argument for an in-app updater; 1.0.0 has none.2129. **Links.** A ⌘-click opens `http`, `https` and `mailto` targets in other applications; the destination's safety is not the application's to judge.21310. **Verification gaps.** No independent security review was made. The Intel build was never run. The no-network property is test-enforced for five source folders and observed, not enforced, for the rest.214215Security reports: contact@spboucher.ai.216
Files main
Menu

Theme