# Vitrinli Documentation Vitrinli is a multithreaded, high-performance IIIF-compatible media server written in C++. It provides image format conversions, metadata preservation, and a Lua scripting interface. # Overview # Overview Vitrinli is a multithreaded, high-performance, IIIF compatible media server developed by the [Data and Service Center for the Humanities](https://dasch.swiss) at the [University of Basel](https://www.unibas.ch/en.html). It is designed to be used by archives, libraries, and other institutions that need to preserve high-quality images while making them available online. Vitrinli implements the Image API 3.0 of the International Image Interoperability Framework ([IIIF](http://iiif.io/)), and efficiently converts between image formats, preserving metadata contained in image files. In particular, if images are stored in [JPEG 2000](https://jpeg.org/jpeg2000/) format, Vitrinli can convert them on the fly to formats that are commonly used on the Internet. Vitrinli offers a flexible framework for specifying authentication and authorization logic in [Lua](https://www.lua.org/) scripts, and supports restricted access to images, either by reducing image dimensions or by adding watermarks. It can easily be integrated with [Knora](http://www.knora.org/). In addition Vitrinli preserves most of the [EXIF](http://www.exif.org), [IPTC](https://iptc.org/standards/photo-metadata/iptc-standard/) and [XMP](http://www.adobe.com/products/xmp.html) metadata and can preserve or transform [ICC](https://en.wikipedia.org/wiki/ICC_profile) color profiles. In addition, a simple webserver is integrated. The server is able to serve most common file types. In addition Lua scripts and embedded Lua (i.e., Lua embedded into HTML pages using the tags … are supported. Vitrinli can also be used from the command line to convert images to/from TIFF, [JPEG 2000](https://jpeg.org/jpeg2000/), JPEG, PNG, and WebP formats. For all these conversions, Vitrinli tries to preserve all embedded metadata such as - [IPTC](https://iptc.org/standards/photo-metadata/iptc-standard/) - [EXIF](http://www.exif.org) - [XMP](http://www.adobe.com/products/xmp.html) - [ICC](https://en.wikipedia.org/wiki/ICC_profile) color profiles. However, due to the limitations of some file formats, it cannot be guaranteed that all metadata and ICC profiles are preserved. - [JPEG2000](https://jpeg.org/jpeg2000/) (J2k) does not allow all types of ICC profiles profiles. Unsupported profile types will be added to the J2k header as comment and will be reinstated if the J2k file is converted back to the TIFF-format. Vitrinli is a [free software](http://www.gnu.org/philosophy/free-sw.en.html), released under the [GNU Affero General Public License](http://www.gnu.org/licenses/agpl-3.0.en.html). It is written in C++ and runs on Linux and macOS. Note: In order to compile Vitrinli, the user has to provide a licensed source of the [kakadu software](https://kakadusoftware.com). Vitrinli runs on Linux (including Debian, Ubuntu, and CentOS) and macOS. Freely distributable binary releases are available as Docker images: [daschswiss/sipi](https://hub.docker.com/r/daschswiss/sipi). # User Guide # Vitrinli – Introduction Vitrinli (formerly SIPI) is an IIIF media server. ## What is Vitrinli? ### 1. A IIIF Image API V3 level 2 conformant image server - Vitrinli is a full multithreaded, high performance, level2 compliant [IIIF Image API 3.0](https://iiif.io/api/image/3.0) written in C++. For the JPEG2000 implementation, it relies on the commercial [kakadu-library](https://kakadusoftware.com), but otherwise it is completely open source on [GitHub](https://github.com/dasch-swiss/vitrinli). It offers special support for multipage PDFs (through Vitrinli-specific extensions to the IIIF Image API). #### IIIF Image API 3.0 conformance matrix The following URL forms are accepted by the IIIF endpoint and have a working implementation behind them. The list mirrors what `info.json` advertises in its `extraFeatures` and `extraFormats` arrays: | Component | Supported forms | | ---------------------------- | -------------------------------------------------------------------------------- | | Region | `full`, `square`, `x,y,w,h` (pixel), `pct:x,y,w,h` (percent) | | Size (no upscale) | `max`, `pct:n`, `w,`, `,h`, `w,h`, `!w,h` | | Size (upscale, `^`-prefixed) | `^max`, `^pct:n`, `^w,`, `^,h`, `^w,h`, `^!w,h` | | Rotation | non-negative decimal `n`; `!n` (mirror then rotate). Leading `+` / `-` rejected. | | Quality | `default`, `color`, `gray`, `bitonal` | | Format | `jpg`, `tif`, `png`, `jp2` (also reachable as `jpx`) | Vitrinli-specific extensions on the same URL surface: | URL form | Behaviour | | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | | `{prefix}/{id}/info.json` | IIIF Image Information document | | `{prefix}/{id}/knora.json` | DSP-specific information document (legacy) | | `{prefix}/{id}/file` | Bypass IIIF processing and stream the file as-is | | `{prefix}/{id}` | 303 redirect to `info.json` (`baseUriRedirect`) | | - Vitrinli has been designed for the long term preservation of images, intended for the needs of the cultural heritage field. Thus it offers | | | some unique features for this purpose: | | | - all file format conversions try to preserve all metadata (EXIF, XMP, IPTC etc.). These functionality is based | | | on the open source [exiv2 library](https://www.exiv2.org). | | | - Vitrinli can deal with and convert ICC color profiles based on the [littlecms library](http://www.littlecms.com). | | | - Vitrinli can embed important preservation data such as the checksum of the pixel values, original filename etc. in the file | | | headers. | | | - it supports SSL (https://…) | | | - Vitrinli embeds the scripting language [LUA](https://www.lua.org) that allows a very flexible, highly customizable | | | deployment that can be adapted to the enviroment Vitrinli is being used in. Before serving any request, a configurable | | | LUA script ("pre flight script") is being executed that can check access rights, restrictions or other stuff. Vitrinli LUA | | | has been extended with many Vitrinli-specific functions (including image conversion, HTTP-client etc.) | | ### 2. An ordinary HTTP webserver - Vitrinli is also a normal webserver that is able to deliver arbitrary files. It also implements LUA embedded into HTML pages. - Using Vitrinli LUA scripts and routing, RESTful interfaces may be implemented. E.g. image upload and conversions may by supported. ### 3. An image format conversion tool #### Generic format conversions - image format conversion are supported between TIFF, JPEG2000, JPG and PNG. Vitrinli can be used either as standalone command line tool or in server mode using [LUA](https://www.lua.org) scripting. - Vitrinli preserves most embedded metadata (EXIF, IPTC, TIFF, XMP) and is preserving and/or converting ICC color profiles. Malformed embedded metadata makes the read or conversion fail rather than being silently dropped. #### Preservation metadata (Vitrinli specific) - Vitrinli is able to add Vitrinli specific metadata to most file formats. These metadata are relevant for long-term preservation and include the following information: - `original filename`: The original file name before conversion - `original mimetype`: The mimetype of the original image before conversion - `pixel checksum`: A checksum (e.g. SHA-256) of the original pixel values. This checksum can be used to verify that a format conversion didn't alter the image content. - `icc profile`: (optional) The raw ICC profile as binary string. This field is added if the destination file format has no standard way to embed ICC color profiles (e.g. JPEG). ### 4. Integrated sqlite3 Database Vitrinli has an integrated sqlite3 database that can be used with special LUA extensions. Thus, Vitrinli can be used as a standalone media server with extended functionality. The sqlite3 database may be used to store metadata about images, user data etc. ## Who is behind Vitrinli? Vitrinli is developed and maintained by Lukas Rosenthaler, professor for Digital Humanities at the University of Basel, in collaboration with the "Data and Service Center for the Humanities" ([DaSCH](https://dasch.swiss). ## How to get Vitrinli? - The easiest way is to use the docker image provided on dockerhup [daschswiss/sipi](https://hub.docker.com/r/daschswiss/sipi). The dockerized version has the binary kakadu library compiled in. - You can compile Vitrinli from the sources on [github](https://github.com/dasch-swiss/vitrinli). Since Vitrinli uses many third-party open source libraries, compiling Yourself is tedious and my be frustrating (but possible). *You have to provide the licensed source of kakadu by Yourself*. See [kakadu software](https://kakadusoftware.com) on how to get a licensed version of the kakadu code. Vitrinli should compile on Linux (Ubuntu) and Apple OS X. ## Vitrinli as IIIF-Server ### Extensions to the IIIF-Standard #### Preflight script - Before executing a IIIF request, a freely configurable LUA-script is being called. This script must return the permission to access the resource ("allow", "restrict" "deny") and the final path to the resource. This allows to handle access rights etc. Within the LUA-script, permission databases etc. may be accessed through RESTful services or using the internal SQLite database. In addition, the path to the resource may be redirected or other limitations imposed (size, watermark etc.). - The preflight script has access to the full HTTP(s) header including cookies and Authorization information. There are also utility functions to decode JSON Web Tokens ([JWT](https://jwt.io)). #### Access to non-image files Sometimes it would be helpful to deliver non-image files such as XML, CSV etc. from the same directory tree as the IIIF-conformant images: - The url to download a file must have the form `http(s)://{server}/{prefix}/{fileid}/file`. The clause */file* at the end indicates that the file should bypass any IIIF URl processing and just be served as file. - Also in this case, a *preflight script* may be configured to control access to such file resources. - if the url has the form `http(s)://{server}/{prefix}/{fileid}/info.json`, Vitrinli returns a JSON containing information about the file. The JSON has the from: ``` { "@context": "http://sipi.io/api/file/3/context.json", "id": "https://localhost:1025/images/csv_test.csv", "internalMimeType": "text/csv", "fileSize": 36 } ``` Please note that Vitrinli determines the mimetype using the magic number. Due to the limitations thereof the mimetype - may not be determined exactly. # Running Vitrinli Vitrinli can be run either as a command-line image converter or as an IIIF media server. ## Quick Start with Docker ``` docker run -p 1024:1024 daschswiss/sipi ``` ## Running Vitrinli as a Command-line Image Converter Vitrinli now uses verb-noun subcommands (`convert`, `query`, `compare`, `verify`, `server`, `health`) instead of the legacy `--convert` / `--query` / `--compare` / `--file` / `--outf` flags. A bare `sipi` invocation errors with a usage message — every operation needs an explicit subcommand. Convert an image file to another format: ``` sipi convert input.tif output.jpg --format jpg ``` Query image file information: ``` sipi query input.tif ``` Compare two image files pixel-wise: ``` sipi compare file1.tif file2.jpg ``` ## Running Vitrinli as a Server ``` sipi server --config config/sipi.config.lua ``` ### JWT secret (`SIPI_JWTKEY`) Any Lua-configured deployment (a `--config`/`SIPI_CONFIGFILE` pointing at a `.lua` file) must supply a jwt_secret of at least 32 bytes via the `SIPI_JWTKEY` environment variable (or the equivalent `--jwtkey` flag / `jwt_secret` config key). There is no shipped default — an empty, too-short, or shipped-literal secret refuses startup (fail closed), since it would let a deployment that inherited a known secret forge JWTs. Example (documentation only — generate your own secret, never reuse this value): ``` export SIPI_JWTKEY='a randomly generated secret, at least 32 bytes long' ``` The old Lua `admin = { user = '…', password = '…' }` block that used to ship alongside `jwt_secret` in `config/sipi.config.lua` is documented for reference only: ``` admin = { user = 'admin', password = 'Sipi-Admin' } ``` ### Configuration file format (`.lua` or `.toml`) `--config` accepts either a Lua file (`.lua`) or a TOML file (`.toml`), dispatched on the extension. The Lua file is parsed by the engine's Lua VM (Vitrinli's historical format); a TOML file is parsed directly by the server and needs no Lua VM in the config path. Route *scripts* are always Lua — TOML replaces the config *file*, not the scripting. > **TOML config is experimental.** It is the first of the native (Rust/TOML) alternatives Vitrinli is introducing for everything Lua is used for today (see [ADR-0017](https://github.com/dasch-swiss/vitrinli/blob/main/docs/adr/0017-extensibility-lua-and-rust.md)). The schema may change without the usual compatibility guarantees until it is validated in production; the server logs a warning on startup when a `.toml` config is loaded. The Lua config path stays fully supported. Once the native alternatives stabilize, Lua will be marked deprecated. A TOML config groups keys into sections that mirror the `server` flag groups, with idiomatic snake_case names: ``` [network] port = 1024 [paths] img_root = "/sipi/images" # required script_dir = "/sipi/scripts" init_script = "/sipi/config/sipi.init.lua" [cache] dir = "/sipi/cache" size = "200M" # "0" disables the cache [image] jpeg_quality = 60 scaling_quality = { jpeg = "high", tiff = "high", png = "high", j2k = "high" } [tls_auth] jwt_secret = "…" [[routes]] method = "POST" route = "/api/upload" script = "upload.lua" # resolved against [paths].script_dir ``` Precedence is `config file < environment variable < command-line flag`, the same as for a Lua config: a CLI flag (or its `SIPI_*` env var) overrides the matching TOML key. `img_root` is required (an empty image root has nothing to resolve); routes with a relative `script` require `[paths].script_dir`. Unknown keys are rejected (a typo is a startup error, not a silently-ignored value), so knobs the Rust server does not own as config — TLS (`ssl_*`), `hostname`, `keep_alive`, thread count, and `logfile` — have no TOML key and are reported as unsupported; these are now CLI-flag/env-var-only knobs, accepted for parse-only compatibility (see [Server Options](#server-options) below), not Lua config or TOML keys. The TOML key for each Lua config key: | TOML key | Lua config key | | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `[network] port` | `port` | | `[paths] img_root` | `imgroot` | | `[paths] script_dir` | `scriptdir` | | `[paths] init_script` | `initscript` | | `[paths] tmp_dir` | `tmpdir` | | `[paths] max_temp_file_age` | `max_temp_file_age` | | `[paths] doc_root` | `fileserver.docroot` | | `[paths] www_route` | `fileserver.wwwroute` | | `[paths] prefix_as_path` | `prefix_as_path` | | `[cache] dir` | `cache_dir` | | `[cache] size` | `cache_size` | | `[cache] n_files` | `cache_nfiles` | | `[limits] memory_limit` | `memory_limit` | | `[limits] admission_mode` | `admission_mode` | | `[limits] tiles_memory_ratio` | `tiles_memory_ratio` | | `[limits] max_post_size` | `max_post_size` | | `[limits] thumb_size` | `thumb_size` | | `[image] jpeg_quality` | `jpeg_quality` | | `[image] scaling_quality.{jpeg,tiff,png,j2k}` | `scaling_quality.{…}` (the `j2k` entry is accepted but currently has no effect — the engine reads that slot under a legacy key) | | `[tls_auth] jwt_secret` | `jwt_secret` | | `[knora] path` | `knora_path` | | `[knora] port` | `knora_port` | | `[logging] level` | `loglevel` | | `[[routes]]` (`method`/`route`/`script`) | `routes` | ## Health Check `sipi health` is a self-contained liveness probe. It performs an HTTP `GET` on the local [`/health`](https://sipi.io/operation/health-endpoint/index.md) endpoint and maps the result to a process exit code, following the Docker/Swarm healthcheck convention: - **0** — the endpoint returned HTTP 200 (healthy). - **1** — connection refused, timeout, or any non-200 response (unhealthy). ``` sipi health # probes http://127.0.0.1:1024/health sipi health --port 80 # probe a server running on a different port ``` The host is always `127.0.0.1` and the path is always `/health`; only the port is configurable. A separate `sipi health` process cannot know whether the running server took its port from a config file, an env var, or `--serverport`, so the caller passes the port it configured (`--port`, default `1024`). The probe uses a short (~2 s) timeout so a wedged server reports unhealthy rather than hanging. Because it needs no `curl` in the image, it is the intended container/orchestrator liveness command (see [Health Endpoint](https://sipi.io/operation/health-endpoint/index.md)). ## Logging Vitrinli uses two logging modes depending on how it is running: - **CLI mode** (`convert`, `compare`, `query`): Plain text output. Errors go to **stderr**, informational messages go to **stdout**. This is the standard Unix convention for command-line tools. When `--json` is also set (see [Structured JSON output](#structured-json-output-cli)), every level is routed to **stderr** so `stdout` stays reserved for the single JSON document. - **Server mode** (`sipi server --config`): JSON-formatted log lines go to **stdout**. This follows container best practices — Docker, Kubernetes, and log collectors (Grafana Loki, Fluentd) expect structured logs on stdout. Each line is a JSON object: `{"level": "INFO", "message": "..."}`. ### Log Levels Vitrinli supports the following log levels (in order of increasing severity): | Level | Description | | --------- | ----------------------------------------------------------------------------------------- | | `DEBUG` | Detailed diagnostic information. | | `INFO` | Normal operational messages (routes added, server started, migrations). | | `NOTICE` | Significant but normal events. | | `WARNING` | Something unexpected but recoverable (e.g., failed XMP parse, incomplete metadata write). | | `ERR` | Errors that affect a specific operation (e.g., image processing failure, ICC error). | | `CRIT` | Critical errors. | | `ALERT` | Conditions requiring immediate attention. | | `EMERG` | System-wide emergencies. | The log level controls which messages are emitted. Setting a level suppresses all messages below it. For example, `WARNING` shows only WARNING, ERR, CRIT, ALERT, and EMERG — suppressing DEBUG, INFO, and NOTICE. The log level can be configured in three ways (in order of precedence): 1. **CLI option**: `--loglevel WARNING` 1. **Environment variable**: `SIPI_LOGLEVEL=WARNING` 1. **Lua config**: `loglevel = "WARNING"` (in the `sipi` block) If none is specified, the default level is `INFO`. ## Command-line Options ### Image Conversion Options These options are accepted by the `convert` subcommand (and where documented in the per-subcommand matrix, by `convert access-file` and `convert service-file`). Usage: `sipi convert [options]`. | Flag | Short | Description | | -------------------- | ----- | ---------------------------------------------------------------------- | | `--format ` | `-F` | Output format: `jpx`, `jp2`, `jpg`, `tif`, `png`, `webp`, `gif` | | `--icc ` | `-I` | Convert to ICC profile: `none`, `sRGB`, `AdobeRGB`, `GRAY` | | `--quality <1-100>` | `-q` | JPEG compression quality (1 = highest compression, 100 = best quality) | | `--pagenum ` | `-n` | Page number for multi-page PDF/TIFF input files | | `--region ` | `-r` | Select a region of interest (4 integer values) | | `--reduce ` | `-R` | Reduce image size by factor (faster than `--scale`) | | `--size ` | `-s` | Resize image to given dimensions | | `--scale ` | `-S` | Resize image by percentage | | `--mirror ` | `-m` | Mirror image: `none`, `horizontal`, `vertical` | | `--rotate ` | `-o` | Rotate image by degrees (0.0 - 360.0) | | `--skipmeta` | `-k` | Strip all metadata from the output file | | `--topleft` | | Enforce TOPLEFT orientation | | `--watermark ` | `-w` | Overlay a watermark (single-channel grayscale TIFF) | | `--Ctiff_pyramid` | | Store output in pyramidal TIFF format | ### Query and Compare Use the `query` and `compare` subcommands. `--query` / `--compare` flag forms are gone. | Subcommand | Description | | ------------------------ | ----------------------------------------- | | `sipi query ` | Dump all information about the given file | | `sipi compare ` | Compare two files pixel-wise | ### Decode deadline Every offline verb (`convert`, `convert access-file`, `convert service-file`, `query`, `compare`) decodes its input under a 120 s wall-clock deadline, the same default the server applies per request. A malformed JPEG 2000 file can wedge the Kakadu decoder indefinitely; when the deadline passes the verb reports `decode exceeded the 120000 ms deadline` and exits non-zero instead of hanging the shell (or the ingest worker driving it). The wedged decode thread is abandoned and ends with the process. ### Structured JSON output (CLI) | Flag | Description | | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `--json` | Emit a single JSON document to `stdout` instead of human-readable output. Accepted by `convert`, `convert access-file`, `query`, and `compare`. Useful for programmatic consumers and for full diagnostics on failures, which the CLI never reports to Sentry (see [Structured Diagnostics (CLI Mode)](#structured-diagnostics-cli-mode)). | Use cases: - **Local debugging** — the primary RDU case. Every `ImageContext` field appears in the JSON document; CLI failures are never sent to Sentry. - **CI pipelines** that need to assert on image properties (`jq '.image.bps'`) or on a specific failure mode (`jq '.phase'`). - **Scripts** that consume sipi output pipeline-style. See [`json-output.md`](https://sipi.io/guide/json-output/index.md) for the full schema, worked examples, and the `stdout` / `stderr` contract. ### JPEG2000 Options | Flag | Description | | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `--Sprofile ` | J2K profile: `PROFILE0`, `PROFILE1`, `PROFILE2`, `PART2`, `CINEMA2K`, `CINEMA4K`, `BROADCAST`, `CINEMA2S`, `CINEMA4S`, `CINEMASS`, `IMF` | | `--rates ` | Bit-rate(s) for quality layers (`-1` for lossless final layer) | | `--Clayers ` | Number of quality layers (default: 8) | | `--Clevels ` | Number of wavelet decomposition levels (default: 8) | | `--Corder ` | Progression order: `LRCP`, `RLCP`, `RPCL`, `PCRL`, `CPRL` (default: `RPCL`) | | `--Stiles ` | Tile dimensions `"{tx,ty}"` (default: `"{256,256}"`) | | `--Cprecincts ` | Precinct dimensions `"{px,py}"` (default: `"{256,256}"`) | | `--Cblk ` | Code-block dimensions `"{dx,dy}"` (default: `"{64,64}"`) | | `--Cuse_sop ` | Include SOP markers (default: yes) | ### Server Options These options are accepted by the `server` subcommand. Usage: `sipi server [options]`. | Flag | Short | Env Var | Default | Description | | ------------------------------------ | ----- | ----------------------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `--config ` | `-c` | `SIPI_CONFIGFILE` | | Server config file — Lua (`.lua`) or TOML (`.toml`); see [Configuration file format](#configuration-file-format-lua-or-toml) | | `--serverport ` | | `SIPI_SERVERPORT` | `80` | HTTP port | | `--sslport ` | | `SIPI_SSLPORT` | `443` | HTTPS port | | `--hostname ` | | `SIPI_HOSTNAME` | `localhost` | Public DNS hostname. Parse-only: accepted for compatibility, not read by the server | | `--keepalive ` | | `SIPI_KEEPALIVE` | `5` | HTTP keep-alive timeout in seconds. Parse-only: accepted for compatibility, unread | | `--nthreads ` | `-t` | `SIPI_NTHREADS` | `0` (auto) | Worker threads (`0` = auto: available parallelism, container-aware, fallback 4) | | `--tiles-thread-ratio ` | | `SIPI_TILES_THREAD_RATIO` | `0.5` | Fraction of workers guaranteed to tiles (0..1); the full partition is hard-capped at the rest | | `--max-waiting ` | | `SIPI_MAX_WAITING` | `2×nthreads` | Max requests that may wait for a worker before HTTP 503 (`0` = no queue, shed immediately; `Retry-After: 1`) | | `--queue-timeout ` | | `SIPI_QUEUE_TIMEOUT` | `5` | Max seconds a request waits in queue before 503 | | `--memory-limit ` | | `SIPI_MEMORY_LIMIT` | `0` (auto) | Total decode-memory envelope (`0` = auto-detect available RAM; `8G`, `500M`); the full partition's budget is envelope × (1 − tiles-memory-ratio) | | `--admission-mode ` | | `SIPI_ADMISSION_MODE` | `advanced` | `basic` (enforce the basic tier only; advanced tier observe-only) or `advanced` (also enforce the memory budget + 503/413) | | `--tiles-memory-ratio ` | | `SIPI_TILES_MEMORY_RATIO` | `0.25` | Fraction of the envelope reserved for tiles + non-decode floor (0..1) | | `--large-decode-threshold-bytes ` | | `SIPI_LARGE_DECODE_THRESHOLD_BYTES` | `33554432` (32 MiB) | Estimated peak-memory at/above which a decode is charged to the full partition; below it bypasses as a tile | | `--preflight-cache-ttl ` | | `SIPI_PREFLIGHT_CACHE_TTL` | `0` (disabled) | Seconds a `pre_flight` access decision is cached per `(prefix, identifier, credential)`. Opt-in; enable (`>0`) only if the hook decides purely on prefix/identifier/Cookie/Authorization (see the Preflight access-cache section in the Lua scripting guide) | | `--preflight-cache-slots ` | | `SIPI_PREFLIGHT_CACHE_SLOTS` | `4096` | Slot count for the preflight access-cache | | `--maxpost ` | | `SIPI_MAXPOSTSIZE` | `300M` | Maximum POST upload size | | `--imgroot ` | | `SIPI_IMGROOT` | `./images` | Image repository root directory | | `--docroot ` | | `SIPI_DOCROOT` | `./server` | Web server document root | | `--wwwroute ` | | `SIPI_WWWROUTE` | `/server` | URL route for web server | | `--scriptdir ` | | `SIPI_SCRIPTDIR` | `./scripts` | Directory for Lua route scripts | | `--tmpdir ` | | `SIPI_TMPDIR` | `./tmp` | Temporary files directory | | `--maxtmpage ` | | `SIPI_MAXTMPAGE` | `86400` | Max age of temp files in seconds | | `--initscript ` | | `SIPI_INITSCRIPT` | `./config/sipi.init.lua` | Path to Lua init script | | `--cachedir ` | | `SIPI_CACHEDIR` | `./cache` | Cache directory | | `--cachesize ` | | `SIPI_CACHESIZE` | `200M` | Maximum cache size (`-1`=unlimited, `0`=disabled) | | `--cachenfiles ` | | `SIPI_CACHENFILES` | `200` | Maximum number of cached files (`0`=no limit) | | `--thumbsize ` | | `SIPI_THUMBSIZE` | `!128,128` | Default thumbnail size (IIIF syntax) | | `--sslcert ` | | `SIPI_SSLCERTIFICATE` | `./certificate/certificate.pem` | SSL certificate path. Parse-only: accepted for compatibility, unread | | `--sslkey ` | | `SIPI_SSLKEY` | `./certificate/key.pem` | SSL key file path. Parse-only: accepted for compatibility, unread | | `--jwtkey ` | | `SIPI_JWTKEY` | | JWT shared secret, required for any Lua-configured deployment (at least 32 bytes; the shipped default is rejected) | | `--loglevel ` | | `SIPI_LOGLEVEL` | `DEBUG` | Sets the engine log level (`DEBUG`/`INFO`/…, see Logging section); applied via `set_log_level` | ### Sentry Error Reporting No CLI flags — these are environment-variable only (see [Environment Variables](#environment-variables) below): `SIPI_SENTRY_DSN`, `SIPI_SENTRY_RELEASE`, `SIPI_SENTRY_ENVIRONMENT`. Read by the Rust shell's `main` (`cli/rust/src/main.rs`), which owns Sentry init for every verb. ### Deprecated Options | Flag | Description | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `--pathprefix[=BOOL]` | Treat the IIIF URL prefix as a subdirectory under imgroot, i.e. `//` (default: true; bare flag means true) | ## Environment Variables All server options can be configured via environment variables. Environment variables override Lua configuration file values but are themselves overridden by command-line flags. | Variable | CLI Flag | Default | Description | | ----------------------------------- | -------------------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `SIPI_CONFIGFILE` | `--config` | | Configuration file path | | `SIPI_RS_PORT` | *(none)* | | Highest-precedence HTTP listen-port override (env-only, no CLI flag). Overrides `--serverport`/`SIPI_SERVERPORT` and the config's `port`. Primarily for parallel dev/test shells; safe to leave unset in production | | `SIPI_SERVERPORT` | `--serverport` | `80` | HTTP port | | `SIPI_SSLPORT` | `--sslport` | `443` | HTTPS port | | `SIPI_HOSTNAME` | `--hostname` | `localhost` | Public hostname. Parse-only: accepted for compatibility, not read by the server | | `SIPI_KEEPALIVE` | `--keepalive` | `5` | Keep-alive timeout (seconds). Parse-only: accepted for compatibility, unread | | `SIPI_NTHREADS` | `--nthreads` | `0` (auto) | Worker threads (`0` = auto: available parallelism, container-aware, fallback 4) | | `SIPI_TILES_THREAD_RATIO` | `--tiles-thread-ratio` | `0.5` | Fraction of workers guaranteed to tiles (0..1); the full partition is hard-capped at the rest | | `SIPI_MAX_WAITING` | `--max-waiting` | `2×nthreads` | Max requests that may wait for a worker before 503 (`0` = no queue, shed immediately) | | `SIPI_QUEUE_TIMEOUT` | `--queue-timeout` | `5` | Max seconds in queue before 503 | | `SIPI_PREFLIGHT_CACHE_TTL` | `--preflight-cache-ttl` | `0` (disabled) | Seconds a `pre_flight` decision is cached per `(prefix, identifier, credential)`. Opt-in; see the Preflight access-cache section in the Lua scripting guide before enabling | | `SIPI_PREFLIGHT_CACHE_SLOTS` | `--preflight-cache-slots` | `4096` | Slot count for the preflight access-cache | | `SIPI_MAXPOSTSIZE` | `--maxpost` | `300M` | Max POST size | | `SIPI_IMGROOT` | `--imgroot` | `./images` | Image root directory | | `SIPI_DOCROOT` | `--docroot` | `./server` | Document root | | `SIPI_WWWROUTE` | `--wwwroute` | `/server` | Web server route | | `SIPI_SCRIPTDIR` | `--scriptdir` | `./scripts` | Lua scripts directory | | `SIPI_TMPDIR` | `--tmpdir` | `./tmp` | Temporary directory | | `SIPI_MAXTMPAGE` | `--maxtmpage` | `86400` | Max temp file age | | `SIPI_INITSCRIPT` | `--initscript` | `./config/sipi.init.lua` | Init script path | | `SIPI_CACHEDIR` | `--cachedir` | `./cache` | Cache directory | | `SIPI_CACHESIZE` | `--cachesize` | `200M` | Max cache size (`-1`=unlimited, `0`=disabled) | | `SIPI_CACHENFILES` | `--cachenfiles` | `200` | Max cached files (`0`=no limit) | | `SIPI_THUMBSIZE` | `--thumbsize` | `!128,128` | Thumbnail size | | `SIPI_SSLCERTIFICATE` | `--sslcert` | `./certificate/certificate.pem` | SSL certificate. Parse-only: accepted for compatibility, unread | | `SIPI_SSLKEY` | `--sslkey` | `./certificate/key.pem` | SSL key. Parse-only: accepted for compatibility, unread | | `SIPI_JWTKEY` | `--jwtkey` | | JWT secret, required for any Lua-configured deployment (at least 32 bytes; the shipped default is rejected) | | `SIPI_ALLOWED_ORIGINS` | *(none)* | | Comma-separated browser Origins allowed to make credentialed cross-origin (CORS) requests; empty/unset = reflect any Origin (default, backward-compatible); set = restrict to the listed origins. Applies to every CORS response, `info.json` included; an `info.json` or `knora.json` request without an Origin still gets `*` | | `SIPI_PUBLIC_HOSTS` | *(none)* | | Comma-separated hosts allowed in the canonical `@id`, the 303 `Location`, the `Link` header, the cache key, and Lua `server.host`; empty/unset = trust `X-Forwarded-Host`/`Host` verbatim (default, backward-compatible); set = a header host on the list passes through, any other host is replaced by the first listed host | | `SIPI_REQUEST_TIMEOUT` | *(none)* | `60` | Handler wall-clock timeout in seconds; a request whose handler exceeds it answers 408 (`0`/unset/unparseable falls back to the default) | | `SIPI_BODY_READ_TIMEOUT` | *(none)* | `10` | Lua-route/docroot request-body-read timeout in seconds; a body that takes longer to read is cut off before admission (`0`/unset/unparseable falls back to the default) | | `SIPI_JPEGQUALITY` | `--quality` | `60` | JPEG quality | | `SIPI_LOGLEVEL` | `--loglevel` | `DEBUG` | Sets the engine log level; applied via `set_log_level` | | `SIPI_SENTRY_DSN` | | | Sentry DSN (no CLI flag) | | `SIPI_SENTRY_RELEASE` | | | Sentry release (no CLI flag) | | `SIPI_SENTRY_ENVIRONMENT` | | | Sentry environment (no CLI flag) | | `SIPI_MEMORY_LIMIT` | `--memory-limit` | `0` (auto) | Total RAM envelope (`0`=auto-detect available RAM, `8G`, `500M`); the full lane gets envelope × (1 − `tiles_memory_ratio`) | | `SIPI_ADMISSION_MODE` | `--admission-mode` | `advanced` | Admission mode: `basic` (enforce basic tier only), `advanced` (also enforce the advanced tier) | | `SIPI_TILES_MEMORY_RATIO` | `--tiles-memory-ratio` | `0.25` | Fraction of the envelope reserved for tiles + non-decode floor (range 0..1) | | `SIPI_LARGE_DECODE_THRESHOLD_BYTES` | `--large-decode-threshold-bytes` | `33554432` (32 MiB) | Estimated peak-memory at/above which a decode is charged to the full lane; below it bypasses as a tile | **Configuration precedence** (highest to lowest): 1. Command-line flags 1. Environment variables 1. Lua configuration file ## Exit Codes and Error Handling ### Exit Codes When running Vitrinli as a command-line image converter, the process exit code indicates whether the conversion succeeded: - **0** — Success. The output file was written correctly. - **1** (`EXIT_FAILURE`) — Image processing error. The image could not be read, converted, or written. **Important for calling services:** Always check the exit code. A non-zero exit code means the output file was not produced (or is incomplete). The `sipi health` subcommand follows the same convention: **0** = healthy (`/health` returned 200), **1** = unhealthy (connection refused, timeout, or non-200). ### Error Output On failure, Vitrinli prints a short error message to **stderr** indicating the failure phase and the specific error. The format is: ``` Error image:
``` Where `` is one of `reading`, `converting`, or `writing`. Example: ``` Error reading image: Unsupported JPEG colorspace JCS_UNKNOWN (file=input.jpg, dimensions=2048x1536, components=4) ``` ### Structured Diagnostics (CLI Mode) CLI conversion failures are not sent to Sentry — only a crash (a panic in the Rust shell) is. A handled read/convert/write failure logs to stderr and, with `--json`, emits the full structured document described in [Structured JSON output (CLI)](#structured-json-output-cli) above: the same image-context fields (`input_file`, `output_file`, `width`, `height`, `channels`, `bps`, `colorspace`, `icc_profile_type`, `orientation`, `file_size_bytes`) plus the failing `phase` (`read`, `convert`, or `write`) and the error message. This is the diagnostic surface for CLI failures — `--json` gets you full context regardless of whether `SIPI_SENTRY_DSN` is set. ### Common Failure Causes | Error | Meaning | | ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Unsupported colorspace (JCS_UNKNOWN) | The JPEG uses a colorspace Vitrinli cannot convert. Re-encode the source image in sRGB. | | Unsupported bits/sample | Only 8 and 16 bits/sample are supported. Images with other bit depths must be converted first. | | Channel/colorspace mismatch | The number of channels does not match the declared colorspace (e.g., 4 channels but RGB). The file metadata may be corrupt. | | ICC profile incompatible | The ICC profile does not match the channel count (e.g., CMYK profile on a 3-channel image). | | Corrupt or truncated file | The input file is incomplete or damaged. | | Unsupported TIFF tiling | The TIFF tile configuration is inconsistent or uses unsupported bit depths. | | EXIF rational with zero denominator | A TIFF-format conversion embeds an EXIF rational tag (e.g. `ExposureTime`, `FNumber`) whose value is `n/0` with `n != 0`. The source metadata is corrupt; a `0/0` ("no value") rational is skipped rather than failing the write. | ### Integration Notes for Calling Services If you call Vitrinli CLI from another service (e.g., a Java service): 1. **Check the exit code.** Non-zero means failure — do not assume the output file exists or is valid. 1. **Parse stderr** (optional). The first line of stderr contains a human-readable error message with the failure phase and details. 1. **Pass `--json`** to get full diagnostics without reproducing the failure — the document's `phase`, `colorspace`, `bps`, and `output_format` fields identify the failure pattern (see [Structured Diagnostics (CLI Mode)](#structured-diagnostics-cli-mode) above). ## Configuration Files Vitrinli's configuration file is written in [Lua](https://www.lua.org/). You can make your own configuration file by adapting `config/sipi.config.lua`. - Check that the port number is correct and that your operating system's firewall does not block it. - Set `imgroot` to the directory containing the files to be served. - Create the directory `cache` in the top-level directory of the source tree. For more information, see the comments in `config/sipi.config.lua` and the [Reference](https://sipi.io/guide/sipi/index.md) page for all configuration parameters. ### HTTPS Support Vitrinli supports SSL/TLS encryption if the [OpenSSL](https://www.openssl.org/) library is installed. You will need to install a certificate; see `config/sipi.config.lua` for instructions. ### IIIF Prefixes Vitrinli supports [IIIF Image API URLs](https://iiif.io/api/image/3.0/#21-image-request-uri-syntax). If the configuration property `prefix_as_path` is set to `true`, the IIIF `prefix` portion of the URL is interpreted as a subdirectory of `imgroot`, and Vitrinli looks for the requested image file in that subdirectory. Otherwise, it looks for the file in `imgroot`. # Basic Information and Reference This section provides the basic information to use Vitrinli as a high performance, versatile media server implementing the [IIIF](https://iiif.io) standards that can be used in many different settings, from a small standalone server providing basic metadata to the deployment in a complex environment. For more information about the IIIF standard see . The basic idea is that an image or rectangular region of an image can be downloaded (e.g. to the browser) with a given width and height, rotation, image quality and format. All parameters are provided with the IIIF conformant URL that has the following form: `http(s)://{server}/{prefix}/{identifier}/{region}/{size}/{rotation}/{quality}.{format}` The parts do have the following meaning: - `{server}`: The DNS name of the server, eg. `iiif.dasch.swiss`. The server may include a portnumber, eg. `iiif2.dasch.swiss:8080`. - `{prefix}`: A path (that may include `/`'s) to organize the assets. Usually the prefix reflect the internal directory or folder hierarchy. However this can be overridden using special features of Vitrinli (see pre-flight-script and sipi configuration file). - `{identifier}`: The identifier of the requested image. By default, it is the filename and its extension. - `{region}`: a region of interest that should be displayed. `full` indicates that the whole image is being requested. For more details see [IIIF regions](https://iiif.io/api/image/3.0/#41-region) - `{size}`: The size of the displayed image (part). `max` indicates the the "natural" maximal resolution should be used. For more details see [IIIF size](https://iiif.io/api/image/3.0/#42-size) - `{rotations}`: The image can be rotated and mirrored before being transmitted to the client. Vitrinli allows for arbitrary rotations. The rotation is a non-negative decimal — digits and `.` only — per [IIIF Image API 3.0 §5.1.1](https://iiif.io/api/image/3.0/#511-rotation). The value `0` indicates no rotation. Prefix with `!` to mirror first, then rotate. See [IIIF rotation](https://iiif.io/api/image/3.0/#43-rotation). - `{quality}`: The quality parameter determines whether the image is delivered in color, grayscale or black and white. Valid values are: - `default`: the "natural" quality of the original image - `color`: A color representation - `gray`: A gray value representation - `bitonal`: A bitonal representation All quality values are supported by Vitrinli - `{format}`: The file format that should be delivered. The IIIF endpoint supports the following formats, independent of the image's storage format: - `jpg`: JPEG. The IIIF spec does not allow per-request selection of the JPEG compression ratio; a server-wide rate is set in the configuration file. - `tif`: TIFF. - `png`: PNG. - `jp2` (also `jpx`): JPEG 2000. `info.json` advertises `extraFormats: ["tif", "jp2"]`; JPEG and PNG are the IIIF default set. ## The Vitrinli executable (`sipi`) The Vitrinli executable is a statically linked program that can be started as - *command line tool* to perform image operations, mainly format conversions - *as server deamon* that provides IIIF conforming media server ### Using Vitrinli as Command Line Tool The Vitrinli command line mode can be used for the following tasks: #### Format Conversions: ``` /path/to/sipi convert infile outfile [options] ``` For DSP preservation-pipeline workflows, use the pipeline-stage forms: `sipi convert access-file ...`, `sipi convert service-file ...`, or `sipi convert preservation-file ...` (the last is a stub awaiting ADR-0012). #### Print Information about File and Metadata: ``` /path/to/sipi query infile ``` #### Compare two Images pixelwise The images may have different formats: if the have exactely the same pixels, they are considered identical). Metadata is ignored for comparison: ``` /path/to/sipi compare file1 file2 ``` #### Health Check Probe a running Vitrinli server's `/health` endpoint and exit `0` (healthy) or `1` (unhealthy). Used as the container/orchestrator liveness command: ``` /path/to/sipi health [--port ] # default port 1024 ``` See [Running Vitrinli](https://sipi.io/guide/running/index.md) and [Health Endpoint](https://sipi.io/operation/health-endpoint/index.md) for details. #### General Options for the Command Line Use In command line mode, Vitrinli supports the following options: - `-h`, `--help`: Display a short help with all options available - `-F `, `--format `: The format of the output file. Valid are `jpx`, `jp2`, `jpg`, `png`, `tif`, `webp`, and `gif`. - `-I `, `--icc `: Convert the outfile to the given ICC color profile. Supported profiles are `sRGB`, `AdobeRGB` and `GRAY`. - `-q `, `--quality `: Only used for the JPEG format. Ignored for all other formats. Its a number between 1 and 100, where 1 is equivalent to the highest compression ratio and lowest quality, 100 to the lowest compression ration and highest quality of the output image. - `-n `, `--pagenum `: Only for input files in multi-page PDF format: sets the page that should be converted. Ignored for all other input file formats. - `-r `, `--region `: Selects a region of interest that should be converted. Needs 4 integer values: `left_upper_corner_X`, `left_upper_corner_Y`, `width`, `height`. - `-s `, `--size `: The size of the resulting image. The option requires a string parameter formatted according to the size-syntax of IIIF [see IIIF-Size](https://iiif.io/api/image/3.0/#42-size). Not giving this parameters results in having the maximalsize (as the value `"max"`would give). - `-s `, `--scale `: Scaling the image size by the given number (interpreted as percentage). Percentage must be given as integer value. It may be bigger than 100 to upscale an image. - `-R `, `--reduce `: Reduce the size of the image by the given factor. Thus `-R 2`would resize the image to half of the original size. Using `--reduce` is usually much faster than using `--scale`, e.g. `--reduce 2` is faster than `--scale 50`. - `-m `, `--mirror `: Takes either `horizontal` or `vertical`as parameter to mirror the image appropriately. - `-o `, `--rotate `: Rotates the image by the given angle. The angle must be a floating point (or integer) value between `0.0`and `w60.0`. - `-k`, `--skipmeta`: Strip all metadata from inputfile. - `-w `, `--watermark `: Overlays a watermark to the output image. must be a single channel, gray valued TIFF. That is, the TIFF file must have the following tag values: SAMPLESPERPIXEL = 1, BITSPERSAMPLE = 8, PHOTOMETRIC = PHOTOMETRIC_MINISBLACK. - `--json`: Emit a single structured JSON document to stdout instead of human-readable output. The document mirrors the internal `ImageContext` that is otherwise sent to Sentry and includes the input/output paths, the decoded image properties, and — on failure — a `phase` (`cli_args` | `read` | `convert` | `write`) with the `error_message`. Useful for programmatic consumers and for debugging when no Sentry DSN is configured. Stderr carries any log output so stdout stays reserved for the single JSON document. Attached only to the `query`, `compare`, and `verify` subcommands per the D5 option-availability matrix; convert flows do not expose `--json`. See [`json-output.md`](https://sipi.io/guide/json-output/index.md) for the full schema and worked examples. Example: ``` sipi query --json input.jpg | jq '.image.bps' ``` #### JPEG2000 Specific Options Usually, the Vitrinli command line tool is used to create JPEG2000 images suitable for a IIIF repository. Vitrinli supports the following JPEG2000 specific options. For a in detail description of these options consult the kakadu documentation! - `--Sprofile `: The following JPEG2000 profiles are supported: `PROFILE0`, `PROFILE1`, `PROFILE2`, `PART2`, `CINEMA2K`, `CINEMA4K`, `BROADCAST`, `CINEMA2S`, `CINEMA4S`, `CINEMASS`, `IMF`. Default: `PART2`. - `--rates `: One or more bit-rates (see kdu_compress help!). A value "-1" may be used in place of the first bit-rate in the list to indicate that the final quality layer should include all compressed bits. - `--Clayers `:Number of quality layers. Default: 8. - `--Clevels `: Number of wavelet decomposition levels, or stages. Default: 8. - `--Corder `: Progression order. The four character identifiers have the following interpretation: L=layer; R=resolution; C=component; P=position. The first character in the identifier refers to the index which progresses most slowly, while the last refers to the index which progresses most quickly. Thus must be one of `LRCP`, `RLCP`, `RPCL`, `PCRL`, `CPRL`, Default: `RPCL`. - `--Stiles `: Tiles dimensions `"{tx,ty}"`. Default: `"{256,256}"`. - `--Cprecincts `: Precinct dimensions `"{px,py}"` (must be powers of 2). Default: `"{256,256}"`. - `--Cblk `: Nominal code-block dimensions `"{dx,dy}"`(must be powers of 2, no less than 4 and no greater than 1024, whose product may not exceed 4096). Default: `"{64,64}"`. - `--Cuse_sop `: Include SOP markers (i.e., resync markers). Default: yes. ### Using Vitrinli as IIIF Media Server In order to use Vitrinli as IIIF media server, some setup work has to be done. The *configuration* of Vitrinli can be done using a configuration file (written in Lua or, equivalently, in TOML — see [Configuration file format](https://sipi.io/guide/running/#configuration-file-format-lua-or-toml)) and/or using environment variables, and/or command line options. The priority is as follows: *`configuration file parameters` are overwritten by `environment variables` are overwritten by `command line options`*. The Vitrinli server requires a few directories to be setup and listed in the configuration file. Then the Vitrinli server is launched as follows: ``` /path/to/sipi server --config /path/to/config-file.lua ``` #### Vitrinli specific extensions to IIIF Vitrinli implements some backwards compatible, non-standard extensions to the IIIF Image API: ##### Access to a raw files Sometimes it may be usefull to store non-image files such as XML-sidecars, manifests as JSON or complete PDF's, etc. in the same environment as the images. For this reason Vitrinli supports an extension of the IIIF API: ``` http(s)://{server}/{prefix}/{identifier}/file ``` The `/file`-path at the end of the URL makes Vitrinli to send the file as it is. Thus, for example a manifest file could be accessed by ``` https://iiif.my.server/images/myimage.json/file ``` This works also for PDF's. The URL ``` https://iiif.my.server/images/mydocument.pdf/file ``` will download the PDF in toto to be opened by an external viewer or the webapplication. It is possible to use the IIIF-`info.json` syntax also on non-image files. In this case the `info.json` has the following format: ``` { "@context": "http://sipi.io/api/file/3/context.json", "id": "http://localhost:1024/images/test.csv", "mimeType": "text/comma-separated-values", "fileSize": 327 } ``` #### Setup of Vitrinli Directories Vitrinli needs the following directories and files setup and accessible (the real names of the directories must be indicated in the configuration file). The following configuration parameters are in the `sipi`-table of the configuration script: - `imgroot=path`: This is the top-directory of the media file repository. Vitrinli should at least have read access to it. If Vitrinli is used to upload and convert files, it must also have write access. The path may be given as absolute path or as relative path.\ *Cmdline option: `--imgroot`*\ *Environment variable: `SIPI_IMGROOT`*\ *Default: `./images`* - `initscript=path/to/init.lua`: Vitrinli needs a minmal set of LUA functions that can be adapted to the local installation. These mandatory functions are definied in a init-script (usually it can be found in the config directory where also the configuration file is located).\ *Cmdline option: `--initscript`*\ *Environment variable: `SIPI_INITSCRIPT`*\ *Default: `./config/sipi.init.lua`* - `tmpdir=path`: For the support of multipart POST Vitrinli requires read/write access to a directory to save temporary files.\ *Cmdline option: `--tmpdir`*\ *Environment variable: `SIPI_IMGROOT`*\ *Default: `./tmp`* - `scriptdir=path`: Path to the directory where the LUA-scripts for the routes (e.g. RESTful services) can be found.\ *Cmdline option: `--scriptdir`*\ *Environment variable: `SIPI_SCRIPTDIR`*\ *Default: `./scripts`* - `cachedir=path`: Vitrinli may optionally use a cache directory to store converted image in order to avoid computationally intensive conversions if a specific variant is requested several times. Vitrinli starts with a warning if the cache directory is defined but not existing.\ *Cmdline option: `--cachedir`*\ *Environment variable: `SIPI_CACHEDIR`*\ *Default: `./cache`* In addition, Vitrinli can act as a webserver that offers image upload and conversion as web service. In order to use this feature, a server directory has to be defined. This definition ist in the `fileserver`-table of the configuration file: - `docroot=path`: Path to the document root of the Vitrinli web server.\ *Cmdline option: `--docroot`*\ *Environment variable: `SIPI_DOCROOT`*\ *Default: `./server`* #### Vitrinli Configuration Parameters The following configuration parameters are used by the Vitrinli server: - `port=portnum`: Portnumber Vitrinli should listen on for incoming HTTP requests.\ *Cmdline option: `--serverport`*\ *Environment variable: `SIPI_SERVERPORT`*\ *Default: `80`* - `ssl_port=portnum`: Portnumber Vitrinli should listen on for incoming SHTTP requests (using SSL).\ *Cmdline option: `--sslport`*\ *Environment variable: `SIPI_SSLPORT`*\ *Default: `443`* - `prefix_as_path=bool`: If `true`, the prefix is used as path within the image root directory. If false, the prefix is ignored and it is assumed that all images are directly located in the image root.\ *Cmdline option: `--pathprefix`*\ *Environment variable: `SIPI_PATHPREFIX`*\ *Default: `false`* - `jwt_secret=string`: Shared secret to encode web tokens. Required for any Lua-configured deployment, at least 32 bytes; there is no default, and the server refuses to start without one.\ *Cmdline option: `--jwtkey`*\ *Environment variable: `SIPI_JWTKEY`*\ *Default: none — must be supplied* - `max_post_size=amount`: Maximal size a file upload may have. The amount has the form "" where `number` is an integer value and `type`an "M" for Megabytes, "G" for Gigabytes and "" (empty) for bytes.\ *Cmdline option: `--maxpost`*\ *Environment variable: `SIPI_MAXPOSTSIZE`*\ *Default: `300M`* Request queuing (how many requests may wait for a worker, and how long) is not a config-file key. It is controlled by the `--max-waiting` / `SIPI_MAX_WAITING` and `--queue-timeout` / `SIPI_QUEUE_TIMEOUT` CLI flags — see [Running Vitrinli](https://sipi.io/guide/running/#command-line-options). - `jpeg_quality=num`: Compression parameter when producing JPEG output. Must be a number between 1 and 100. Unfortunately, the IIIF Image API does not allow to give a JPEG quality (=compression) on the IIIF URL. Vitrinli allows to configure the compression quality system wide with this parameter. Allowed values are in he range [1..100] where 1 the worst quality (and highest compression factor = smallest file size) and 100 the highest quality (with the lowest compression factor = biggest file size). Please note that Vitrinli is not able to provide lossless compression for JPEG files.\ *Cmdline option: `--quality`*\ *Environment variable: `SIPI_JPEGQUALITY`*\ *Default: `60`* - `thumb_size=string`: Default size for thumbnails. Parameter must be IIIF conformant size string. This configuration parameter can be used to define a default value for creating thumbnails. It has no direct implications but can be used in LUA scripts (e.g. the pre_flight-function).\ *Cmdline option: `--thumbsize`*\ *Environment variable: `SIPI_THUMBSIZE`*\ *Default: `!128,128`* - `max_temp_file_age=num`: The maximum allowed age of temporary files (in seconds) before they are deleted.\ *Cmdline option: `--maxtmpage`*\ *Environment variable: `SIPI_MAXTMPAGE`*\ *Default: `86400`* (one day) #### Cache Configuration Vitrinli uses a file-based LRU cache to store converted images, avoiding expensive re-conversions when the same variant is requested multiple times. The cache is keyed by the Cache key (the canonical IIIF URL plus watermark and size-restriction suffixes) and validated against the source file's modification time — stale entries are automatically replaced. **Eviction:** When the cache reaches its size or file-count limit (high-water mark at 100%), LRU eviction removes the least-recently-used entries until usage drops to 80% (low-water mark). Both limits are enforced independently — whichever is reached first triggers eviction. **Special values for `cache_size`:** - `'-1'` — unlimited cache (no size eviction) - `'0'` — cache disabled entirely (no files are cached) - `'200M'`, `'1G'` — enforced limit with LRU eviction **Monitoring:** Vitrinli exports its metrics over OTLP, to the endpoint in `OTEL_EXPORTER_OTLP_ENDPOINT`; there is no `GET /metrics` scrape endpoint. The names below are what the standard OTLP-to-Prometheus normalization produces at the collector. Cache counters (`sipi_cache_hits_total`, `sipi_cache_misses_total`, `sipi_cache_evictions_total`, `sipi_cache_skips_total`) and gauges (`sipi_cache_size_bytes`, `sipi_cache_files`, `sipi_cache_size_limit_bytes`, `sipi_cache_files_limit`) report cache health. For server load and throttling, use the admission metrics (`sipi_admission_permits_in_use` and `sipi_admission_permits_total` for saturation, `sipi_admission_tile_waiting`/`sipi_admission_full_waiting` for per-partition queue depth, `sipi_admission_tile_shed_total`/`sipi_admission_full_shed_total` for per-partition sheds). Request latency is the semantic-convention histogram `http_server_request_duration_seconds`, labelled by `http_route`, `http_request_method`, and `http_response_status_code`. `sipi_tiff_pyramid_reduced_decodes_total` counts TIFF decodes served from a reduced pyramid level (a zoomed-out or thumbnail request that read a smaller stored resolution instead of the full-resolution image). The following configuration parameters determine the behaviour of the cache: - `cache_dir=path`: Path to the cache directory. Created automatically if missing. *Cmdline option: `--cachedir`* *Environment variable: `SIPI_CACHEDIR`* *Default: `./cache`* - `cache_size=amount`: Maximum cache size. Use `'-1'` for unlimited, `'0'` to disable, or a size string like `'200M'` or `'1G'`. Eviction triggers at 100% and purges down to 80%. *Cmdline option: `--cachesize`* *Environment variable: `SIPI_CACHESIZE`* *Default: `200M`* - `cache_nfiles=num`: Maximum number of cached files. Set to `0` for no file-count limit. Eviction triggers when either size or file-count limit is reached. *Cmdline option: `--cachenfiles`* *Environment variable: `SIPI_CACHENFILES`* *Default: `200`* Deprecated keys The old configuration keys `cachedir`, `cachesize`, and `cache_hysteresis` are still accepted with a deprecation warning. The `cache_hysteresis` parameter has been removed — eviction now always uses a fixed 80% low-water mark. See `DEPRECATIONS.md` for details. #### Configuration of the HTTP File Server Vitrinli offers HTTP file server for HTML and other files. Files with the ending `.elua` are HTTP-files with embeded LUA code. Everything between the ... tags is interpreted as LUA code and the output embedded in the data stream for the client. All configurations for the HTTP server are in the `fileserver` table: - `docroot=path`: Path to the document root of the file server.\ *Cmdline option: `--docroot`*\ *Environment variable: `SSIPI_DOCROOT`*\ *Default: `./server`* - `wwwroute=string`: Route for the file server should respond to requests.That is, a file with the name "dada.html" is accessed with `http://dnsname/server/dada.html`, if the `wwwroute`is set to `/server`.\ *Cmdline option: `--wwwroute`*\ *Environment variable: `SIPI_WWWROUTE`*\ *Default: `/server`* #### Configuration of Administrator Access Vitrinli allows special administrator access for some tasks. In order to allow for this, an administrator has to be defined as follows: ``` admin = { -- -- username of admin user -- user = 'admin', -- -- Administration password -- password = 'Sipi-Admin' } ``` If You're using the administrator user, please make sure that the config file is not exposed! #### Routing Table Vitrinli allows to implement RESTful interfaces or other services based on LUA-scripts which are located in the scripts directory. In order to use these LUA-scripts as endpoints, the appropriate routes have to be defined in the `routes` table. An entry has the following form: - `method`: the HTTP request. Supported are `GET`, `POST`, `PUT` and `DELETE`. - `route`: A URL path that may contain `/`'s. - `script`: Name of the LUA script in the script directory. Thus, the routing section of a Vitrinli configuration file may look as follows: ``` routes = { { method = 'POST', route = '/api/upload', script = 'upload.lua' }, { method = 'GET', route = '/test/orientation', script = 'orientation.lua' } } ``` # Structured JSON Output (`--json`) When the `--json` flag is set on a `query` / `compare` / `verify` subcommand invocation (e.g. `sipi query --json ` or `sipi verify service-file --json `) sipi emits a single JSON document to `stdout` instead of human-readable text. The document mirrors the internal `ImageContext` that sipi otherwise sends to Sentry, so every CLI run — success or failure — yields the same structured payload a Sentry event would. This page is the reference for the schema, the emission rules, and the exit-code / stream contract. ## Contract - `stdout` contains **exactly one** JSON document terminated by a trailing newline. Nothing precedes the opening `{` and nothing follows the matching `}`. - `stderr` carries every log line (info, warning, and error). This is a change from the default CLI log routing, where info/warn go to `stdout`. - Exit codes are unchanged: `0` on success, non-zero on failure. - The flag is CLI-only: passing `--json` together with `--config` (server mode) is silently ignored. Server-mode errors continue to go through Sentry and HTTP responses. - `--json` attaches via the `output_opts` group to the `query`, `compare`, and all `verify` subcommands (per the D5 option-availability matrix). It is not exposed on `convert` flows. - The schema is **not versioned** today — there is a single consumer (local debugging / ad-hoc integrations) and the cost of adding a `schema_version` field exceeds its value while there is only one version. Future changes are additive and documented on this page. ## Success payload Emitted when the conversion completes successfully. ``` { "status": "ok", "mode": "cli", "input_file": "/path/to/input.jpg", "output_file": "/tmp/out.jp2", "output_format": "jpx", "file_size_bytes": 26688, "image": { "width": 404, "height": 201, "channels": 3, "bps": 8, "colorspace": "RGB", "icc_profile_type": "sRGB", "orientation": "TOPLEFT" } } ``` | Field | Type | Description | | ------------------------ | ------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `status` | string | Always `"ok"` on the success payload. | | `mode` | string | Always `"cli"`. | | `input_file` | string | Absolute path to the source image. | | `output_file` | string | Absolute path to the produced output file. | | `output_format` | string | Output format (`"jpx"`, `"tif"`, `"jpg"`, `"png"`). | | `file_size_bytes` | integer | Size of the source image in bytes. | | `image` | object | Decoded image properties (see below). | | `image.width` | integer | Width in pixels. | | `image.height` | integer | Height in pixels. | | `image.channels` | integer | Samples per pixel (e.g. 3 for RGB, 4 for CMYK/RGBA). | | `image.bps` | integer | Bits per sample (8 or 16). | | `image.colorspace` | string | Photometric interpretation: `MINISBLACK`, `MINISWHITE`, `RGB`, `YCBCR`, `SEPARATED`, etc. | | `image.icc_profile_type` | string | Well-known profile name (`sRGB`, `AdobeRGB`, `CMYK (USWebCoatedSWOP)`, `Gray D50`, …) or `"unknown/embedded"` for arbitrary ICC buffers. | | `image.orientation` | string | TIFF orientation tag value (e.g. `TOPLEFT`). | ## Error payload Emitted when any phase of the conversion fails. ``` { "status": "error", "mode": "cli", "phase": "read", "error_message": "Images with 1 bit/sample not supported in file ...", "input_file": "/path/to/bilevel.tif", "output_file": "/tmp/out.jp2", "output_format": "jpx", "file_size_bytes": 4768164, "image": { "width": 8040, "height": 9624, "channels": 1, "bps": 1, "colorspace": "MINISWHITE", "icc_profile_type": "", "orientation": "TOPLEFT" } } ``` | Field | Type | Description | | --------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | `status` | string | Always `"error"` on the error payload. | | `phase` | string | `"cli_args"`, `"read"`, `"convert"`, or `"write"` (in order of when they can fire). | | `error_message` | string | The message from the thrown exception (or the parameter validation failure). | | `image` | object, optional | Populated with whatever `ImageContext` captured before the failure point; **omitted entirely** when `phase == "cli_args"` because no image was loaded. | ### Phase semantics | Phase | Meaning | | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `cli_args` | Failure during CLI argument validation — invalid `--size` / `--scale` syntax, unknown output extension. Fires before any image is loaded; the `image` object is omitted. | | `read` | Failure while decoding the input file (corrupt JPEG, unsupported TIFF variant, I/O error). The `image` object reflects any properties parsed from the header before the failure. | | `convert` | Failure during the intermediate processing pipeline — orientation, ICC conversion, rotation, watermarking. The `image` object reflects the fully-decoded input image. | | `write` | Failure while encoding or writing the output file (format-specific encoder errors, disk full). | ### Reserved fields `request_uri` is part of the internal `ImageContext` struct (it is populated during HTTP request handling) but is **intentionally omitted** from the CLI `--json` output. It is reserved for potential future server-side use of this emitter. ## Worked examples ### Success — convert a JPEG to JPEG 2000 ``` $ sipi --json --file input.jpg out.jp2 2>/dev/null | jq { "status": "ok", "mode": "cli", "input_file": "input.jpg", "output_file": "out.jp2", "output_format": "jpx", "file_size_bytes": 26688, "image": { "width": 404, "height": 201, "channels": 3, "bps": 8, "colorspace": "RGB", "icc_profile_type": "sRGB", "orientation": "TOPLEFT" } } ``` ### `cli_args` error — invalid `--scale` ``` $ sipi --json --file input.jpg out.jp2 --scale bogus 2>/dev/null | jq { "status": "error", "mode": "cli", "phase": "cli_args", "error_message": "Error in scale parameter: ...", "input_file": "", "output_file": "", "output_format": "", "file_size_bytes": 0 } ``` Note the absence of `image`. ### Shell pipeline The structured output is shell-pipeable because log chatter is kept out of `stdout`: ``` if sipi --json --file input.jpg out.jp2 2>sipi.log | jq -e '.status == "ok"' >/dev/null; then echo "conversion succeeded" else echo "conversion failed — see sipi.log" cat sipi.log fi ``` # Lua Scripting # Vitrinli Lua Interface Vitrinli has an embedded [LUA](http://www.lua.org) interpreter. LUA is a simple script language that was developped specifically to be embedded into applications. For example the games [minecraft](https://www.minecraft.net) and [World of Warcraft](https://worldofwarcraft.com/de-de/) make extensive use of LUA scripting for customization and programming extensions. Each HTTP request to Vitrinli runs in a fresh, independent Lua instance (language version 5.3). Therefore, LUA may be used in the following contexts: - Preflight function - Embedded in HTML pages - RESTful services using the Vitrinli routing Each lua-instance in Vitrinli includes additional Vitrinli-specific information: - global variables about the Vitrinli configuration - information about the current HTTP request - Vitrinli specific functions for - processing the request and send back information - getting image information and transforming images - accessing SQLite databases In general, the Vitrinli LUA function make use that a Lua function's return value may consist of more than one element (see [Multiple Results](http://www.lua.org/pil/5.3.html)): *Each request runs in its own thread with its own, freshly built Lua VM. Globals do not survive across requests; within one request, the init script and the hook or route script share the same VM and globals. The VM is sandboxed and resource-limited — see the next section.* ## Sandbox and resource limits Scripts run in a hardened, per-request Lua VM: - **Standard library whitelist.** Only `string`, `table`, `math`, `utf8` and `package` are loaded. The `io` and `debug` libraries are absent, and the base-library escape hatches `dofile`, `loadfile`, `load` and `collectgarbage` are removed, as are `package.loadlib` and `package.searchpath`. - **`os` shim.** The `os` table provides exactly `os.getenv`, `os.clock` and `os.date` (a C-locale strftime subset, including `%c`, `%x`, `%X`, the `*t` table form and the `!` UTC prefix). `os.execute`, `os.remove`, `os.time` and the rest of the stock `os` library are absent — use `server.systime()` for the current epoch time and the `server.fs.*` functions for file operations. - **Restricted `require`.** `require 'name'` resolves plain module names (letters, digits and `_` only) against the configured script directory (`scriptdir`) and nowhere else; `package.path` and `package.cpath` are empty. - **Memory cap.** Lua-heap allocations are capped per request (default 64 MiB; operator knob `SIPI_LUA_MEMORY_LIMIT`, in bytes). An untrapped over-cap allocation kills the script. As in stock Lua, `pcall` can catch the allocation error itself — but the cap stays in force for every subsequent allocation. - **Execution deadline.** Each request VM gets one wall-clock budget covering the init script, the hook or route script, and every binding call (default 5 seconds; operator knob `SIPI_LUA_TIMEOUT_MS`). On expiry the script is killed; `pcall` cannot trap its way past the deadline, and blocking calls (`server.http`, sqlite) never wait past the remaining budget. - **Kill behavior.** A script killed before any output was sent yields an HTTP 500 with a generic body. A script killed — or failing with an uncaught error — after output started has its response stream aborted (never a clean end-of-body). A killed `pre_flight` decision is never written to the preflight access-cache. Kills are counted in the `sipi_lua_kills_total{reason}` metric and logged. - **Fail-closed startup.** An error in the init script refuses server startup. Whether `pre_flight`/`file_pre_flight` are defined is probed once at boot; if a later edit to the init script breaks it, affected requests fail with 500. - **Bytecode cache.** The init script, route scripts and `require`d modules are compiled once and cached as bytecode, invalidated by file modification time and size — a script edit takes effect on the next request without a restart. Adding a *new* preflight hook still requires a restart, since the hook probes are boot-frozen. - **Filesystem bindings are not path-confined.** `server.fs.*` and the other path-taking bindings (roughly a dozen across the API) accept any path the script constructs; none of them jail the result under `imgroot`, `scriptdir`, or any other configured root. This makes the `docroot` fileserver — which executes `.lua`/`.elua` scripts it finds under `docroot` — a remote-code-execution vector if `docroot` overlaps any root a request can write to. Startup refuses to start when the configured `fileserver.docroot` equals or nests with `imgroot`, `tmpdir`, `scriptdir`, or `cache_dir`; keep `docroot` disjoint from every writable or Lua-accessible directory. There is deliberately no `confine(path)` helper at the binding layer: scripts are operator-supplied, not untrusted input, and the startup overlap check closes the one misconfiguration that turns a script bug into RCE — adding per-call confinement across ~12 bindings would be redundant defense-in-depth. ## Preflight function It is possible to define a LUA pre-flight function for *IIIF*-requests and independently one for *file*-requests (indicated by a */file* postfix in the URL). Both are optional and are best located in the init-script (see [configuration options](https://sipi.io/guide/sipi/#setup-of-vitrinli-directories) of Vitrinli). It is executed after the incoming HTTP request data has been processed but before an action to respond to the request has been taken. It should be noted that the pre-flight script is only executed for IIIF-specific requests (either using the IIIF URL-syntax or the */file* postfix). All other HTTP requests are being directed to "normal" HTTP-server part of Vitrinli. These can utilize the lua functionality by embedding LUA commands within the HTML. ### IIIF preflight function The IIIF preflight function must have the name **pre_flight** with the following signature: ``` function pre_flight(prefix,identifier,cookie) return "allow", filepath end ``` The preflight function takes 3 parameter: - `prefix`: This is the prefix that is given on the IIIF url [mandatory]\ *http(s)://{server}/**{prefix}**/{id}/{region}/{size}/{rotation}/{quality}.{format}*\ Please note that the prefix may contain several "/" that can be used as path to the repository file - `identifier`: The image identifier (which must not correspond to an actual filename in the media files repositoy of the Vitrinli IIIF server) [mandatory] - `cookie`: A cookie containing authorization information. Usually the cookie contains a Json Web Token [optional] The pre-flight function must return at least 2 parameters: - `permission`: A string or a table indication the permission to read the image. In a simple case it's either the string `"allow"` or `"deny"`.\ To allow more flexibility, the following permission tables are supported: - Restricted access with watermark. The watermark must be a TIFF file with a single 8-bit channel (gray value image). For example:\ `{ type = 'restrict', watermark = './wm/mywatermark.tif' }` - Restricted access with size limitation. The size must be a [IIIF size expression](https://iiif.io/api/image/3.0/#42-size). For example:\ `{ type = 'restrict', size='!256,256' }`\ The size expression turns the image into its own, smaller image of the restricted dimensions (RW, RH): `info.json` reports (RW, RH) as `width`/`height`, as its largest `sizes` entry and as `maxWidth`/`maxHeight`. Region and size in an image request resolve against (RW, RH), not the native pixels, and every response is cut from one rendering of the whole image at (RW, RH), so tiles at size `max` stitch to `full/max` exactly. A request whose output (before rotation) is wider than RW or taller than RH, `^` upscaling included, is a 400. A client cannot recover more than `full/max` by requesting regions.\ The embedded size fields of a size-restricted output (EXIF `PixelXDimension`/`PixelYDimension`, `ImageWidth`/`ImageLength`/`ImageHeight` including maker-note ones, `RelatedImageWidth`/`RelatedImageLength`, `DefaultCropSize`, `ActiveArea` and the DNG `Original*Size` tags; XMP `exif:PixelXDimension`/`exif:PixelYDimension`, `tiff:ImageWidth`/`tiff:ImageLength` and `Iptc4xmpExt:MaxAvailWidth`/`MaxAvailHeight`) state the delivered size, and every embedded preview image (the EXIF thumbnail, SubIFD and maker-note previews, XMP `xmp:Thumbnails` and `xmpGImg:image`, the IPTC `Preview` record, and the same inside the Photoshop image resources an EXIF block can carry) is dropped; image resources that cannot be rewritten (unparseable, or carrying slices) fail the request with a 500. All other embedded metadata, rights and copyright included, is returned unchanged.\ A watermark-only `restrict` keeps the native dimensions and coordinates.\ A size that can never reduce an image (`max`, `pct:` of 100 or more, `red:0`) is refused when no watermark is set (an empty `watermark` is none): 403 on the image and on `info.json`, 404 on `knora.json`. A size that leaves an axis below 2 px is refused with or without a watermark. An image already inside a box size (e.g. 100×80 under `!128,128`) is served at its native size. - `"stream"` marks the representation as one to be consumed in place rather than kept as a file — streamed audio or video, typically. **It expresses intent and enforces nothing:** Vitrinli serves a `stream` decision exactly as `allow`, with the same bytes and the same headers, and only counts it (`sipi.preflight.decisions{permission="stream"}`). Do not rely on it as an access control. - Vitrinli also supports the [IIIF Authentification API](https://iiif.io/api/auth/1.0/). See section IIIF Authentification on how to implement this feature in the pre-flight function. - `filepath`: The path to the Service File in the media files repository. This path can be assembled using the `prefix` and `identifier` using any additional information (e.g. accessing a database or using the LUA restful client) The most simple working pre-flight looks as follows assuming that the `identifier`is the name of the Service File in the repository and the `prefix` is the path: ``` function pre_flight(prefix, identifier, cookie) if config.prefix_as_path then filepath = config.imgroot .. '/' .. prefix .. '/' .. identifier else filepath = config.imgroot .. '/' .. identifier end return 'allow', filepath end ``` Above example preflight function allows all files to be served without restriction. #### Preflight access-cache (opt-in) and its contract Vitrinli can cache the `pre_flight` access decision to avoid re-running the hook for repeated requests to the same image, which matters when the hook makes a remote call (e.g. to an auth service). The cache is **disabled by default** and is enabled with `--preflight-cache-ttl ` / `SIPI_PREFLIGHT_CACHE_TTL` (the TTL is the maximum staleness of a revoked or expired permission). The cache key is `(prefix, identifier, Cookie header, Authorization header)` **only**. A cached decision is therefore reused for any later request that matches those fields, regardless of the rest of the request. Even though `pre_flight` receives only `(prefix, identifier, cookie)` as arguments, the hook body can also read the full request through the `server` bindings — `server.uri` (the complete IIIF path, including region/size/quality), any other header via `server.header`, the host, and the client IP. If your hook's decision depends on any of those, the cache will serve a stale or wrong decision to a different request that shares only the keyed fields. > **Enable the cache only if your `pre_flight` decision is a pure function of `(prefix, identifier, Cookie, Authorization)`.** A hook that consults `server.uri`, other headers (e.g. an `X-Api-Key`), the host, or the client IP must leave the cache disabled (the default), or it risks returning access decisions made for a different request. #### More complex example of preflight function The following example uses some Vitrinli lua funtions to access an authorization server to check if the user (identified by a cookie) is allowed to see the specific image. We are using [Json Web Tokens](https://jwt.io) (JWT) which are supported by Vitrinli specific LUA functions. Please note that the Vitrinli JTW-functions support an arbitrary payload that has not to follow the JWT recommendations. In order to encode, the JWT_ALG_HS256 is beeing used together with the key that is defined in the Vitrinli configuration as [jwt_secret](https://sipi.io/guide/sipi/#jwt-secret). ``` function pre_flight(prefix, identifier, cookie) -- -- make up the file path -- if config.prefix_as_path then filepath = config.imgroot .. '/' .. prefix .. '/' .. identifier else filepath = config.imgroot .. '/' .. identifier end -- -- we need a cookie containing the user information that will be -- sent to the authorization server. The payload may be any table, -- but it must carry a valid 'exp' claim: server.decode_jwt requires -- and validates it. -- if cookie then -- -- we decode the cookie in order to get a table of key/value pairs -- success, userinfo = server.decode_jwt(cookie) if not success then return 'deny', filepath end -- -- prepare the RESTful call to the authorization server -- -- add the image identifier to the info table: userinfo["imgid"] = identifier -- encode the userinfo to a JWT-like token: local new_cookie = server.generate_jwt(userinfo) local url = 'http://auth.institution.org/api/getauth/' .. identifier local auth_information = { Cookie = new_cookie } -- -- make the HTTP request with a timeout of 500 ms -- success, result = server.http('GET', url, auth_information, 500) if success then -- -- we got a response from the server -- success, response_json = server.json_to_table(result.body) if success then -- everything OK return { type = response_json.type, restriction = response_json.restriction }, filepath else return 'deny', filepath end else return 'deny', filepath end else return 'deny', filepath end end ``` Above example assumes that the cookie data is a string that contains encrypted user data from a table (key/value pair). Jason Web Token. This token is decoded and the information about the image to be displayed is added. Then the information is encoded as a new token that ist transmitted to the RESTful interface of the authentification server. The answer is assumed to be json containing information about the type ('allow', 'deny', 'restrict') and the restriction settings. The pre-flight function uses the following Vitrinli-specific LUA global variables and function: - [config.imgroot](#configimgroot): (Global variable) Root directory of the image repository. - [server.http()](#serverhttp): (Function) Used to create a RESTful GET request. - [server.generate_jwt()](#servergenerate_jwt): (Function) Create a new JWT token from a key/value table. - [server.json_to_table()](#serverjson_to_table): (function) Convert a JSON into a LUA table. ### File preflight function An URL in the form `http(s)://{server}/{prefix}/{identifier}/file` serves the given file as binary object (including propere mimetype in the header etc.). The file has to reside in the directory tree defined for IIIF requests. In these cases, a preflight script name `file_pre_flight` is being called if defined. Its signature is as follows: ``` function file_pre_flight(filepath, cookie) end ``` A simple example allowing access only to the file *"unit/test.csv"* would be: ``` function file_pre_flight(filepath, cookie) if filepath == "./images/unit/test.csv" then return "allow", filepath else return "deny", "" end end ``` This script would deny all other file access and the Vitrinli IIIF server responds with a `401 Unauthorized` error. ## LUA embedded in HTML The HTTP server that is included in Vitrinli can serve any type of file which are just transfered as is to the client. However, if a file has an extension of `.elua`, it is assumed to be a HTML file with embedded LUA code. ALL Vitrinli-specific LUA functions and global variables are available. Embedding works with the special tag `` and ``. All text between the opening and closing tag is interpreted as LUA code. Vitrinli provides an extra LUA function to output data to the client ([server.print](#serverprint)). Thus, dynamic, server-generated HTML may be created. A sample page that displays some information about the server configuration and client info could like follows: ``` SIPI Configuration Info

SIPI Configuration Info

Configuration variables

if server.has_openssl then server.print('') end
imgroot : server.print(config.imgroot)
docroot : server.print(server.docroot)
scriptdir : server.print(config.scriptdir)
cachedir : server.print(config.cache_dir)
tmpdir : server.print(config.tmpdir)
port : server.print(config.port)
SSL port:' .. config.sslport .. '
maximal post size: : server.print(config.max_post_size)

Client information

Host in request : server.print(server.host)
IP of client : server.print(server.client_ip)
URL path : server.print(server.uri)

Important Note: "IP of client" and "Host in request" may indicate the information of a proxy and notof the actual client!

Request Header Information

for key, val in pairs(server.header) do server.print('') end
' .. key .. ':' .. val . '
``` ### Embedded LUA and enforcing SSL The supplied example initialization file offers a LUA function that enforces the use of a SSL encryption page proteced by a user name and password. It is used as follows by adding the following code *before the `` opening tag*: ``` if server.secure then protocol = 'https://' else protocol = 'http://' end success,token = authorize_page('admin.sipi.org', 'administrator', extecteduser, expectedPassword) if not success then return end ``` where `expectedUser` and `extectedPassword` are the user/password combination the user is expected to enter. ### File uploads to Vitrinli The Vitrinli specific LUA function allow the upload of files using POST requests with `multipart/form-data` content. The global variable `server.uploads` contains\`the information about the uploads. The following variables and function help to deal with uploads: - [server.uploads](#serveruploads) : information about the files in the upload request. - [server.copyTmpfile](#servercopytmpfile) : copies a fie from the upload location to the destination directory. In addition the file system functions that Vitrinli provides may be used. See the scripts `upload.elua` and `do-upload.elua` in the server directory, and `upload.lua` in the scripts directory for a working example. ## RESTful API and custom routes Custom routes to implement a RESTful API can be defined in Vitrinli's configuration file using the `routes` configuration variable. For example: ``` routes = { { method = 'GET', route = '/status', script = 'get_repository_status.lua' }, { method = 'POST', route = '/make_thumbnail', script = 'make_image_thumbnail.lua' } } ``` Vitrinli looks for these scripts in the directory specified by `scriptdir` in its configuration file. The first route that matches the beginning of the requested URL path will be used. > **Do not pass secrets in query strings.** When tracing is enabled, the request URL — **including its query string** — is recorded on the exported span (the OpenTelemetry HTTP semantic conventions capture `url.query`). A custom route or preflight script that reads a token, password, or other secret from a query-string parameter will leak it into your traces. Carry secrets in a `Cookie` or `Authorization` header (the `pre_flight` examples above use a cookie), never in the URL. ## IIIF Authentication API 1.0 in Vitrinli The `pre_flight` function is also responsible for activating the IIIF Auth API. In order to do so, the pre_flight script returns a table that contains all necessary information. For details about the IIIF Authentication API 1.0 see the [IIIF documentation](https://iiif.io/api/auth/1.0/). The following fields have to be returned by the `pre_flight`-function as LUA-table: - `type`: String giving the type. Valid are:\ `"login"`, `"clickthrough"`, `""kiosk"` or `"external"`. - `cookieUrl`: URL where to get a valid IIIF Auth cookie for this service. - `tokenUrl`: URL where to get a valid IIIF Auth token for this service. - `confirmLabel`: Label to display in confirmation box. - `description`: Description for login window. - `failureDescription`: Information, if login fails. - `failureHeader`: Header for failure window. - `header`: Header of login window - `label`: Label of the login window In addition, the filepath has to be returns. A full response may look as follows: ``` return { type = 'login', cookieUrl = 'https://localhost/iiif-cookie.html', tokenUrl = 'https://localhost/iiif-token.php', confirmLabel = 'Login to SIPI', description = 'This Example requires a demo login!', failureDescription = 'Access Policy', failureHeader = 'Authentication Failed', header = 'Please Log In', label = 'Login to SIPI', }, filepath ``` Vitrinli will use this information returned by the `pre_flight` function to return the appropriate responses to the client requests based on the IIIF Authentication API 1.0. Check for support of the IIIF Authentication API 1.0 for [mirador](https://projectmirador.org) and [universalviewer](https://universalviewer.io), both applications which suppport the IIIF standards. ## Vitrinli variables available to Lua scripts There are many globally accessible LUA variables made available which reflext the configuration of Vitrinli and the state of the server and request. This variables a read only and created for every request. ### Vitrinli configuration variables This variables are defined ither in the configuration file if Vitrinli, in environemt variables at startup or as command line option when starting the server. #### config.hostname ``` config.hostname ``` The configured hostname, exposed to Lua route scripts (e.g. to build absolute preview URLs). Defaults to `localhost`; not used by the server itself. #### config.port ``` config.port ``` Portnumber where the Vitrinli server listens (see [serverport](https://sipi.io/guide/sipi/#portnum) in configuration description). #### config.sslport ``` config.sslport ``` Portnumber for SSL connections of Vitrinli (see [sslport](https://sipi.io/guide/sipi/#sslport) in configuration description). #### config.imgroot ``` config.imgroot ``` Root directory for IIIF-served images (see [imgroot](https://sipi.io/guide/sipi/#imgroot) in configuration description). #### config.docroot ``` config.docroot ``` Root directory for WEB-Server (see [docroot](https://sipi.io/guide/sipi/#docroot) in configuration description). #### config.max_temp_file_age ``` config.max_temp_file_age ``` maximum age of temporary files (see [max_temp_file_age](https://sipi.io/guide/sipi/#maxtmpfileage) in configuration description). #### config.prefix_as_path ``` config.prefix_as_path` ``` `true` if the prefix should be used as path info (see [prefix_as_path](https://sipi.io/guide/sipi/#prefixaspath) in configuration description). #### config.init_script ``` config.init_script ``` Path to initialization script (see [initscript](https://sipi.io/guide/sipi/#scriptinit) in configuration description). #### config.scriptdir ``` config.scriptdir ``` Path to script directory. (see [scriptdir](https://sipi.io/guide/sipi/#scriptdir) in configuration description). #### config.cache_dir ``` config.cache_dir ``` Path to cache directory for iIIF served images. (see [cachedir](https://sipi.io/guide/sipi/#cachedir) in configuration description). #### config.cache_size ``` config.cache_size ``` Maximal size of cache (see [cachesize](https://sipi.io/guide/sipi/#cachesize) in configuration description). #### config.cache_n_files ``` config.cache_n_files ``` Maximal number of files in cache. (see [cache_nfiles](https://sipi.io/guide/sipi/#cachenfiles) in configuration description). #### config.jpeg_quality ``` config.jpeg_quality ``` Unfortunately, the IIIF Image API does not allow to give a JPEG quality (=compression) on the IIIF URL. Vitrinli allows to configure the compression quality system wide with this parameter. Allowed values are in he range [1..100] where 1 the worst quality (and highest compression factor = smallest file size) and 100 the highest quality (with lowest compression factor = biggest file size). Please note that Vitrinli is not able to provide lossless compression for JPEG files. (see [jpeg_quality](https://sipi.io/guide/sipi/#jpegquality) in configuration description). #### config.thumb_size ``` config.thumb_size ``` Default thumbnail image size. (see [thumb_size](https://sipi.io/guide/sipi/#thumbsize) in configuration description). #### config.max_post_size ``` config.max_post_size ``` Maximal size of POST data allowed (see [max_post_size](https://sipi.io/guide/sipi/#maxpostsize) in configuration description). #### config.tmpdir ``` config.tmpdir ``` Temporary directory to store uploads. (see [tmpdir](https://sipi.io/guide/sipi/#tmpdir) in configuration description). ### Vitrinli Server Variables Vitrinli server variables are dependent on the incoming request and are created by Vitrinli automatically for each request. #### server.method ``` server.method ``` The HTTP request method. Is one of `OPTIONS`, `GET`, `HEAD`, `POST`, `PUT`, `DELETE`, `TRACE`, `CONNECT` or `OTHER`. #### server.has_openssl ``` server.has_openssl ``` `true` if OpenSSL is available. This variable is determined compilation time. Usually SSL should be included, but Vitrinli can be compiled without SSL support. There is no option in the configuration file for this. #### server.secure ``` server.secure ``` `true` if the connection was made over HTTPS using SSL. #### server.host ``` server.host ``` The hostname of the Vitrinli server that was used in the request. #### server.client_ip ``` server.client_ip ``` The IPv4 or IPv6 address of the client connecting to Vitrinli. #### server.client_port ``` server.client_port ``` The port number of the client socket. #### server.uri ``` server.uri ``` The URL path used to access Vitrinli (does not include the hostname). #### server.header ``` server.header ``` A table containing all the HTTP request headers(in lowercase). #### server.cookies ``` server.cookies ``` A table of the cookies that were sent with the request — one entry per cookie, keyed by the cookie's name in its original case. #### server.get ``` server.get ``` A table of GET request parameters. #### server.post ``` server.post ``` A table of POST or PUT request parameters. #### server.request ``` server.request ``` All request parameters. #### server.content ``` server.content ``` If the request had a body, the variable contains the body data. Otherwise it's `nil`. #### server.content_type ``` server.content_type ``` Returns the content type of the request. If there is no type or no content, this variable is `nil`. #### server.docroot ``` server.docroot ``` The document root of the built-in web server, when one is configured; `nil` otherwise. #### server.uploads ``` server.uploads ``` This is an array of upload parameters, one per file. Each one is a table containing: - `fieldname`: the name of the form field. - `origname`: the original filename. - `tmpname`: a temporary path to the uploaded file. - `mimetype`: the MIME type of the uploaded file as provided by the browser. - `filesize`: the size of uploaded file in bytes. The upload can be accessed as follows: ``` for index, value in pairs(server.uploads) do -- -- copy the uploaded file to the image repository using the original name -- server.copyTmpfile(index, config.imgdir .. '/' .. value["origname"]) end ``` ### Knora-specific variables The development of Vitrinli came out of the need to have a flexible, high performance IIIF server for the Swiss National research infrastructure [Data and Service Center for the Humanities](https://dasch.swiss) (DaSCH). The aim of the DaSCH is to guarantee long-term accessibility of research data from the Humanities. The operates a specialized platform [Knora](https://knora.org). The following variables are for internal use only. #### config.knora_path ``` config.knora_path ``` Path to knora REST API (only for Vitrinli used with Knora) #### config.knora_port ``` config.knora_port ``` Port that the Knora API uses ## Vitrinli functions available to Lua scripts Vitrinli provides the following functions that can be called from Lua scripts. Each function returns two values. The first value is `true` if the operation succeeded, `false` otherwise. If the operation succeeded, the second value is the result of the operation, otherwise it is an error message. ### Vitrinli Connection Functions These LUA function alter the way the HTTP connection is handled. #### server.setBuffer ``` success, errmsg = server.setBuffer([bufsize][,incsize]) ``` Accepted for compatibility: the response is streamed by the server, so the call validates its arguments and succeeds without changing behavior. Optionally the buffer size and increment size can be given. Returns `true, nil` on success or `false, errormsg` on invalid arguments. #### server.sendHeader ``` success, errormsg = server.sendHeader(key, value) ``` Sets an HTTP response header. Returns `true, nil` on success or `false, errormsg` on failure. #### server.sendCookie ``` success, errormsg = server.sendCookie(key, value [, options-table]) ``` Sets a cookie in the HTTP response. Returns `true, nil` on success or `false, errormsg` on failure. The optional `options-table` is a Lua table containing the following keys: - `path` - `domain` - `expires` (value in seconds) - `secure` (boolean) - `http_only` (boolean) - `same_site` (string) Response cookies default to `Secure; HttpOnly; SameSite=Lax`. The `http_only` and `same_site` options can override those defaults (e.g. `same_site = ""` clears `SameSite`); `secure` only ever turns the flag on. #### server.sendStatus ``` server.sendStatus(code) ``` Sends an HTTP status code. This function is always successful and returns nothing. #### server.print ``` success, errormsg = server.print(values) ``` Prints variables and/or strings over the HTTP connection to the client that originated the request. Returns `true, nil` on success or `false, errormsg` on failure. #### server.requireAuth ``` success, table = server.requireAuth() ``` This function retrieves HTTP authentication data that was supplied after sending a `'WWW-Authenticate'`-header (e.g. by issuing a the following commands to enter the HTTP login dialog: ``` server.setBuffer() server.sendStatus(401); server.sendHeader('WWW-Authenticate', 'Basic realm="Sipi"') ``` It returns `true, table` on success or `false, errormsg` on failure. The result of the authorization is returned as table with the following elements: - `status`: Either `BASIC`, `BEARER`, `NOAUTH` (no authorization header) or `ERROR` - `username`: A string containing the supplied username (only existing if stats is `BASIC`) - `password`: A string containing the supplied password (only existing if stats is `BASIC`) - `token`: A string containing the raw token information (only if status `BEARER`) - `message`: A string containing the error message (only if status `ERROR`) Example: ``` success, auth = server.requireAuth() if not success then server.sendStatus(501) server.print("Error in getting authentication scheme!") return -1 end if auth.status == 'BASIC' then -- -- everything OK, let's create the token for further -- calls and ad it to a cookie -- if auth.username == os.getenv('SIPI_ADMIN_USER') and auth.password == os.getenv('SIPI_ADMIN_PASSWORD') then tokendata = { iss = "sipi.unibas.ch", aud = "knora.org", user = auth.username, exp = server.systime() + 3600 } success, token = server.generate_jwt(tokendata) if not success then server.sendStatus(501) server.print("Could not generate JWT!") return -1 end success, errormsg = server.sendCookie('sipi', token, {path = '/', expires = 3600}) if not success then server.sendStatus(501) server.print("Couldn't send cookie with JWT!") return -1 end else server.sendStatus(401) server.sendHeader('WWW-Authenticate', 'Basic realm="Sipi"') server.print("Wrong credentials!") return -1 end elseif auth.status == 'BEARER' then success, jwt = server.decode_jwt(auth.token) if not success then server.sendStatus(501) server.print("Couldn't deocde JWT!") return -1 end if (jwt.iss ~= 'sipi.unibas.ch') or (jwt.aud ~= 'knora.org') or (jwt.user ~= os.getenv('SIPI_ADMIN_USER')) then server.sendStatus(401) server.sendHeader('WWW-Authenticate', 'Basic realm="Sipi"') return -1 end elseif auth.status == 'NOAUTH' then server.setBuffer() server.sendStatus(401); server.sendHeader('WWW-Authenticate', 'Basic realm="Sipi"') return -1 else server.sendStatus(401) server.sendHeader('WWW-Authenticate', 'Basic realm="Sipi"') return -1 end ``` ### Vitrinli File System Function These functions offer tools to manipuale files and directories, and to gather file information. #### server.fs.ftype ``` success, filetype = server.fs.ftype(filepath) ``` Checks the filetype of a given filepath. Returns either `true, filetype` (with filetype one of `"FILE"`, `"DIRECTORY"`, `"CHARDEV"`, `"BLOCKDEV"`, `"LINK"`, `"FIFO"`, `"SOCKET"` or `"UNKNOWN"`) or `false, errormsg`. #### server.fs.modtime ``` success, modtime = server.fs.modtime(filepath) ``` Retrieves the last modification date of a file in seconds since epoch UTC. Returns either `true`, `modtime` or `false`, `errormsg`. #### server.fs.is_readable ``` success, readable = server.fs.is_readable(filepath) ``` Checks if a file is readable. Returns `true, readable` (boolean) on success or `false, errormsg` on failure. #### server.fs.is_writeable ``` success, writeable = server.fs.is_writeable(filepath) ``` Checks if a file is writeable. Returns `true, writeable` (boolean) on success or `false, errormsg` on failure. #### server.fs.is_executable ``` success, errormsg = server.fs.is_executable(filepath) ``` Checks if a file is executable. Returns `true, executable` (boolean) on success or `false, errormsg` on failure. #### server.fs.exists ``` success, exists = server.fs.exists(filepath) ``` Checks if a file exists. Checks if a file exists. Returns `true, exists` (boolean) on success or `false, errormsg` on failure. #### server.fs.unlink ``` success, errormsg = server.fs.unlink(filename) ``` Deletes a file from the file system. The file must exist and the user must have write access. Returns `true, nil` on success or `false, errormsg` on failure. #### server.fs.mkdir ``` success, errormsg = server.fs.mkdir(dirname, mode) ``` Creates a new directory with the specified permissions. Both parameters are required; `mode` is a Unix permission integer (e.g. `tonumber('0755', 8)`). Returns `true, nil` on success or `false, errormsg` on failure. #### server.fs.rmdir ``` success, errormsg = server.fs.rmdir(dirname) ``` Deletes a directory. Returns `true, nil` on success or `false, errormsg` on failure. #### server.fs.getcwd ``` success, curdir = server.fs.getcwd() ``` Gets the current working directory. Returns `true, current_dir` on success or `false, errormsg` on failure. #### server.fs.readdir ``` success, filenames = server.fs.readdir(dirname) ``` Gets the names of the files in a directory, not including `.` and `..`. Returns `true, table` on success or `false, errormsg` on failure. #### server.fs.copyFile ``` success, errormsg = server.fs.copyFile(source, destination) ``` Copies a file from source to destination. Returns `true, nil`on success or `false, errormsg` on failure. #### server.fs.moveFile ``` success, errormsg = server.fs.moveFile(from, to) ``` Moves a file. The move connot cross filesystem boundaries! `true, nil`on success or `false, errormsg` on failure. ### Other Helper Function #### server.http ``` success, result = server.http(method, "http://server.domain[:port]/path/file" [, header] [, timeout]) ``` Performs an outbound HTTP request. Currently implements only GET requests. Parameters: - `method`: The HTTP request method. Currently must be `"GET"`. - `url`: The HTTP URL. - `header`: An optional table of key-value pairs representing HTTP request headers. - `timeout`: An optional number of milliseconds for the *whole* request (connect, send and receive; default 2000). The effective timeout is additionally capped by the remaining execution deadline of the request, so an outbound call can never outlive its request budget. Hardened semantics: - Redirects are **not** followed: a `3xx` response is returned to the script as-is (with its `location` header). - The response body is capped at 16 MiB; a larger body fails the call. - Authentication is not supported. When Vitrinli is handling a request under an active distributed trace, `server.http` automatically adds a W3C `traceparent` header to the outbound request so the downstream service continues the same trace (e.g. a `pre_flight` authorization call to dsp-api). If the `header` table already contains a `traceparent`, that value is kept and no header is injected. On success the result is a table: ``` result = { status_code = value, -- HTTP status code returned header = { name = value [, name = value, ...] }, body = data, duration = milliseconds } ``` On failure the second return value is the error message string. Example: ``` success, result = server.http("GET", "http://www.salsah.org/api/resources/1", 100) if success then server.print("Status: ", result.status_code, "
") server.print("Duration: ", result.duration, " ms

") server.print("Body:
", result.body) else server.print("ERROR: ", result) end ``` #### server.table_to_json ``` success, jsonstr = server.table\_to\_json(table) ``` Converts a (nested) Lua table to a JSON string. Returns `true, jsonstr` on success or `false, errormsg` on failure. #### server.json_to_table ``` success, table = server.json_to_table(jsonstr) ``` Converts a JSON string to a (nested) Lua table. Returns `true, table` on success or `false, errormsg` on failure. #### server.generate_jwt ``` success, token = server.generate_jwt(table) ``` Generates a [JSON Web Token](https://jwt.io/) (JWT) with the supplied table as payload, signed with HS256 using the configured [jwt_secret](https://sipi.io/guide/sipi/#jwt-secret). Returns `true, token` on success or `false, errormsg` on failure. The payload may contain arbitrary keys and/or the JWT claims as follows. (The type `IntDate` is a number of seconds since 1970-01-01T0:0:0Z): - `iss` (string => StringOrURI) OPT: principal that issued the JWT. - `exp` (number => IntDate): expiration time on or after which the token MUST NOT be accepted for processing. **Required** in any token that will be verified with `server.decode_jwt`. - `nbf` (number => IntDate) OPT: identifies the time before which the token MUST NOT be accepted for processing. - `iat` (number => IntDate) OPT: identifies the time at which the JWT was issued. - `aud` (string => StringOrURI) OPT: identifies the audience that the JWT is intended for. The audience value is a string, typically the base address of the resource being accessed, such as `https://contoso.com`. - `prn` (string => StringOrURI) OPT: identifies the subject of the JWT. - `jti` (string => String) OPT: provides a unique identifier for the JWT. #### server.decode_jwt ``` success, table = server.decode_jwt(token) ``` Decodes and verifies a [JSON Web Token](https://jwt.io/) (JWT) and returns its content as table. Returns `true, table` on success or `false, errormsg` on failure. Verification is strict: - The signature must be a valid HS256 signature over the configured [jwt_secret](https://sipi.io/guide/sipi/#jwt-secret); tokens using any other algorithm (including `none`) are rejected. - The token must carry an `exp` claim that is not in the past (a small clock-skew leeway is applied). #### server.parse_mimetype ``` success, mimetype = server.parse_mimetype(str) ``` Parses a mimtype HTTP header string and returns a pair containing the actual mimetype and the charset used (if available). It returns `true, pair` with pair as mimetype and charset on success, `false, errormsg` on failure. #### server.file_mimetype ``` success, table = server.file_mimetype(path) success, table = server.file_mimetype(index) ``` Determines the mimetype of a file. The *first* form is used if the file path is known. The *second* form can be used for uploads by passing the upload file index. It returns `true, table` on success or `false, errormsg` on failure. The table has 2 members: - `mimetype` - `charset` #### server.file_mimeconsistency ``` success, is_consistent = server.file_mimeconsistency(path) success, is_consistent = server.file_mimeconsistency(index) ``` Checks if the file extension and the mimetype determined by the magic of the file is consistent. The *first* form requires a path (including the filename with extension), the *second* can be used for checking uploads by passing the file index. It returns `true, is_consistent` on success or `false, errormsg` in case of an error. `is_consistent` is true if the mimetype corresponds to the file extension. #### server.copyTmpfile ``` success, errormsg = server.copyTmpfile(from, to) ``` Vitrinli saves each uploaded file in a temporary location (given by the config variable `tmpdir`) and deletes it after the request has been served. This function is used to copy the file to another location where it can be retrieved later. Returns `true, nil` on success or `false, errormsg` on failure. Parameters: - `from`: an index (integer value) of array server.uploads. - `target`: destination path #### server.systime ``` systime = server.systime() ``` Returns the current system time on the server in seconds since epoch. #### server.log ``` server.log(message, loglevel) ``` Writes a message to the built-in logger. Severity levels are: - `server.loglevel.LOG_EMERG` - `server.loglevel.LOG_ALERT` - `server.loglevel.LOG_CRIT` - `server.loglevel.LOG_ERR` - `server.loglevel.LOG_WARNING` - `server.loglevel.LOG_NOTICE` - `server.loglevel.LOG_INFO` - `server.loglevel.LOG_DEBUG` #### server.secure_equals ``` equal = server.secure_equals(a, b) ``` Constant-time string comparison for credential checks (e.g. Basic-auth username/password), to avoid leaking timing information through an early-exit `==` comparison. Returns a boolean. #### server.uuid ``` success, uuid = server.uuid() ``` Generates a random UUID version 4 identifier in canonical form, as described in [RFC 4122](https://tools.ietf.org/html/rfc4122). Returns `true, uuid` on success or `false, errormsg` on failure. #### server.uuid62 ``` success, uuid62 = server.uuid62() ``` Generates a Base62-encoded UUID. Returns `true, uuid62` on success or `false, errormsg` on failure. #### server.uuid_to_base62 ``` success, uuid62 = server.uuid_to_base62(uuid) ``` Converts a canonical UUID string to a Base62-encoded UUID. Returns `true, uuid62` on success or `false, errormsg` on failure. #### server.base62_to_uuid ``` success, uuid = server.base62_to_uuid(uuid62) ``` Converts a Base62-encoded UUID to canonical form. Returns `true, uuid` on success or `false, errormsg` on failure. ## Helper Functions The `helper` table carries Vitrinli-internal helpers. #### helper.filename_hash ``` success, hashed_path = helper.filename_hash(filename) ``` Converts a filename into Vitrinli's hashed storage path (the on-disk layout the repository uses). Returns `true, hashed_path` on success or `false, errormsg` on failure. # Lua image functions Through Lua scripting, Vitrinli allows a wide area of utilities to analyze, manipulate and convert images to/from different formats. This functionality allows to use Vitrinli e.g. for offering image upload and converting these images into IIIF conformant long-term storage formats (e.g. JPEG2000). It allows to programmatically modify an image before delivering it to the client, or to extract data from the images. The basic concept is a specialized Lua image object that offers all methods to manipulate images. ### SipiImage.new(filename) This method creates a new image object by reading an image file that has to be located somewhere on the Vitrinli server. The simple forms are: ``` img = SipiImage.new("filepath") img = SipiImage.new(index) ``` The first variant opens a file given by "filepath", the second variant opens an uploaded file directly using the integer index to the uploaded files. If the index of an uploaded file is passed as an argument, this method adds additional metadata to the `SipiImage` object that is constructed: the file's original name, its MIME type, and its SHA256 checksum. When the `SipiImage` object is then written to another file, this metadata will be stored in an extra header record. If a filename is passed, the method does not add this metadata. The more complex form is as follows: ``` img = SipiImage.new("filename", { region=, size=, reduce=, original=origfilename, hash="md5"|"sha1"|"sha256"|"sha384"|"sha512" }) ``` This creates a new Lua image object and loads the given image into it. The second form allows to indicate a region, the size or a reduce factor and the original filename. All parameters are optional. The meaning of the parameters are: - `region`: A region in IIIF format the image should be cropped to. - `size`: The size of the resulting image as valid IIIF size string. - `reduce`: An much faster alternative to size, if the image size will be reduced by a integer factor (2=half size, 3=one third size etc.) - `original`: The original file name that should be recorded in the metadata - `hash`: Accepted and validated for compatibility (valid entries are `md5`, `sha1`, `sha256`, `sha384` and `sha512`), but the checksum algorithm actually used is decided at write time. For example to read an image and include the Vitrinli preservation metadata, the function is called as follows: ``` SipiImage.new("path_to_file", { original="my_image.tif", hash="md5" } ``` This call will include the preservation metadata (please note that in this case the original filename is mandatory, since Lua has know direct knowledge about the original filename. The filepath given as first parameter must not and normally does not correspond to the original filename). The `hash`-parameter indicates to use the md5-algorithm for the has of the pixel values. ### SipiImage.dims() ``` success, dims = img:dims() if success then server.print('nx=', dims.nx, ' ny=', dims.ny, ' ori=', dims.orientation) end ``` The method can also be called with a file path instead of an image object, returning the dimensions without keeping the image around: ``` success, dims = SipiImage.dims("path_to_file") ``` This method returns basic information about the image. It returns a Lua table withg the following items: - *nx*: Number of pixels in X direction (image width) - *ny*: Number of pixels in Y direction (image height) - *orientation*: Orientation of image which is an integer with the following meaning: - *1*: (TOPLEFT) The 0th row represents the visual top of the image, and the 0th column represents the visual left-hand side. - *2*: (TOPRIGHT) The 0th row represents the visual top of the image, and the 0th column represents the visual right-hand side. - *3*: (BOTRIGHT) The 0th row represents the visual bottom of the image, and the 0th column represents the visual right-hand side. - *4*: (BOTLEFT) The 0th row represents the visual bottom of the image, and the 0th column represents the visual left-hand side. - *5*: (LEFTTOP) The 0th row represents the visual left-hand side of the image, and the 0th column represents the visual top. - *6*: (RIGHTTOP) The 0th row represents the visual right-hand side of the image, and the 0th column represents the visual top. - *7*: (RIGHTBOT) The 0th row represents the visual right-hand side of the image, and the 0th column represents the visual bottom. - *8*: (LEFTBOT) The 0th row represents the visual left-hand side of the image, and the 0th column represents the visual bottom. ### SipiImage.exif() ``` success, value-or-errormsg = img:exif() ``` Return the value of an exif parameter. The following EXIF parameters are supported: - *"Orientation"*: Orientation (integer) - *"Compression"*: Compression method (integer) - *"PhotometricInterpretation"*: The photometric interpretation (integer) - *"SamplesPerPixel"*: Samples per pixel (integer) - *"ResolutionUnit"*: 1=none, 2=inches, 3=cm (integer) - *"PlanarConfiguration"*: Planar configuration, 1=chunky, 2=planar (integer) - *"DocumentName"*: Document name (string) - *"Make"*: Make of camera or scanner (string) - *"Model"*: Model of camera or scanner (string) - *"Software"*: Software used for capture (string) - *"Artist"*: Artist that created the image (string) - *"DateTime"*: Date and time of creation (string) - *"ImageDescription"*: Image description - *"Copyright"*: Copyright info - ### SipiImage.crop() ``` success, errormsg = img:crop() ``` Crops the image to the given rectangular region. The parameter must be a valid IIIF-region string. ### SipiImage.scale() ``` success, errormsg = img:scale() ``` Resizes the image to the given size as IIIF-conformant size string. ### SipiImage.rotate(angle [, mirror]) ``` success, errormsg = img:rotate(angle) success, errormsg = img:rotate(angle, mirror) ``` Rotates the image by the given angle in degrees (a number). The optional second parameter is a boolean; `true` mirrors the image before rotating. ### SipiImage.topleft() Rotates an image to the standard TOPLEFT orientation if necessary. Please note that viewers using tiling (e.g. [openseadragon](https://openseadragon.github.io)) require images in TOPLEFT rotation. Thus, it is highly recommended that all images served by Vitrinli IIIF will be set to TOPLEFT orientation. This process may involve rotation of 90, 180 or 270 degrees and possible mirroring which does *not* change the pixel values through interpolation. ### SipiImage.watermark(wm-file-path) ``` success, errormsg = img:watermark(wm-file-path) ``` Applies the given watermark file to the image. The watermark file must be a single channel 8-Bit gray value TIFF file. ### SipiImage.write(filepath, [compression_params]) ``` success, filepath = img:write(filepath) success, filepath = img:write('HTTP.jpg') ``` The first version writes the image to a file on the Vitrinli server, the second streams the encoded file over the HTTP connection (which is done whenever the basename of the output file is `HTTP` or `http`). On success the second return value is the given filepath. Parameters: - `filepath`: Path to output file. The file format is determined by the filename extension. Supported are - `jpg`, `jpeg` : writes a JPEG file - `tif`, `tiff` : writes a TIFF file - `png` : writes a PNG file - `jpx`, `j2k`, `jp2` : writes a JPEG2000 file An unsupported extension raises a Lua error (catch it with `pcall`). - `compression_params`: (optional) An optional Lua table with compression parameters (which are dependent on the chosen output file format!) can be given. All compression parameters are optional. An invalid value for a validated parameter, or an unknown parameter name, raises a Lua error. - JPEG format: - `quality`: Number between 1 and 100 (1 highest compression, worst quality, 100 lowest compression, best quality) - JPEG2000 format: - `Sprofile`: Any of `PROFILE0`, `PROFILE1`, `PROFILE2`, `PART2`, `CINEMA2K`, `CINEMA4K`, `BROADCAST`, `CINEMA2S`, `CINEMA4S`, `CINEMASS`, `IMF`. Defaults to `PART2`. - `Creversible`: Use the reversible compression algorithms of JPEG2000. Must be string `yes` or `no`. Defaults to `yes`. - `Cuse_sop`: Include SOP markers. Must be string `yes` or `no`. - `Clayers`: Number of layers to use. - `Clevels`: Number of levels to use. - `Corder`: Ordering of file components. Must be one of the following strings: `LRCP`, `RLCP`, `RPCL`, `PCRL` or `CPRL`. - `Cprecincts`: A kakadu conformant precinct string. - `Cblk`: A kakadu conformant code-block size string. - `rates`: rates string as used in kakadu. - Service-File stamping (Preservation metadata): - `file_role`: Must be the string `"service-file"`. Marks the output as a Service File; requires `origname` and `mimetype`, and the output format must be JPEG2000 or TIFF. - `origname`: The original filename to record. - `mimetype`: The original MIME type to record. ### SipiImage.send(format) ``` success, errormsg = img:send(format) ``` Sends the file to the HTTP connection. Supported format strings: - `jpg`, `jpeg` : sends a JPEG file - `tif`, `tiff` : sends a TIFF file - `png` : sends a PNG file - `jpx`, `j2k` : sends a JPEG2000 file An unsupported format string raises a Lua error (catch it with `pcall`). ### SipiImage.mimetype_consistency(mimetype, filename) ``` success, consistent = img:mimetype_consistency(mimetype, original_filename) ``` This method checks if the supplied MIME type (e.g. received from the browser during upload), the file's magic number ([file signature](https://en.wikipedia.org/wiki/List_of_file_signatures)), and the file extension are consistent. **Parameters:** - `mimetype` (string): The expected MIME type (e.g., `"image/tiff"`). - `original_filename` (string): The original filename with extension (e.g., `"photo.tif"`). **Returns:** `(true, boolean)` on success where the boolean indicates consistency, or `(false, error_message)` on failure. Please note that MIME type handling can be quite complex, since the correspondence between file extensions and MIME types is not unambiguous. In addition the file signature cannot identify all MIME types. For example, a "comma separated values" file (extension `.csv`) can have a MIME type of `application/csv`, `text/csv`, `text/x-csv`, `application/vnd.ms-excel` and more. However, the file signature will usually return `text/plain`. Vitrinli tries to cope with these ambiguities. ### Example: Image Processing Pipeline ``` -- Read an image, crop, scale, rotate, and write to a new format img = SipiImage.new("input.tif") img:crop("100,100,500,500") img:scale("400,") img:rotate("90") img:write("output.jpx") ``` ``` -- Process an uploaded file and send the result via HTTP img = SipiImage.new(1) -- first uploaded file img:topleft() img:scale("!800,800") img:send("jpg") ``` # Using SQLite in Vitrinli Vitrinli supports [SQLite](https://www.sqlite.org/) 3 databases, which can be accessed from Lua scripts. You should use [pcall](https://www.lua.org/pil/8.4.html) to handle errors that may be returned by SQLite. ## Opening an SQLite Database ``` db = sqlite(path_to_db [, access]) ``` This creates a new opaque database object. Errors raise real Lua errors (hence the `pcall` advice above). The parameters are: - `path_to_db`: path to the sqlite3 database file. - `access`: Method of opening the database. Allowed are - `'RO'`: readonly access. The file must exist and the Vitrinli server must have read access to it. - `'RW'`: read and write access. The file must exist and the Vitrinli server must have read/write access to it. This is the default when the parameter is omitted. - `'CRW'`: If the database file does not exist, it will be created and opened with read/write access. If the database is locked by another writer, calls wait at most the remaining execution deadline of the request. To close the database, you can do this: ``` db = ~db ``` This marks the connection closed: any later use of the database or of a query object prepared from it raises a `database is closed` error. The underlying connection is freed once every query object prepared from it is gone. Alternatively, Lua's garbage collection will free the database object and all resources when they are no longer used. ### Preparing a Query The Vitrinli sqlite interface supports direct queries as well as prepared statements. A direct query is constructed as follows: ``` qry = db << 'SELECT * FROM image' ``` Or, if you want to use a prepared query statement: ``` qry = db << 'INSERT INTO image (id, description) VALUES (?,?)' ``` The result of the `<<` operator (`qry`) will then be a query object containing a prepared query. If the query object is not needed anymore, it may be destroyed: ``` qry = ~qry ``` Query objects should be destroyed explicitly if not needed any longer. ### Executing a Query Executing (calling) a query object gets the next row of data. If there are no more rows, `nil` is returned. The row is returned as a table of values with **0-based** column indices; a column whose value is SQL `NULL` is absent from the table (its index is `nil`). ``` row = qry() while (row) do print(row[0], ' -> ', row[1]) row = qry() end ``` Or with a prepared statement: ``` row = qry('SGV_1960_00315', 'This is an image of a steam engine...') ``` The second way is used for prepared queries that contain parameters (`?` placeholders, bound 1-based from the first call argument). Calling a query object with arguments resets the statement and rebinds all parameters. Supported bind types are strings, integers, floats, booleans and `nil`. # Development # Building Vitrinli from Source Code Vitrinli's build system is **Bazel** (orchestrating every C/C++ target, the OCI Docker image, and the Rust e2e + smoke tests). Nix's role is reduced to **provisioning a dev shell** with bazelisk + the host tools the `gh_release_archive` repository_rule needs on PATH (`gh`, for the Kakadu fetch). All build commands are wrapped by recipes in the root `justfile`. Run `just` to see the full list. Every CI step invokes one of these recipes — there are no inline `bazel ...` calls in any workflow. ## Quick start ``` nix develop # bazelisk + host tools on PATH just bazel-build-server # bazel build --stamp //src/cli/rust:sipi (the Rust server shell) ./bazel-bin/src/cli/rust/sipi server --config config/sipi.localdev-config.lua ``` `just run` chains the two: it depends on `bazel-build` and starts sipi with the localdev config in one step. For Bazel concepts, common commands, `--config=` flags, and querying the build graph, see **[Building with Bazel](https://sipi.io/development/bazel/index.md)**. For dev-shell setup (Determinate Nix install, what the shell provides), see **[Nix dev shell](https://sipi.io/development/nix/index.md)**. ## Prerequisites ### Kakadu (JPEG 2000) Vitrinli uses [Kakadu](http://kakadusoftware.com/), a proprietary JPEG 2000 toolkit licensed separately. The archive is published as a release asset on the private [`dasch-swiss/dsp-ci-assets`](https://github.com/dasch-swiss/dsp-ci-assets) repo and is fetched at build time by a custom Bazel `gh_release_archive` repository_rule (`bazel/gh_release.bzl`) that shells out to `gh release download`. ``` gh auth login # one-time; needs dasch-swiss org membership just bazel-build # the repository_rule fetches Kakadu on first build ``` CI passes `GH_TOKEN: ${{ secrets.DASCHBOT_PAT }}` on every Bazel step so the repository_rule resolves there too. See [Kakadu setup](https://sipi.io/development/kakadu/index.md) for details and the version-bump procedure. ### Adobe ICC Color Profiles Vitrinli uses Adobe ICC color profiles, which are downloaded automatically by the Bazel build. The user is responsible for reading and agreeing with Adobe's license conditions, which are specified in `Color Profile EULA.pdf` at the repo root. ## Building a Docker image The Docker image is built by Bazel `rules_oci` (`//src:sipi_image`). There is no `Dockerfile` — `src/BUILD.bazel` is the single source of truth. A running Docker daemon is still required for `docker load` / `docker push`, but `docker buildx` is not used (multi-arch manifest assembly happens via `crane index append` on a coordinator job). ``` just bazel-docker-build-arm64 # or -amd64; loads daschswiss/sipi:latest just bazel-test-smoke # builds //src:sipi_image and probes the loaded image ``` ### Per-arch builds (used by CI) ``` just bazel-docker-build-amd64 # build + load amd64 as daschswiss/sipi:latest just bazel-docker-build-arm64 # build + load arm64 just bazel-docker-extract-debug amd64 # surface sipi-amd64.debug for sentry-cli just bazel-docker-push-amd64 # push as :v-amd64 + :latest-amd64 just bazel-docker-push-arm64 # push as :v-arm64 + :latest-arm64 just bazel-docker-publish-manifest # crane index append → daschswiss/sipi:v ``` Each per-arch CI runner builds + pushes only its matching architecture (`target_compatible_with` rejects cross-arch invocations). A coordinator job runs `crane index append` to stitch the two pushed digests into a multi-arch manifest at `daschswiss/sipi:v`. ## Cross-platform builds The full test matrix runs on macOS-aarch64, linux-x86_64, and linux-aarch64. CI exercises every variant on every platform; a green CI run verifies macOS as well as Linux. A macOS host cross-compiles the Linux OCI image directly — the hermetic-llvm toolchain declares every exec×target pair and bundles a per-target glibc + libc++ + compiler-rt, so no sysroot, VM, or host Linux toolchain is needed. `rules_foreign_cc` was the only thing that host-bound the build; with it gone (ADR-0015), every native `cc_library` (kakadu/libtiff/exiv2/…) compiles through the relocatable clang for the target platform: ``` just bazel-cross-build-image amd64 # build //src:sipi_image for linux-x86_64 just bazel-cross-build-image arm64 # build //src:sipi_image for linux-aarch64 ``` These are build-only (no `docker load`, since a macOS host has no Linux Docker daemon). Cross-compilation is a supported capability but is **not currently CI-gated** — verify it locally with the recipes above (a CI gate was prototyped and removed for being too slow; the approach is being reconsidered). To actually load/run the image, either use a Linux host's `bazel-docker-build-{amd64,arm64}` or a lightweight Linux VM such as [OrbStack](https://orbstack.dev/) with the dev shell available inside it (`nix develop` from a shared workdir). ## All `just` targets Run `just` with no arguments to see the live list. Key target groups: | Target | Description | | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `bazel-build [*FLAGS]` | `bazel build --stamp //src/cli:sipi` (fastbuild; pass `-c opt`/`--config=asan` etc.) | | `bazel-test [*FLAGS]` | `bazel test //test/unit/... //test/approval/... //test/e2e/...` (no coverage) | | `bazel-coverage [*FLAGS]` | Same target set, instrumented; emits combined lcov for Codecov | | `bazel-test-unit` | `bazel test //test/unit/...` | | `bazel-test-approval` | `bazel test //test/approval:approvaltests` | | `bazel-test-e2e [*FLAGS]` | All Rust e2e `rust_test` targets | | `bazel-test-smoke [*FLAGS]` | Docker smoke test (consumes Bazel-built image tarball) | | `image-scan [*FLAGS]` | grype gate: fail on fixed High/Critical CVEs in the image's OS packages (needs `grype`; on macOS pass `--platforms=//platforms:linux_*`) | | `bazel-build-sanitized [*FLAGS]` | `bazel build --config=asan --config=ubsan //src/cli:sipi` | | `bazel-cross-build-image {amd64,arm64}` | Cross-build `//src:sipi_image` for the Linux target arch (build-only; darwin→linux gate) | | `bazel-docker-build-{amd64,arm64}` | Build + load per-arch image as `daschswiss/sipi:latest` | | `bazel-docker-push-{amd64,arm64}` | Push to `daschswiss/sipi:{latest,v}-${arch}` | | `bazel-docker-publish-manifest` | `crane index append` → multi-arch manifest at `daschswiss/sipi:v` | | `bazel-docker-extract-debug arch` | Build `:sipi_debug_layout`, surface `sipi-.debug` | | `run` | `just bazel-build` then run sipi with the dev config | | `valgrind` | `just bazel-build` then run sipi under Valgrind | | `docs-build` | Build documentation site (`mkdocs build`) | | `docs-serve` | Serve documentation locally for preview | ## Documentation ``` just docs-build # build documentation site just docs-serve # serve documentation locally for preview ``` # Building with Bazel [Bazel](https://bazel.build/) is the build system for Vitrinli. It owns the entire build graph — every C/C++ target (sipi binary, the native third-party `cc_library` deps, unit + approval tests), the OCI Docker image, and the Rust e2e + smoke test binaries. [Nix](https://sipi.io/development/nix/index.md) is no longer the build orchestrator — it provisions the *dev shell* (bazelisk, `gh` for the Kakadu fetch, `crane`, `just`, etc.) and nothing else. ## Mental model A few concepts that make the rest of this page click: **MODULE.bazel** is the project's manifest. It declares the Bazel modules sipi depends on (`rules_oci`, the BCR `llvm` (hermetic-llvm) module, `rules_rust`, the BCR codec/util `bazel_dep`s, …) and pins the native-`cc_library` deps' source archives via `http_archive`. Version bumps live here. **BUILD.bazel** files describe the *target graph*. Each first-party package — `//src`, `//src/server/rust`, `//src/cli/rust`, `//test/unit/`, `//bazel/...` — has its own BUILD.bazel that declares its `cc_library`/`cc_binary`/`cc_test`/ `oci_image`/`rust_test` targets and visibility rules. **Hermetic toolchain.** The BCR `llvm` (hermetic-llvm) module, pinned at 0.8.25, registers a single constraint-based LLVM 23.1.2 toolchain that every cc action runs under — it serves all platforms. libc++ is the default stdlib. The bundle ships per-target glibc (~2.28) + libc++ + compiler-rt on Linux (no external Chromium debian sysroots) and fetches the macOS SDK hermetically from Apple's CDN (no host Xcode CLT). The host compiler version is irrelevant — `bazel build //src/cli:sipi` produces the same binary on macOS, linux-x86_64, and linux-aarch64 (modulo platform-specific codegen). See [ADR-0014](https://sipi.io/adr/0014-toolchain-provider-swap.md). **Stamping.** `tools/workspace_status.sh` reads `version.txt` and emits `STABLE_*` keys (`STABLE_SIPI_VERSION`, `STABLE_GIT_COMMIT`, …). `expand_template` substitutes them into `include/SipiVersion.h.in` so `sipi --version` reports the right string. Keys are also consumed by the `oci_image` rule to stamp Docker labels and tags. **Caching.** Bazel keeps three caches: | Cache | What it holds | Where | | ---------------- | ------------------------------------------- | --------------------------------------------- | | Action cache | Hashed action outputs (compile, link, test) | `bazel info output_base` | | Repository cache | Downloaded `http_archive` source tarballs | `~/.cache/bazel/_bazel_/cache/repos/v1` | | Disk cache | Action cache mirrored to a stable path (CI) | `~/.cache/bazel-disk` (CI only) | `bazel build //src/cli:sipi` after a single-file edit re-runs only the affected compile + link via the action cache — typically sub-second through link. ## Quick start ``` nix develop # bazelisk + host tools on PATH just bazel-build-server # bazel build --stamp //src/cli/rust:sipi (the Rust server shell) ./bazel-bin/src/cli/rust/sipi server --config config/sipi.localdev-config.lua # Subsequent edits: just bazel-build-server # incremental, sub-second through link ``` `just run` chains the two: it depends on `bazel-build` and starts sipi with the localdev config in one step. ## Common commands Every CI step invokes one of these recipes — there are no inline `bazel ...` invocations in workflows. ``` # Build sipi (fastbuild — fast incremental for inner-loop edits) just bazel-build # bazel build --stamp //src/cli:sipi just bazel-build --config=release # production build: -c opt + hardening (matches Docker image) just bazel-build --config=asan # ASan+UBSan; same flag form for ad-hoc variants # Tests just bazel-test-unit # bazel test //test/unit/... (12 components) just bazel-test-approval # bazel test //test/approval:approvaltests just bazel-test-e2e # Rust e2e tests via rules_rust just bazel-test-smoke # Docker smoke test (OCI tarball loaded by the test) # Coverage (canonical CI build — what ci.yml invokes on every PR) just bazel-coverage # unit + approval + e2e under instrumentation; # lcov at bazel-out/_coverage/_coverage_report.dat # Sanitizer just bazel-build-sanitized # bazel build --config=asan --config=ubsan //src/cli:sipi # Docker (rules_oci) just bazel-docker-build-amd64 # build + load amd64 image as daschswiss/sipi:latest just bazel-docker-build-arm64 # arm64 equivalent just bazel-docker-publish-manifest # crane index append → daschswiss/sipi:v just bazel-docker-extract-debug # produce sipi-.debug for sentry-cli ``` ## `--config=` flags Defined in `.bazelrc`. Each flag composes with `bazel build` / `bazel test` to switch the build configuration. | Flag | Effect | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `-c opt` | `-O3 -DNDEBUG`. Optimized codegen (the Docker image adds hardening — use `--config=release`). | | `--config=release` | `-c opt` + `_FORTIFY_SOURCE=2` hardening. The production build; what the Docker image ships. | | `-c dbg` | `-O0 -g`. Full debug symbols; what `bazel-build-sanitized` consumes. | | `--config=asan` | AddressSanitizer + DWARF inline; consults `.lsan_suppressions.txt` at e2e time. | | `--config=ubsan` | UndefinedBehaviorSanitizer. Composes with `--config=asan`. | | `--config=rbe-darwin` | Opt-in: compile on the NativeLink worker from an Apple Silicon Mac, tests run locally. See [Local use from macOS](https://sipi.io/development/rbe/#local-use-from-macos). | ## Querying the build graph `bazel query` answers structural questions about the target graph without running an action: ``` # What does //src/cli:sipi depend on? bazel query 'deps(//src/cli:sipi)' --output=label_kind | head -20 # Which targets transitively depend on //src/util:util? bazel query 'rdeps(//..., //src/util:util)' --output=label # Which BUILD files declare cc_test targets? bazel query 'kind("cc_test", //test/unit/...)' --output=label # What sources does //src/cache:cache_test compile? bazel query 'attr("srcs", "", //src/cache:cache_test)' --output=build ``` `bazel cquery` is the configured-graph variant: it accounts for `select()` and platform-specific deps, useful when querying targets that vary by config (`//src:sipi_image` is `target_compatible_with`-gated to Linux, etc.). ## Cache hygiene CI cache strategy is documented in `.github/workflows/ci.yml` (see the long "CACHE STRATEGY" comment block): - Disk cache managed by `actions/cache@v5` (not `setup-bazel`'s built-in disk-cache wiring) so an analysis-phase failure cannot 0-byte-poison the cache. - Targeted key formula on inputs that actually affect the native-dep action keys: `MODULE.bazel{,.lock}`, `bazel/**`, `.bazelrc`, `.bazelversion`, `flake.lock`. App/test sources are deliberately excluded. - Repository cache off in CI (would persist ~4 GB per arch and evict the real disk-cache speedup). Locally, `bazel clean` flushes per-action outputs while preserving downloaded archives; `bazel clean --expunge` flushes everything including the repository cache. ## Kakadu The proprietary Kakadu SDK is fetched at build time by a custom `gh_release_archive` repository_rule (`bazel/gh_release.bzl`) that shells out to `gh release download` against `dasch-swiss/dsp-ci-assets`. Auth flows through `GH_TOKEN`; locally `gh auth login` once is enough, in CI the workflow injects `GH_TOKEN: ${{ secrets.DASCHBOT_PAT }}` on every Bazel-invoking step. See [Kakadu setup](https://sipi.io/development/kakadu/index.md) for the full version-bump procedure. ## Cross-platform Linux-only targets (`//src:sipi_image`, `//src:image_load`, `//src:image_push_*`, `//src:sipi_debug_layout`) are gated by `target_compatible_with = ["@platforms//os:linux"]` — on the **target** OS, not the host. A macOS host builds them by setting the target platform explicitly (`--platforms=//bazel/platforms:linux_{amd64,arm64}`), which the hermetic-llvm toolchain cross-compiles end to end (bundled per-target glibc + libc++; no sysroot). `just bazel-cross-build-image {amd64,arm64}` wraps this. Cross-compilation is **not currently CI-gated** (a gate was prototyped and removed for being too slow; the approach is being reconsidered) — verify it locally. Without a `--platforms` override the default host platform on macOS is darwin, which fails the linux gate and skips the target. Fuzzing has its own opt-in config. `//src/iiifparser/fuzz:parse_request_fuzz` builds and corpus-replays everywhere by default; `--config=fuzz` arms the real libFuzzer engine and is Linux-only. See [Fuzzing](https://sipi.io/development/fuzzing/index.md). For Linux-target builds from a macOS host, see [Building from source](https://sipi.io/development/building/#cross-platform-builds). ## Reference - [`MODULE.bazel`](https://github.com/dasch-swiss/vitrinli/blob/main/MODULE.bazel) — module manifest + every third-party `http_archive` pin - [`.bazelrc`](https://github.com/dasch-swiss/vitrinli/blob/main/.bazelrc) — flag defaults, sanitizer/fuzz configs, production hardening (stack-protector-strong, \_FORTIFY_SOURCE=2, stack-clash-protection, BindNow) with per-config exemptions for asan/ubsan (which `--config=fuzz` inherits when paired with them) - [`tools/workspace_status.sh`](https://github.com/dasch-swiss/vitrinli/blob/main/tools/workspace_status.sh) — emits `STABLE_*` keys consumed by `expand_template` and `oci_image`'s stamping - [Bazel: BUILD files](https://bazel.build/concepts/build-files) - [Bazelmod (`MODULE.bazel`)](https://bazel.build/external/module) - [`rules_oci`](https://github.com/bazel-contrib/rules_oci) - [`cmake_configure_file`](https://github.com/wep21/cmake_configure_file) - [hermetic-llvm (`llvm` BCR module)](https://github.com/hermeticbuild/hermetic-llvm) - [ADR-0014: toolchain provider swap](https://sipi.io/adr/0014-toolchain-provider-swap.md) # Nix dev shell Nix's role in Vitrinli is **dev-shell provisioning only**. It assembles a reproducible bash environment with bazelisk, `gh` (consumed by the `gh_release_archive` repository_rule for the Kakadu fetch), `crane` (used by `bazel-docker-publish-manifest`), and `jpylyzer` (JP2 conformance validator). No host C/C++ build tools are needed — every dep is a BCR `bazel_dep` or a native `cc_library` compiled by the hermetic LLVM toolchain. Rust + LLVM toolchains are provisioned hermetically by Bazel (`rules_rust` + the BCR `llvm` (hermetic-llvm) module in `MODULE.bazel`) — the Bazel cc actions never use the dev-shell `clang`. It is **not** the build system. Vitrinli's binaries, tests, and Docker image are all produced by Bazel. See [Building with Bazel](https://sipi.io/development/bazel/index.md). ## One-time setup **Install [Determinate Nix](https://docs.determinate.systems/).** The Determinate installer enables flakes and `nix develop` by default. macOS and Linux are both supported. ``` curl -fsSL https://install.determinate.systems/nix | sh -s -- install ``` After the installer finishes, restart your shell and verify: ``` nix --version ``` That's the entire setup. There is no Cachix dependency, no Kakadu FOD pre-fetch step, and no GH_TOKEN export needed at the shell layer (the `gh_release_archive` Bazel repository_rule reads `GH_TOKEN` itself from the build environment; locally `gh auth login` is enough). ## Entering the dev shell ``` nix develop # default shell — Clang + libc++ + host tools just bazel-build # subsequent commands work as usual ``` Three shells are exposed: | Shell | Stdenv | Purpose | | ------------ | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `default` | `llvmPackages_19.libcxxStdenv` | Clang + libc++ for non-Bazel tooling (clang-tidy, ad-hoc shell compiles). The Bazel cc actions run under the hermetic LLVM 23.1.2 toolchain, not this stdenv. 99% of work happens here. | | `gcc` | `pkgs.gcc14Stdenv` | Diagnostic escape hatch when the LLVM toolchain produces a confusing error. Not used by CI. | | `llvm-tools` | `llvmPackages_19.libcxxStdenv` | `default` + `llvmPackages_19.llvm` (host `llvm-cov`, `llvm-profdata`). For LOCAL coverage runs only — local devs running `just bazel-coverage` should enter this shell. CI resolves the same tools hermetically from the Bazel toolchain (`//bazel:llvm-*` aliases), not from this shell. Sanitizer runs no longer need it: the e2e macro attaches the hermetic `//bazel:llvm-symbolizer` as a test runfile under `--config=asan`. | ``` nix develop .#gcc # GCC + libstdc++ environment nix develop .#llvm-tools # default + LLVM host binaries on PATH ``` `bazel build` invokes its own hermetic LLVM toolchain regardless of which shell is active — the dev-shell stdenv only matters for ad-hoc shell-level compilation. ## What's on the PATH `flake.nix` is the source of truth (60 lines, dev-shells only). Highlights: - **bazelisk** + a `bazel` shim — reads `.bazelversion` and downloads the matching Bazel. - **gh, cacert** — the `gh_release_archive` Bazel repository_rule shells out to `gh release download`; `cacert` provides a TLS bundle on headless Linux dev shells. - **go-containerregistry** — provides `crane`, used by `just bazel-docker-publish-manifest` to assemble the multi-arch manifest from per-arch digests. - **just** — recipe runner. - **python3Packages.jpylyzer** — JP2 conformance validator used to verify regenerated JP2 goldens (see ADR-0010). - **llvmPackages_19.llvm** *(coverage shell only)* — `llvm-cov` / `llvm-profdata` for `just bazel-coverage`. Bazel's `collect_cc_coverage.sh` hard-requires `COVERAGE_GCOV_PATH` and `LLVM_COV` env vars on every test action; the justfile recipe resolves them via `$(command -v llvm-{cov,profdata})`. ## Shell hooks The default shell hook does two things: - Exports `SSL_CERT_FILE` from the `cacert` package so `gh`'s Go-based TLS works on headless Linux dev shells. - On macOS, prepends `/usr/bin` to `PATH` so Apple's `/usr/bin/xcrun` resolves ahead of nixpkgs' xcbuild stub (which returns the apple-sdk-14.4 stub — private frameworks only, no `libc++.tbd`). Note: the hermetic-llvm toolchain now fetches the macOS SDK from Apple's CDN, so the Bazel cc actions no longer depend on this `xcrun` SDK probe; the hook is retained for host tools that still shell out to `xcrun`. ## direnv If you use [direnv](https://direnv.net/), drop a one-line `.envrc`: ``` # .envrc use flake ``` `direnv allow` once and the dev shell auto-activates whenever you `cd` into the repo. Combined with editor integrations (e.g. JetBrains [direnv plugin](https://plugins.jetbrains.com/plugin/15285-direnv-integration), [VS Code direnv extension](https://marketplace.visualstudio.com/items?itemName=Rubymaniac.vscode-direnv)) this gives the IDE the same PATH/env as the terminal. # CI and Release This page documents Vitrinli's CI pipeline and release automation. ## Release automation (release-please) Releases are fully automated via [release-please](https://github.com/googleapis/release-please). When commits are merged to `main`, release-please reads their [Conventional Commit](https://www.conventionalcommits.org/) prefixes to determine the SemVer bump and generate the changelog. **Configuration files:** - `.github/release-please/config.json` — changelog sections, release type - `.github/release-please/manifest.json` — current version - `.github/workflows/release-please.yml` — GitHub Actions workflow **How commit types map to releases:** the type → changelog-section → SemVer-bump table is single-sourced in [Commit and PR Conventions § Commit message schema](https://sipi.io/development/commit-conventions/#commit-message-schema). The machine source release-please actually reads is [`.github/release-please/config.json`](https://sipi.io/.github/release-please/config.json). Every commit appears in the release notes in its own section, and — because the scope is mandatory — each line reads `concern: subject`. A release containing only internal-work commits (`refactor`/`docs`/`test`/`build`/`chore`) is a patch release: release-please keeps a release PR open for it, and the maintainer decides when to merge it. Correct type + scope are critical, and enforced A commit without a valid type is invisible to release-please — it won't trigger a release or appear in the changelog. Both the type (one of the eight allowed) and a mandatory scope are enforced in CI by the `commit-lint` job (`commitlint-rs`). See [Commit and PR Conventions](https://sipi.io/development/commit-conventions/index.md) for the full schema, the scope vocabulary, what `fix:` means, and `just commit-lint`. ## Pull request CI Workflow: `.github/workflows/ci.yml`. Trigger: `pull_request` plus manual `workflow_dispatch`. No Nix anywhere in this workflow — every job provisions Bazel and `just` on a plain GitHub-hosted runner via the `.github/actions/ci-setup` composite action (see "CI environment provisioning" below). Nix remains the local dev-shell provisioner only. ### `changes` gate A `changes` job runs first and inspects the diff to decide whether the sanitizer job (below) needs to run: it looks for changes under `src/`, `include/`, `test/`, `bazel/`, `platforms/`, `config/`, `scripts/`, `MODULE.bazel*`, `.bazelrc`, `.bazelversion`, `BUILD.bazel`, `justfile`, `.lsan_suppressions.txt`, `ci.yml`, and `.github/actions/`. A docs-only PR skips the sanitizer job — a skipped required job still satisfies branch rulesets. The `test` matrix has no `needs:` on this job and starts immediately, in parallel with it. A manual `workflow_dispatch` run bypasses the filter and always runs the sanitizer job. ### Test matrix The `test` job runs on three platforms — `linux-amd64`, `linux-arm64`, `darwin-arm64` — and all three legs start immediately; none of them wait on a separate lint gate. Every leg runs: 1. **Build + test** — `just bazel-test` (fastbuild, no instrumentation; unit + approval + e2e in a single Bazel invocation). 1. **Docker smoke tests (Linux only)** — `just bazel-test-smoke` builds `//src:sipi_image` as a transitive `data` dep of the `:docker_smoke` rust_test, the test loads the OCI tarball into the local Docker daemon, and runs the smoke suite against the loaded container. 1. **Image CVE gate (Linux only)** — `just image-scan` runs grype (pinned release, installed in-job) over the image tarball the smoke step built, and fails on any High/Critical CVE with a fixed version in the OS packages (distroless base + `bookworm.lock.json`). `.grype.yaml` documents the false positives it ignores. 1. **Docker Scout** (linux-amd64 PRs only, one leg — a single PR comment, informational, never fails the job): `Docker Scout — compare to production`, `Docker Scout — CVE report (SARIF)`, and `Upload SARIF to GitHub Security`. The standalone `lint` job is gone. Its lint checks — `bazel-rustfmt-check` and `bazel-clippy-check` — now run as extra steps inside the `test / linux-arm64` leg, the shortest of the three legs, instead of gating the matrix from a separate job. A separate `docs` job runs `just docs-build` (mkdocs strict-mode build) on ubuntu-latest. The `docs-build` job is the gate that catches broken cross-links and stale nav entries on every PR. ### Path-gated sanitizer job The `sanitizer` job (`asan-ubsan / amd64`) runs ASan+UBSan over the unit and e2e suites in a single `just bazel-test-sanitized` invocation, gated by the `changes` job above. Running both suites in one `bazel test` compiles the instrumented `sipi` tree exactly once — a single action graph shares the ~5500-file compile across both suites (two separate jobs would each compile the full tree). Runs on linux-x86_64 only (the macOS toolchain args omit the sanitizer header path). ASan/LSan symbol resolution uses the hermetic LLVM 23.1.2 `//bazel:llvm-symbolizer` (version-matched to clang 23.1.2), which the e2e macro attaches as a test runfile under `--config=asan` and points `ASAN_SYMBOLIZER_PATH` at — so the tests (unit + e2e) execute on the RBE worker, symbolizer included, rather than on the runner. ### Dependency advisory scan A `dependency-audit` job runs `just audit` against the checked-in Cargo-format lockfile — see "Dependency advisory scanning" below for what it covers. Self-contained (no Bazel/RBE setup); not currently a required branch-protection check. ### CI environment provisioning Every Bazel-invoking job in `ci.yml` (and in `publish.yml`, `coverage.yml`, `fuzz.yml`) starts with the `.github/actions/ci-setup` composite action, which wraps: - `bazelbuild/setup-bazelisk` — bazelisk on PATH (reads `.bazelversion`). - `extractions/setup-just` — `just` on PATH. - Optional git-LFS restore/pull (test images), when the job needs them. - The Bazel repository cache (`actions/cache` over `~/.cache/bazel-repo`), keyed on `MODULE.bazel.lock`. - The existing `.github/actions/bazel-rbe` composite action, for the RBE mTLS material and cross-compile flags. `gh` is preinstalled on GitHub-hosted runners, so no setup step provisions it. `GH_TOKEN` is passed as plain step `env:` on the `just bazel-*` invocation that needs it (the `gh_release_archive` repository_rule shells out to `gh release download` for the Kakadu fetch) — there is no Nix-impure-env hack involved. ### Forked PR behavior Every Bazel-invoking step sets `GH_TOKEN: ${{ secrets.DASCHBOT_PAT }}` on its `env:` so the `gh_release_archive` repository_rule can authenticate. Forked PRs don't have access to `DASCHBOT_PAT`, so the Kakadu fetch fails and the build short-circuits. Internal PRs are unaffected. ### Required checks Branch rulesets require the three `test / *` legs (`test / linux-amd64`, `test / linux-arm64`, `test / darwin-arm64`) plus the `asan-ubsan / amd64` job. The `docs` job, the `dependency-audit` job and the `changes` gate itself are not required checks. (The asan-ubsan job was previously split into `asan-ubsan-unit / amd64` + `asan-ubsan-e2e / amd64`; the ruleset must be updated to the merged name.) **`main` is protected by a *ruleset*, not by classic branch protection.** `GET /repos/dasch-swiss/vitrinli/branches/main/protection` therefore answers `404 Branch not protected`, which is true only of the classic mechanism and says nothing about the ruleset. Read the rules from the rulesets API instead, or just read this section: ``` gh api repos/dasch-swiss/vitrinli/rulesets # find the ruleset id gh api repos/dasch-swiss/vitrinli/rulesets/ --jq '[.rules[].type]' ``` The same ruleset pins **`rebase` as the only allowed merge method** (alongside `required_linear_history`), so `gh pr merge --squash` and `--merge` are rejected. This is the mechanism behind the "a PR lands as one commit by default" convention in `CLAUDE.md`: every branch commit reaches `main` verbatim, with no squash to tidy it, which is why branches are cleaned up before merge. Note that dsp-api and dsp-app are the opposite — squash-only — so the habit does not carry between repos. ## Post-merge coverage Workflow: `.github/workflows/coverage.yml`. Trigger: `workflow_dispatch` only (manual runs) — see the workflow's header comment for why the `push: branches: [main]` trigger stays disabled under the current hermetic-llvm toolchain. A single `linux-amd64` job runs via `ci-setup` and calls `just bazel-coverage`. The recipe's `collect_cc_coverage.sh` needs `COVERAGE_GCOV_PATH`/`LLVM_COV` on PATH; those resolve from the hermetic Bazel toolchain's `//bazel:llvm-profdata`/`//bazel:llvm-cov` aliases, not from a Nix dev shell — no `.#llvm-tools` shell is involved in CI. The combined lcov report at `bazel-out/_coverage/_coverage_report.dat` is uploaded to Codecov. **Why split out:** Coverage instrumentation adds 1.5–2× compile overhead and slower test runtime; running it on every PR push across three platforms wasted CI minutes without commensurate signal. Per-PR coverage delta in Codecov is the trade-off — drift shows up immediately after merge instead. To restore PR-scoped signal selectively, add a `pull_request: paths: ['src/**']` trigger to this workflow. ## Dependency advisory scanning Workflow: `.github/workflows/ci.yml`, job `dependency-audit`. Runs `just audit` — `cargo-audit` and `osv-scanner` (installed in-job; neither is in the Nix dev shell) scanning `Cargo.Bazel.lock`, the checked-in Cargo-format lockfile materialized by `crate.from_specs(cargo_lockfile = ...)` in `MODULE.bazel` (`crate_universe`'s own `MODULE.bazel.lock` is JSON, which neither tool reads). Repin with `CARGO_BAZEL_REPIN=1 bazel build //src/server/rust:lib` after any `crate.spec()` change. Covers the single `@crates` hub: server, cli, scripting and the e2e suite. Dependabot is off: no version-update or security-update PRs. GitHub Actions, the Nix flake inputs and the BCR `bazel_dep`s are bumped by hand. This closes one gap, not the whole dependency surface: `dependency-audit` does not see the native `http_archive` / `cc_library` pins below — they have no lockfile-based advisory feed. The OS/runtime packages in the *image layers* are gated by `just image-scan` in the `test` job (grype, fails on fixed High/Critical) and reported by Docker Scout (`ci.yml`'s PR-time report and `publish.yml`'s release-time Critical gate). Neither reaches these statically-linked libraries. A failing `image-scan` is fixed by bumping the snapshot in `bazel/distroless/bookworm.yaml` (then `bazel run @bookworm//:lock`) or the `distroless_base` digest in `MODULE.bazel`. ### Quarterly native-pin review Manually check each project's release page against the pinned version in `MODULE.bazel` and CVE feeds (NVD, GitHub Advisory Database) for the pinned version. Bump via a normal version-pin PR (update `sha256`/`strip_prefix`/`url` or the BCR module version) when a fix is available. **Native `cc_library` (`http_archive`, hand-pinned — see [ADR-0015](https://sipi.io/adr/0015-native-cc_library-over-foreign_cc.md)):** | Dependency | Pinned via | Releases | | ---------- | --------------------------------------------------------- | --------------------------------------------------------------------------------- | | libtiff | `tiff` `http_archive` | | | exiv2 | `exiv2` `http_archive` | | | lcms2 | `lcms2` `http_archive` | | | jansson | `jansson` `http_archive` | | | jbigkit | `jbigkit` `http_archive` | no GitHub releases; upstream page: | | mimalloc | `mimalloc` `http_archive` | | | tracy | `tracy` `http_archive` (dev-only, `--config=tracy`-gated) | | | Kakadu | `kakadu_extension` (proprietary, license-gated) | (private, org-restricted) | **BCR `bazel_dep` drop-ins** (image codec / parsing surface — see CLAUDE.md's Dependencies table for the full BCR list; excludes pure build-tooling deps like `rules_cc`/`rules_rust`/`rules_python`): | Dependency | Releases | | ------------- | ------------------------------------------------------------------------- | | libpng | | | libjpeg_turbo | | | libwebp | | | libdeflate | | | zlib | | | bzip2 | no GitHub releases; upstream page: | | xz | | | zstd | | | sqlite3 | no GitHub release notes; changelog: | | libexpat | | | libmagic | | | Lua | no GitHub releases; upstream page: | | curl | | | OpenSSL | | | protobuf | | ## Tag release CI/CD Workflow: `.github/workflows/publish.yml`. Trigger: tag push matching `v*`. Like `ci.yml`, every Bazel-invoking job provisions its environment via the `.github/actions/ci-setup` composite action — no Nix. Gate model: 1. `validate-docker / {amd64, arm64}` — each per-arch runner builds the Docker image via `just bazel-docker-build-${arch}` and runs `just bazel-test-smoke` against it. 1. `release-gate` — fires on `validate-docker` success. 1. Publish jobs run after the gate: 1. `publish-docker / {amd64, arm64}` — rebuilds the per-arch image, extracts the `.debug` file via `just bazel-docker-extract-debug ${arch}`, pushes via `just bazel-docker-push-${arch}`, records the image with Docker Scout, runs a Docker Scout CVE gate (`only-severities: critical`, `exit-code: true` — fails the job on any Critical finding in the image layers; see "Dependency advisory scanning" above for what this does and doesn't cover), uploads SBOM, pushes debug symbols to Sentry. It does not repeat the smoke test — `validate-docker` already validated the same commit. 1. `manifest` — needs `publish-docker`; runs `just bazel-docker-publish-manifest` (`crane index append`) to assemble the multi-arch manifest at `daschswiss/sipi:v` from the two pushed per-arch digests, and tags it `:latest`. Provisioned via `imjasonh/setup-crane` + `extractions/setup-just` only — no Bazel/RBE setup, since the recipe only shells out to `crane`. 1. `sentry` — also needs `publish-docker` directly and runs in parallel with `manifest` (not after it), finalising the Sentry release. 1. `docs` — needs `release-gate`; mkdocs deploy. ## Remote build execution and caching CI builds run on a self-hosted **NativeLink Remote Build Execution** backend: a single x86_64 worker that cross-compiles all three target arches (`linux-amd64`, `linux-aarch64`, `darwin-aarch64`), fronting a remote cache (AC + CAS, mTLS). Clients reach it through the proxy on `rbe-01.ops.dasch.swiss:443`, the only externally reachable port. The connection, mTLS, and cross-compile flags are assembled by the [`bazel-rbe`](https://sipi.io/.github/actions/bazel-rbe) composite action and injected per workflow step — Bazel does not expand env vars in `.bazelrc`, so they live in the workflow, not the rc file. The backend-agnostic tuning flags (`--remote_download_minimal`, `--remote_local_fallback`, `--remote_timeout`, `--remote_max_connections`) live in `.bazelrc` and are no-ops without a remote configured; the cross-leg flags live in `.bazelrc` `build:rbe-cross`. See **[Remote build execution](https://sipi.io/development/rbe/index.md)** for the full topology, the cross-compile flag rationale, and the developer-facing workflow, and the [`ops-tf`](https://github.com/dasch-swiss/ops-tf) / [`infra`](https://github.com/dasch-swiss/infra) repos (private) for the VM provisioning and the NativeLink service configuration. ## Local reproduction Every CI step invokes `just ` — there are no inline `bazel ...` calls in any workflow. CI itself runs Nix-free (see "Pull request CI" above); locally, Nix still provisions the dev shell. To reproduce any CI job locally, run the same recipe inside `nix develop`. With a personal client certificate, add `--config=rbe-darwin` on a Mac to compile on the worker (see [Local use from macOS](https://sipi.io/development/rbe/#local-use-from-macos)): ``` nix develop # Full PR test job, one arch (matches `ci.yml test`) just bazel-test just bazel-test-smoke # Coverage (matches `coverage.yml`; needs the .#llvm-tools shell locally) nix develop .#llvm-tools --command just bazel-coverage # Sanitizer unit + e2e (matches the `sanitizer` job in ci.yml) just bazel-test-sanitized --config=asan --config=ubsan # Docker image with split debug symbols (what publish.yml does) just bazel-docker-build-amd64 just bazel-test-smoke just bazel-docker-extract-debug amd64 just bazel-docker-push-amd64 just bazel-docker-publish-manifest ``` **CI invokes justfile only.** If a CI step is not a `just ` invocation, that's a drift signal — either the step is non-build glue (e.g. artifact upload, Codecov upload, Sentry push) or the justfile is missing a recipe and should grow one. ## Fuzz testing Workflow: `.github/workflows/fuzz.yml`. Trigger: `schedule` at `17 3 * * *` (03:17 UTC) plus manual `workflow_dispatch` — the repo's only scheduled workflow. One job on `ubuntu-24.04`: it restores the previous nightly's working corpus from the `fuzz-corpus` artifact, builds the instrumented libFuzzer binary with `just bazel-build-fuzz` (RBE-eligible, `bep-fuzz` artifact attached like the other legs), fuzzes `//src/iiifparser/fuzz:parse_request_fuzz` for 600s, minimizes and re-uploads the corpus, then runs a 300s ASan-paired pass. Linux-amd64 only — `--config=fuzz` cannot link the libFuzzer runtime on darwin, exactly like the sanitizer gate. macOS coverage is the corpus-replay mode of the same target, which rides along in the `//src/...` test sweeps on every PR. A crash makes libFuzzer exit 77, which fails the job; the reproducers and logs upload as a `fuzz-crashes` artifact and triage is manual. See [Fuzzing](https://sipi.io/development/fuzzing/index.md) for the harness, the corpus policy, and the recipes. # Remote Build Execution This page documents Vitrinli's Remote Build Execution (RBE) setup: its purpose, how the cross-compilation pattern works, the key correctness fix in the hermetic-llvm toolchain, measured performance characteristics, and how CI wires everything together. The backend (`dasch-remotebuild-prod-01`) is DaSCH-hosted and defined outside this repo: the libvirt VM in [`ops-tf`](https://github.com/dasch-swiss/ops-tf) (`live/virt-03/prod/vms/`), the NativeLink/bazel-remote service configuration in [`infra`](https://github.com/dasch-swiss/infra) (`OS/ansible/roles/dasch.nativelink`, including its README and store-topology notes). ## Why Vitrinli uses RBE The goal is **cross-compilation**: building all three supported targets — `linux-amd64`, `linux-aarch64`, and `darwin-aarch64` — on a single x86_64 worker, so each GitHub Actions runner does not need a native matching toolchain. Without RBE each platform leg runs its full compile on the runner that matches its arch. The hermetic-llvm toolchain (see [Building with Bazel](https://sipi.io/development/bazel/index.md)) can cross-compile end-to-end (bundled per-target glibc + libc++; no sysroot), so it can build all three targets on a single x86_64 machine. RBE is the mechanism that routes those compiles to a shared x86_64 worker regardless of which runner triggered the build. Speed is not the justification. On a warm cache, RBE and the previous cache-only setup have essentially identical per-PR wall-clock latency (see [Performance](#performance)). ## Architecture ### Backend A self-hosted NativeLink VM acts as the single Bazel backend. It runs two services: | Service | Port | Protocol | Purpose | | ------------ | -------- | ----------- | ------------------------------------------------------------------------ | | NativeLink | `:50051` | gRPC + mTLS | Remote Cache (AC + CAS) + Remote Executor | | bazel-remote | `:50052` | gRPC + mTLS | `http_archive` download cache; no client configures it today (see below) | Both ports are internal. From outside the DaSCH network the only reachable port is `rbe-01.ops.dasch.swiss:443`, a proxy in front of NativeLink; every client, CI included, connects there (`grpcs://rbe-01.ops.dasch.swiss:443`). Both services present a certificate signed by the same NativeLink CA, so a single `--tls_certificate` flag validates both, with no CA bundle. No client sets `--experimental_remote_downloader` today (see the remote section of `.bazelrc`): Bazel fetches a `FetchBlob` digest's bytes from the `--remote_cache` CAS, so a downloader that does not share that CAS is unusable. External archives are cached client-side by `--repository_cache`. When a client does point the downloader at bazel-remote, it caches the source tarballs for `http_archive` rules (jbigkit, the Apple macOS SDK, etc.). On a `FetchBlob` miss bazel-remote fetches the URL itself, verifies the `sha256` qualifier, stores the blob, and every later request for that hash is a permanent hit. The first successful build after an upstream is reachable from the VM warms it for good; no manual step is required. See [Bazel issue #14646](https://github.com/bazelbuild/bazel/issues/14646) for the known limitation: when the VM cannot reach an upstream the runner CAN reach, a green local-fallback build does not write back to the download cache. ### Why a separate bazel-remote, not just NativeLink NativeLink *does* implement the Remote Asset API (`FetchServer` / `PushServer`, `build.bazel.remote.asset.v1`), so the obvious question is why we don't point `--experimental_remote_downloader` at `:50051` and drop bazel-remote. The reason is *how* each implements `FetchBlob`: - **NativeLink's Fetch is push-then-serve.** `fetch_blob` (nativelink-service `fetch_server.rs`) hashes the URI + qualifiers to a digest, does a single store lookup, and on a miss returns `NotFound` — it never contacts the upstream. It only serves assets that were *explicitly pushed* into its `fetch_store` first. (Its only `reqwest` HTTP client backs the GCS store, not URL fetching.) - **bazel-remote's Fetch is a transparent proxy.** On a miss it fetches the URL itself, verifies the `sha256` qualifier, stores the blob, and serves it thereafter. `--experimental_remote_downloader` relies on the proxy behavior — it expects the endpoint to transparently mirror `http_archive` tarballs on first use. Replacing bazel-remote with NativeLink's FetchServer would mean building a separate warming pipeline that fetches every external dependency and pushes it (blob + asset mapping) into NativeLink ahead of the build, i.e. reimplementing bazel-remote's proxy logic. So the two services are not redundant: NativeLink caches and runs *build actions* (AC/CAS + executor); bazel-remote transparently mirrors *source downloads*. (Verified against NativeLink v1.5.2 — revisit if a later release adds proxy-fetch-on-miss.) ### GitHub Actions wiring The `.github/actions/bazel-rbe` composite action encapsulates all RBE wiring: 1. It reads the org-level secrets `REMOTEBUILD_CA_CERT`, `REMOTEBUILD_CLIENT_CERT`, `REMOTEBUILD_CLIENT_KEY` and the variable `REMOTEBUILD_RUNNER_ENDPOINT` (the NativeLink RE-API, through the `:443` proxy). 1. It writes the mTLS material outside the workspace checkout (`$RUNNER_TEMP/.nl/`) so cert files can never enter a Bazel action's input set. 1. It emits a `flags` output — a single Bazel flag string — that every subsequent `just bazel-*` invocation appends verbatim. Fork PRs do not have access to org secrets; the action emits an empty `flags` string and the build falls through to a cold local build. `ci.yml`'s test matrix passes `matrix.bazel-platform` (`//platforms:linux_x86_64`, `//platforms:linux_aarch64`, or `//platforms:darwin_aarch64`) as the `target-platform` input to the composite action, so each leg cross-compiles for its own target on the worker. ## The cross-compile + test-local pattern ### The problem `rules_rust` exec-config tools — `process_wrapper`, build scripts, proc-macros — must run on the exec platform (the x86_64 worker). When a cross leg runs on an arm64 or darwin runner, these tools would otherwise resolve their exec platform to the LOCAL host (per [rules_rust #327](https://github.com/bazelbuild/rules_rust/issues/327)), shipping an arm64 or darwin binary to the x86_64 worker where it cannot execute. C++ was unaffected because hermetic-llvm registers cross toolchains for both `exec=x86_64 → target=aarch64` directions out of the box. Rust did not. ### The fix Five changes work together: **1. Cross Rust toolchains** (`MODULE.bazel`): ``` rust.toolchain( ... extra_target_triples = ["aarch64-unknown-linux-gnu", "aarch64-apple-darwin"], ) ``` This registers the exec=x86_64 → aarch64 cross Rust toolchains so `rules_rust` exec-config tool resolution no longer falls through to the host. **2. Exec platform declaration** (`platforms/BUILD.bazel`): `//platforms:linux_x86_64` carries `exec_properties = {cpu_arch: x86_64}`, mirroring `--remote_default_exec_properties`. NativeLink routes actions to the worker on that property. **3. `--extra_execution_platforms`** (composite action, all legs): ``` --extra_execution_platforms=//platforms:linux_x86_64[,] ``` `//platforms:linux_x86_64` is listed first so compiles and exec-config tools resolve to the worker. The target platform is appended on cross legs so Bazel's default test toolchain (`default_test_toolchain_type`, new in Bazel 9) can resolve an exec platform matching the target arch, which the test runner needs. **4. `--host_platform`** (`.bazelrc` `build:rbe-cross`, cross legs only): ``` --host_platform=//platforms:linux_x86_64 ``` This pins `rules_rust`'s exec transition to x86_64 per the rules_rust #327 pattern. Not applied on the amd64 leg (host and worker already match). **5. `--noremote_local_fallback`** (`.bazelrc` `build:rbe-cross`, cross legs only): If the worker is unreachable and the build falls back to the local arm64/darwin runner, the x86_64 `process_wrapper` binary would be dispatched there and crash. Cross legs therefore disable local fallback. The amd64 leg retains the `.bazelrc` graceful fallback. ### Where tests execute ``` --strategy=TestRunner=local # cross legs only (arm64/darwin) ``` **Cross legs (arm64/darwin).** Test binaries are cross-compiled on the x86_64 worker but executed locally on the native runner — the cross-built binary can't run on the x86_64 worker, and the runner has the right kernel ABI and filesystem. `bazel-rbe` emits `--config=rbe-cross`, which sets `--strategy=TestRunner=local`, only on these legs. **Native x86_64 legs (amd64 `test` + `sanitizer`).** Tests EXECUTE on the worker (exec == target == x86_64): results cache remotely and the runner skips the multi-GB output download under `--remote_download_minimal`. The e2e tests are tagged `exclusive-if-local` (see below), so on isolated workers they run in parallel rather than serially. Under `--config=asan` the e2e macro attaches `//bazel:llvm-symbolizer` as a runfile and sets `ASAN_SYMBOLIZER_PATH` to its runfiles path, so the sanitizer e2e tests run remotely too (a runner-side absolute symbolizer path would not exist on the worker). `docker_smoke` is the sole local exception, kept on the runner by its plain `exclusive` tag and its Docker-daemon dependency. ### The `exclusive-if-local` and `no-sandbox` tags on e2e tests E2E tests are tagged `exclusive-if-local` and `no-sandbox` in `test/e2e/sipi_e2e_test.bzl` (`docker_smoke` keeps plain `exclusive` in `test/e2e/BUILD.bazel`). Neither is `local`, and that is permanent and correct. - `exclusive-if-local` runs the tests serially only when they execute locally (dev, cross legs), preventing port collisions between binaries that all bind `11024 + PID % 16384` on the shared runner. On the native x86_64 RBE leg each test runs on its own isolated worker, so there is no shared port range and Bazel runs them in parallel. Plain `exclusive` would disable remote execution entirely — Bazel can't guarantee exclusivity on a machine it doesn't own — which is why `docker_smoke` (which must stay on the runner for its Docker daemon) keeps `exclusive`. - `local` propagates to the test's COMPILE action and pins the compile to the runner. On a cross leg this routes an arm64/darwin process_wrapper to the x86_64 worker — it crashes. `local` breaks cross-compilation. - `no-sandbox` disables the Bazel sandbox for the TEST RUN only (the compile is unaffected). It does not prevent cross-compilation. The reason e2e tests need `no-sandbox` at all: Vitrinli's `validate_resolved_path` guard in `src/server/rust/src/path.rs` canonicalises the request path via `realpath(3)` (Rust's `std::fs::canonicalize`). Under the Bazel sandbox, path resolution returns the writable runfiles path rather than the `TEST_TMPDIR` copy, so sipi rejects legitimate test files with HTTP 400. Disabling the sandbox sidesteps this runfiles-symlink interaction. This is also the open question when e2e tests execute remotely: the NativeLink executor must honor `no-sandbox` (materialise real files under a stable root) for the guard to pass. The guard itself is correct and must not be weakened for testing. ## The hermetic-llvm headers glob patch ### The problem Remote execution requires every action input to be declared as a discrete file so Bazel can construct the action's Merkle input tree. If an input is a bare source-directory artifact (one opaque directory node), Bazel references the directory but its subtree may not be enumerated — the include subdirectory is dropped from the Merkle tree, and the remote executor receives an incomplete input set. Local sandboxed builds follow the directory symlink and succeed. Remote builds fail with `fatal error: 'linux/limits.h' file not found`. Warm action-cache hits skip the compile entirely and mask the gap, so the failure is deterministic only on a cold cache and appears intermittent on a warm one. hermetic-llvm injects the Linux kernel + glibc system headers through two independent paths, both using bare source-directory artifacts: - **Path A** — `cc_args(data = [..._directory])` in `toolchain/args/linux`. Feeds the ordinary target-config compiles. - **Path B** — `cc_library(name = "kernel_headers" / "gnu_libc_headers", hdrs = ["include"])`, consumed via `@llvm-project//libcxx,libcxxabi,libunwind implementation_deps`. The ONLY header source for exec-config "stage0" runtime compiles, which receive no `cc_args` kernel headers at all. ### The fix `bazel/patches/hermetic_llvm_headers_glob.patch` applies two coupled changes to hermetic-llvm via a `single_version_override` in `MODULE.bazel`: 1. `directory.bzl` gains an `expand_files` opt-in. When `True`, `DefaultInfo` carries the individual header files (a recursive glob minus `make headers_install` byproducts) rather than one source-directory artifact. This fixes Path A. The macOS SDK sysroot is left unexpanded — globbing it would bloat every darwin compile with unnecessary inputs. 1. `kernel/extension/kernel-headers.BUILD.bazel` and `runtimes/glibc/extension/glibc-headers.BUILD.bazel` change `hdrs = ["include"]` to `hdrs = glob(["include/**"])`. This makes every individual header a declared action input for the stage0 runtime compiles. This fixes Path B — the path the `expand_files` change does not reach. The patch targets `directory.bzl`, `kernel/extension/kernel-headers.BUILD.bazel`, and `runtimes/glibc/extension/glibc-headers.BUILD.bazel`. Re-check it on every `llvm` bump with the path A and path B `aquery` commands below, run with this patch taken out of the override (the override's other patch, `hermetic_llvm_darwin_rtlib.patch`, stays): while the kernel and glibc header inputs are the two bare `include` directories, the patch is still needed; once both paths list individual header files, drop this patch. Local verification (no RBE required): ``` # Sanity-check the patch + MODULE changes on the host toolchain nix develop -c just bazel-build # Cross-compile a Linux target from macOS nix develop -c bazel build --platforms=//platforms:linux_x86_64 //src/logging:logging # Path A: confirm no bare source-directory artifact in the action inputs nix develop -c bazel aquery \ --platforms=//platforms:linux_x86_64 \ 'mnemonic("CppCompile", //src/logging:logging)' \ --include_artifacts # Path B: the stage0 runtime compiles nix develop -c bazel aquery \ --platforms=//platforms:linux_x86_64 \ 'mnemonic("CppCompile", deps(@llvm-project//libcxx:libcxx.static.stage0_non_asan) union deps(@llvm-project//libunwind:libunwind.static))' \ --include_artifacts # All inputs should be named files, not bare directory nodes. ``` ## Performance ### What the numbers mean The relevant metric is wall-clock time for a build triggered by a **new commit** — every PR push is a new commit, and `--stamp` changes the binary, which causes all tests to re-run regardless of cache state. A same-commit re-run (`gh run rerun`) hits a cache-hit floor of ~3–5 minutes (compiles AND test results cached) and is not representative. Do not use re-run measurements to compare build backends. ### Measured latency (warm vs cold) Measured by parsing `--profile` JSON artifacts. (`bazel analyze-profile` was removed in Bazel 9; parse the JSON directly.) | scenario | cache-only (Cloud Run + GCS) | RBE (single worker) | | ---------------------------------------------- | ---------------------------- | ------------------- | | Build + run all tests / leg (warm, new commit) | ~8.6–9.8 min | ~8.8–9.5 min | | Total leg wall-clock (warm) | ~11–13 min | ~11–13 min | | Cold (empty CAS / scale-from-zero) | ~13 min | 23–29 min | On a warm cache the two approaches are essentially equal. RBE is slower cold because all three legs share one worker and each has to rebuild the shared exec-config toolchain from scratch concurrently (only ~220–430 cross-leg cache hits on a cold run). The cache-only setup has no shared bottleneck. A ~6–9 minute fixed per-leg overhead (`ci-setup` provisioning, LFS pull, Docker Scout) is identical either way and cannot be accelerated by RBE. **RBE buys no per-PR speed on a single worker. Its value is cross-compilation and the ability to scale out workers.** ### Build-graph parallelism analysis The available parallelism of a Bazel build is: ``` available_parallelism = total_action_work_seconds / critical_path_seconds ``` Measured from the `--profile` JSON for the regular build (fastbuild): - **I/O-bound, not CPU-bound.** Output download (CAS fetch) is 6.4–9.3× the remote compute time per leg. The worker executes only ~2.3–2.5× actions concurrently despite having 16 vCPUs — it idles. `max_inflight_tasks=0` (unlimited) so the worker is not slot-limited. - **Available parallelism ≈ 5.8×–17×** (6× counting pure CPU, up to 17× counting I/O overlap). A single regular build keeps roughly 6 cores busy. - **amd64 critical path** is dominated (~87%) by `Tar src/ffmpeg_layer_amd64.tar` (≈21.6 min cold under `--remote_download_toplevel`; mitigated by `--remote_download_minimal`). The slowest translation units are `util/Parsing.cpp` (65–71s) and `protobuf/descriptor.cc` (48–59s). - **Toolchain bootstrap** is ~18% of total action-seconds. The exec-config toolchain (exec=linux-x86_64) is shared across all three legs. On a warm CAS all legs reuse it; on a cold run they race. The asan/ubsan build is CPU-bound with ~37× available parallelism (683 seconds of compile work over an ~18-second critical path). That is the configuration where adding more worker cores has the most impact. **Ranked levers for build latency:** 1. `--remote_download_minimal` (build-without-the-bytes, already the `.bazelrc` default): stops fetching intermediate action outputs. The biggest single lever for an I/O-bound build — amd64 warm latency drops ~19%. 1. Persistent warm SSD CAS (the everyday PR case): 7–8.6 min amd64, ~2.7–3 min cross. 1. More workers. Do not raise `--jobs` on a single worker — `--jobs=64` was tested and caused `UNAVAILABLE` across all legs on a cold cache (the build is I/O-bound; more client fan-out piles up CAS pressure without adding CPU). The documented scaling path is a worker pool, not a higher `--jobs` value. **Update:** the backend moved from the 16-vCPU GCP demonstrator to a 250-core / 512 GB box on our own infra. `--jobs` was raised to 128 (and `--remote_max_connections` to 200 in `.bazelrc`) as a first-cut bump, not yet re-measured — the CAS-I/O ceiling above was never actually a function of core count, so this assumes (unverified) that the new box's disk/network throughput scaled along with its CPU count. Re-run the [Performance](#performance) measurements above on the new backend and revise this section once real numbers exist. ### Warm-cache action distribution | leg | cache-hit (warm) | remote-exec (warm) | | -------------- | ---------------- | ------------------ | | amd64 | ~3,948 | ~751 | | arm64 (cross) | ~3,226 | ~77 | | darwin (cross) | ~3,102 | ~50 | Cross legs execute very few actions remotely on a warm cache (almost everything hits the shared AC), which is why their warm wall-clock drops to ~2.4–2.9 min. ## Docker Scout warm-cache fix Docker Scout inspects `daschswiss/sipi:latest` from the local Docker daemon. The image is loaded as a side effect of the `:docker_smoke` test's own `docker load` step. On a warm cache the smoke test is a cache hit and never runs — the image is absent and Docker Scout fails with `No such image`. The fix: `bazel-test-smoke` in `ci.yml` runs `bazel run //src:image_load` explicitly before the test. This both loads the image into the daemon and materialises the OCI tarball on disk under `--remote_download_minimal` (where it would otherwise not be fetched). The smoke test then finds the image regardless of its cache state. ## Local use from macOS A developer on an Apple Silicon Mac opts in with `--config=rbe-darwin`. Compiles run on the x86_64 worker and the tests run on the Mac, as on CI's darwin-arm64 leg. Without the config, a local build never contacts the backend. ### The `dasch-rbe` contract `build:rbe-darwin` includes `--config=dasch-rbe`, which each developer defines in their own `~/.bazelrc`, with absolute paths (Bazel expands neither `~` nor environment variables in the TLS flags): ``` build:dasch-rbe --remote_executor=grpcs://rbe-01.ops.dasch.swiss:443 build:dasch-rbe --remote_cache=grpcs://rbe-01.ops.dasch.swiss:443 build:dasch-rbe --remote_instance_name=main build:dasch-rbe --remote_default_exec_properties=cpu_arch=x86_64 build:dasch-rbe --tls_certificate=/absolute/path/to/ca.crt build:dasch-rbe --tls_client_certificate=/absolute/path/to/client.crt build:dasch-rbe --tls_client_key=/absolute/path/to/client.key build:dasch-rbe --experimental_remote_cache_eviction_retries=5 build:dasch-rbe --jobs=64 ``` It differs from CI's flag string on purpose: - No `--remote_upload_local_results=true`: `rbe-darwin` sets `--noremote_upload_local_results` after `dasch-rbe`, so actions that run on the laptop do not write action-cache entries. - `--jobs=64`, not 192: the worker is shared with CI. - No `--noremote_cache_compression`: compression is off by default. Without a `dasch-rbe` definition, Bazel fails with "Config value 'dasch-rbe' is not defined". ### The client certificate Issue a personal client certificate (`extendedKeyUsage=clientAuth`, signed by `dasch-remotebuild-ca`) as the [`infra`](https://github.com/dasch-swiss/infra) repository describes in `OS/ansible/roles/dasch.nativelink/README.md` § PKI Setup. `ca.crt` is the public `dasch-remotebuild-ca` certificate. - Bazel reads only PKCS#8 keys (`BEGIN PRIVATE KEY`). A PKCS#1 key (`BEGIN RSA PRIVATE KEY`, from `openssl genrsa` on LibreSSL) fails with "Unable to decode key". Convert it with `openssl pkcs8 -topk8 -nocrypt -in client-rsa.key -out client.key`, then delete `client-rsa.key`. - Keep the key mode 0600 in a mode 0700 directory, outside any repository and outside synced folders. Ask for a certificate as short-lived as the infra role allows. ### Commands ``` just bazel-test --config=rbe-darwin just bazel-build-server --config=rbe-darwin # runnable bazel-bin/src/cli/rust/sipi ``` Supported: `bazel-build`, `bazel-build-server`, `bazel-test`, `bazel-test-unit`, `bazel-test-e2e`. Not supported: recipes that `bazel run` an exec-config tool (`bazel-rustfmt`, `compile-commands`) and `bazel-coverage`, because `--host_platform` makes those tools x86_64 Linux binaries. `rbe-darwin` adds `--config=rbe-cross` (the cross-leg flags, see [The fix](#the-fix)), the darwin platforms and `--remote_download_toplevel`, so that top-level outputs such as the `sipi` binary reach `bazel-bin`. `--noremote_local_fallback` matters most here: with fallback on, a failed remote action reruns on the Mac with x86_64 exec tools and fails with "cannot execute binary file", which hides the real error. Expected noise: Rust compiles on the Linux worker print "invoking `xcrun --sdk macosx --show-sdk-path` to find MacOSX.sdk failed", and the Linux exec tools get an unused `-mmacosx-version-min`. Both are harmless. `build --action_env=PATH` puts the Nix dev shell's `PATH` into action keys, so where `PATH` reaches an action, a local build does not reuse CI's entry and executes on the worker. This costs worker time and storage only. ### Security: accepted risk NativeLink authenticates by CA signature only and has no revocation list. Any holder of a valid certificate can write the action cache of instance `main` directly over the remote-execution API, whatever their Bazel flags say, and CI and release builds read that cache. `--noremote_upload_local_results` keeps an honest client's local results out; it is not an access control. Personal certificates widen the set of holders from the CI identity to every opted-in developer. If a key leaks: rotate the CA (this also re-issues CI's certificate) and flush the action cache. A separate instance or store for developers, or a read-only developer identity, would remove the risk; both are infra changes. ## CI topology `ci.yml`'s `test` job runs the matrix on all three platforms. Each leg: 1. Calls `.github/actions/ci-setup` with its `matrix.bazel-platform`, which provisions bazelisk + `just` on the plain GitHub-hosted runner and internally calls `.github/actions/bazel-rbe` to obtain the `$RBE_FLAGS` string — no Nix involved. 1. Passes `$RBE_FLAGS` to every `just bazel-*` invocation. 1. Runs `just bazel-test` (unit + approval + e2e). 1. On Linux: runs `just bazel-test-smoke` (which first calls `bazel run //src:image_load`). 1. On Linux: runs `just image-scan` (grype CVE gate over the same image). 1. On linux-amd64 PRs: runs Docker Scout. `ci.yml`'s path-gated `sanitizer` job, plus `coverage.yml`, `fuzz.yml`, and `publish.yml`, all go through the same `ci-setup` action so every Bazel invocation benefits from the shared remote cache. ## Reference - `.github/actions/bazel-rbe/action.yml` — the composite action; source of truth for CI's connection flags and per-leg platforms - `.bazelrc` `build:rbe-cross` — source of truth for the cross-leg flags, shared by CI and `build:rbe-darwin` - `bazel/patches/hermetic_llvm_headers_glob.patch` — the remote-execution safety patch - `bazel/patches/hermetic_llvm_darwin_rtlib.patch` — drops the unused `-rtlib` from macOS Rust links; not RBE-related, applied by the same override - `MODULE.bazel` — `single_version_override` for the `llvm` module (patch application) and `rust.toolchain(extra_target_triples = ...)` (cross toolchain registration) - `platforms/BUILD.bazel` — `//platforms:linux_x86_64` exec properties - `test/e2e/sipi_e2e_test.bzl` and `test/e2e/BUILD.bazel` — `no-sandbox` tag on e2e tests - [`ops-tf`](https://github.com/dasch-swiss/ops-tf) (`live/virt-03/prod/vms/`) and [`infra`](https://github.com/dasch-swiss/infra) (`OS/ansible/roles/dasch.nativelink`) — VM provisioning and NativeLink store configuration / operations (private repos) - [RBE Write Pressure](https://sipi.io/development/rbe-write-pressure/index.md) — why the store disk writes terabytes/day, and the client-side levers that reduce it (worker materialization, not client uploads) # Developing Vitrinli ## Using an IDE ### CLion If you are using [CLion](https://www.jetbrains.com/clion/), open the project root and let CLion's Bazel support index the workspace via the [Bazel for IntelliJ](https://plugins.jetbrains.com/plugin/8609-bazel) plugin (project from `MODULE.bazel`). Launch CLion from inside the Nix dev shell so it inherits the build environment: ``` nix develop clion . ``` A direnv setup (see [Nix dev shell](https://sipi.io/development/nix/#direnv)) gives the IDE the same PATH/env without launching it from a terminal. ### clangd clangd and clang-tidy read `compile_commands.json` at the workspace root. Generate it (it is git-ignored) with: ``` just compile-commands ``` Re-run it after adding or moving a C++ file or changing a target's deps or copts. Build once first (`just bazel-build`) so generated headers exist under `bazel-out/`. The compile commands name the hermetic clang as driver, so start clangd with `--query-driver='**'` to let it query that driver for its system include paths. In Zed, set it in `settings.json`: ``` { "lsp": { "clangd": { "binary": { "arguments": ["--query-driver=**"] } } } } ``` The repo-root `.clangd` strips flags clangd cannot parse. A clangd older than the hermetic LLVM (22) may report errors inside the toolchain's own builtin headers (e.g. `unknown type name '__mfp8'` on aarch64). The toolchain ships a matching clangd; `just compile-commands` prints its path. Point the editor's clangd binary at it to avoid the version skew. ## Running locally A dedicated local development config is provided at `config/sipi.localdev-config.lua`. It points `imgroot` at the bundled test images and uses small cache limits (1 MB, 10 files) so IIIF requests work out of the box and cache eviction is easy to observe. ### Start the server ``` nix develop just run # bazel build + run sipi server --config localdev ``` The server starts on `http://localhost:1024`. `just run` depends on `just bazel-build` so the binary at `bazel-bin/src/cli/sipi` is always rebuilt before the run. After the first cold build (the native `cc_library` deps kakadu/libtiff/exiv2/etc compile from source), incremental rebuilds re-run only the affected compile + link through Bazel's per-action cache — typically sub-second through link. ### Try some requests ``` # Fetch an IIIF image with a transformation (creates a cache entry) # Note: requests that need no processing (same format, full size, no rotation) # are served directly from the original file and bypass the cache. curl http://localhost:1024/unit/gradient-stars.tif/full/max/0/default.jpg -o /tmp/test.jpg ``` The server exports metrics over OTLP, not a scrape endpoint. Cache behaviour is observable directly from the on-disk cache directory (`./cache` under the localdev config). Make several different image requests to fill the cache past its 1 MB / 10 file limits and watch entries evict from `./cache`: ``` # Format conversions (TIF → JPG) trigger caching — all well under 2 MB curl http://localhost:1024/unit/gradient-stars.tif/full/max/0/default.jpg -o /dev/null curl http://localhost:1024/unit/lena512.tif/full/max/0/default.jpg -o /dev/null curl http://localhost:1024/unit/cielab.tif/full/max/0/default.jpg -o /dev/null # Resized requests also trigger caching curl http://localhost:1024/unit/MaoriFigure.jpg/full/200,/0/default.jpg -o /dev/null curl http://localhost:1024/unit/MaoriFigureWatermark.jpg/full/200,/0/default.jpg -o /dev/null ls ./cache ``` ### Available configs | Config file | Purpose | | --------------------------------- | ---------------------------------------------------------- | | `config/sipi.config.lua` | Production-like defaults (`./images` imgroot, 20 MB cache) | | `config/sipi.localdev-config.lua` | Local development (test images, tiny cache, DEBUG logging) | | `config/sipi.test-config.lua` | Automated test suite | ## Writing tests For the authoritative testing strategy (pyramid, layer definitions, decision tree, IIIF coverage matrix, feature inventory), see [Testing strategy](https://sipi.io/development/testing-strategy/index.md). Unit + approval tests use [GoogleTest](https://github.com/google/googletest) (approval tests additionally use [ApprovalTests.cpp](https://github.com/approvals/ApprovalTests.cpp)). End-to-end and HTTP-contract tests are written in Rust and live under `test/e2e/`. All tests build under Bazel: ``` just bazel-test-unit # bazel test //src/... //test/unit/... just bazel-test-approval # bazel test //test/approval:approvaltests just bazel-test-e2e # all rust_test e2e targets just bazel-test-smoke # Docker smoke test bazel test //src/iiifparser/fuzz:parse_request_fuzz # fuzz-corpus replay (also inside the //src/... sweeps) ``` CI runs the full pyramid through `just bazel-coverage` (unit + approval + e2e under instrumentation, lcov for Codecov). ### Unit tests Unit tests use GoogleTest with ApprovalTests. `test/unit/fixtures/` holds shared fixture generators (test images, EXIF payloads) consumed by tests across packages, not a test suite itself. Per-module Bazel packages co-locate their unit tests alongside the sources (per ADR-0003). Co-located tests today: - `//src/observability:metrics_registry_test` — metrics-registry seam tripwire: pins every metric field against how it reaches production OTLP via the `SipiMetricsSnapshot` bridge - `//src/metadata:icc_normalize_test`, `//src/metadata:essentials_test`, `//src/metadata:exif_rational_test` — ICC normalization, the Essentials packet, and EXIF rational-array decode - `//src/util:util_test` — util: Hash, Parsing, PathRedact, filename hashing, urldecode - `//src/iiifparser/cpp/value_objects:iiifparser_test` — IIIF value-object parsers + seam round-trip + decode dims - `//src/iiifparser/cpp/classifier:iiif_handler_test` — the `parse_iiif_uri` classifier + its regression corpus - `//src/iiifparser/rust:iiif_parser_test` — the production Rust IIIF URL parser (domain, parse, request modules) - `//src/iiifparser/rust:corpus_regression_test` — the Rust parser swept over the shared corpus - `//src/image:image_test` — `SipiImage` construction, mutation, pixel accessors, and the Essentials-packet service-file prefix invariant - `//src/image_processing:image_processing_test` — scale/rotate/crop, channel-count and equality/pixel-delta regressions, and the engine-direct IIIF transform matrix - `//src/format_handlers:formats_test`, `//src/format_handlers:output_sink_test` — per-format read/write/read_shape regression suites (TIFF, JPEG, PNG, J2K) + the write sink - `//src/format_handlers:tiff_codecs_test` — libtiff ingest-codec coverage proof (JPEG/LZMA/ZSTD/WebP/JBIG compiled in) - `//src/cache:cache_test` — LRU cache: indexing, crash recovery, persistence, add/check/remove, dual-limit eviction, blocked-file handling - `//src/logging:logger_test` — logger - `//src/throttling/cpp:memory_budget_test` — decode memory budget: CAS accounting, RAII guard, peak-memory estimator Run one component: ``` bazel test //src/iiifparser/cpp/value_objects:iiifparser_test --test_output=streamed ``` When adding a new unit test, declare a `cc_test` target in the module's own `BUILD.bazel`, co-located with the sources it exercises (per ADR-0003) — follow the pattern of the co-located tests listed above rather than adding a `test/unit//` directory. CI runs `just bazel-coverage` — which exercises every `cc_test` under `//src/...` (co-located unit tests) plus `//test/unit/...`, `//test/approval/...`, and `//test/e2e/...` in a single pass — so a missing `cc_test` target, or one not reachable from `//src/...`, means no CI coverage. ### Rust end-to-end tests Rust e2e tests live in `test/e2e/` and use `reqwest` for HTTP, `serde_json` for JSON validation, and `insta` for golden snapshots. They cover IIIF compliance, server behaviour, and upload functionality. Run via Bazel — `rules_rust` produces one `rust_test` target per `tests/.rs`: ``` just bazel-test-e2e # full suite (CI canonical) bazel test //test/e2e:server # single target, inner-loop bazel test //test/e2e:server --test_output=streamed # see live output ``` The full suite resolves the sipi binary via `$SIPI_BIN`, defaulting to `bazel-bin/src/cli/rust/sipi`. Override `SIPI_BIN` to point at a sanitized build (`bazel build --config=asan`) when investigating ASan findings. Sequential execution Each test starts its own Vitrinli server on a unique port. The `sipi_e2e_test` Bazel macro sets `--test-threads=1` so this works out of the box. ### Smoke tests Smoke tests live in `test/e2e/tests/docker_smoke.rs` and run against a built Docker image. They verify basic server functionality after a Docker build: ``` just bazel-test-smoke # builds //src:sipi_image, loads tarball, probes ``` ### Approval tests Approval tests live in `test/approval/` and use snapshot-based testing for regression detection. They run as part of every `just bazel-test`, `just bazel-coverage`, or focused `just bazel-test-approval` invocation. `SOURCE_DATE_EPOCH=946684800` and `SIPI_WORKSPACE_ROOT="."` are injected by `test/approval/BUILD.bazel`'s `env = {}` block, so the wall-clock-stamped ICC creation date that lcms2 stamps into JPEG / PNG / JP2 (and ICC-carrying TIFF) outputs is overwritten with a fixed value. Without these env vars, the seconds field drifts by one byte across consecutive runs. When running the binary directly outside of `bazel test`, export the same value first: ``` SOURCE_DATE_EPOCH=946684800 SIPI_WORKSPACE_ROOT="." \ ./bazel-bin/test/approval/approvaltests \ --gtest_filter='ImageEncodeBaseline.*' ``` Without it, expect `.received.*` files for every ICC-touching test — that's a deliberate test-infrastructure side-effect, not a regression. See [`test/approval/CHANGELOG.approval.md`](https://sipi.io/test/approval/CHANGELOG.approval.md) for the full list and the re-approval procedure, and `docs/adr/0002-icc-profile-determinism-test-only.md` in the project root for the design rationale. ### Fuzzing Coverage-guided libFuzzer fuzzing of the production Rust IIIF parser lives in `src/iiifparser/fuzz/`. `bazel test //src/iiifparser/fuzz:parse_request_fuzz` is a corpus replay that runs on every platform; `just fuzz` and the nightly `fuzz.yml` run the mutation loop on Linux. The canonical how-to — the C++→Rust shim seam, the two modes, the corpus policy, and crash triage — is [Fuzzing](https://sipi.io/development/fuzzing/index.md). ### Microbenchmarks Performance work uses the Google Benchmark suite: `just bench ` and `just bench-compare `. The canonical how-to — tiers, fixtures, the before/after workflow, and the regression decision rule ("no benchmark, no hot-path change") — is [Benchmarking](https://sipi.io/development/benchmarking/index.md). ## Managing dependencies Every C/C++ dependency is one of two shapes (there is no `rules_foreign_cc` — see [ADR-0015](https://sipi.io/adr/0015-native-cc_library-over-foreign_cc.md)): - **BCR `bazel_dep`** — a one-line pin in `MODULE.bazel` for libs whose Bazel Central Registry module is a true drop-in (zlib, libpng, libjpeg_turbo, libwebp, curl, openssl, …). - **Native `cc_library`** — for libs with no BCR module or where stock BCR would compromise capability (libtiff, exiv2, lcms2, jansson, sentry, jbigkit, kakadu). The source is fetched by an `http_archive` in `MODULE.bazel`; the build rule is a hand-written `cc_library` in `bazel/.BUILD.bazel` (referenced as the archive's `build_file`), compiled by the hermetic LLVM toolchain like first-party code. Config headers are reproduced via the `cmake_configure_file` module. To bump a **BCR `bazel_dep`**: change the `version` string and run `bazel build //src/cli:sipi` + `just bazel-test`; commit `MODULE.bazel` and `MODULE.bazel.lock`. To bump a **native `cc_library`** dep: 1. Edit the relevant `http_archive(...)` in `MODULE.bazel` — update `url` and clear `sha256`. 1. Run `bazel build //src/cli:sipi` once; Bazel reports the actual sha256 in the failure output. Paste it into the block. 1. Re-diff any `*.cmake.in` config templates the `bazel/.BUILD.bazel` reproduces — upstream may have added a `#cmakedefine`/`@VAR@` token that `cmake_configure_file` now needs declared. 1. Run `bazel build //src/cli:sipi` and `just bazel-test` to confirm. 1. Commit `MODULE.bazel`, `MODULE.bazel.lock`, and any `bazel/.BUILD.bazel` change. Adding a brand-new dependency: prefer a BCR `bazel_dep` if the module is a true drop-in. Otherwise add an `http_archive(...)` + a native `cc_library` in `bazel/.BUILD.bazel` (use a sibling lib as the template) and wire it into the consumers (`//src:sipi_lib`, `//src/util:util`, …) via `@//:`. Kakadu is special: it is fetched via a custom `gh_release_archive` repository_rule (`bazel/gh_release.bzl`) that shells out to `gh release download`. See [Kakadu setup](https://sipi.io/development/kakadu/index.md). ## Commit and PR conventions The commit message schema (Conventional Commit types, the scope vocabulary, and what `fix:` means), the rebase/one-commit-per-PR git workflow, and the PR description format all live in a single source: [`commit-conventions.md`](https://sipi.io/development/commit-conventions/index.md). # Error Model The image/codec layer's failure contract: what type carries an error, what policy each failure maps to at the three seams that consume it, and which exception mechanisms remain in permanent, deliberate use. The decision this document reflects is [ADR-0024](https://sipi.io/adr/0024-value-based-image-errors.md); this page is the living catalog of the contract as it stands, not the decision record itself. ## The value type: `Sipi::SipiValueError` `src/error/cpp/SipiValueError.h` (`//src/error`) defines: - `ErrorCode` — an `enum class`, one variant per distinct failure category a caller can act on (decode rejection, unsupported format, malformed/oversized input, encode/write failure, client-abort, shape-probe failure, metadata-parse failure, invalid request parameter). New failure categories get a new variant — never folded into an existing one. - `SipiValueError` — the value itself: an `ErrorCode`, a diagnostic message, and a `std::source_location` captured at construction. Cheap to move; the diagnostic string is not eagerly formatted. - `client_message()` — path-redacted, no source location. Safe to surface in an HTTP response body or a Lua-visible error string. - `diagnostic_message()` — full detail (source file + line), for server-side logs and Sentry. - `Result` — `template using Result = std::expected;`, defined in the same header. ## Policy as data: `policy_for(ErrorCode)` A `constexpr ErrorPolicy policy_for(ErrorCode)` returns `{ HttpStatusClass, SentryPolicy, MetricHint }` for a given code. This is the single source of truth for a `SipiValueError`'s failure policy — no seam dispatches on `ErrorCode` with its own scattered `catch`-equivalent `switch`. Each seam maps the returned `HttpStatusClass` to its own vocabulary — a concrete `SipiStatus` on the HTTP seam, an emitted error string on the Lua seam, an exit code on the CLI seam. | `ErrorCode` | `HttpStatusClass` | `SentryPolicy` | `MetricHint` | | -------------------------- | ----------------- | ---------------------------- | --------------------- | | `kDecodeFailed` | `kInternalError` | `kReport` (+ `ImageContext`) | none | | `kUnsupportedFormat` | `kInternalError` | `kReport` | none | | `kMalformedInput` | `kInternalError` | `kReport` | none | | `kWriteFailed` | `kInternalError` | `kReport` (+ `ImageContext`) | none | | `kClientAbort` | `kInternalError` | `kSkip` | `kClientDisconnected` | | `kShapeProbeFailed` | `kInternalError` | `kReport` | none | | `kMetadataParseFailed` | `kInternalError` | `kReport` | none | | `kInvalidRequestParameter` | `kClientError` | `kSkip` | none | `kInvalidRequestParameter` is the one `ErrorCode` whose `HttpStatusClass` is `kClientError` rather than `kInternalError`: it marks a client-supplied IIIF parameter the engine cannot honour (for example, a requested scale target of one sample or fewer on an otherwise well-formed source image), as distinct from `kMalformedInput`, which stays `kInternalError` because it flags a problem with the repository's own content (a corrupt or degenerate source file) rather than with the request. `std::bad_alloc` is deliberately not an `ErrorCode` and never appears in this table — it stays exception-based permanently (ADR-0024 Decision 7). It has no `MetricHint` to key on, since it never carries an `ErrorCode`: every seam maps it to `HttpStatusClass::kInternalError` and increments the `memory_alloc_failures_total` metric (`src/observability/cpp/metrics.h`) directly at the `catch` site, outside `policy_for`. ## Embedded metadata parse failures are fatal on read Vitrinli is a repository: it must not admit corrupt material. Every embedded metadata blob a decode path hands to `Exif::parse`, `Iptc::parse`, or `Icc::parse` (JPEG's APP1/APP2/APP13 segments, J2K's UUID boxes and `colr` box, PNG's `iCCP`/`zTXt` chunks, TIFF's IPTC/ICC tags) must parse cleanly or the read fails with `kMetadataParseFailed` — there is no partial-metadata success path. A handler that decoded past a malformed blob with the metadata simply dropped was a pre-repository-era shortcut, not a supported outcome. `Icc::createRGB` is a different operation — it synthesizes an ICC profile from a file's colour tags rather than parsing an embedded blob — but the same ground applies: colour tags that cannot be built into a profile mean the file is corrupt, so synthesis failure is fatal too. `Xmp` is stored verbatim (see `src/metadata/cpp/xmp.h`) and has no parse step to fail. There is no reader-level exception to this contract: malformed ICC, IPTC, and EXIF — whether parsed from an embedded blob or synthesized by `Icc::createRGB` from colour tags — are all fatal in every codec handler (JPEG, J2K, PNG, TIFF), including PNG's "Raw profile type exif" text chunk (`src/format_handlers/cpp/SipiIOPng.cpp`). ### EXIF rationals on TIFF write `SipiIOTiff::writeExif` applies the same fatal-on-corruption stance to the write path. libtiff converts an EXIF rational tag to a `float` before storing it, so a scalar rational `n/0` with `n != 0` has no valid float representation; Vitrinli treats it as corrupt metadata and rejects the write with `kMetadataParseFailed` rather than silently dropping it. A scalar `0/0`, by contrast, is EXIF's own "no value" convention (e.g. an unmeasured `BrightnessValue`) and carries no value to reject — it is skipped, and the tag is simply omitted from the output. The `LensSpecification` tag (`EXIF_DT_RATIONAL_PTR`, a fixed four-rational array) is written all-or-nothing: any `n/0` element rejects the whole write, and otherwise any `0/0` element skips the whole tag, since libtiff's fixed-count `TIFFSetField` call has no per-element "unknown" encoding. ## Legacy mechanisms and their disposition | Mechanism | Package | Status | | ------------------------------- | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Sipi::SipiError` | `iiifparser` | Unchanged. Exception-based, out of scope for this migration — a different package with its own lifetime (ADR-0021). The seams keep catching it by type for HTTP-400 dispatch. | | `Sipi::SipiSizeError` | `iiifparser` | Unchanged, same reasoning as `SipiError`. | | `Sipi::SipiImageError` | `image` | No fallible operation throws it. Narrowed to the unrecoverable/invariant class: allocation-size overflow (`checked_buf_size_or_throw` in `SipiImage.cpp`, `SipiIOTiff.cpp`, `compose.cpp`), `memTiffOpen`'s raw `malloc` failures, `SipiImage`'s construction/geometry invariants, and the `getPixel`/`setPixel` accessors — all programming errors with no input path. | | `Sipi::InfoError` (bare `enum`) | `image` | Deleted; superseded by the dedicated `ErrorCode` variant `kShapeProbeFailed`. | | `std::bad_alloc` | n/a | Unchanged, permanent. See above. | ## The three seams Each seam converts a fallible operation's `Result`/`SipiValueError` into its own failure vocabulary. What each seam catches by exception type differs: - **`src/ffi/cpp/serve_image.cpp`** (HTTP) — `HttpStatusClass` → `SipiStatus`; `SentryPolicy::kReport` populates an `ImageContext` and calls `report_image_error`; `MetricHint` increments the matching `Sipi::observability::Metrics` counter. Its own `try`/`catch` blocks vary by step: the image-read step catches `std::bad_alloc`, `SipiImageError`, and `Sipi::SipiSizeError`; the later rotate/quality-conversion steps catch `std::bad_alloc` and `Sipi::SipiError`; the watermark step catches `Sipi::SipiError` and `std::exception`. It also catches `iiifparser`'s `SipiError`/`SipiSizeError` elsewhere in the file (out of scope for this migration, ADR-0021) for its HTTP 400. None of these name `kdu_exception`. - **`src/ffi/cpp/image_handle.cpp`** (Lua userdata surface, behind `src/scripting/rust/bindings/image.rs`) — `client_message()` is emitted as the Lua-visible error string; there is no HTTP status or Sentry report on this surface. `sipi_image_new` (the entry that calls `SipiImage::read`) hand-rolls its own three-stage catch, in order: `Sipi::SipiError`, then `std::exception`, then a bare `catch (...)`. - **CLI offline verbs** (`src/cli/cpp/cli_app.cpp`, `src/cli/cpp/commands/convert_access_file.cpp`, `convert_service_file.cpp`, `verify.cpp`, `health.cpp`) — `diagnostic_message()` reaches the operator through the verb's own reporting path: `log_err` to stderr, plus the optional `--json` report on `sipi convert` (`emit_json_report`) or `report_error` on `convert access-file`. The exit code is a plain binary `EXIT_SUCCESS`/`EXIT_FAILURE` — a richer `HttpStatusClass`-derived exit-code mapping is not implemented today. Each verb body catches `SipiImageError` and/or `std::exception` around its own calls; none name `kdu_exception`. None of the three seams' own `try`/`catch` blocks name Kakadu's `kdu_exception` (an `int`-like type, not a `std::exception`) — and none need to, because it is stopped further out by a bare `catch (...)` wall. Inside `SipiIOJ2k::read`, only the source-open/`access_codestream`/`open_stream` call and the `codestream.create` call are wrapped in `try`/`catch (kdu_exception&)`, converting those two failures to a `Result`. Several later calls on the same decode path are not inside any `try`: `codestream.access_siz()`, `codestream.apply_input_restrictions(...)`, `codestream.get_dims(...)`, and `jpx_layer.access_colour(0)`. A `kdu_exception` raised from any of those escapes `SipiIOJ2k::read` uncaught by any type-specific handler in the call chain above it, and is stopped only by the outer catch-all at each seam's boundary: `sipi_guard`'s bare `catch (...)` at the `extern "C"` boundary (`src/ffi/cpp/serve_response.h`) for the HTTP entries that go through `sipi_serve_image`, `sipi_image_new`'s own bare `catch (...)` for the Lua userdata surface, and `sipi_cli_main`'s bare `catch (...)` around `CLI11_PARSE` for the CLI. This is why `src/format_handlers/fuzz/codec_fuzz_harness.h` keeps a bare `catch (...)` around its own `read` calls — it exercises the same decode path directly, outside any seam. ## Error-variant principle Enumerate failure variants per operation; never collapse distinct failures into one generic code to avoid extending the `policy_for` table. A catch-all that silently genericizes a new failure is the failure mode this model exists to prevent. # Downstream Dependencies This page documents which runtime packages the `daschswiss/sipi` Docker image provides and why, so downstream consumers don't need to rediscover this. ## Vitrinli's Bundled Lua Scripts The Lua scripts shipped with Vitrinli (`sipi.config.lua`, `sipi.init.lua`, `send_response.lua`) have **no system tool dependencies**. They use only Vitrinli's built-in Lua API (`server.http()`, `server.decode_jwt()`, `server.parse_mimetype()`, etc.) — no `io.popen()` or `os.execute()` calls. ## Runtime Image Packages The `daschswiss/sipi` Docker image (final stage) includes these packages: | Package | Required by | How it's used | | ----------------------- | --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `curl` | `knora-sipi` healthcheck | `healthcheck.sh`: `curl -sS --fail 'http://localhost:1024/...'` | | `openssl` | sipi binary | TLS for outbound HTTPS connections | | `ca-certificates` | sipi binary | TLS certificate trust store for HTTPS | | `LC_ALL=C.UTF-8` (env) | sipi binary | UTF-8 byte handling for exiv2 metadata, Lua string functions, `std::locale()`. Built into glibc — no separate `locales` package required. | | `ffmpeg` | dsp-ingest (`MovingImageService`) | `ffprobe` for video metadata (dimensions, duration, FPS). dsp-ingest runs `docker run --entrypoint ffprobe daschswiss/knora-sipi:...` in local dev, or calls `ffprobe` directly in production. | | `libmagic1` + `file` | sipi binary | MIME type detection (linked at compile time; runtime `.mgc` database needed) | | `tzdata` | system | Timezone support (`TZ=Europe/Zurich`) | | `sha256sum` (coreutils) | `knora-sipi` Lua scripts | `util.lua:file_checksum()` calls `/usr/bin/sha256sum` | ## Downstream Consumers | Consumer | Image | What it uses from sipi container | | ----------------------------------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | `knora-sipi` (dsp-api `sipi/` subproject) | `daschswiss/knora-sipi` (base: `daschswiss/sipi`) | Lua scripts + sipi HTTP server. Needs `curl`, `sha256sum`, `libmagic1`, `LC_ALL=C.UTF-8`, `openssl`, `ca-certificates`. | | dsp-ingest (`SipiClientLive`) | `daschswiss/knora-sipi` (via `docker run` in local dev) | sipi CLI (`sipi query`, `sipi convert ... --format ... --topleft`). Migration to the verb-noun surface tracked in DEV-6541 (cross-repo paired release). | | dsp-ingest (`MovingImageService`) | `daschswiss/knora-sipi` (via `docker run --entrypoint ffprobe` in local dev) | `ffprobe` for video metadata extraction. Needs `ffmpeg` package. | | dsp-tools | `daschswiss/knora-sipi` (via Docker Compose) | HTTP API only (port 1024). No direct tool dependencies on container internals. | | fileidentification | none | No dependency on sipi. Standalone tool with its own ffmpeg/imagemagick/libreoffice. | # Fuzz Testing Coverage-guided libFuzzer fuzzing across two families of attacker-controlled input: the production IIIF URL parser, and the C++ codec decode handlers (TIFF, JPEG, PNG, JPEG 2000; DEV-7066). Both compose the same way — a `cc_fuzz_test` from `rules_fuzzing`, `--config=fuzz` for the mutation loop, `--config=fuzz --config=asan` for the sanitizer-paired pass — but they fuzz different code and different bug classes, and the sections below call out where the two diverge. ## The production IIIF parser Fuzzing of `iiif_parser::parse_request` (`src/iiifparser/rust/request.rs`). That function is the first parser every HTTP request hits: it classifies the URI (`Iiif | InfoJson | KnoraJson | Redirect | FileDownload`) and parses `{region}/{size}/{rotation}/{quality}.{format}` out of attacker-controlled input, so a panic there is a remote-triggerable request failure. The harness lives entirely inside Bazel. The target is `//src/iiifparser/fuzz:parse_request_fuzz`, a `cc_fuzz_test` from `rules_fuzzing`, seeded from the shared regression corpus `//src/iiifparser/corpus:seed_corpus`. It replaces the C++ libFuzzer harness that fuzzed the oracle-only classifier and was retired with the oracle ([ADR-0020](https://sipi.io/adr/0020-oracle-removal.md)). ### The C++→Rust shim seam libFuzzer's entry point is `LLVMFuzzerTestOneInput`, a C symbol, and `rules_fuzzing` is a C++/Java rule set — so the Rust parser is entered through a small `extern "C"` shim: ``` src/iiifparser/fuzz/ ├── BUILD.bazel # rust_static_library shim + cc_fuzz_test ├── shim.rs # extern "C" sipi_fuzz_parse_request → parse_request └── fuzz_target.cc # LLVMFuzzerTestOneInput → shim ``` This is the repo's only **C++-calls-Rust** link — every other FFI edge (`src/ffi/`, `src/server/rust/src/ffi.rs`) is Rust→C++. The declaration in `fuzz_target.cc` is hand-mirrored from the Rust signature, following the `src/ffi/cpp/sipi_ffi.h` convention (no cbindgen). The seam never leaves the package, and Bazel enforces that rather than merely documenting it: both targets are `testonly` (`cc_fuzz_test` forwards `testonly` to its raw `cc_binary`, and marks every target it generates `testonly` itself), and the package declares no default visibility. Nothing that ships can even name the shim, let alone depend on it. Naming a target on the command line needs no visibility, so `just fuzz` and the nightly still build `:parse_request_fuzz_bin` directly. The shim rejects invalid UTF-8 rather than lossy-converting it: every production caller (axum path extraction) hands the parser a valid `&str`, so a U+FFFD input would only yield findings unreachable from a real request. The parse result is discarded — `Err` is a normal outcome for a malformed URI; the contract under test is that no input panics. This is also what a corpus file *means* here: a seed is fed to the parser verbatim, and a non-UTF-8 seed is a no-op. Note that `corpus_regression_test` sweeps the same files with a **lossy** decode, so it can exercise a byte sequence this harness skips. ## The C++ codec decode handlers Fuzzing of the `SipiIO` decode entry points — `read_shape` and `read` — for each of the four format handlers: `SipiIOTiff`, `SipiIOJpeg`, `SipiIOPng`, `SipiIOJ2k` (DEV-7066). Eight targets live in `src/format_handlers/fuzz/`: a decode-only target per handler (`//src/format_handlers/fuzz:tiff_decode_fuzz`, `:jpeg_decode_fuzz`, `:png_decode_fuzz`, `:j2k_decode_fuzz`) and a matching decode-then-encode round-trip target (`:tiff_roundtrip_fuzz`, `:jpeg_roundtrip_fuzz`, `:png_roundtrip_fuzz`, `:j2k_roundtrip_fuzz`). This reopens the codec-level gap [ADR-0020](https://sipi.io/adr/0020-oracle-removal.md) left when the oracle-only C++ fuzz harness was retired — no other test layer feeds these handlers arbitrary byte streams. The motivating bug class is crafted-input memory corruption in header/marker parsing (TIFF IFD entries, JPEG APPn segments, PNG chunks, JP2 boxes) that no unit test catches and that hand review finds only by luck. The decode-only targets never call `SipiIO::write`, so every encoder was unreachable from the fuzzer — the blind spot a JP2-encode bug and a JPEG-marker-write bug both shipped through undetected. The round-trip targets close it: `run_roundtrip` (`codec_fuzz_harness.h`) decodes exactly like the decode-only pass, then, if the decode produced an image, re-encodes it through every format `SipiImage::write` supports ("tif", "jpx", "png", "jpg"). A write failure or thrown exception is a valid fuzz outcome, same as a decode rejection; only a crash or sanitizer report is a finding. ### The temp-file mechanism `SipiIO` has no in-memory decode overload anywhere — every handler's `read_shape`/`read` take a filesystem path — so the shared harness (`src/format_handlers/fuzz/codec_fuzz_harness.h`) writes each fuzzer-supplied buffer to one fixed per-process temp path before driving the handler over it. The path name embeds `getpid()`: libFuzzer runs each process single-threaded, so a per-iteration temp file with a stable, truncated-and-rewritten name avoids filesystem churn, and the pid keeps parallel `-jobs=N` workers from colliding on the same path. `TEST_TMPDIR` is honoured when set (Bazel's `cc_fuzz_test` replay engine sets it), falling back to the platform temp directory otherwise. ### Expected-reject vs finding Each call to `read_shape` and `read` returns a `Result`, and the harness checks it only for presence: a codec rejecting malformed input reports that through the `Result` holding no value, not through an exception — so a clean rejection from `read_shape` still lets `read` run. Each call is additionally wrapped in its own try/catch, because a decoder can still throw en route to producing that `Result`: `std::bad_alloc`, the allocation-guard throws that stay exception-based by design (`checked_buf_size_or_throw`, `memTiffOpen`'s raw `malloc` failures), and Kakadu's `kdu_exception`. Findings are what escapes both catch blocks entirely: SIGSEGV, SIGABRT, sanitizer reports. The harness also has a bare `catch (...)` alongside `catch (const std::exception &)`, because `kdu_exception` is an `int`-like type, not a `std::exception` — without it, a Kakadu-thrown rejection on a malformed JP2 would itself register as an uncaught-exception finding. ### The decode-size budget The shape probe (`read_shape`) always runs, on every input — the full second step, `read`, does not. The harness estimates the decode buffer implied by the probe's geometry and skips `read` entirely once that estimate exceeds 512 MiB (`kMaxHarnessDecodeBytes` in `codec_fuzz_harness.h`); container/header parsing coverage is untouched by the skip, since `read_shape` is where that coverage lives. The budget exists because `validate_decode_dims` (`src/image/cpp/SipiIO.h`) caps each dimension and the channel count individually, but never their product — so a small, cheaply crafted header can legally claim a multi-gigabyte decode buffer and still pass the guard. In production, that claim is bounded at the FFI seam by the full-lane decode memory budget (`MemoryBudgetGuard`, `src/ffi/cpp/serve_image.cpp`); the harness drives the handler directly and has no equivalent budget, so without the skip a 275-byte file can end a fuzzing leg on an out-of-memory that says nothing about codec correctness. Raising `-rss_limit_mb` is not a substitute: a crafted header can claim dimensions up to the per-dimension cap on both axes at once, so no fixed RSS limit survives that argument — only skipping the oversized decode does. ### Per-target knobs Each codec target passes `-max_len` and (except J2K) a `-dict=` flag; all nine targets (including the parser) pass `-timeout=25`. - **`-max_len` caps**: 16 KB for TIFF and JPEG (decode and round-trip alike), 8 KB for PNG (decode and round-trip), 32 KB for the J2K decode target, 16 KB for the J2K round-trip target. The bug class these harnesses hunt is header/marker parsing at the front of the file, so a small cap concentrates the mutation budget there instead of on bulk pixel data a full-size image would carry. - **Dictionaries**: `src/format_handlers/fuzz/dicts/{tiff,jpeg,png}.dict`, vendored verbatim from AFL++ (see the package README for provenance and license). Each round-trip target reuses its decode-side counterpart's dictionary. There is no canonical J2K dictionary upstream, so neither J2K target runs with one. They are passed as explicit `-dict=` flags from the `justfile` recipes rather than through `rules_fuzzing`'s `dictionary` `cc_fuzz_test` attribute: that attribute only reaches libFuzzer through the rule's Python launcher via `FUZZER_DICTIONARY_PATH`, and this repo executes the built `..._bin` binary directly rather than through the launcher — running via `bazel run` (which the launcher needs) would sandbox away corpus growth (see Recipes below). - **`-timeout=25`**: applied uniformly, including to the parser target and to `fuzz-corpus-merge`'s `-merge=1` pass — libFuzzer's 1200s per-input default exceeds any of these budgets, so a hang would silently consume a run instead of being reported as a finding. ### `detect_leaks` The ASan-paired pass (below) sets `ASAN_OPTIONS=detect_leaks=0` for the JPEG and PNG legs only. libjpeg-turbo's and libpng's error paths raise via `setjmp`/`longjmp`, which skips destructors past the jump — a documented LSan false-positive source, not a real leak. TIFF and J2K unwind via real C++ exceptions and keep leak detection on, and the parser target carries no ASan special-casing at all. This is never disabled repo-wide, and it is an outcome adopted up front rather than one found by running the pass: LSan is a Linux-only ASan feature, and the local macOS ASan link is broken (see the sanitizer gate notes), so it cannot be verified on a developer Mac — the first nightly run against real crafted-JPEG/PNG input is what confirms the false-positive theory rather than an unrelated leak. ## Two modes, one target family `rules_fuzzing`'s default engine is `//fuzzing/engines:replay` with instrumentation `none`, so **without** `--config=fuzz` every target — the parser and all eight codec handlers (decode and round-trip) — needs no libFuzzer runtime and, e.g., ``` bazel test //src/iiifparser/fuzz:parse_request_fuzz bazel test //src/format_handlers/fuzz:tiff_decode_fuzz bazel test //src/format_handlers/fuzz:tiff_roundtrip_fuzz ``` is a corpus-replay regression run: every seed through the harness, asserting no crash. All nine build and run on every platform — macOS included — and ride along in the `//src/...` sweeps (`just bazel-test`, `bazel-test-unit`, `bazel-test-sanitized`, `bazel-coverage`), so every PR replays every corpus, and the sanitizer leg replays them under ASan/UBSan. `--config=fuzz` (`.bazelrc` §Fuzzing) switches to the real libFuzzer engine and arms SanitizerCoverage. That is the mutation loop. For the parser target this also arms coverage on the Rust crate graph (below); for the codec targets it arms coverage across the linked C++ handler code directly, since those targets have no Rust in their dependency graph. **Coverage instrumentation of the Rust side** (parser target only) uses only stable rustc flags — `-Cpasses=sancov-module` plus `-Cllvm-args=-sanitizer-coverage-*`, applied config-wide through `rules_rust`'s singular `extra_rustc_flag` build setting (target config only; exec-config proc-macros and build scripts are untouched). No nightly toolchain, no `-Zsanitizer`, no Cargo. libFuzzer observes the Rust edges: 894 inline 8-bit counters versus 8 for a shim-only build, and a recommended dictionary of substrings of Rust-only string literals (`ault` from `default`) that exist nowhere in the C++ shim. The config also sets `--compilation_mode=opt`. Fuzzing throughput *is* coverage — a nightly has a fixed wall-clock window — and there is nothing to step through in a debugger, since a finding is a saved reproducer replayed separately. Two flags come back on top of it, for the Rust parser target: - `-Cdebug-assertions=on` and `-Coverflow-checks=on`, which `-c opt` turns off. An integer overflow in a coordinate or dimension parser is exactly the bug class this target hunts, and it is a panic in debug and a silent wraparound in release — turning the checks back on is what makes the fuzzer see it. - `std::hint::black_box` around the discarded parse result in `shim.rs`, so LLVM cannot prove the call dead and delete the code under test. `-Cpanic=abort` is deliberately **not** set. It would apply config-wide and so break `bazel test --config=fuzz` on every Rust test target (the prebuilt sysroot's `test` crate is unwind-compiled), and it buys nothing: a Rust panic unwinding out of an `extern "C"` fn has aborted since Rust 1.71, so the panic→SIGABRT→libFuzzer-crash path through `sipi_fuzz_parse_request` is a language guarantee. Verified with an injected panic: the abort arrives via `core::panicking::panic_cannot_unwind`, exit code 77, reproducer saved. ### ASan pairing `--config=fuzz --config=asan` composes — the repo's own sanitizer config, not `rules_fuzzing`'s `cc_engine_sanitizer` (which injects `-fsanitize=…` without provisioning a runtime and must stay at its `none` default). For the codec targets, ASan instruments the actual decoder C++ code directly (TIFF/JPEG/ PNG/J2K are C++ all the way down from the harness to the handler), so this is the primary sanitizer coverage for that bug class, not a boundary check. For the parser target, mind the narrower scope: ASan instruments the C++ shim, libFuzzer itself, and the linked native runtime — **not** the Rust crate graph (that would need nightly `-Zsanitizer`, which this design avoids). The value of the paired pass there is the shim boundary (`*const u8, usize` → `&[u8]` → `&str`), libFuzzer's own buffer handling, and the runtime; the Rust parser is safe code that already runs under the ASan/UBSan CI leg via its unit, corpus-regression, and replay tests. ### Linux and macOS `--config=fuzz` links on both platforms. Since **0.8.18**, hermetic-llvm stages the compiler-rt libFuzzer runtime for darwin (`libclang_rt.fuzzer_osx.a`, upstream [PR #700](https://github.com/hermeticbuild/hermetic-llvm/pull/700)), closing the gap where `@llvm//toolchain:resource_dir` used to select `[]` for `@platforms//os:macos`. The clang driver also links `libclang_rt.ubsan_osx_dynamic` on darwin, so `--@llvm//config:ubsan=true` is required there too (already set by `--config=fuzz`). This applies uniformly to all nine targets, including the Kakadu-linked J2K harnesses (decode and round-trip) — Kakadu itself is a native `cc_library` dependency with no darwin-specific gap here. One macOS-only wrinkle, unrelated to the LLVM runtime: `rules_fuzzing`'s Python launcher deps (`absl-py`) resolve as an sdist, and `rules_python`'s macOS sdist path shells out to `xcrun xcodebuild`, which the Nix dev shell's SDK stub lacks. `.bazelrc` handles this globally by pointing the **repo-rule** `DEVELOPER_DIR` at the Command Line Tools (`/Library/Developer/CommandLineTools`), which makes `rules_python` take its non-Xcode branch and skip the `xcodebuild` call — for the replay build in the `//src/...` sweep as well as `--config=fuzz`. Build actions are unaffected; they compile against the hermetic-llvm SDK. A macOS dev therefore needs the Command Line Tools installed (`xcode-select --install`); no full Xcode. The broader `--config=fuzz --config=asan` pairing stays Linux-only for the nightly mutation loop — the macOS ASan header path is still gapped (see the sanitizer gate) — but the plain replay-mode `bazel test` of every target, codec targets included, runs on macOS same as Linux. ## Recipes ``` just bazel-build-fuzz # build all five instrumented binaries (Linux + macOS; CI-invoked, RBE-eligible) just fuzz tiff -max_total_time=60 # run the mutation loop locally; TARGET selects the harness, FLAGS pass through to libFuzzer just fuzz-corpus-merge tiff # import coverage-adding inputs from the latest nightly artifact for TARGET ``` `TARGET` is a short name, not a Bazel label: `parse_request` (the default), `tiff`, `jpeg`, `png`, `j2k`. `bazel-build-fuzz` builds the `_bin` and `_corpus` targets for all five harnesses in one invocation — e.g. `//src/iiifparser/fuzz:parse_request_fuzz_bin` and `//src/format_handlers/fuzz:tiff_decode_fuzz_bin` — the `_bin` target, not the test target: `_bin` is what the loop executes, and only a top-level target materialises locally under the `--remote_download_minimal` default. Each target's path (e.g. `bazel-bin/src/iiifparser/fuzz/parse_request_fuzz_bin`) is a stable symlink `fuzzing_binary` declares into the transitioned config's config-hashed `…_raw_` path; never hardcode the latter. Every generated target except the test itself is `manual`-tagged upstream, so the `_bin`/`_corpus` targets are built by naming them explicitly, not by a `//src/...` wildcard. `just fuzz` and the nightly both execute the built binary **directly**, not via `bazel run` — the sandbox would silently discard corpus growth. The working corpus for a given `TARGET` lives under the gitignored `.fuzz/corpus//` — strictly per-format, never shared across targets — re-seeded on every run from the target's built `_corpus` target under `bazel-bin`, which already merges both corpus tiers (below), so there is no separate seed list to duplicate. Crash reproducers land in `.fuzz/artifacts/`. Each `cc_fuzz_test` also generates a `_fuzz_run` launcher for `bazel run`; it is not what CI or the recipes use, for the sandbox reason above. ## Corpus policy — two tiers plus the merge path between them The parser and the codec targets share the same two-tier shape, but source the hand-picked tier differently. 1. **Checked-in seed corpus.** 1. Parser: `src/iiifparser/corpus/` (241 files, exposed as `//src/iiifparser/corpus:seed_corpus`), shared with the C++ classifier test and `//src/iiifparser/rust:corpus_regression_test`. 1. Codec targets: two separate locations merged by the `seed_corpus` filegroup in each `src/format_handlers/corpus//BUILD.bazel` — the hand-picked fixtures reached through `//test/_test_data:fuzz_seeds_{tiff,jpeg,png,j2k}` (crafted-malformed images already used by that codec's unit tests, plus a smallest-valid fixture; these are Git LFS), and the checked-in `src/format_handlers/corpus//` directory itself as the growth tier (empty today). Both cases grow only deliberately: a human-committed merge (below), or a crash reproducer committed alongside the fix for the bug it reproduces. CI never writes either. 1. **Live working corpus** — chained between nightly runs as a GitHub Actions **artifact** per target, `fuzz-corpus-`, not a cache. Artifacts chain explicitly across runs, are downloadable for the manual merge step, and are not subject to cache eviction. Each nightly leg seeds `.fuzz/corpus` from that target's generated two-tier corpus (the built `_corpus` Bazel target — for the codec targets, that generated directory is what makes the `test/_test_data` fixture seeds reachable at all by a binary executed outside Bazel) plus the artifact of the last successful run (falling back to the generated seeds alone on the first run or after the 90-day retention expires), fuzzes, minimizes with libFuzzer `-merge=1`, and uploads the result as this run's artifact. 1. **Periodic pull-into-repo** — `just fuzz-corpus-merge ` downloads the latest `fuzz-corpus-` artifact and `-merge=1`s it into that target's checked-in corpus directory (`src/iiifparser/corpus/` or `src/format_handlers/corpus//`), so only coverage-adding inputs are imported, then prints the diff. Reviewing and committing is manual. This is the only path from the live corpus to the checked-in one. **Known imprecision for the codec targets**: the checked-in tier (`src/format_handlers/corpus//`) does not contain the `test/_test_data` fixture seeds — those live in a separate package. `-merge=1` only sees coverage relative to its destination directory, so it can propose importing an input whose coverage the fixtures already reach but the checked-in directory does not yet contain. The recipe does not attempt to correct for this; it stops at a diff precisely so a maintainer reviews what is actually being added rather than trusting the merge blindly. `-merge=1 ` is libFuzzer's own minimization — it copies an input into the destination only if it adds coverage the destination lacks, which is why it needs the instrumented binary. ## Nightly CI `.github/workflows/fuzz.yml`, scheduled `17 3 * * *` (03:17 UTC — off-peak for the team and off the congested top of the hour), plus `workflow_dispatch` for manual runs. One job, a **9-leg matrix** (`parse_request`, `tiff`, `jpeg`, `png`, `j2k`, `tiff_roundtrip`, `jpeg_roundtrip`, `png_roundtrip`, `j2k_roundtrip`) on `ubuntu-24.04` with `fail-fast: false` — a crash in one leg must never discard another target's corpus growth for the night. Each leg runs the same five phases: build, restore the working corpus, fuzz for 600s, minimize and upload the `fuzz-corpus-` artifact, then a 300s ASan-paired pass over the minimized corpus. The minimize-and-upload steps run on `!cancelled()`, and the ASan pass comes after them, so a finding anywhere still chains that leg's corpus growth forward — losing a night of coverage to a crash would be a second injury. This is safe because libFuzzer writes reproducers to `-artifact_prefix` and never into the corpus directory, so a crashing input cannot enter the chain via the merge. The ASan pass's own corpus additions are deliberately discarded — it exists to exercise the codec/shim/runtime boundary, not to grow coverage. Two requirements are specific to the codec legs: - **Git LFS must be checked out** (`lfs: true` on the checkout, plus `lfs: "true"` into the CI-setup composite action). The codec seed corpora route through `test/_test_data`, which is Git LFS. Without it, those fixtures materialise as ~131-byte pointer files, and the codec harnesses would spend their whole budget fuzzing pointer text instead of image bytes — silently worthless coverage, not a loud failure, which is why this is called out rather than left implicit. - **`GH_TOKEN` must be job-level**, not step-level: `kakadu_archive`'s `gh_release_archive` repository rule re-evaluates on every `bazel` invocation, and each leg invokes `bazel` (via `bazel-build-fuzz`) twice — the plain build and the ASan-paired build. A step-scoped token would miss whichever invocation didn't carry it. The parser-only leg builds Kakadu too (one `bazel-build-fuzz` invocation builds all five binaries) even though it doesn't read it, so the job-level token covers every leg uniformly. `-timeout=25` is passed to both loops and to the merge in every leg: libFuzzer's 1200s per-input default exceeds the whole budget, so a hang would silently consume the run instead of being reported. The merge also gets `-rss_limit_mb=4096`, since `-merge=1` holds the whole feature set in memory as the corpus grows. The two J2K legs (`j2k`, `j2k_roundtrip`) additionally run both loops in libFuzzer fork mode with `-fork=1 -ignore_timeouts=1 -ignore_ooms=0 -timeout_exitcode=0` (matrix column `libfuzzer_extra`). Kakadu's box parser has an unpatchable hang class (DEV-7080) that the seam deadline in `serve_image.cpp` contains in production, but the codec harness drives `SipiIOJ2k::read_shape` directly, below that seam, and the mutator finds a fresh instance on most nights. In fork mode the parent keeps fuzzing past a timed-out child; the child still writes its `timeout-*` reproducer to `-artifact_prefix`, so the instance is recorded in the `fuzz-crashes-` artifact of a green leg. `-timeout_exitcode=0` is needed on top of `-ignore_timeouts=1` because the fork parent exits with its *last* child's exit code, so a tolerated timeout in the final child would otherwise still fail the step with 70. Crashes and OOMs still fail the leg. The other seven legs keep the strict per-input timeout: a hang in libtiff/libjpeg/libpng or in Vitrinli's own code is a fixable finding. The ASan pass runs every leg with `ASAN_OPTIONS=detect_container_overflow=0`. The fuzz binary links the libFuzzer runtime, which hermetic-llvm builds unsanitized (`cc_unsanitized_library`) against the same libc++ the instrumented code uses, so libc++'s container annotations are updated by some objects in the link and checked by others — the documented false-positive shape for that one detector. It fired three times with no defect behind it: the Rust parser leg (DEV-7081), `Exiv2::append` on `tiff_roundtrip` (the identical decode-then-JP2-write path is green under the `asan-ubsan` CI job, which links no libFuzzer; the reproducer is pinned as `tiff_exif_make_jp2_roundtrip.tif`), and libFuzzer's own fork driver on the j2k legs before a single input ran. Heap, stack, and global overflow detection are unaffected, and the container detector stays on for the `asan-ubsan` job's unit and e2e tests, which cover the same code without libFuzzer. Both loops run with `RUST_BACKTRACE=1` and the hermetic `llvm-symbolizer` (resolved to `.fuzz/llvm-symbolizer` by `just bazel-build-fuzz`) wired into the sanitizer runtime that prints the crash trace — `UBSAN_OPTIONS=external_symbolizer_path` for the plain loop, `ASAN_SYMBOLIZER_PATH` for the ASan pass. Without it, first-party frames print as bare `binary+0xOFFSET`. **Crash semantics.** A Rust panic aborts at the `extern "C"` boundary → SIGABRT (parser target); a memory-safety finding in a codec handler raises a signal directly (SIGSEGV/SIGABRT) or trips a sanitizer report under the ASan pass. Either way libFuzzer writes the input as `crash-` under `-artifact_prefix` and exits **77**. That exit code fails the step, so the workflow needs no crash-detection logic of its own — only preservation: the reproducers and the libFuzzer logs are uploaded as a `fuzz-crashes-` artifact (30-day retention) on failure. Triage is manual; no issue is auto-filed. **Why nightly is enough.** The per-PR regression net for every target is the replay-mode `bazel test` (the target's corpus through the harness and the engine path, on every platform, and under ASan/UBSan on the sanitizer leg), plus — for the parser only — `//src/iiifparser/rust:corpus_regression_test` (the crate API swept directly over the whole corpus). A newly introduced crash that the existing corpus already reaches fails the PR. Only a crash that requires *mutation* to reach waits for the next nightly, and up to 24h of latency on that class of finding is accepted deliberately — the alternative is a long-running loop in the PR path. ## Crash triage A nightly failure is a manual triage, not an auto-filed issue: 1. **Reproduce** from the saved artifact — `.fuzz/artifacts/` locally, or the `fuzz-crashes-` CI artifact — by running the leg's built binary directly against the single reproducer file, e.g.: ``` just bazel-build-fuzz ./bazel-bin/src/format_handlers/fuzz/tiff_decode_fuzz_bin path/to/crash- ``` The artifact directory is not exclusively crashes: libFuzzer names a saved reproducer `crash-`, `oom-`, or `timeout-` depending on how the process died, and the CI artifact is uploaded as `fuzz-crashes-` regardless of which prefix it holds. 1. **Classify the finding** before deciding what to do with it — a nightly failure is not automatically a codec bug: 1. **Sanitizer report inside Vitrinli code.** A real bug. Steps 3-5 below apply as written. 1. **Sanitizer report whose stack is entirely inside libFuzzer or the C++ runtime.** Not a Vitrinli finding. One observed instance was an ASan report inside libFuzzer's own `Sha1ToString` → `std::basic_stringbuf::str()` → libc++'s internal-buffer initialisation, with the saved reproducer being the *empty input* — a tell that the finding sits outside the target entirely. This gets its own issue against the toolchain, not a `fix:` on a codec. 1. **Out-of-memory (`oom-` prefix).** Check the reproducer's claimed geometry first. An allocation the decode-size budget above is meant to prevent means the harness needs adjusting, not the codec — the codec never got the chance to reject it. An allocation the codec should have refused on its own is a real bug. 1. **Timeout (`timeout-` prefix).** Reproduce with the timeout raised before dismissing it as a slow decode. A genuine hang inside a third-party codec is still a finding — it is an availability bug on the production `read_shape`/`read` path, even though the fix cannot be a patch to that codec's source. **Never pin a hanging input into the seed corpus**: the corpus is replayed by `bazel test` on every PR, so a hanging seed would hang the test suite instead of failing it. 1. **Fix as its own commit**, typed `fix:` — the bug already exists on `main`, so `fix:` is the correct Conventional Commit type regardless of when the fuzz target that found it landed. 1. **Commit the reproducer** into the target's checked-in corpus directory (`src/iiifparser/corpus/` or `src/format_handlers/corpus//`) alongside the fix, so it replays forever in the `//src/...` sweeps rather than only living in a 30-day CI artifact. Skip this for a finding classified outside Vitrinli code, and never do it for a timeout. 1. **Open a Linear issue** tracking the finding and its fix. No step here is automated: the nightly preserves the reproducer and fails loudly, and a person decides what — if anything — a given finding is worth. # Benchmarking Vitrinli uses [Google Benchmark](https://github.com/google/benchmark) for in-process microbenchmarks of the production codec and the IIIF parser front door. The suite exists to enforce one convention: > **No benchmark, no hot-path change.** Before changing any image decode/encode hot path (`src/format_handlers/cpp/*`, `SipiImage` read/write, `iiifparser`), a microbenchmark must exist — add one if it doesn't — and the change is justified with a before/after comparison in the PR. The suite was motivated by Ruven Pillay's *Evaluating IIIF Server Performance* (IIIF Annual Conference 2026, `docs/benchmarks/01_Ruven_Pillay_Evaluating_IIIF_Server_Performance.pdf`), which benchmarked Vitrinli as the slowest server tested for TIFF and JPEG. The microbenchmarks measure *intra-Vitrinli* per-stage cost — what can be measured rigorously and locally; the PDF's cross-server, end-to-end HTTP comparison is deliberately out of scope (apples-to-oranges across machines and OSes). ## The tiers One manual-tagged `cc_binary` per pipeline stage, named `_benchmark` and co-located with the module it measures: | Tier | Source | What it times | | --------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `parse` | `src/iiifparser/cpp/value_objects/parse_benchmark.cpp` | The five IIIF URL component parsers + the full per-request parse. Pure CPU, no fixtures. | | `decode` | `src/format_handlers/cpp/decode_benchmark.cpp` | `SipiImage::read()` across the input-format matrix (tiled-pyramid TIFF none/zstd/webp, JP2, plain-JPEG and flat-TIFF slow baselines) in two access shapes: full-resolution tile and `!256,256` thumbnail; plus a full decode of the ISO/IEC 15444-4 `file3.jp2` (chroma subsampled 2x2), read from the source tree. | | `process` | `src/image_processing/cpp/process_benchmark.cpp` | The operators between decode and encode: `scaleFast`/`scaleMedium`/`scale`, `rotate` (90° fast path + 45° general), `crop`, `to8bps`, `convertToIcc`, `removeChannel`. | | `encode` | `src/format_handlers/cpp/encode_benchmark.cpp` | `SipiImage::write()` for the four formats Vitrinli emits: JPEG (Q75/Q90), PNG, TIFF, JPEG2000. | Benchmarks are co-located with the module they measure (ADR-0003 direction: `*_benchmark.cpp` beside the source, the Abseil/Bloomberg-BDE/Chromium convention). The `parse`/`decode`/`encode`/`process` targets have all been promoted into their modules (`//src/iiifparser/cpp/value_objects`, `//src/format_handlers`, `//src/image_processing`). A `**/*_benchmark.cpp` glob exclude on `//src:sipi_lib` keeps the sources out of the production library and the coverage build, and `tags = ["manual"]` keeps the targets out of `bazel test //...`. HTJ2K is absent from the decode matrix: Kakadu's HT block coder is license-gated (`FBC_ENABLED`, evaluation-only) and the production Vitrinli build can neither encode nor decode HT codestreams. ## Fixtures - The `parse` tier needs none. - The `process` tier reuses small checked-in repo fixtures (`test/_test_data/images/`) with the specific shapes its operators need (alpha channel, 16 bps, CMYK, known dimensions). - The `decode`/`encode` tiers consume `@sipi_bench_fixtures` — a 321 MB variant matrix generated from one 7216×5412 photographic master by `tools/benchmark/generate_fixtures.sh` (the checked-in provenance: pinned source, pinned tool versions, exact commands). It is hosted as a release asset on `dasch-swiss/dsp-ci-assets` and fetched lazily — the first `just bench decode` downloads it; production and CI test builds never do. ## Running ``` just bench # tier ∈ parse | decode | process | encode just bench parse --benchmark_filter=ParseSize --benchmark_min_time=2s ``` `just bench` builds the binary with `-c opt` (matching production codegen — never fastbuild, never sanitized or instrumented) and execs it directly, exporting `SOURCE_DATE_EPOCH=946684800` + `SIPI_WORKSPACE_ROOT=.` (ADR-0002 ICC determinism + fixture resolution), `SIPI_BENCH_FIXTURES_DIR` (the `@sipi_bench_fixtures` runfiles location) and a throwaway `TEST_TMPDIR` for encode outputs. All Google Benchmark [flags](https://github.com/google/benchmark/blob/main/docs/user_guide.md) pass through. ## The before/after workflow ``` just bench decode --benchmark_repetitions=20 \ --benchmark_out=before.json --benchmark_out_format=json # ... make the hot-path change, rebuild happens automatically ... just bench decode --benchmark_repetitions=20 \ --benchmark_out=after.json --benchmark_out_format=json just bench-compare before.json after.json ``` `bench-compare` runs the vendored google_benchmark `compare.py` (`//tools/benchmark:compare`, hermetic Python + numpy/scipy via the `sipi_bench_pip` hub — nothing needed on the host). It prints per-benchmark deltas with a Mann-Whitney U-test and an `OVERALL_GEOMEAN`: - green/red numbers are the relative change (`+0.05` = 5% slower), - the U-test p-value (with `--benchmark_repetitions`) tells you whether the two distributions actually differ. ## The regression decision rule On Apple Silicon you cannot disable turbo or thermal throttling; rely on statistics instead: - Run both sides with `--benchmark_repetitions=20` on a quiesced machine and demand a baseline CV ≤ ~2% (`_cv` rows in the repetition output). A CV of 5–10% means the machine is too noisy — re-run cooler or raise `--benchmark_min_time`. - Trust a delta only if it is **green (p < 0.05) AND the median shift exceeds the baseline CV**. Treat sub-3% deltas as noise; trust ≥5% green shifts. - **Same machine, same `-c opt` binary, for both before and after.** Never compare a Mac "before" against a Linux "after". This is never a CI gate — cross-machine comparisons are meaningless and shared runners are too noisy. The numbers live in PR descriptions, produced on the author's machine. ## Adding a benchmark 1. Put `_benchmark.cpp` beside the code it measures (it moves with the module when ADR-0003 promotes it). 1. Declare a `cc_binary` in `src/BUILD.bazel` next to the existing ones: `tags = ["manual"]`, `testonly = True`, deps on `//src:sipi_lib` + `@google_benchmark//:benchmark_main` (+ `//test:test_paths` and `env`/`data` if it reads fixtures or emits ICC-stamped output). 1. Keep file I/O and source decoding out of the timed loop (decode once, deep-copy per iteration outside the timing if the operator mutates), and defeat the optimizer with `benchmark::DoNotOptimize` / `benchmark::ClobberMemory`. 1. `just bench ` — there is nothing to register anywhere else. ## Concurrent-load measurement `just bench` measures a single decode/encode in isolation. It cannot see how a change behaves when many requests run at once — the regime that matters for decisions about worker-thread counts, pool sizing, or anything whose cost is paid in contention rather than per-call work. A single-request speedup can coincide with no aggregate gain (or a regression) once the request pool is saturated. `just loadtest-decode "10,20,40"` covers that gap. It builds the production Rust shell (`//src/cli/rust:sipi`, `-c opt`), serves `load_test.jpx` via `config/sipi.loadtest-config.lua`, and drives it with `tools/loadtest/loadgen.py`: N concurrent clients each requesting a distinct native-resolution tile (distinct region → cache miss → real decode), reporting throughput and p50/p90/p99 per concurrency level after a warm-up window. The pool is sized from the host core count (`nthreads = 0`), so the listed concurrencies straddle its saturation point. Same rules as the microbench: never CI-gated, run on a quiesced machine, and compare a "before" branch against an "after" **on the same host** (build and run each branch in turn — do not run a build during a measurement, it steals cores). Interpretation caveats: the effect of thread-count changes scales with core count, so a result on a 10-core laptop does not settle behavior on a high-core production host; and the Rust FFI pool already bounds concurrent decodes to its permit count, which caps the worst-case thread total. # Allocator replay harness `tools/allocator-replay/` measures the **container RSS behavior of the production image under a fixed JP2 decode load** — the harness that root-caused the 2026-07-29 vre-prod-01 OOM and gated the mimalloc switch ([ADR-0019](https://sipi.io/adr/0019-mimalloc-production-allocator.md)). Run it whenever a change touches the JP2 decode path's threading or allocation behavior (`src/format_handlers/cpp/SipiIOJ2k.cpp`, Kakadu thread handling, decode buffering), the allocator itself (`bazel/mimalloc.BUILD.bazel`, the `_ALLOCATOR` dep in `src/cli/rust/BUILD.bazel`), or allocator-relevant image env. Microbenchmarks (`just bench decode`) measure speed; this harness measures what those decodes do to resident memory over time — a regression here reaches production as an OOM, not a slow chart. ## What it measures, and how to read it The replay drives a containerized sipi with a deterministic JP2-only request mix (large decodes weighted, per-request cache-key variety) and samples container RSS every ~2 s. The signal is the **per-minute RSS floor** — the lowest sample each minute: - **Peaks** are legitimate in-flight decodes; ignore them (but they size the container limit: transient 2–3 GiB at this load is normal). - **A flat floor** means freed memory actually leaves the process. Flat is within ±0.5 GiB/h of zero over 15 minutes. - **A ratcheting floor** means memory that the engine freed is not coming back. Vary *only the allocator* (env or image) on the identical load to split the two possible causes: if another allocator flat-lines, it is allocator retention; if every allocator ratchets, it is a leak. Fifteen minutes is enough to show or rule out a ratchet at this request rate; it says nothing about multi-day creep. ## Usage ``` just bazel-build # the CLI generates the corpus on first run just bazel-docker-build-arm64 # or -amd64: the image under test cd $(mktemp -d) # runs write .csv/.errors to $PWD REPO= # the image under test (daschswiss/sipi:latest by default) $REPO/tools/allocator-replay/replay.sh candidate 900 # allocator variants on the same load, e.g. reproducing the glibc baseline # against a release image: IMAGE=daschswiss/sipi:v6.2.2 $REPO/tools/allocator-replay/replay.sh glibc 900 IMAGE=daschswiss/sipi:v6.2.2 $REPO/tools/allocator-replay/replay.sh arena2 900 -e MALLOC_ARENA_MAX=2 ``` Each run prints the per-minute floors and a least-squares floor slope at the end. `.errors` should contain only the corpus's known non-200s (the `!3000,3000` upscale 400s on small images); anything else is a finding. ## Baselines (2026-07-29, ~100 req/min, 6 workers, 6 GiB limit) | configuration | floor slope | note | | --------------------------- | ---------------- | -------------------------------------------- | | glibc default (v6.2.2) | **+2.5 GiB/h** | reproduces the prod OOM ratchet | | glibc, `MALLOC_ARENA_MAX=2` | flat | the 6.2.3 stopgap | | jemalloc `LD_PRELOAD` | flat | validated fallback | | mimalloc 2.2.4 (BCR) | **OOM at min 6** | abandoned-segment retention; never ship | | mimalloc v3.4.3 (shipped) | flat | floors 0.5–1 GiB | | pre-6.2.1 build, glibc | flat | single-threaded decode: no churn, no ratchet | The last row is the provenance pin: the glibc ratchet began with the 6.2.1 multithreaded-decode change (`7bdb6349`) — per-request Kakadu worker-thread creation is the churn that drives every allocator's worst case, which is why this harness must run again if that threading model changes. In production, the same split is visible without a replay via the `sipi.malloc.*` gauges (`in_use` vs `retained`; see `src/server/rust/src/malloc_stats.rs`). # Profiling Vitrinli integrates [Tracy](https://github.com/wolfpld/tracy), a real-time, nanosecond-resolution instrumentation profiler, to answer one question that the production metrics cannot: **for a given workload, where inside the request does the time actually go?** Tracy is opt-in, local-dev only, and adds zero overhead to normal builds. ## When to use what Vitrinli has several observability and measurement tools. They do not overlap — each answers a different question, in a different place. Reaching for the wrong one wastes effort. | Tool | Question it answers | Scope | Where it runs | Overhead | | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------ | ------------------------- | ------------------------------- | | **Prometheus + Grafana** | *How does the service behave for real users — latency/cache/throughput distribution, in aggregate, over time? Is it trending worse?* | All requests, aggregated | **Production**, always-on | Negligible | | **Sentry** | *What broke, with what stack and context?* | Individual errors | Production | Negligible | | **OpenTelemetry tracing** | *For this one slow request, which stage ate the time?* | Per-request span tree | Production / staging | Low | | **Tracy** *(this doc)* | *Where in the code does the time go for this workload — per function, lock, allocation, thread, at ns resolution?* | One workload, deep | **Local dev**, opt-in | High while the GUI is connected | | **`just bench`** ([Benchmarking](https://sipi.io/development/benchmarking/index.md)) | *Did my specific change make this operation measurably faster?* | One isolated op | Local dev | Measurement harness | | **`just valgrind`** | *Is there a memory error or leak?* | Correctness, not speed | Local dev | Very high | A note on the production stack, because the three pieces are often conflated: **OpenTelemetry** is the instrumentation *standard* (how telemetry is emitted), **Prometheus** is the aggregate *metrics store* (the counters/gauges/histograms, which the collector derives from the OTLP stream), and **Grafana** is the *visualization* layer on top. Vitrinli's Rust server emits **OpenTelemetry traces + OTLP metrics** (with Sentry for errors): per-request spans via `OtelAxumLayer`, W3C `traceparent` continuation in and out (incl. propagation to dsp-api on the Lua preflight's outbound call), the engine counters bridged to OTLP, and the `http.server.request.duration` latency histogram. None of them tell you which C++ function consumed the milliseconds — that is Tracy's job. ## The loop The tools are stages of one workflow, not alternatives: 1. **Grafana** surfaces *what matters to users* and *whether there is a problem* (e.g. p99 latency on JP2 region requests is bad; cache hit-rate dropped). 1. Reproduce that workload **locally**. 1. **Tracy** shows you *where the time goes* in the code for that workload (e.g. it is Kakadu decode, not encode; or an unexpected lock). 1. **`just bench` + `just bench-compare`** *prove the fix* with the [statistical-significance rule](https://sipi.io/development/benchmarking/index.md), on the same `-c opt` binary and machine. 1. Ship; **Grafana** *confirms* the production win. Tracy is step 3. Prometheus/Grafana are steps 1 and 5. Optimize from data, not from a hunch about which function "feels slow." ## Building and running ``` just bazel-build-tracy # -c opt --config=tracy //src/cli/rust:sipi ./bazel-bin/src/cli/rust/sipi server --config config/sipi.localdev-config.lua ``` `just bazel-build-tracy` builds at `-c opt` (so the timeline reflects production codegen) and adds `--config=tracy`, which defines `TRACY_ENABLE` and `TRACY_ON_DEMAND` (see `.bazelrc`). Because the config touches every compile, the first Tracy build is a cold `-c opt` rebuild — subsequent ones are incremental. **On-demand.** With `TRACY_ON_DEMAND` the server collects nothing until the Tracy GUI connects, so it is safe to leave a Tracy build running. Connection is over TCP port **8086**. ## Viewing the timeline The instrumented process listens on TCP port **8086** (`127.0.0.1`). The Tracy profiler can either connect to a live client or open a saved `.tracy` capture, and comes in two forms. ### Browser — no install (easiest) is a WASM build that runs entirely in the page — nothing to install. It does both: click **Connect** and enter the client address (`127.0.0.1:8086` for a local run, or `host:8086` elsewhere), or load a saved `.tracy` capture file from disk. ### Native desktop GUI The installable equivalent (same live-connect and capture-file loading). - **Linux:** `nix develop .#profiling` puts `tracy` (GUI) and `tracy-capture` on your `PATH`. - **macOS:** `brew install tracy` (the nixpkgs GUI build is unreliable on aarch64-darwin, so it is not in the `profiling` shell on macOS). Launch the profiler and click **Connect** (it auto-discovers a local client, or enter `host:8086`). To record a `.tracy` file headlessly — for CI, sharing, or feeding either viewer's file loader — `tracy-capture -o sipi.tracy` connects to the running client and captures until it disconnects. Either way, drive the server with IIIF requests; each worker thread (`sipi-worker`) shows a per-request timeline. ## What is instrumented Zones mirror the four [benchmark tiers](https://sipi.io/development/benchmarking/index.md), so Tracy is the *live, end-to-end* counterpart to the *isolated, microbenchmark* view. A typical IIIF request decomposes as: ``` iiif_handler ├─ parse_iiif_uri (parse tier) └─ serve_iiif (request handler) ├─ SipiCache::check (cache tier) ├─ SipiImage::read (decode tier) │ └─ SipiIOJpeg::read (or SipiIO{J2k,Tiff,Png}::read) ├─ SipiImage::scale (process tier) ├─ SipiImage::rotate ├─ SipiImage::convertToIcc ├─ SipiIOJpeg::write (encode tier) └─ SipiCache::add ``` Instrumentation lives behind one first-party shim, [`src/observability/cpp/profiling.h`](https://sipi.io/src/observability/cpp/profiling.h): code includes it and uses `SIPI_ZONE()` / `SIPI_ZONE_N("name")` rather than the Tracy macros directly, so the profiler dependency sits at a single site. ## Adding a zone ``` #include "observability/profiling.h" void SomeClass::hotMethod() { SIPI_ZONE_N("SomeClass::hotMethod"); // or SIPI_ZONE() to use the function name // ... } ``` `SIPI_ZONE*` expand to Tracy zones only under `--config=tracy`; in every other build they compile to nothing. The macros are RAII-scoped — the zone closes when the enclosing scope exits, including on early `return`. For a deeper dive (sampling, locks, memory, GPU), see the upstream [Tracy manual](https://github.com/wolfpld/tracy/releases) (`tracy.pdf`). ## Why it is free when off Tracy is an unconditional Bazel dependency, but inert without `--config=tracy`: the entire profiler — sockets, sampling, the allocation arena — is gated behind `TRACY_ENABLE`, so a normal build links no listening socket and collects nothing. See [`docs/adr/0016-tracy-opt-in-dev-profiler.md`](https://sipi.io/adr/0016-tracy-opt-in-dev-profiler.md) for the rationale behind the always-present-but-inert wiring. # Testing Strategy This document defines the authoritative testing strategy for sipi. It maps the IIIF Image API 3.0 specification, sipi's extensions (Lua scripting, cache, CLI, knora integration), and Rust migration readiness onto a concrete testing pyramid. Use this document to determine **where** a new test should live, **what** layer it belongs to, and **how** to assess coverage. ## Vitrinli Feature Inventory Vitrinli is a multithreaded, high-performance, IIIF-compatible media server written in C++23. The following is an exhaustive inventory of every feature area. Each feature needs test coverage — the [coverage matrices](#iiif-image-api-30-coverage-matrix) later in this document track the current state. ### IIIF Image API 3.0 Vitrinli implements the full [IIIF Image API 3.0](https://iiif.io/api/image/3.0/) at Level 2 compliance: | Feature Area | Parameters | Source | | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | | **Region** (Section 4.1) | `full`, `square`, `x,y,w,h`, `pct:x,y,w,h` | `src/iiifparser/cpp/value_objects/SipiRegion.cpp` | | **Size** (Section 4.2) | `max`, `w,`, `,h`, `w,h`, `!w,h`, `pct:n`, `^` upscale variants | `src/iiifparser/cpp/value_objects/SipiSize.cpp` | | **Rotation** (Section 4.3) | Arbitrary angles (float), `!` mirror prefix | `src/iiifparser/cpp/value_objects/SipiRotation.cpp` | | **Quality** (Section 4.4) | `default`, `color`, `gray`, `bitonal` | `src/iiifparser/cpp/value_objects/SipiQualityFormat.cpp` | | **Format** (Section 4.5) | `jpg`, `png`, `tif`, `jp2`, `webp` | `src/iiifparser/cpp/value_objects/SipiQualityFormat.cpp` | | **Identifiers** (Section 3) | URL-encoded, `%2F` slash, prefix-based resolution | `src/iiifparser/cpp/value_objects/SipiIdentifier.cpp` | | **Info.json** (Section 5) | Full response: `@context`, `id`, `type`, `protocol`, `profile`, `width`, `height`, `sizes`, `tiles`, `extraFormats`, `extraFeatures`, `preferredFormats` | `src/server/rust/src/info.rs` | | **Content negotiation** | `Accept: application/ld+json` → JSON-LD with `@context`; default → `application/json` | `src/server/rust/src/info.rs` | | **HTTP behavior** (Section 7) | Base URI redirect, HEAD, CORS, Link headers, canonical URI, 400/401/403/404/500/501 errors | `src/server/rust/src/routes.rs` | | **IIIF Extension: `red:n`** | Reduce factor for JP2 (faster subsampling on read) — sipi-specific, not in IIIF spec | `src/iiifparser/cpp/value_objects/SipiSize.cpp` | IIIF Auth exclusion Vitrinli does **not** implement the IIIF Authentication API. Access control is handled via custom Lua preflight scripts (`pre_flight`, `file_pre_flight`) that return allow/deny/restrict permissions. This is intentional — the Knora/DSP integration requires custom auth flows (cookie-based sessions) that don't map to the IIIF Auth spec. ### Image Format Support **Input/Output Formats:** | Format | Handler | Read | Write | Notes | | -------- | ------------ | ---- | ----- | ---------------------------------------------------------------------------------- | | TIFF | `SipiIOTiff` | Yes | Yes | Multi-page, tiled, pyramid; LZW/ZIP/CCITT compression; 1/8/16-bit; RGB/YCbCr/CMYK | | JPEG | `SipiIOJpeg` | Yes | Yes | 8-bit, progressive and baseline; configurable quality | | PNG | `SipiIOPng` | Yes | Yes | Palette/gray/RGB/RGBA; 1/2/4/8/16-bit | | JPEG2000 | `SipiIOJ2k` | Yes | Yes | Via Kakadu (commercial license); reduce factor; quality layers; progression orders | | WebP | `SipiIOWebp` | Yes | Yes | Via libwebp | **Metadata Systems:** | System | Library | Read | Write | Source | | ------------ | ---------- | ---- | ----- | --------------------------------- | | EXIF | Exiv2 | Yes | Yes | `src/metadata/cpp/exif.cpp` | | XMP | Exiv2 | Yes | Yes | `src/metadata/cpp/xmp.cpp` | | IPTC | Exiv2 | Yes | Yes | `src/metadata/cpp/iptc.cpp` | | ICC Profiles | littleCMS2 | Yes | Yes | `src/metadata/cpp/icc.cpp` | | Essentials | Custom | Yes | Yes | `src/metadata/cpp/essentials.cpp` | **Predefined ICC Profiles:** sRGB, AdobeRGB, GRAY_D50, LUM_D65, CMYK_standard, LAB, ROMM_GRAY. **Essentials** is a custom metadata packet embedded in image headers. It stores: original filename, MIME type, pixel data checksum (MD5/SHA1/SHA256/SHA384/SHA512), and a backup of the ICC profile. This survives format conversions and enables provenance tracking. **Color Space Support:** RGB, Grayscale, Bitonal, YCbCr, CMYK (with conversion to sRGB), CIELab (with conversion). 8 TIFF orientations handled; `topleft()` normalization for tiling compatibility. 16-bit big-endian internal representation with automatic 8-bit conversion where needed. ### Image Processing Pipeline The IIIF processing pipeline applies transformations in spec-mandated order: 1. **Region** — crop the source image 1. **Size** — scale to requested dimensions 1. **Rotation** — rotate and/or mirror 1. **Quality** — color space conversion (color, gray, bitonal) 1. **Format** — encode to output format Each step allocates an intermediate buffer. Peak memory is ~2x image size per transform step. **Watermarking** is applied as an additional step when the preflight script returns a `restrict` permission with a watermark path. Watermark files must be single-channel 8-bit gray TIFF (SAMPLESPERPIXEL=1, BITSPERSAMPLE=8, PHOTOMETRIC=MINISBLACK). ### HTTP Server (Rust axum shell) The production HTTP server is the Rust axum shell (`src/server/rust` + `src/cli/rust`), which drives the C++ image engine over the FFI seam: | Feature | Details | Source | | ---------------- | ----------------------------------------------------------------------------------------------------------------- | --------------------------------------- | | SSL/TLS | Terminated at Traefik in front of the shell; `sslport`/`sslcert`/`sslkey` keys parse but are inert | `src/server/rust/src/config.rs` | | Threading | Bounded worker pool with a request queue (env-tunable: `SIPI_NTHREADS`, `SIPI_MAX_WAITING`, `SIPI_QUEUE_TIMEOUT`) | `src/server/rust/src/routes.rs` | | Keep-alive | `keepalive`/`SIPI_KEEPALIVE` CLI/env flag; parse-only, unread | `src/server/rust/src/config.rs` | | Chunked transfer | axum/hyper streaming responses | `src/server/rust/src/sink.rs` | | Range requests | HTTP 206 Partial Content | Handler-level | | CORS | Via Lua preflight scripts | `scripts/` | | Methods | GET, POST, PUT, DELETE | `src/server/rust/src/lib.rs` | | Authentication | JWT (HS256), HTTP Basic Auth, cookie support | `src/scripting/rust/bindings/server.rs` | | Max POST size | Configurable (`max_post_size`, default 300M) | `src/server/rust/src/config_file.rs` | | Multipart upload | Form-data file upload retained as a Lua route (ADR-0017) | `scripts/` | ### Caching System File-based LRU cache with dual-limit eviction (`src/cache/cpp/SipiCache.h`, `src/cache/cpp/SipiCache.cpp`): | Feature | Details | | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | **Eviction policy** | LRU by access time; evicts down to 80% low-water mark | | **Size limit** | `cache_size`: `'-1'`=unlimited, `'0'`=disabled, or `'200M'`, `'1G'` | | **File count limit** | `cache_nfiles`: 0=no limit | | **Crash recovery** | Serialized index on disk; rebuild from directory scan if index missing | | **Concurrent access** | Mutex-protected; `blocked_files` map prevents reads during writes | | **Cache key** | Canonical IIIF URL plus watermark and size-restriction suffixes, hashed with SHA-256 for the index | | **Metrics** | hits, misses, evictions, skips, size, file count — the scalar counters cross the FFI seam via `SipiMetricsSnapshot` and export over OTLP (see below) | | **API endpoints** | None. There is no `/api/cache` route on the Rust shell; observe cache behaviour via the on-disk cache-dir file count | | **Cache metadata** | Image dimensions, tile info, pyramid levels, MIME type, checksum per entry | ### Lua Scripting System Per-request isolated Lua 5.3.5 interpreter with full server access: **SipiImage Lua Class:** | Method | Description | | --------------------------------------------------------- | ----------------------------------------------- | | `SipiImage.new(filepath)` | Load image from file | | `SipiImage.new(upload_index)` | Load from uploaded file | | `SipiImage.new(filepath, {region=, size=, reduce=, ...})` | Load with IIIF options | | `img:dims()` | Get dimensions (nx, ny, orientation) | | `img:exif(tag)` | Read EXIF data | | `img:crop(region)` | Crop to IIIF region | | `img:scale(size)` | Resize to IIIF size | | `img:rotate(rotation)` | Rotate/mirror | | `img:topleft()` | Normalize orientation | | `img:watermark(path)` | Apply watermark | | `img:write(target)` | Write to file or `'HTTP.jpg'` for HTTP response | **Server Object:** | Method/Property | Description | | ------------------------------------------------------------ | ----------------------- | | `server.method`, `.path`, `.get`, `.post`, `.content` | Request data | | `server.sendStatus(code)` | Set HTTP status | | `server.sendHeader(name, value)` | Set response header | | `server.print(...)` | Write response body | | `server.setBuffer()` | Enable buffered output | | `server.requireAuth()` | Require HTTP basic auth | | `server.generate_jwt(table)` | Create HS256 JWT | | `server.decode_jwt(token)` | Decode/verify JWT | | `server.http(method, url, headers, timeout)` | Outbound HTTP request | | `server.json_to_table(json)` / `server.table_to_json(t)` | JSON conversion | | `server.getMimeType(filename)` | MIME detection | | `server.log(msg, level)` | Structured logging | | `server.uuid_to_base62(uuid)` / `server.base62_to_uuid(b62)` | UUID encoding | **Cache Object:** | Method | Description | | --------------------------------- | ----------------------------------------------------- | | `cache.filelist(sort)` | List entries (sort: AT_ASC, AT_DESC, FS_ASC, FS_DESC) | | `cache.delete(canonical)` | Remove entry by canonical URL | | `cache.purge()` | Trigger LRU eviction | | `cache.nfiles()` / `cache.size()` | Current counts | **SQLite Integration:** `server.db` provides Lua access to SQLite databases for custom data storage. **Preflight Scripts:** - `pre_flight(prefix, identifier, cookie)` → returns permission (`allow`, `deny`, `restrict`) + filepath for IIIF requests - `file_pre_flight(prefix, identifier, cookie)` → same for raw file downloads - Restriction types: `watermark` (overlay image), `size` (reduce dimensions) **Custom Routes:** Lua scripts mapped to HTTP method + URL pattern via config `routes` table. ### CLI Mode Vitrinli operates in three CLI modes (`src/cli/cpp/cli_app.cpp`): **File Conversion:** `sipi infile outfile [options]` | Option | Description | | ----------------- | --------------------------------------------- | | `-F, --format` | Output format (jpg, tif, png, jpx, j2k, webp) | | `-I, --icc` | ICC profile conversion (sRGB, AdobeRGB, GRAY) | | `-q, --quality` | JPEG quality (1-100) | | `-n, --pagenum` | Multi-page file page selection | | `-r, --region` | Crop region (pixels) | | `-s, --size` | IIIF-format size | | `--scale` | Percentage scaling | | `-R, --reduce` | JP2 reduce factor | | `-m, --mirror` | Mirror: horizontal, vertical | | `-o, --rotate` | Rotation angle (0-360) | | `-k, --skipmeta` | Strip all metadata | | `-w, --watermark` | Apply watermark (TIFF) | **JP2-specific options:** `--Sprofile`, `--Clayers`, `--Clevels`, `--Corder`, `--Cprecincts`, `--Cblk`, `--Stiles`, `--Cuse_sop`, `--rates`, `--Ctiff_pyramid` **Query Mode:** `sipi query infile` — print image metadata. **Compare Mode:** `sipi compare file1 file2` — compare two images. **Server Mode:** the Rust axum shell (`//src/cli/rust:sipi server --config config.lua`) with CLI overrides for port, hostname, imgroot, cache settings, JWT, admin credentials, logging, etc. (TLS terminates at Traefik; `sslcert`/`sslkey` flags parse but are inert.) ### Configuration System Lua-based configuration (`src/ffi/cpp/SipiConf.h`, `src/ffi/cpp/SipiConf.cpp`): | Category | Keys | | -------------------- | ----------------------------------------------------------------------- | | **Server** | `port`, `nthreads` | | **Image repository** | `imgroot`, `prefix_as_path` | | **Image processing** | `jpeg_quality`, `scaling_quality.{jpeg,tiff,png,j2k}` (high/medium/low) | | **Cache** | `cache_dir`, `cache_size`, `cache_nfiles` | | **Request handling** | `max_post_size`, `tmpdir`, `max_temp_file_age` | | **Lua** | `initscript`, `scriptdir`, `thumb_size` | | **Authentication** | `jwt_secret` (≥32 bytes) | | **Static files** | `fileserver.docroot`, `fileserver.wwwroute` | | **Knora/DSP** | `knora_path`, `knora_port` | | **Routes** | `routes` table: `{method, route, script}` | **Deprecated keys:** `cachedir` → `cache_dir`, `cachesize` → `cache_size`, `cache_hysteresis` → removed (80% low-water mark is now hardcoded). ### Metrics (OTLP) The cache counters and gauges are exported over OTLP, not a scrape endpoint. The C++ engine maintains them (`src/observability/cpp/metrics.h`, `src/observability/cpp/metrics.cpp`); the scalar fields cross the FFI seam via `SipiMetricsSnapshot` and the Rust shell (`src/server/rust/src/metrics.rs`) emits them over OTLP. There is no `GET /metrics` route. Test accordingly: cache observability goes through on-disk cache-dir file counts (`cache.rs`), not a scrape endpoint. | Metric | Type | Description | | ------------------------ | ------- | ------------------------------------- | | `cache_hits_total` | Counter | Total cache hits | | `cache_misses_total` | Counter | Total cache misses | | `cache_evictions_total` | Counter | Total files evicted | | `cache_skips_total` | Counter | Cache checks skipped (cache disabled) | | `cache_size_bytes` | Gauge | Current cache size | | `cache_files` | Gauge | Current cached file count | | `cache_size_limit_bytes` | Gauge | Configured size limit | | `cache_files_limit` | Gauge | Configured file count limit | ### Upload & Ingest - Multipart form-data file upload via POST - Format conversion on upload (e.g., TIFF → JP2) via Lua routes - knora.json sidecar generation with checksums, MIME type, original filename, dimensions - Essentials metadata embedded during ingest ### Security Features | Feature | Details | | ------------------------- | ------------------------------------------------------------------- | | JWT validation | HS256 with configurable secret; decode + verify in Lua | | HTTP Basic Auth | Via `server.requireAuth()` in Lua routes | | Preflight access control | `pre_flight` / `file_pre_flight` scripts return allow/deny/restrict | | Path traversal prevention | URL-decoded identifier validation | | Max POST size | Configurable (`max_post_size`, default 300M) | | Admin auth | Separate admin user/password for management endpoints | ### Integration Features | Feature | Details | | --------------- | --------------------------------------------------------------------------------------- | | **Knora/DSP** | Session cookie validation, knora.json sidecar, configurable API path/port | | **File access** | Raw file download via `/prefix/identifier/file` with `file_pre_flight` auth | | **Sentry** | Error reporting via `SIPI_SENTRY_DSN`, `SIPI_SENTRY_ENVIRONMENT`, `SIPI_SENTRY_RELEASE` | ### Build & Deployment | Feature | Details | | ------------------------- | --------------------------------------------------------------------------------------------- | | **Build systems** | Bazel (Nix provisions the dev shell only) | | **CI** | GitHub Actions: unit tests, e2e tests, fuzz (nightly), Docker builds | | **Documentation** | MkDocs Material site, LLM-optimized `llms.txt` output | | **Dependency management** | Bazel `bazel_dep` (BCR) + `http_archive` source pins with SHA-256 checksums in `MODULE.bazel` | ______________________________________________________________________ ## Testing Pyramid Four layers, from fastest/narrowest to slowest/broadest: ``` ┌─────────┐ │ Fuzz │ Continuous (nightly CI) │ Testing │ Finds crashes & edge cases ┌───┴─────────┴───┐ │ E2E Contract │ Rust harness (reqwest) │ Tests (HTTP) │ Tests the API contract ┌───┴─────────────────┴───┐ │ Integration / Snapshot │ insta golden baselines │ Tests │ Regression detection ┌───┴─────────────────────────┴───┐ │ Unit Tests │ GoogleTest (C++) where it's the only reach │ + Rust unit tests │ New: Rust #[test] + proptest (preferred) └──────────────────────────────────┘ ``` **Distribution target (post-Rust-migration steady state):** ~50% unit, ~30% e2e contract, ~15% snapshot/integration, ~5% fuzz. Current distribution (~47% unit, ~52% e2e) is inverted because the C++ codebase lacks Rust unit tests; as migration progresses and Rust `#[test]` modules grow, the ratio will shift toward the target. ## Layer Definitions ### Layer 1: Unit Tests (fastest, most numerous) **Purpose:** Test individual functions and parsers in isolation. | Sublayer | Framework | Location | When to use | | --------------------- | ---------------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | C++ unit | GoogleTest | `test/unit/` | When the behavior cannot be reached from Rust e2e — internal C++ state, FFI boundaries, RAII / exception paths, concurrency primitives | | Rust unit (preferred) | `#[test]` + `proptest` | Future `src/` modules | During Rust migration: inline `#[cfg(test)]` modules | | Rust property-based | `proptest` | Future `src/` modules | Parsers, serializers, roundtrip invariants | **What belongs here:** - IIIF URL parsing (region, size, rotation, quality, format) - Filename hashing - Configuration parsing - HTTP header parsing, URL encoding/decoding - Image metadata extraction - Any pure function with well-defined inputs/outputs **C++ unit-test policy:** Default to Rust unit tests or Rust e2e for new coverage — they survive the migration and exercise the contract clients see. Add C++ unit tests where they are the only practical reach, and only there. In practice this means: - **Internal C++ state** that has no HTTP-observable surface (cache eviction order, memory-budget acquire/release, parser intermediate AST). - **FFI / C-library boundaries** where the bug class lives in the C++↔C interop (libtiff variadic-arg type widths, kakadu callback lifetimes, lcms2 profile ownership) and Rust e2e would observe only the downstream symptom. - **Move/copy/RAII semantics** that pure-function tests can pin but server-level tests cannot (assignment-operator buffer lifecycle, exception-safety guarantees, `noexcept` move correctness). - **Concurrency primitives** with lock-free or atomic semantics (`SipiMemoryBudget`) where deterministic e2e reproduction is impractical. - **Engine-internal coverage:** C++ engine components the Rust shell drives (cache management, decode pipeline) are covered with C++ unit tests that travel with the C++ code. This documents existing engine behavior and avoids false failures when internal C++ behavior changes while the HTTP contract the shell exposes stays fixed. (Lua scripting is Rust-hosted — its coverage is the Rust `#[test]` files in `src/scripting/rust/`.) Behavior that *is* HTTP-observable belongs in Rust e2e — not in C++ unit tests. ### Layer 2: Snapshot / Golden Baseline Tests **Purpose:** Detect unintended output changes via approved golden baselines. | Framework | Location | When to use | | ------------------- | --------------------------- | --------------------------------------------------------------------------- | | `insta` (Rust) | `test/e2e/tests/snapshots/` | info.json structure, HTTP headers, response metadata | | ApprovalTests (C++) | `test/approval/` | Image-conversion metadata fingerprints; byte-exact encoder output baselines | **ApprovalTests scope:** New C++ approval suites are admissible only for byte-exact encoder-output gating against dependency migrations (e.g. libtiff, libjpeg, kakadu, lcms2 version bumps) and for metadata fingerprints that have no Rust-side equivalent. Functional behaviour belongs in Layer 3 (Rust e2e), not here. **What belongs here:** - Full info.json structure (field names, types, values) - HTTP response header sets (content-type, CORS, Link) - knora.json response structure - Image metadata fingerprints (EXIF tags, XMP fields, ICC profile name) — golden baselines prevent silent metadata drift during code changes or format handler updates - Byte-exact encoder output baselines for dep-migration regression gating (TIFF/JP2/PNG goldens captured under deterministic encoder settings) - Any complex output where field-by-field assertion is fragile **Pattern:** Use `insta::assert_json_snapshot!` with redactions for dynamic fields (`id`, timestamps). **ICC determinism gate.** Approval tests under `test/approval/image_encode_baseline_test.cpp` are byte-stable only when `SOURCE_DATE_EPOCH` is set. lcms2 stamps wall-clock UTC into bytes 24-35 of every freshly-created ICC profile (and several emit paths in SipiImage round-trip through that), so without the env var the seconds field drifts across consecutive runs of the same binary. `Icc::iccBytes()` overwrites those bytes (and zeros the Profile ID at bytes 84-99) when the env var is set; CMake injects `SOURCE_DATE_EPOCH=946684800` (2000-01-01T00:00:00Z UTC) into the `sipi.approvaltests` invocation via `set_tests_properties(... ENVIRONMENT ...)`. Production never sets the var and retains lcms2's wall-clock behaviour. See [`docs/adr/0002-icc-profile-determinism-test-only.md`](https://sipi.io/adr/0002-icc-profile-determinism-test-only.md) for the architectural rationale and [`test/approval/CHANGELOG.approval.md`](https://sipi.io/test/approval/CHANGELOG.approval.md) for the maintainer's how-to. ### Layer 3: E2E Contract Tests (HTTP-level) **Purpose:** Test sipi's HTTP API contract — the behavior visible to clients. These tests survive the Rust migration because they test the contract, not the implementation. | Sublayer | Framework | Location | When to use | | ------------------ | ---------------- | ----------------- | ----------------------------------------------------------------------------------------------- | | All HTTP contracts | Rust (`reqwest`) | `test/e2e/tests/` | Status/header smokes, multi-step workflows, response body inspection, uploads, golden snapshots | **What belongs here:** - IIIF Image API 3.0 compliance (ALL testable requirements) - Content negotiation (Accept header → Content-Type) - CORS (preflight, origin echo, wildcard) - Authentication/authorization (401, 403) - Error handling (400, 404, 500, 501) - File upload and retrieval - Lua endpoint contracts - Cache behavior (hit/miss via headers or metrics) - Video/non-image file handling - CLI mode testing (via process spawn + file output verification) - Range requests - Concurrent request handling ### Layer 4: Property & Fuzz Testing **Purpose:** Find crashes, memory safety issues, and edge cases in parsers and input handlers. | Framework | Location | When to use | | -------------------------------------- | ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- | | `proptest` (Rust) | `test/e2e/tests/proptest_iiif_uri.rs` | Property-based coverage of the Rust IIIF URI parser (`parse_request`) | | Corpus regression (Rust) | `src/iiifparser/rust/corpus_regression_test.rs` | Fixed sweep of the 241-file shared corpus through `parse_request` — the per-PR net | | libFuzzer (`rules_fuzzing` + FFI shim) | `src/iiifparser/fuzz/` → `//src/iiifparser/fuzz:parse_request_fuzz` | Coverage-guided fuzzing of `//src/iiifparser/rust:iiif_parser` (`parse_request`) | | libFuzzer (codec decode harnesses) | `src/format_handlers/fuzz/` → `//src/format_handlers/fuzz:{tiff,jpeg,png,j2k}_decode_fuzz` | Coverage-guided fuzzing of the four `SipiIO` codec decode entry points (DEV-7066) | **Status: shipped.** Every fuzz target has two modes from one definition. By default (`rules_fuzzing`'s `replay` engine, no libFuzzer runtime) it is a corpus-replay regression test that builds and runs on every platform and rides along in the `//src/...` sweeps — including the sanitizer leg. `--config=fuzz` arms the real libFuzzer engine plus SanitizerCoverage on the Rust crate graph (for `parse_request_fuzz`) or the C++ codec handlers (for the four `format_handlers` decode harnesses); that mode is Linux-only and runs nightly. ``` bazel test //src/iiifparser/fuzz:parse_request_fuzz # corpus replay, any platform bazel test //src/format_handlers/fuzz:tiff_decode_fuzz # corpus replay, any platform just fuzz -max_total_time=60 # mutation loop, Linux ``` The retired C++ libFuzzer harness (`//fuzz/handlers`) fuzzed the oracle-only C++ classifier and went away with the oracle. See [Fuzzing](https://sipi.io/development/fuzzing/index.md) for the shim seam, the corpus policy, and the nightly workflow. **What belongs here:** - IIIF URI parser (`//src/iiifparser/rust:iiif_parser` (`parse_request`)) - Image format header parsing (`//src/format_handlers/fuzz:{tiff,jpeg,png,j2k}_decode_fuzz`, the `SipiIO` decode entry points) - Any function that processes untrusted input ## Test Decision Tree ``` New test needed? ├── Is it testing a pure function/parser? │ ├── C++ component not yet migrated → maintain existing GoogleTest (no new suites) │ └── Rust component → #[test] + proptest for property-based ├── Is it testing HTTP API behavior? │ └── Rust e2e (`reqwest` + `serde_json` / `insta` for snapshots) ├── Is it regression detection for complex output? │ └── insta snapshot (JSON structure, headers) — this is a Rust e2e test with insta ├── Is it testing untrusted input handling? │ └── proptest (`proptest_iiif_uri.rs`) + the corpus regression sweep; the nightly │ libFuzzer target (`//src/iiifparser/fuzz`) covers mutation ├── Is it testing image output correctness? │ └── Rust e2e with `image` crate decode + dimension/checksum verification └── Does it need filesystem setup or custom server config? └── Rust e2e with tempfile + custom SipiServer::start config ``` **Clarifications:** - "Image output correctness" tests are a specialization of e2e contract tests, not a separate layer - Snapshot tests (`insta`) live inside Rust e2e test files — they are e2e tests that use snapshot assertions - Tests needing cache verification require a cache-enabled server config (use `sipi.cache-test-config.lua` which has cache configured) - Python e2e tests have been retired and replaced by Rust e2e tests. See [Python Test Deprecation](#python-test-deprecation--parity-checklist) for the parity checklist - Flaky tests (e.g., races against file flush) should use the `retry_flaky()` helper — see [Flaky Test Handling](#flaky-test-handling) ## IIIF Image API 3.0 Coverage Matrix The following matrix maps every testable IIIF spec requirement to its test status. This is the authoritative coverage reference. ### Info.json (Section 5) | Requirement | Status | Test | Notes | | --------------------------------------- | ------------------ | --------------------------------------- | ------------------------------------- | | `@context` field present and correct | :white_check_mark: | `info_json_context` | | | `id` matches base URI | :white_check_mark: | `info_json_id_contains_base_uri` | | | `type` = `ImageService3` | :white_check_mark: | `info_json_type_imageservice3` | | | `protocol` = `http://iiif.io/api/image` | :white_check_mark: | `info_json_protocol` | | | `profile` = `level2` | :white_check_mark: | `info_json_profile_level2` | | | `width` and `height` integers | :white_check_mark: | `info_json_dimensions_match_lena512` | | | `sizes` array with valid dimensions | :white_check_mark: | `info_json_sizes_have_valid_dimensions` | | | `tiles` with scaleFactors | :white_check_mark: | `info_json_tiles_have_scale_factors` | | | `extraFormats` | :white_check_mark: | `info_json_extra_formats` | | | `preferredFormats` | :white_check_mark: | `info_json_preferred_formats` | | | `extraFeatures` (17 features) | :white_check_mark: | `info_json_all_17_extra_features` | | | Golden baseline snapshot | :white_check_mark: | `info_json_golden_snapshot` | insta | | Header snapshot (CT, CORS, Link) | :white_check_mark: | `info_json_headers_snapshot` | insta | | Content-Type without Accept | :white_check_mark: | `info_json_content_type_default` | `application/json` | | Content-Type with Accept: ld+json | :white_check_mark: | `jsonld_media_type_with_accept` | | | Link header on default request | :white_check_mark: | `jsonld_default_has_link_header` | | | Canonical Link header | :white_check_mark: | `canonical_link_header` | | | Profile Link header | :white_check_mark: | `profile_link_header` | emitted on image responses (DEV-6733) | | X-Forwarded-Proto HTTPS rewrite | :white_check_mark: | `info_json_x_forwarded_proto_https` | | | Required fields structural check | :white_check_mark: | `info_json_has_required_fields` | | | Structural: sizes array exists | :white_check_mark: | `info_json_has_sizes_array` | | | Structural: tiles array exists | :white_check_mark: | `info_json_has_tiles_array` | | | Structural: extraFeatures exists | :white_check_mark: | `info_json_has_extra_features` | | ### Region (Section 4.1) | Requirement | Status | Test | Notes | | ----------------------------- | ------------------ | ------------------------------------- | ------------------------------------------------------------- | | `full` | :white_check_mark: | `full_iiif_url_returns_image` | | | `square` | :white_check_mark: | `region_square` | | | `pct:x,y,w,h` | :white_check_mark: | `region_percent` | | | `x,y,w,h` (pixel) | :white_check_mark: | `region_pixel`, `region_pixel_offset` | | | Overflow → crop at edge | :white_check_mark: | `region_beyond_bounds_is_cropped` | | | Start beyond image → error | :white_check_mark: | `region_start_beyond_image` | | | Zero width → 400 | :white_check_mark: | `region_zero_width` | | | Invalid syntax → error | :white_check_mark: | `region_invalid_syntax` | | | Region + size combination | :white_check_mark: | `size_after_region` | | | Region + rotation combination | :white_check_mark: | `rotation_after_region` | | | Region crop (specific) | :white_check_mark: | `iiif_region_crop` | | | Region dimension verification | :white_check_mark: | `region_dimension_verification` | decodes output, asserts pixel dims match the requested region | ### Size (Section 4.2) | Requirement | Status | Test | Notes | | ----------------------------- | ------------------ | --------------------------------- | ----------------------------------------------- | | `max` | :white_check_mark: | `full_iiif_url_returns_image` | implicit | | `w,` (width) | :white_check_mark: | `size_by_width` | | | `,h` (height) | :white_check_mark: | `size_by_height` | | | `w,h` (exact) | :white_check_mark: | `size_exact` | | | `!w,h` (best fit) | :white_check_mark: | `size_best_fit` | | | `pct:n` | :white_check_mark: | `size_percent` | | | `^` upscaling | :white_check_mark: | `size_upscaling` | | | No upscale beyond original | :white_check_mark: | `size_no_upscale_beyond_original` | | | Invalid syntax → error | :white_check_mark: | `size_invalid_syntax` | | | Output dimension verification | :white_check_mark: | `size_dimension_verification` | decodes output, asserts actual pixel dimensions | | `^max` upscale to limits | :white_check_mark: | `size_upscale_max` | | | `^,h` (height-only upscale) | :white_check_mark: | `size_upscale_height` | | | `^w,h` (exact with upscale) | :white_check_mark: | `size_upscale_exact` | | | `^!w,h` (confined upscale) | :white_check_mark: | `size_upscale_confined` | | | `^pct:n` (upscale percent) | :white_check_mark: | `size_upscale_percent` | | ### Rotation (Section 4.3) | Requirement | Status | Test | Notes | | ---------------------------- | ------------------ | --------------------------------- | ----------------------------------------------- | | `0` (no rotation) | :white_check_mark: | `full_iiif_url_returns_image` | implicit | | `90` | :white_check_mark: | `iiif_rotation_90` | | | `180` | :white_check_mark: | `rotation_180` | | | `270` | :white_check_mark: | `rotation_270` | | | Arbitrary (e.g. 22.5) | :white_check_mark: | `rotation_arbitrary` | | | `!0` (mirror only) | :white_check_mark: | `mirror_rotation` | | | `!180` (mirror + rotate) | :white_check_mark: | `mirror_plus_180` | | | Invalid → error | :white_check_mark: | `rotation_invalid` | | | Rotation output verification | :white_check_mark: | `rotation_dimension_verification` | decodes output, asserts dimensions swap for 90° | ### Quality (Section 4.4) | Requirement | Status | Test | Notes | | ----------------------------- | ------------------ | ------------------------------ | ---------------------------------------------------------------- | | `default` | :white_check_mark: | `full_iiif_url_returns_image` | implicit | | `color` | :white_check_mark: | `quality_color` | | | `gray` | :white_check_mark: | `quality_gray` | | | `bitonal` | :white_check_mark: | `quality_bitonal` | | | Invalid → error | :white_check_mark: | `quality_invalid` | | | `extraQualities` in info.json | :white_check_mark: | `extra_qualities_in_info_json` | asserts array shape when present; absence documented, not failed | ### Format (Section 4.5) | Requirement | Status | Test | Notes | | --------------------------------- | ------------------ | ------------------------------ | ----- | | `jpg` + Content-Type | :white_check_mark: | `format_jpg_content_type` | | | `png` + Content-Type | :white_check_mark: | `format_png_content_type` | | | `tif` + Content-Type | :white_check_mark: | `format_tiff_content_type` | | | `jp2` + Content-Type | :white_check_mark: | `format_jp2_content_type` | | | Unsupported (gif, pdf, webp, bmp) | :white_check_mark: | `unsupported_formats_rejected` | | ### CORS (Section 7.1) | Requirement | Status | Test | Notes | | ------------------------------------------------- | ------------------ | ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- | | Info.json ACAO without Origin | :white_check_mark: | `cors_info_json_without_origin` | `*`, no credentials | | Info.json ACAO with Origin | :white_check_mark: | `cors_info_json_with_origin` | Echoed Origin + credentials, `Vary: Origin` | | Info.json ACAO with Origin and Cookie | :white_check_mark: | `cors_info_json_with_origin_and_cookie` | Echoed Origin + credentials | | Info.json 401 auth challenge with Origin | :white_check_mark: | `cors_info_json_auth_challenge_with_origin` | Echoed Origin + credentials | | Info.json OPTIONS preflight | :white_check_mark: | `cors_preflight_info_json` | Echoed Origin + credentials, explicit methods and headers | | Info.json under `SIPI_ALLOWED_ORIGINS` | :white_check_mark: | `allowed_origins_allowlist_gates_info_json_cors` | `security.rs`; denied Origin gets no ACAO | | Knora.json `Vary: Origin` with and without Origin | :white_check_mark: | `cors_knora_json_varies_on_origin` | `*` without Origin, echoed Origin + credentials with one | | Image ACAO with Origin | :white_check_mark: | `cors_image_with_origin` | | | Image ACAO without Origin | :white_check_mark: | `cors_image_without_origin` | | | Error ACAO with Origin (400/401/403/404) | :white_check_mark: | `cors_error_responses_with_origin` | Image, info.json, knora.json and `/file` (no `/file` 403: the test hook never restricts); echoed Origin + credentials | | Error ACAO on a 503 shed | :white_check_mark: | `lua_route_occupies_the_full_lane` | `admission_control.rs`; echoed Origin + credentials | | Error ACAO under `SIPI_ALLOWED_ORIGINS` | :white_check_mark: | `allowed_origins_allowlist_gates_info_json_cors` | `security.rs`; 404 echoes a listed Origin, an unlisted one gets only `Vary: Origin` | | OPTIONS preflight | :white_check_mark: | `cors_preflight` | | ### HTTP Behavior (Section 7) | Requirement | Status | Test | Notes | | --------------------------------------------- | ------------------ | ----------------------------------- | ---------------------------- | | Base URI → redirect to info.json | :white_check_mark: | `base_uri_redirect` | | | HEAD request | :white_check_mark: | `head_iiif_image_empty_body` | | | 401 unauthorized | :white_check_mark: | `deny_unauthorized_image` | | | 404 not found | :white_check_mark: | `id_random_gives_404` | | | Path traversal rejected | :white_check_mark: | `path_traversal_rejected` | | | Incomplete URL → error | :white_check_mark: | `id_incomplete_iiif_url` | | | Malformed URL → error | :white_check_mark: | `id_malformed_iiif_url` | | | Empty identifier → error | :white_check_mark: | `invalid_iiif_url_empty_identifier` | | | HEAD returns headers | :white_check_mark: | `head_request_returns_headers` | | | Missing file → 404 | :white_check_mark: | `returns_404_for_missing_file` | | | HTTP 304 conditional requests | :white_check_mark: | `conditional_request_304` | If-Modified-Since round-trip | | Operation ordering (Region→Size→Rot→Qual→Fmt) | :white_check_mark: | `operation_ordering` | | | Fractional percent regions (e.g. pct:0.5,...) | :white_check_mark: | `fractional_percent_region` | | ### Identifier (Section 3) | Requirement | Status | Test | Notes | | ----------------------- | ------------------ | -------------------------- | ----------------------------------------------------------------------------------------------- | | Encoded slash `%2F` | :white_check_mark: | `id_escaped_slash_decoded` | | | Encoded `#` (`%23`) | :white_check_mark: | `id_escaped` | resolves to the on-disk `#` file (DEV-6732) | | Subdirectory identifier | :white_check_mark: | via server tests | | | Non-ASCII identifiers | :white_check_mark: | `id_non_ascii` | | | ARK/URN identifiers | :x: GAP | — | Not tested (may not apply — sipi identifiers are opaque path segments, not a namespaced scheme) | ## Vitrinli Extension Coverage Matrix Two Rust-shell features the C++-era gap list assumed are permanently **removed**, not gaps: the Prometheus `/metrics` scrape (OTLP replaces it) and the Lua `/api/cache` admin endpoint (the route is unregistered and the Lua `cache` table bindings were never carried over). SSL/TLS is likewise **N/A** — TLS terminates at Traefik in front of the shell; `sslcert`/`sslkey` parse but are inert. `admin_upload.lua` / `/admin/upload` never existed in this repo. | Feature | Status | Test Location | Notes | | --------------------------------------------------------------------------------- | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | File upload (TIFF→JP2) | :white_check_mark: | `upload.rs` | | | Upload knora.json | :white_check_mark: | `upload.rs` | | | Upload JPEG with comment block | :white_check_mark: | `upload.rs` | | | Video knora.json metadata | :white_check_mark: | `server.rs` | | | Lua test_functions endpoint | :white_check_mark: | `server.rs` | | | Lua mediatype endpoint | :white_check_mark: | `server.rs` | | | Lua mimetype_func endpoint | :white_check_mark: | `server.rs` | | | Lua knora_session_cookie | :white_check_mark: | `server.rs` | | | Lua orientation endpoint | :white_check_mark: | `server.rs` | | | Lua exif_gps endpoint | :white_check_mark: | `server.rs` | | | Lua read_write endpoint | :white_check_mark: | `server.rs` | | | SQLite API | :white_check_mark: | `server.rs::sqlite_api` | | | Missing sidecar handling | :white_check_mark: | `server.rs::missing_sidecar_handled_gracefully` | | | Concurrent request handling | :white_check_mark: (ignored) | `server.rs::concurrent_requests` | `#[ignore]`'d — the engine-pool semaphore sheds load (503) under concurrent bursts by design; the test itself is correct, revisit when the cluster-A permit-release work lands | | File access allowed/denied | :white_check_mark: | `server.rs` | | | Knora.json validation | :white_check_mark: | `server.rs::knora_json_image_required_fields`, `knora_json_image_dimensions` | | | Upload edge cases | :white_check_mark: | `upload.rs` | | | Video metadata extensions | :white_check_mark: | `server.rs::video_knora_json_checksums` | | | Small-file range requests | :white_check_mark: | `range_requests.rs` | 7 tests | | Large-file range requests (10MB+) | :white_check_mark: | `range_requests.rs` | 8 tests | | Cache hit/miss verification | :white_check_mark: | `cache.rs::cache_hit_avoids_decode`, `head_does_not_warm_cache` | observed via on-disk cache-dir file count, not `/metrics` (removed) | | CLI mode (file conversion) | :white_check_mark: | `test/e2e/tests/cli.rs` | `sipi convert ` covered | | Prometheus metrics endpoint | N/A — removed | — | OTLP replaces it on the Rust shell; there is no scrape endpoint | | SSL/TLS endpoints | N/A — removed | — | TLS terminates at Traefik; the Rust shell serves plain HTTP only, flags parse-only | | Image dimension verification | :white_check_mark: | `iiif_compliance.rs::region_dimension_verification`, `size_dimension_verification`, `rotation_dimension_verification` | decodes output and asserts actual pixel dimensions | | EXIF preservation through IIIF pipeline | :white_check_mark: | `iiif_compliance.rs::metadata_iiif_pipeline`; `server.rs::lua_exif_gps` | HTTP-level; `server.rs::restricted_output_rewrites_dimension_metadata` diffs every `Exif.*` line (via `sipi query`) against the unrestricted output | | XMP preservation through IIIF pipeline | :white_check_mark: | `server.rs::restricted_output_keeps_rights_metadata_verbatim`; unit `formats_test` `JpegMetadataSegments.*` | XMP `dc:rights` and EXIF `Copyright` of `CIELab16.tif` survive byte for byte in jpg/png/tif/jp2 outputs; `cli_json.rs` covers malformed XMP; a jpg XMP packet over one segment is split into Extended XMP with the rights in the standard packet, an EXIF over one segment loses only its previews; a block that still does not fit (EXIF, unsplittable XMP) is left out with a warning and the JPEG is delivered | | ICC profile preservation/conversion | :x: GAP | — | C++ unit tests exist but no HTTP-level round-trip test | | IPTC metadata preservation | :white_check_mark: | `heritage_jpeg.rs`; `server.rs::every_output_format_keeps_the_iptc_metadata` | resilient parse of heritage APP13/IPTC; `CIELab16.tif`'s `Iptc.*` lines (Copyright included) equal the source's in jpg/png/tif/jp2 outputs, restricted and unrestricted; IPTC over one segment continues in further APP13 segments (unit `JpegMetadataSegments.LargeIptcContinuesInFurtherApp13Segments`) | | Essentials round-trip | :white_check_mark: | `upload.rs::metadata_essentials_roundtrip` | | | CLI conversion metadata fidelity | :white_check_mark: | `cli.rs::cli_metadata_fidelity` | | | MIME consistency check (`/api/mimetest`) | :white_check_mark: | `server.rs::mime_consistency` | all 6 cases ported | | Thumbnail generation (`/make_thumbnail`) | :white_check_mark: | `server.rs::thumbnail_generation`, `thumbnail_convert_from_file` | | | Convert from binaries (`/convert_from_binaries`) | :white_check_mark: | `server.rs::image_conversion_from_binaries` | | | Temp directory cleanup | :white_check_mark: | `server.rs::temp_directory_cleanup` | | | Restricted image size reduction | :white_check_mark: | `server.rs::restricted_image_reduction` | | | Restricted image as its own image (RW, RH) | :white_check_mark: | `dsp_api_closure.rs::restricted_info_json_states_the_restricted_dims_as_its_maximum`, `restricted_info_json_dims_equal_full_max`, `restricted_tiles_at_size_max_stitch_to_full_max`, `restricted_left_half_region_is_the_left_half_of_full_max`, `restricted_canonical_link_is_in_restricted_coordinates`, `permission_code_1_restricts_the_size_of_a_region_request`; unit `//src/ffi:serve_image_test` (`RestrictedImage.*`, `Sizes/RestrictedSize.*`) | ADR-0028: region/size resolve against (RW, RH), exact `full/max` on non-dividing sizes, tiles stitch, pre-rotation (RW, RH) bound, passthrough guard, `/rx` cache-key marker; `info.rs::size_restricted_image_states_its_max_size` | | `full/max` on unrestricted images is native (DEV-6118) | :white_check_mark: | `iiif_compliance.rs::full_max_on_unrestricted_images_is_the_native_size` | JP2 and TIFF, `max` and `^max` | | Restriction refusals and the box size | :white_check_mark: | `security.rs::no_op_restrictions_are_refused_on_every_route`, `restricted_knora_json_dims_match_info_json`, `image_inside_restriction_box_is_served_at_native_size` | A size that never reduces (`max`, `pct:100`, empty watermark) is refused on the image, info.json and knora.json; knora.json dims equal info.json's; an image inside a box size is served at native size | | JP2 component subsampling | :white_check_mark: | `server.rs::subsampled_jp2_serves_full_image`; `cli_conversions.rs` `jp2_decode_file3`; unit `//src/format_handlers:formats_test` (`J2kSubsampling.*`, `J2kSubsamplingRegion.*`) | ISO 15444-4 `file3.jp2` decodes full, reduced and by region against the reference; unsupported factors fail fast | | JP2 channel order from the `cdef` mapping | :white_check_mark: | `cli_conversions.rs` `jp2_decode_file2`; unit `//src/format_handlers:formats_test` (`J2kChannelOrder.*`) | YCbCr converted in Y/Cb/Cr order, with and without a reversing `cdef` | | Writing over a larger existing file | :white_check_mark: | unit `//src/format_handlers:formats_test` (`FormatOverwrite.*`, `JpegWrite.OverwritingLargerFileTruncatesIt`) | No stale trailing bytes in any format | | EXIF `addKeyVal` replaces an existing value | :white_check_mark: | unit `//src/metadata:exif_rational_test` (`ExifAddKeyVal.*`) | Tag/group overloads; an unsupported type throws and keeps the value | | Size-restricted output dimension metadata | :white_check_mark: | `server.rs::restricted_output_rewrites_dimension_metadata`; `serve_image_test` `RestrictedImage.MetadataDropsPreviewsAndStatesTheDeliveredSize`, `RestrictedImage.ExifImageResourcesDropPreviewsAndStateTheDeliveredSize`; unit `//src/metadata:pixel_dimensions_test` | EXIF and XMP size fields state the delivered size, no EXIF thumbnail, maker-note preview, XMP thumbnail or Photoshop thumbnail resource (crafted source), every other EXIF/IPTC line equal to the unrestricted output | | 4-bit palette PNG upload | :white_check_mark: | `upload.rs` | `upload_4bit_palette_png` | | Cache API routes (`/api/cache`) | N/A — removed | — | route unregistered, Lua `cache` table bindings absent from `src/` | | Favicon endpoint | :x: GAP | — | favicon route exists (`src/server/rust/src/lib.rs`); its only e2e test was removed with the differential suite | | Memory safety (ASan/LSan) | :white_check_mark: | `ci.yml`'s `sanitizer` job | unit + e2e suites against an ASan+UBSan-instrumented binary (see Cross-Cutting section below) | | Thread safety (TSan) | :x: GAP | — | Untested for data races; future optional nightly variant | | Performance regression detection | :white_check_mark: | `latency.rs` | smoke thresholds only (info.json / cache-miss / cache-hit); load-baseline tier intentionally deferred to staging (see Cross-Cutting section) | | Corrupt/truncated image handling | :white_check_mark: | `iiif_compliance.rs::corrupt_jpeg_handling`, `corrupt_png_handling`, `corrupt_image_handling` (truncated JP2) | JP2 decode converts Kakadu's thrown error into a `SipiImageError` (like JPEG/PNG); the server returns a clean error and stays up (DEV-6731) | | Lua route handler errors | :white_check_mark: | `server.rs::lua_route_error_handling` | | | Zero-byte / empty file upload | :white_check_mark: | `upload.rs::empty_file_upload` | | | Invalid server config startup | :white_check_mark: | `config.rs::invalid_config_startup` | | | Double-encoded URL handling | :white_check_mark: | `iiif_compliance.rs::double_encoded_url` | `%252F`: the Rust shell single-decodes (DEV-6700) | | Extremely long URL / header | :x: GAP | `//src/iiifparser/fuzz:parse_request_fuzz` (URL half only) | URL half closed: libFuzzer mutates URI length without bound (nightly, Linux) and the corpus replay runs on every PR. The header half is still untested — the fuzz target takes the URI, not HTTP headers | | JWT validation edge cases | :white_check_mark: | `security.rs::jwt_expired_token`, `jwt_alg_none_bypass`, `jwt_tampered_payload` | the preflight response-sink crash (DEV-6670) is fixed — a Bearer token to an `/auth`-prefixed image no longer null-derefs | | Image decompression bomb | :white_check_mark: | `security.rs::decompression_bomb_rejection` | | | Upload size enforcement | :white_check_mark: | `upload.rs::upload_size_enforcement` | | | CRLF header injection | :white_check_mark: | `security.rs::crlf_header_injection`; `input_validation.rs::crlf_in_identifier_no_header_injection` | | | Cache key collision | :white_check_mark: | `cache.rs::cache_key_isolation` | | | Error message information disclosure | :white_check_mark: | `security.rs::error_no_path_disclosure`; `input_validation.rs::path_traversal_no_content_leaked` | | | Slowloris / connection exhaustion | :white_check_mark: (ignored) | `security.rs::slowloris_resilience` | `#[ignore]`'d for CI timing flakiness, not a coverage gap | | `parseSizeString` edge cases | :white_check_mark: | `config.rs::parse_size_string_edge_cases` | | | Deprecated config key migration | :white_check_mark: | `config.rs::config_deprecated_key_migration` | | | CLI argument overrides | :white_check_mark: | `config.rs::config_cli_overrides` | | | Empty jwt_secret behavior | :white_check_mark: | `security.rs::config_empty_jwt_secret` | | | Invalid Lua config syntax | :white_check_mark: | `config.rs::invalid_config_startup` | | | Config with nonexistent paths | :white_check_mark: | `config.rs::config_nonexistent_paths` | | | SImage Lua API coverage | :x: GAP | — | Methods tested only via black-box HTTP, not a direct Lua-API unit harness | | Lua JWT round-trip | :white_check_mark: | `server.rs::lua_jwt_round_trip` | | | Lua UUID round-trip | :white_check_mark: | `server.rs::lua_uuid_round_trip` | non-deterministic body | | Lua `server.http` outbound | :white_check_mark: | `server.rs::lua_http_client_error_handling` | | | Lua error propagation to HTTP | :white_check_mark: | `server.rs::lua_route_error_handling` | | | HTTP keep-alive | :white_check_mark: | `connection.rs::http_keep_alive` | | | Chunked transfer encoding | :white_check_mark: | `connection.rs::chunked_transfer_upload` | | | Connection: close header | :white_check_mark: | `connection.rs::connection_close_header` | | | Thread pool exhaustion | :x: GAP | — | 503 load-shedding exists (semaphore-backed pool) but has no dedicated saturation test; masked today by `flaky_test_attempts` on suite-load bursts | | Graceful shutdown | :white_check_mark: | `connection.rs::graceful_shutdown`; `shutdown.rs` (×3) | | | Multi-page TIFF `@page` e2e | :x: GAP (documented) | `iiif_compliance.rs::multipage_tiff_page_selection` | `#[ignore]`'d — page selection may not be implemented; test documents current behavior | | CMYK→sRGB through IIIF pipeline | :white_check_mark: | `iiif_compliance.rs::cmyk_through_iiif_pipeline` | | | CIELab through IIIF pipeline | :white_check_mark: | `iiif_compliance.rs::cielab_through_iiif_pipeline` | | | 16-bit depth through IIIF pipeline | :white_check_mark: | `iiif_compliance.rs::bit16_through_iiif_pipeline` | | | Progressive JPEG handling | :white_check_mark: | `iiif_compliance.rs::progressive_jpeg_input` | | | TIFF with JPEG compression | :white_check_mark: | `iiif_compliance.rs::tiff_jpeg_compression_input` | documents current (non-crashing) behavior for the known scanline-order edge case | | 1-bit TIFF (bi-level) | :white_check_mark: | unit + rust-e2e (`bilevel_tiff.rs`) | MINISWHITE and MINISBLACK, LZW and uncompressed | | JPEG YCCK colorspace | :white_check_mark: | unit | Was throw; now decoded via CMYK path | | JPEG CMYK with APP14 (Photoshop) — inverted before ICC | :white_check_mark: | unit | regression test | | JPEG CMYK without APP14 (raw) — not inverted | :white_check_mark: | unit | regression test (negative case) | | JPEG with APP13 before APP1 + non-ASCII IPTC | :white_check_mark: | unit + `heritage_jpeg.rs` | heritage collection regression | | CLI `--json` output contract | :white_check_mark: | unit + rust-e2e (`cli_json.rs`) | success + error payloads, single-document stdout | | CLI `query` / `compare` / `verify` subcommands | :white_check_mark: | `cli.rs::cli_query_dumps_image_info`, `cli_compare_identical_files_reports_match`, `cli_compare_differing_files_reports_mismatch`, `cli_verify_pipeline_service_and_access_files` | the verify pipeline test exercises `convert service-file` → `verify service-file` → `convert access-file` → `verify access-file` end to end | | Watermark application via HTTP | :white_check_mark: | `server.rs::watermark_applied_via_http` | | | Restrict + watermark combined | :white_check_mark: | `server.rs::restrict_plus_watermark` | | | Watermark cache key separation | :white_check_mark: | `cache.rs::watermark_cache_separation` | | | CLI watermark mode | :white_check_mark: | `cli.rs::cli_convert_watermark_changes_output_bytes` | asserts a valid JPEG whose bytes differ from a plain convert of the same input | | Concurrent cache writes (same key) | :white_check_mark: | `cache.rs::cache_returns_consistent_results` | | | Cache eviction during active reads | :white_check_mark: | `cache.rs::cache_eviction_during_read` | | | Concurrent file uploads | :white_check_mark: | `upload.rs::concurrent_file_uploads` | | | Lua state thread isolation | :white_check_mark: (ignored) | `server.rs::lua_state_thread_isolation` | `#[ignore]`'d — same engine-pool 503-shedding reason as `concurrent_requests`, not a coverage gap; the test itself asserts per-thread Lua global isolation via `/test_thread_isolation` | | Cache disabled mode (`cache_size=0`) | :white_check_mark: | `cache.rs::cache_disabled_mode` | | | Cache LRU purge under size limit | :white_check_mark: | `cache.rs::cache_lru_purge_correctness` | | | Cache nfiles limit enforcement | :white_check_mark: | `cache.rs::cache_nfiles_limit` | | | Keep-alive timeout enforcement | :white_check_mark: | `connection.rs::keepalive_timeout_enforcement` | | | Sustained load memory growth | :white_check_mark: | `resource_limits.rs::sustained_load_memory_growth` | | | Concurrent large image decode memory | :white_check_mark: | `resource_limits.rs::concurrent_large_image_decode` | | | Full-lane budget rejection (advanced 413, tile bypass, in-budget, basic) | :white_check_mark: | `admission_control.rs` (×4, each on its own cache dir) | Transient 503 is engine-unit-covered (`MemoryBudgetTest`), not e2e — a live-server 503 is a decode-timing race | | Two-lane admission (thread cap, tile floor/burst, per-partition shed, classifier) | :white_check_mark: | `//src/throttling/rust:admission` crate tests (engine-free) | | | Intermediate buffer accumulation | :white_check_mark: | `resource_limits.rs::transform_pipeline_memory` | | | Cache as memory pressure relief | :white_check_mark: | `cache.rs::cache_hit_avoids_decode` | | ## Gap Summary | Category | Covered | Gaps | Coverage | | ------------------- | ------- | ----------- | -------- | | Info.json fields | 23 | 0 | 100% | | Region parameters | 12 | 0 | 100% | | Size parameters | 15 | 0 | 100% | | Rotation parameters | 9 | 0 | 100% | | Quality parameters | 6 | 0 | 100% | | Format parameters | 5 | 0 | 100% | | CORS | 13 | 0 | 100% | | HTTP behavior | 13 | 0 | 100% | | Identifiers | 4 | 1 (ARK/URN) | 80% | | Vitrinli extensions | 100 | 7 | 93% | | **Total** | **200** | **8** | **96%** | *(Three additional Vitrinli-extension rows — Prometheus `/metrics`, `/api/cache`, SSL/TLS — are excluded from this count entirely: they are removed-on-the-Rust-shell features, not gaps. See the N/A note above the extension matrix.)* **Key remaining gap categories** (7 rows, all in Vitrinli extensions): - **Deep metadata survival** (1 gap): ICC profile HTTP-level round-trip — EXIF/IPTC/XMP now covered - **Concurrency edge cases** (1 gap): thread-pool-exhaustion saturation test (`concurrent_requests`/`lua_state_thread_isolation` are written and correct, just `#[ignore]`'d for the unrelated 503-shedding reason above — not gaps) - **Hardening depth** (2 gaps): TSan (nightly-future), extremely long URL/header (URL half now covered by the nightly libFuzzer target; the header half is untested) - **Test-harness depth** (1 gap): a direct SImage Lua-API unit harness (vs. black-box HTTP coverage) - **Test removed with the differential suite** (1 gap): favicon endpoint — the route exists but its only e2e test lived in the removed differential suite - **Documented, not missing** (1 row): multi-page TIFF `@page` — `#[ignore]`'d pending a real page-selection implementation, not an untested behavior ## Cross-Cutting: Memory Safety (Sanitizer Builds) Memory leaks and undefined behavior are not a separate pyramid layer but a **build variant** that runs existing tests with compiler instrumentation. This is critical for sipi's long-running C++ image engine, where leaks accumulate over the process lifetime. **Current state:** ASan+UBSan infrastructure is in place — Bazel `--config=asan` and `--config=ubsan` blocks in `.bazelrc`, `just bazel-build-sanitized` (`bazel build --config=asan --config=ubsan //src/cli:sipi`), and one path-gated `sanitizer` job in `ci.yml` that exercises the unit and e2e suites against the instrumented binary in a single `just bazel-test-sanitized` invocation. Known findings to triage on first run: - **`SipiFilenameHash::operator=` memory leak** — `operator=` allocates `new vector` without deleting the old `hash` pointer. Confirmed by code inspection. Fix: add `delete hash;` before the new allocation, or switch to `std::unique_ptr`. - **Potential: `SipiFilenameHash` copy constructor** — also `new`s without freeing, but only leaks if the destination object was previously constructed with a different hash (doesn't happen via typical usage). - **Expected: false positives from external libraries** — exiv2, lcms2, and other vendored libraries may trigger ASan warnings that aren't sipi bugs. These should be suppressed via an ASan suppression file if needed. **Sanitizer stack:** | Sanitizer | Catches | Flag | Overhead | | ---------------------------------- | --------------------------------------------------- | ---------------------- | -------- | | ASan (AddressSanitizer) | Buffer overflow, use-after-free, double-free, leaks | `-fsanitize=address` | ~2x | | UBSan (UndefinedBehaviorSanitizer) | Integer overflow, null deref, misaligned access | `-fsanitize=undefined` | ~1.2x | | TSan (ThreadSanitizer) | Data races, deadlocks | `-fsanitize=thread` | ~5-15x | **Infrastructure:** | Component | Status | Details | | ------------------------------------------------ | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--config=asan` / `--config=ubsan` in `.bazelrc` | Done | `-fsanitize=address` / `-fsanitize=undefined` plus `-fno-omit-frame-pointer`, `-fno-optimize-sibling-calls`, `--strip=never`, `--compilation_mode=dbg` (DWARF inline so `.lsan_suppressions.txt` symbol-name suppressions match) | | `just bazel-build-sanitized` | Done | Wraps `bazel build --config=asan --config=ubsan //src/cli:sipi` | | PR CI (`ci.yml`'s `sanitizer` job) | Done | Bazel-built binary at `bazel-bin/src/cli/sipi`; runs `just bazel-test-sanitized` (unit + e2e in one invocation) `--config=asan --config=ubsan`; `.lsan_suppressions.txt` consumed by LSan via `LSAN_OPTIONS` | | TSan variant | Future | Optional nightly, separate from ASan (can't combine) | **Strategy:** PR CI runs both the unit and e2e suites against an ASan+UBSan-instrumented binary, as two parallel jobs gated on native/build-relevant path changes. TSan remains a future option. ## Cross-Cutting: Performance Regression Detection **Current state:** OTLP-exported metrics include cache counters/gauges and the semantic-convention `http.server.request.duration` histogram (5ms–10s buckets), which normalizes to `http_server_request_duration_seconds` at the collector. CI infrastructure includes smoke latency assertions in PR CI. Throughput-style load testing is intentionally **not** run in CI — synthetic `wrk` against three IIIF endpoints on a shared GitHub runner does not mirror dasch-prod-01's actual workload (cold-cache reads of medium-sized JP2s under spiky concurrency) and the prior nightly `loadtest.yml` artifacts were not consulted. Meaningful load testing belongs in a staging environment with realistic fixtures and traffic shape. **Strategy (three tiers):** | Tier | What | Tool | When | | ------------------------- | ---------------------------------------------------------------------------------- | ------------------------------- | ----------------------------------------------------------------------------------------------------------------- | | Smoke latency | Assert response time < threshold in e2e tests | Rust `Instant::now()` | PR CI | | Load baseline | Throughput against realistic workload | `wrk` / `k6` | **Future** — staging environment, not CI | | Component microbenchmarks | Parse / decode / process / encode tiers, before/after comparisons for hot-path PRs | Google Benchmark (`just bench`) | **Done** — local dev loop, never a CI gate; see [Benchmarking](https://sipi.io/development/benchmarking/index.md) | **Smoke latency thresholds (proposed):** - Info.json request: < 50ms - 512x512 JPEG delivery (cache miss): < 500ms - 512x512 JPEG delivery (cache hit): < 100ms - These catch gross regressions (10x slowdown), not subtle changes ## Snapshot Review Workflow Vitrinli uses [insta](https://insta.rs/) for golden baseline snapshots. When a snapshot changes: 1. Run tests: `just bazel-test-e2e` (pending snapshots are written as `*.snap.new` next to the existing `*.snap`) 1. Review the diff between each `.snap` and `.snap.new` (a regular `git diff` works, or open both in your editor) 1. For intentional changes, replace: `mv path/to/foo.snap.new path/to/foo.snap` 1. For regressions, delete the `.snap.new` and fix the code 1. Commit updated `.snap` files For interactive review, install `cargo-insta` ad-hoc — it operates on `.snap.new` files and doesn't need the dev-shell rust toolchain: ``` nix shell nixpkgs#cargo-insta --command cargo insta review ``` **When to use insta:** - info.json response structure - HTTP response header sets - knora.json response structure - Image metadata fingerprints **Pattern:** Use `insta::assert_json_snapshot!` with `redact` for dynamic values: ``` insta::assert_json_snapshot!(info_json, { ".id" => "[base_uri]", }); ``` ## CI Integration | Target | Just Recipe | When | Notes | | --------------------------- | ---------------------------------------------------------------------------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | C++ unit tests (CI) | `just nix-build` (`.#dev` checkPhase) | PR CI | GoogleTest via ctest, runs in the Nix sandbox | | C++ unit tests (Bazel) | `just bazel-test-unit` | local + CI | `bazel test //test/unit/...`. CI runs them via `just bazel-coverage`. | | C++ approval tests (CI) | `just nix-build` (`.#dev` checkPhase) | PR CI | ApprovalTests via ctest; `SOURCE_DATE_EPOCH=946684800` injected by CMake | | C++ approval tests (Bazel) | `just bazel-test-approval` | local + CI | `bazel test //test/approval:approvaltests`; env injection via `BUILD.bazel`. CI runs them via `just bazel-coverage`. | | Rust e2e tests (CI) | `just nix-test-e2e` | PR CI | Pre-built binaries from `.#e2e-tests` (crane); reads `$SIPI_BIN` | | Rust e2e tests (inner-loop) | `bazel test //test/e2e:` | local | Same hermetic toolchain as CI | | Docker smoke (CI) | `just bazel-test-smoke` | PR + tag CI | Bazel-built OCI tarball, `docker load`ed by the test | | Differential parity | *(retired)* | — | The strangler parity gate and the retained C++ oracle server it compared against have been removed; the Rust shell is the sole production surface | | Hurl contract tests | *(retired)* | — | Folded into Rust e2e (`tests/http_contracts.rs` + `iiif_compliance.rs`) | | Python e2e tests | *(retired)* | — | Replaced by Rust e2e tests | | Fuzz corpus replay | `just bazel-test` / `bazel-test-unit` / `bazel-test-sanitized` / `bazel-coverage` | PR CI, all platforms | `//src/iiifparser/fuzz:parse_request_fuzz` and `//src/format_handlers/fuzz:{tiff,jpeg,png,j2k}_decode_fuzz` under `rules_fuzzing`'s default `replay` engine; picked up by the `//src/...` wildcard | | Fuzz mutation loop | `just bazel-build-fuzz` + the runner-local loop (`just fuzz` locally) | nightly (`fuzz.yml`), Linux only | libFuzzer + SanitizerCoverage on the Rust parser via the `//src/iiifparser/fuzz` shim and on the C++ codec handlers via `//src/format_handlers/fuzz`; see [Fuzzing](https://sipi.io/development/fuzzing/index.md) | | Sanitizer builds | `just bazel-build-sanitized` (`bazel build --config=asan --config=ubsan //src/cli:sipi`) | PR | ASan+UBSan; e2e suite against `bazel-bin/src/cli/sipi` with `.lsan_suppressions.txt` | ## Python Test Deprecation — Parity Checklist Python e2e tests (`test/e2e/`) have been retired. The following per-function parity checklist confirmed Rust coverage before removal. ### test_01_conversions.py (2 tests) — RETIRED | Python Test | Rust Equivalent | Notes | | ----------------------------- | --------------------------------- | ----------------------------------- | | `test_iso_15444_4_decode_jp2` | `cli_file_conversion` in `cli.rs` | JP2→TIFF decode with PAE comparison | | `test_iso_15444_4_round_trip` | `cli_file_conversion` in `cli.rs` | TIFF→JP2→TIFF round-trip | ### test_02_server.py (32 tests) — RETIRED | Python Test | Rust Equivalent | Notes | | ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | | `test_sipi_starts` | `server_starts_and_responds` in `smoke.rs` | | | `test_sipi_log_output` | — | Dropped: infrastructure check ("Added route" in stdout), not behavioral | | `test_lua_functions` | `lua_test_functions` in `server.rs` | | | `test_clean_temp_dir` | `temp_directory_cleanup` in `server.rs` | | | `test_lua_scripts` | `lua_mediatype` in `server.rs` | | | `test_lua_mimetype` | `lua_mimetype_func` in `server.rs` | | | `test_knora_session_parsing` | `lua_knora_session_cookie` in `server.rs` | | | `test_file_bytes` | `full_iiif_url_returns_image` in `iiif_compliance.rs` | Status+content-type check; byte-exact comparison covered by dimension verification and snapshot tests | | `test_restrict` | `restricted_image_reduction` in `server.rs` | Verifies 128x128 via image decode | | `test_deny` | `deny_unauthorized_image` in `iiif_compliance.rs` | | | `test_not_found` | `returns_404_for_missing_file` in `smoke.rs` | | | `test_iiif_url_parsing` | `invalid_iiif_url_empty_identifier`, `id_incomplete_iiif_url`, `id_malformed_iiif_url` in `iiif_compliance.rs` | Multiple tests cover all 5 invalid URL patterns | | `test_read_write` | `lua_read_write` in `server.rs` | | | `test_jpg_with_comment` | `upload_jpeg_with_comment_block` in `upload.rs` | | | `test_odd_file` | `upload_odd_file` in `upload.rs` | | | `test_head_response_should_be_empty` | `head_iiif_image_empty_body` in `iiif_compliance.rs` + `head_request_returns_headers` in `smoke.rs` | | | `test_mimeconsistency` | `mime_consistency` in `server.rs` | All 6 test cases ported | | `test_thumbnail` | `thumbnail_generation` + `thumbnail_convert_from_file` in `server.rs` | | | `test_image_conversion` | `image_conversion_from_binaries` in `server.rs` | `/convert_from_binaries` endpoint | | `test_knora_info_validation` | `knora_json_image_required_fields` + `upload_tiff_knora_json` in `upload.rs` | Image and CSV sidecar flows | | `test_json_info_validation` | Info.json tests in `iiif_compliance.rs` + `info_json_x_forwarded_proto_https` | Full structure + X-Forwarded-Proto | | `test_knora_json_for_video` | `video_knora_json` in `server.rs` | | | `test_handling_of_missing_sidecar_file_for_video` | `missing_sidecar_handled_gracefully` in `server.rs` | | | `test_sqlite_api` | `sqlite_api` in `server.rs` | | | `test_iiif_auth_api` | `iiif_auth_api` in `server.rs` | 401 + IIIF Auth service block in info.json | | `test_orientation_topleft` | `lua_orientation` in `server.rs` | Lua endpoint tests same code path | | `test_4bit_palette_png` | `upload_4bit_palette_png` in `upload.rs` | | | `test_upscaling_server` | `size_upscaling` + `size_upscale_*` in `iiif_compliance.rs` | Status + dimension verification | | `test_file_access` | `file_access_allowed` + `file_access_denied` in `server.rs` | | | `test_concurrency` | `concurrent_requests` in `server.rs` | | | `test_orientation` | `lua_orientation` in `server.rs` | | | `test_exif_gps` | `lua_exif_gps` in `server.rs` | | ### test_03_iiif.py (1 test) — RETIRED | Python Test | Rust Equivalent | Notes | | ---------------------- | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `test_iiif_validation` | — | Explicitly excluded: calls external `iiif-validate.py` binary, effectively a no-op when validator unavailable. IIIF compliance covered by 80+ tests in `iiif_compliance.rs` | ### test_04_range_requests.py (12 active tests) — RETIRED | Python Test | Rust Equivalent | Notes | | -------------------------------------------- | --------------------------------------------------------------- | --------------- | | `test_small_file_no_range` | `small_file_no_range` in `range_requests.rs` | | | `test_small_file_range_first_100_bytes` | `small_file_range_first_100_bytes` in `range_requests.rs` | | | `test_small_file_range_middle_bytes` | `small_file_range_middle_bytes` in `range_requests.rs` | | | `test_small_file_range_last_byte` | `small_file_range_last_byte` in `range_requests.rs` | | | `test_small_file_open_ended_from_start` | `small_file_open_ended_from_start` in `range_requests.rs` | | | `test_small_file_open_ended_from_middle` | `small_file_open_ended_from_middle` in `range_requests.rs` | | | `test_large_file_no_range` | `large_file_full_download` in `range_requests.rs` | | | `test_large_file_range_first_megabyte` | `large_file_range_first_1mb` in `range_requests.rs` | | | `test_large_file_range_middle_chunk` | `large_file_range_middle_chunk` in `range_requests.rs` | | | `test_large_file_range_last_chunk` | `large_file_range_last_bytes` in `range_requests.rs` | Last 1000 bytes | | `test_large_file_range_single_last_byte` | `large_file_range_single_last_byte` in `range_requests.rs` | | | `test_large_file_open_ended_from_start` | `large_file_open_ended_from_start` in `range_requests.rs` | | | `test_large_file_open_ended_from_middle` | `large_file_open_ended_from_middle` in `range_requests.rs` | | | `test_large_file_multiple_ranges_simulation` | `large_file_sequential_range_reassembly` in `range_requests.rs` | | ### Infrastructure files — RETIRED | File | Notes | | ------------------ | ---------------------------------------------------------------------------- | | `conftest.py` | Test manager, fixtures, nginx control — replaced by `test/e2e/tests/common/` | | `config.ini` | Python test config — replaced by Rust test harness | | `nginx/` | Nginx reverse proxy for SSL testing — Rust tests use direct HTTPS | | `requirements.txt` | Not present (deps managed by Nix/pip) | ## Rust Migration Testing Path When a C++ component is migrated to Rust: 1. **Before migration:** Ensure e2e contract tests cover the component's behavior 1. **During migration:** Write Rust unit tests (`#[test]`, `proptest`) for the new implementation 1. **After migration:** Existing e2e tests validate the Rust implementation matches C++ behavior 1. **Cleanup:** Remove corresponding C++ unit tests (they tested the old implementation) The `insta` golden baselines are critical — they capture the Rust shell's exact response output and detect any implementation drift. ## Flaky Test Handling Some e2e tests are inherently racy — for example, a test that uploads a file and immediately GETs the converted result may fail if the server hasn't flushed to disk yet. Rather than retrying at the CI job level, handle flakiness at the **test level** using the `retry_flaky()` helper from the test harness (`test/e2e/src/lib.rs`): ``` use sipi_e2e::retry_flaky; #[test] fn my_flaky_test() { let srv = server(); // ... setup ... retry_flaky(3, || { match client().get(&url).send() { Ok(resp) if resp.status().as_u16() == 200 => Ok(()), Ok(resp) => Err(format!("HTTP {}", resp.status())), Err(e) => Err(format!("{}", e)), } }); } ``` **Guidelines:** - `retry_flaky(max_attempts, closure)` retries the closure up to `max_attempts` times with a 2-second sleep between attempts - The closure returns `Ok(())` on success or `Err(message)` on failure - Failed attempts emit `[retry_flaky]` log lines for CI visibility - Only use for tests with a known race condition — do not mask real bugs with retries - If a test needs more than 3 retries, the underlying issue should be fixed instead ## Future Additions - **Doc tests:** Once sipi has Rust library code (post-migration), `///` example doc tests become valuable (Component microbenchmarks — formerly listed here as a post-Rust-migration `criterion` aspiration — exist today as the C++ Google Benchmark suite; see [Benchmarking](https://sipi.io/development/benchmarking/index.md). If/when the codec migrates to Rust, the discipline carries over to `criterion` unchanged.) # Commit and PR Conventions ## Git Workflow We use a **rebase workflow**. All changes are made on a branch, then rebased onto `main` before being merged. This keeps a clean, linear history. The goal is a **meaningful history on `main`**: every commit on main should be a deliberate, self-contained unit of change. Working commits ("WIP", "fix typo", "address review feedback") do not belong on main. - **Rebase-merge**: PRs are integrated using rebase-merge (not squash or merge commits). Every commit on the branch lands on main verbatim — so the branch history *is* the main history. There is no squash-on-merge safety net; whatever you leave on the branch is what ships. - **The history's reader is a coding agent.** This is the leading principle for cleanup. An agent reaches a commit through `git blame`, `git log -- ` and `git log -S`, and the commit message is where it learns why the code is the way it is. Curate the branch for that reader: **one commit per module per slice**, with a body that explains the end state. See [Commit Organization](#commit-organization). - **Clean up before merging (mandatory)**: before a PR is merged, rewrite the branch (interactive rebase) to that shape. Squash aggressively, in service of that principle: fold working commits, fixups and trial-and-error into the commit they belong to, reword messages, and reorder as needed. ### Stacked PRs When a PR depends on another open PR, stack them with [`gh stack`](https://gh.io/stacks) (`gh extension install github/gh-stack`), not by retargeting PR bases by hand. GitHub then knows the PRs form a stack, and the tool keeps the branches rebased on each other. - A stack is one chain, bottom to top. Do not base two PRs on the same PR: only stack work that really depends on the PR below it. Independent work gets its own PR from `main`. - Start with `gh stack init ` and add layers with `gh stack add `. `gh stack init ` adopts existing branches. - `gh stack submit` pushes the branches, opens or updates the PRs and links them. `gh stack rebase` cascades a rebase through the stack, and `gh stack sync` also fetches and pushes. - Merge with `gh stack merge --rebase`. The repository allows rebase merges only. - The commit rules above apply to every layer: each PR is curated before merge, and its commits land on `main` verbatim. ## Commit message schema We use [Conventional Commits](https://www.conventionalcommits.org/). These prefixes drive [release-please](https://sipi.io/development/ci/#release-automation-release-please) to determine SemVer bumps and generate the changelog — **using the correct prefix is required, not optional**. ``` type(scope): subject body ``` **Every commit has a type and a scope** — both are mandatory (see [Scopes](#scopes)). This is the whole table; there are exactly eight types: | Type | Meaning | Changelog section | Version bump | | ---------- | -------------------------------------------------- | ------------------------ | ------------ | | `feat` | New user-visible functionality | Features | minor | | `fix` | Bug fix (see [What `fix:` means](#what-fix-means)) | Bug Fixes | patch | | `perf` | Performance improvement | Performance Improvements | patch | | `refactor` | Code restructuring, no behavior change | Code Refactoring | patch | | `docs` | Documentation | Documentation | patch | | `test` | Adding or refactoring tests | Tests | patch | | `build` | Build system or dependencies | Build System | patch | | `chore` | Miscellaneous maintenance | Miscellaneous Chores | patch | Every type is visible in the release notes, in its own section, rendered in the order above. Because the scope is mandatory, every changelog line reads `concern: subject`. This table is the single human source for the type vocabulary; the machine source is [`.github/release-please/config.json`](https://sipi.io/.github/release-please/config.json). Breaking changes take a `!` suffix (or a `BREAKING CHANGE:` footer) and bump the **major** version: ``` feat(cache)!: remove the deprecated cache-purge endpoint ``` Example: ``` feat(jwt): support more authentication methods ``` The release-please config sentence-cases subjects in the changelog, so write the subject in normal prose case (`feat(cache): add dual-limit eviction`, not `feat(cache): Add ...`). ### Removed types `revert`, `style`, and `ci` are **not** valid types — the commit-lint gate rejects them, and release-please hides them if one ever slips onto `main`. - **CI/build automation** → `chore(ci): ...` (lands in Miscellaneous Chores). Dividing CI into concerns is not worthwhile, and a dedicated Continuous Integration changelog section is noise; it belongs under maintenance. - **Formatting-only changes** → fold into the functional commit, or `chore(): ...`. `rustfmt`/`clang-format` are enforced gates, so a standalone formatting commit should be rare. - **Reverts** → `fix(): revert ...` or `chore(): revert ...` depending on whether it corrects released behavior. (release-please's built-in revert auto-negation no longer applies; reverts are rare and handled by hand.) ### What `fix:` means A `fix:` corrects behavior that exists on `main` — a bug a deployer could hit today, or that a released version shipped. It earns a "Bug Fixes" changelog line precisely because deployers need to know. The same change filed as `chore:` or `refactor:` still appears in the release notes, but under a section nobody scanning for a regression will read. A bug you introduced earlier in the **same branch** is not a `fix:`. Fold it into the commit that introduced it (`git commit --fixup=`, then `git rebase --autosquash`) so it never lands on `main` and never generates a changelog entry for a bug nobody ever saw. Corollary: if you discover a genuine pre-existing `main` bug while doing unrelated work, give it its **own** `fix:` commit — don't bury it inside the `feat:`/`refactor:` you happened to be writing. ## Scopes **A scope is mandatory.** Every commit is `type(scope): subject`, so every release-notes line reads `concern: subject`. There is no scopeless form. The scope names the **concern the change serves** — the module whose responsibility it belongs to, not the directory the edited files happen to sit in. Telemetry code under `src/server/rust/` is `observability`; an `ffi` seam field whose only purpose is to carry a metric across is `observability` too. Scope by what the change is *about*, not where it landed. The canonical module list — which is also the scope vocabulary — lives in [`CONVENTIONS.md` § Module Layout](https://sipi.io/CONVENTIONS.md). Use one of these names, lowercase: - **Module scopes:** `image`, `format_handlers`, `metadata`, `iiifparser`, `scripting`, `util`, `jwt`, `cache`, `memory-budget`, `memory`, `observability`, `logging`, `cli`, `ffi`, `lua`, `server` (`scripting` = the C++ Lua runtime in `src/scripting/`; `lua` stays the Lua *scripts*/config in `scripts/` + `config/*.lua`; the retired `handlers` scope folded into `iiifparser` per DUNE-014) - **Test-layer scopes** (`e2e`, `approval`) — for changes to a test layer's own harness or fixtures. A test *about* a specific concern takes that concern's scope (`test(observability): ...`), not the layer: the `test` type already says it is a test, so the scope is free to name the concern. A unit-test change takes the scope of the module under test. - **Cross-cutting scopes** (changes not tied to one module): `deps`, `bazel`, `ci`, `nix`, `docker`, `docs`. Use `docs` for the agent-context / domain documentation that spans no single module — the root `CLAUDE.md` / `CONVENTIONS.md` / `CONTEXT.md` and the ADRs. A doc change about one module still takes that module's scope. Rules: - Lowercase, kebab-case. `ci` not `CI`; `bazel` not `bazel-build`. - A commit that spans several modules may list them comma-separated: `refactor(cli,server): ...`. - **Concern over location.** When code for one module's responsibility lives under another module's directory, scope by the responsibility, not the enclosing directory. `server/rust/src/metrics.rs` → `observability`. - **No catch-all.** There is no `repo`/`all` scope. If none of the enumerated scopes genuinely fits, ask the maintainer before inventing one — new scopes are added to the canonical list in `CONVENTIONS.md` deliberately, not ad hoc. The commit-lint gate enforces only that a scope is *present* (it does not yet restrict *which* scope — there is no closed vocabulary). The list above is the advisory vocabulary; keep to it. ## Enforcement Commit messages are gated in CI by [`commitlint-rs`](https://github.com/KeisukeYamashita/commitlint-rs) via the `commit-lint` job in [`ci.yml`](https://sipi.io/.github/workflows/ci.yml) (a composite action at `.github/actions/commit-lint`). The rules live in [`.commitlintrc.yml`](https://sipi.io/.commitlintrc.yml): the `type` allowlist above is mandatory, `scope-empty` makes the scope mandatory, and the subject must be non-empty. Run the same check locally before pushing: ``` just commit-lint # lints origin/main..HEAD just commit-lint # lints ..HEAD ``` `commitlint-rs` is in the Nix dev shell (`nix develop`); CI installs it with `cargo install`. Merge commits are skipped by the linter (message rules do not apply to them). The rebase workflow is enforced separately by the `require linear history` branch-protection rule, which blocks any merge commit from landing on `main`. ## Commit Organization ### Principle Shape the history for the agent that will read it. An agent asks two questions of it: "why is this line the way it is?" (`git blame`, then the commit body) and "how did this module get here?" (`git log -- `). Both are answered best by **one commit per module per slice**: - **Too fine** (a commit per fix, per review round, per working step) makes `git log -- ` a list of steps the agent must replay to learn the current state, and each body explains one step rather than the design. - **Too coarse** (the whole PR as one commit when it spans several slices) makes `git blame` land every line on one message that cannot explain any of them. A slice is the unit the plan delivered: a phase, or a feature within it. Inside a slice, split by module (the scopes in [`CONVENTIONS.md` § Module Layout](https://sipi.io/CONVENTIONS.md)), so each commit stays within one module's paths and its scope names that module. A shared piece a slice adds goes in its own commit ahead of the modules that use it, so no commit uses something that lands after it. A small PR that is one slice in one module is one commit. ### The body is written for an agent The subject says what changed. The body carries what the diff cannot: - the decisions taken and the alternatives rejected, with the reason; - the invariants the code relies on and where they are enforced; - the gotchas a later change would trip over; - the stable sources behind them (an ADR, a `DEV-` id, a doc page). It describes the end state of the slice, never the journey to it: no "first tried", no review-round history, no test counts or benchmark runs, no behaviour that existed only on the branch. A long body is fine; an agent reads all of it. ### Rules 1. Each `feat:` or `fix:` commit = one changelog entry in the sections developers deploying Vitrinli read first. 1. Internal work (`build:`, `ci:`, `refactor:`, `docs:`, `chore:`, `test:`) lands in its own changelog section further down. Squash aggressively, in service of the agent reader: fold every working, fixup and trial-and-error commit until each commit is one module in one slice, and stop there. Squashing past that point makes the history too coarse for `git blame`. 1. Ask: "would a developer deploying Vitrinli care about this change?" If yes → `feat:` or `fix:`. If no → an internal-work prefix. 1. Debugging journeys (trial-and-error, reverts of in-branch mistakes, iterative fixes) belong in the PR description, not the commit history. See [What `fix:` means](#what-fix-means). ### Where context lives | Layer | Audience | Content | | --------------- | ----------------------------- | -------------------------------------------------------- | | Commit messages | Release notes readers | Every change; `feat:`/`fix:` carry the user-visible ones | | PR description | Reviewers + future developers | Full context including challenges | | Learnings docs | Future Claude + engineers | Structured, searchable knowledge | | Code comments | Code readers | "Why not the obvious approach" | ## PR Description Format The repository ships a [`.github/PULL_REQUEST_TEMPLATE.md`](https://sipi.io/.github/PULL_REQUEST_TEMPLATE.md) that pre-populates this structure when you open a PR. ### Template ``` Fixes LINEAR-ID, LINEAR-ID, ... ## Motivation Why the change exists. What problem it solves for users. ## Summary What it does, in a few sentences. ## Key Changes ### [Topic] - what changed and where ## Review Guide One section per phase in this PR. ### [Phase] What to review, the key files, how it was verified, the decisions taken. ## Decisions What was tried and why the choice. The maintainer's answers to deviations. ## Gotchas What a later change would trip over. Each gotcha is actionable: "do X instead of Y", not "this is hard". ## Learnings The files added to the learnings directory, or why there are none. ## Test Plan - [ ] how each verification step was met, or why it does not apply ``` Use `Part of LINEAR-ID` instead of `Fixes LINEAR-ID` when the PR advances an umbrella issue it does not close. ### Why this format matters The "Decisions" section captures the debugging journey that the curated commit history deliberately omits. The `/eng:workflows:compound` skill reads PR descriptions to generate structured learnings — well-structured decisions become high-quality learnings automatically. ### What goes where | Information | Put it in... | | ---------------------------------- | ----------------------------------------------- | | New feature / breaking change | Commit message (`feat:` / `feat!:`) | | Bug fix | Commit message (`fix:`) | | Build/CI/refactor details | Commit message (`build:` / `ci:` / `refactor:`) | | Why the work was needed | PR Motivation section | | What was tried and failed | PR Decisions section | | Architecture decisions + rationale | PR Decisions section | | Things to watch out for | PR Gotchas section | | Structured, searchable knowledge | Learnings doc (dasch-specs) | # Reviewer Guidelines Checklist for human and AI reviewers. Not every item applies to every PR — use judgment. ## Documentation & Discoverability - [ ] New config keys: documented in `docs/src/guide/sipi.md`, `docs/src/guide/running.md`, and config file inline comments - [ ] Deprecation warnings: include the new key name and an example of the corrected config line - [ ] New CLI flags/env vars: `--help` text updated, documented in `running.md` - [ ] New HTTP endpoints: documented with request/response format - [ ] If a feature is only discoverable by reading source, it's not done ## Configuration & Defaults - [ ] Lua config, CLI args, and env vars all accept the same semantics and produce the same defaults - [ ] Defaults are consistent across all entry points (`SipiConf.cpp`, `cli_app.cpp` CLI, documentation) - [ ] Invalid values produce clear startup errors with guidance on valid values - [ ] Deprecated keys: old names accepted with warning, both old+new in same config is a hard error ## Commit & PR Hygiene - [ ] Commits follow [commit-conventions.md](https://sipi.io/development/commit-conventions/index.md) — `feat:` / `fix:` for changes a deployer cares about, `build:` / `test:` / `refactor:` for internal work - [ ] One topic per commit (rebase-merge = commits land as-is on `main`) - [ ] PR description follows the template (Motivation, Summary, Key Changes, Test Plan) ## C++ Quality - [ ] Builds clean under Clang 15+ and GCC 13+ with `-Wall -Werror` - [ ] No new compiler warnings introduced - [ ] Thread safety: shared data structures accessed under appropriate locks - [ ] No raw `new`/`delete` — use smart pointers or RAII - [ ] Error paths: resources cleaned up, partial state not left behind - [ ] C library calls: argument types match exactly (see [REVIEW.md](https://sipi.io/REVIEW.md) "C library boundary safety" section) - [ ] Multi-buffer operations: loop bounds match the buffer being indexed, not a different buffer's dimensions - [ ] C resource handles (`DIR*`, `FILE*`, `TIFF*`) wrapped in RAII — no manual cleanup paths - [ ] GoogleTest unit tests added for new logic; existing tests updated if behavior changes - [ ] E2E tests added or updated for user-visible behavior changes - [ ] Sanitizer CI passes with zero findings for PRs touching `src/` ## Logging - [ ] Per-item operations at DEBUG level, summaries at INFO - [ ] Warnings for recoverable issues (e.g., missing optional files, deprecated config) - [ ] Errors for unrecoverable issues that prevent operation ## Metrics - [ ] New metrics use correct metric types (counter for monotonic, gauge for current state, histogram for distributions) - [ ] Metric names follow `sipi_` prefix convention with `_total` suffix for counters - [ ] Instrumentation points are in the correct layer (not duplicated across call chain) ## Consistency - [ ] Follow existing patterns (route registration in the Rust axum router, `app()` in `src/server/rust/src/lib.rs`; native third-party deps as `cc_library` in `bazel/.BUILD.bazel`; test layout in `test/unit/`) - [ ] Config example files updated alongside code changes - [ ] New fields mirror structure of similar existing fields ## Ubiquitous Language Identifiers, comments, commit messages, and PR text use the canonical terms in [`CONTEXT.md`](https://sipi.io/CONTEXT.md), not the aliases its `_Avoid_` lines list. Common slips to reject: - [ ] **Bitstream**, not "file" as a domain noun for the served byte stream (*file* survives only in URL paths and filesystem discussion) - [ ] **Region**, not "ROI" / "crop" / "crop coords" - [ ] **Size**, not "scale" / "dimensions"; **Decode level**, not "reduce" (except as a codec-API parameter name) - [ ] **Cache key**, not "canonical URL" when the string is used to key the cache (*Canonical URL* = the IIIF spec form only) - [ ] **Throttling**, not "backpressure" for the load-driven 503/400 rejection policies - [ ] **Bitstream Information document** / **Image Information document**, not "info.json" (the file name) for the response schemas ## Testing Strategy Compliance - [ ] New tests placed in the correct pyramid layer — consult the [decision tree](https://sipi.io/development/testing-strategy/#test-decision-tree) - [ ] New HTTP behavior tests are Rust e2e - [ ] Tests verify behavior (dimensions, content, structure), not just status codes - [ ] Snapshot tests use `insta` with appropriate redactions for dynamic fields - [ ] No new `test/unit/` directories — C++ unit tests are frozen (maintain existing only) - [ ] If a gap from the [coverage matrix](https://sipi.io/development/testing-strategy/#iiif-image-api-30-coverage-matrix) is closed, the matrix is updated ## Security - [ ] No path traversal possible via user-supplied inputs (IIIF identifiers, config paths, cache file names) - [ ] Internal-only endpoints documented as requiring reverse proxy protection - [ ] No secrets or credentials in log output # Release Notes # Release Notes Release notes are maintained on GitHub: - **[CHANGELOG.md](https://github.com/dasch-swiss/vitrinli/blob/main/CHANGELOG.md)** — Full changelog (auto-generated by [release-please](https://github.com/googleapis/release-please)) - **[GitHub Releases](https://github.com/dasch-swiss/vitrinli/releases)** — Release artifacts and summaries - **[Docker Hub](https://hub.docker.com/r/daschswiss/sipi/tags)** — Published container images