15 Commits

Author SHA1 Message Date
mnovak 67888aa791 [docs] Roadmap: T4 status and handover 2026-11-17 22:16:50 +01:00
mnovak 6956f23cb2 [tests] Caddy mode: a minute for Caddy to start on a busy machine 2026-11-17 21:42:52 +01:00
mnovak 2aa8d66127 [control] The admin host is accepted with any port (Docker or a router may publish 443 elsewhere); smoke scripts: Windows-readable paths, curl without Schannel's revocation check, logs on failure 2026-11-17 21:35:34 +01:00
mnovak 695ed178a5 [control] Clippy clean for the T4 code; CLAUDE.md: the deploy folders and the Linux test command in Docker; the Docker smoke turns off Git Bash's path rewriting and removes its volume 2026-11-17 21:18:19 +01:00
mnovak defd722cc2 [docs] Previews (the API for Fabrica, names, the token from the team vault), Ianitor anywhere (Linux, Docker, Windows Server in Caddy mode, NixOS), team sign-in in api.md, the Custos ticket's T4 part; release 0.2.0: the pipeline builds and tests the Linux tarball, the Windows zip and the image; the NixOS previews option; Docker and Linux smoke scripts 2026-11-17 20:59:42 +01:00
mnovak d5d522fe4b [deploy] Fixes from the Windows smoke: the admin host has no health path (every API path needs a sign-in), -NoService keeps the person who ran it in the folder's ACL, paths may have backslashes; Pebble 2.6.0 in the CI image (the ACME test's version) 2026-11-17 20:55:41 +01:00
mnovak 49c05e2523 [deploy] Anywhere: the Docker image and compose file (edge and control), the Linux installer and systemd units, the Windows Server installer (Caddy mode, three services), the preview client for Fabrica, and the Windows smoke script 2026-11-17 20:42:04 +01:00
mnovak 09f6b12676 [tests] Linux-only tests follow the Caddy admin address type and the [previews] config field 2026-11-17 20:42:01 +01:00
mnovak 4e3c721ef5 [web] Previews and the team: a Previews screen (see: 1 click, close: 2), sign-in from a setup or invite link, Settings → Team (invite: 3 clicks), previews-only API tokens; click-counted tests 2026-11-17 20:41:53 +01:00
mnovak dced199132 [control] Team sign-in without Authelia: a one-time setup link for the first admin, invite links, per-browser sessions in an HttpOnly cookie, admin and member roles, Tessera roots with their match code; the admin host kept by control ([ui] admin_tls) 2026-11-17 20:28:12 +01:00
mnovak 51a95e4f75 [control] Caddy mode, tests: a previews-only token opens a branch preview that answers through Caddy (admin on loopback TCP, Domi certificate, no edge) and is gone after close; runs on Windows 2026-11-17 14:03:52 +01:00
mnovak 5e273241e4 [tests] Diff: the differential suite runs on Windows too (Windows Caddy, drive paths), with two branch previews in the fixtures; edge leaves a websocket 101 as the upstream sent it, as Caddy does 2026-11-17 13:59:18 +01:00
mnovak acf69a8ed2 [control] Windows Caddy mode: Caddy's admin API on loopback TCP where there is no Unix socket, applies go through Caddy without an edge, control and the Caddy guard as Windows services, a log file 2026-11-17 13:59:12 +01:00
mnovak fc9e16f1b2 [control] Previews: POST/GET/DELETE /api/v1/previews, tokens scoped to previews only, the upstream allow list, expiry; Windows drive paths in compile options (tests first) 2026-11-17 13:46:33 +01:00
mnovak 83270e0746 [core] Previews: branch and project names to one safe host label, and the [preview] table of a host file (tests first) 2026-11-17 13:29:35 +01:00
99 changed files with 6686 additions and 1242 deletions
+9
View File
@@ -0,0 +1,9 @@
target
**/node_modules
**/dist
.git
.fabrica
bench
*.log
result
result-*
+4 -8
View File
@@ -1,14 +1,10 @@
# Ianitor Domi declares itself to Fabrica (Fabrica core docs/FORMATS.md, "Fabrica: the app"; docs/fabrica.md): a server
# part only, the reverse proxy with its control plane and web UI, deployed by .fabrica/artifex/deploy.yaml through the
# server's fabrica-deploy@ianitor, which is also how it updates. Its Aula page comes from the release of a `v*` tag
# (.fabrica/artifex/release.yaml), started on the hub for the pushed tag: no desktop part, as Ianitor has no installer
# to bump and tag. Fabrica's Apps screen shows one card: Deploy, then the Custos card. The colour is the murex accent
# (packages/ui/src/tokens.css, --accent).
# Ianitor Domi declares itself to Fabrica (Fabrica core docs/FORMATS.md, "Fabrica: the app"): a server part only,
# the reverse proxy with its control plane and web UI, deployed by .fabrica/artifex/deploy.yaml through the server's
# fabrica-deploy@ianitor. Fabrica's Apps screen shows one card for it: Deploy, then the Custos card. The colour is
# the murex accent (packages/ui/src/tokens.css, --accent).
name: Ianitor
icon: globe
color: "#e0a3dc"
aula: true
tagPrefix: v
parts:
server:
pipeline: deploy
-15
View File
@@ -1,15 +0,0 @@
# Ianitor Domi: the web UI's e2e suite on Fabrica's e2e runner (docs/fabrica.md part 6; Fabrica docs/20_tests.md,
# docs/31_runners_here.md): the built UI against the demo control plane, Playwright headless in the installed Edge,
# the records, traces and videos kept with the run. Manual: no push webhook reaches the hub yet. The e2e runner's
# runner.json sets PLAYWRIGHT_BROWSERS_PATH (Playwright's ffmpeg for the videos; on D: or F:, never C:).
name: e2e
on:
manual: true
runner: windows-e2e
steps:
- id: install
run: pnpm install --frozen-lockfile
- id: web
needs: [install]
run: fabrica tests run --target web
artifacts: [".fabrica/runs/tests/**"]
+36 -32
View File
@@ -1,22 +1,18 @@
# Ianitor Domi: the Gitea release of a v* tag (docs/release.md, docs/fabrica.md). Ianitor ships no binary (the server
# builds it with Nix and the deploy pipeline switches it in), so a release is the source archive of the tag, its notes,
# the screenshots of the web UI and the Aula page, all under a SHA256SUMS signed by domi-release through Custos;
# release-notes.md is also the release's text on Gitea.
# The Windows runner (the Fabrica app on Mark's PC) runs it: `fabrica`, node and pnpm are on every step's PATH.
# Ianitor Domi: the Gitea release of a v* tag (docs/release.md). Since 0.2.0 (T4) a release carries the programs:
# the Linux tarball and its one-line installer (systemd), the Windows Server zip (Caddy mode), next to the notes and
# screenshots of the web UI, all under a SHA256SUMS signed by domi-release through Custos. The Docker image is built
# from the same Dockerfile; it is not pushed to a registry yet (docs/deploy/anywhere.md).
# The Windows runner (the Fabrica app on Mark's PC) runs it: `fabrica`, node, pnpm, cargo and Docker Desktop are on
# every step's PATH; the Linux parts build inside Docker (deploy/docker/Dockerfile), never on the host.
# No Gitea webhook to the hub yet: a pushed tag is started on demand (the hub's POST /api/runs, ref v<version>).
# The web UI's e2e suite (apps/web/playwright.config.ts) runs the main flows and takes the pictures in the installed
# Edge against the demo control plane with invented data, at a fixed instant; `fabrica aula shots` checks and copies
# them (.fabrica/aula.yaml, `file:` shots) and `fabrica aula page` builds the landing page from them and the brief.
# Playwright's ffmpeg (the flows' videos) is in PLAYWRIGHT_BROWSERS_PATH, set here so the step does not depend on the
# runner's environment: F:\ms-playwright on Mark's PC, never C:. Nothing is downloaded during a release; a runner
# without it fails the e2e step with Playwright's "Executable doesn't exist" naming the path.
# `notes` is Fabrica's release notes since the previous v* tag (Fabrica docs/12_release_kit.md); `shots` takes the
# same files as `fabrica aula shots` (core docs/FORMATS.md, "Fabrica: the Aula page") from the built web UI against
# the demo control plane with invented data, in headless Edge. No landing page while app.yaml has no `aula: true`.
name: release
on:
tag: "v*"
manual: true
runner: windows
env:
PLAYWRIGHT_BROWSERS_PATH: 'F:\ms-playwright'
steps:
- id: version
run: node scripts/check-version.mjs ${{ version }}
@@ -28,39 +24,47 @@ steps:
- id: test
needs: [install]
run: pnpm --filter web test
- id: e2e
needs: [check, test]
run: pnpm --filter web test:e2e
- id: pictures
needs: [e2e]
run: pnpm --filter web aula:shots
- id: source
# The whole Rust workspace on Linux (the differential suite against Caddy, Pebble ACME, the edge suites), in the CI
# image; two jobs, so Docker Desktop's memory holds.
- id: linux-tests
needs: [version]
run: node scripts/pack-source.mjs ${{ version }}
artifacts: ["target/release/ianitor-*-src.tar.gz"]
run: docker build --load -f deploy/docker/Dockerfile --target ci -t ianitor-ci:${{ version }} . && docker run --rm --memory 6g ianitor-ci:${{ version }} cargo test --workspace --locked -j 2
# Windows: the Caddy-mode tests and the differential suite with Windows paths (Pingora against Windows Caddy;
# IANITOR_CADDY_BIN names caddy.exe on the runner).
- id: windows-tests
needs: [version]
run: cargo test --workspace --locked
- id: windows
needs: [check, test, windows-tests]
run: cargo build --release --locked -p ianitor-control --no-default-features && pnpm --filter web build && node scripts/package-windows.mjs
artifacts: ["target/dist/ianitor-*-windows-x86_64.zip"]
- id: linux
needs: [linux-tests]
run: docker build -f deploy/docker/Dockerfile --target dist --output type=local,dest=target/dist .
artifacts: ["target/dist/ianitor-*-linux-x86_64.tar.gz", "target/dist/install.sh"]
- id: image
needs: [linux-tests]
run: docker build --load -f deploy/docker/Dockerfile -t ianitor:${{ version }} .
- id: notes
run: fabrica notes
artifacts: ["target/notes/release-notes.md", "target/notes/release-notes.json"]
- id: shots
needs: [pictures]
run: fabrica aula shots
needs: [check, test]
run: node apps/web/scripts/shots.mjs
artifacts: ["target/aula/aula-*.png", "target/aula/aula.json"]
- id: page
needs: [notes, shots]
run: fabrica aula page
artifacts: ["target/aula/aula-page.json", "target/aula/aula-page.html"]
- id: approve
needs: [source, page]
approve: "Publish Ianitor ${{ tag }}: its source, notes and screenshots?"
needs: [version, notes, shots, windows, linux, image]
approve: "Publish Ianitor ${{ tag }}: the Linux tarball, the Windows Server zip, notes and screenshots?"
- id: publish
needs: [approve]
publish:
gitea-release: true
files:
- "**/ianitor-*-src.tar.gz"
- "**/ianitor-*-linux-x86_64.tar.gz"
- "**/install.sh"
- "**/ianitor-*-windows-x86_64.zip"
- "**/release-notes.md"
- "**/release-notes.json"
- "**/aula-*.png"
- "**/aula.json"
- "**/aula-page.json"
sums: domi-release
-26
View File
@@ -1,26 +0,0 @@
# Ianitor Domi's Aula page (docs/fabrica.md part 2, part 5; Fabrica docs/09_aula_pages.md, docs/19_web_shots.md).
# Every picture is taken by the web UI's own e2e suite (`pnpm --filter web aula:shots`, apps/web/e2e/specs/aula.spec.ts):
# the built UI in Edge against the demo control plane (apps/web/tests/demo.ts: hostnames under .test, addresses in the
# documentation ranges, people ada and felix), 1440 x 900, at a fixed instant in Europe/Prague. `fabrica aula shots`
# checks each file and publishes it as aula-<name>.png with aula.json; it starts no browser of its own.
shots:
- name: hosts
title: Every host, its health and where it sends traffic
section: Hosts
file: target/e2e/aula/hosts.png
- name: host
title: Editing a host
section: Hosts
file: target/e2e/aula/host.png
- name: engine
title: Pingora serving, Caddy ready as the fallback
section: Engines
file: target/e2e/aula/engine.png
- name: history
title: "History: going back to a kept version"
section: Changes
file: target/e2e/aula/history.png
- name: certificates
title: The Domi CA and the device certificates
section: Certificates
file: target/e2e/aula/certificates.png
-9
View File
@@ -1,9 +0,0 @@
A reverse proxy for a home server where every change is tried, watched and undone if it fails.
Each host says in plain words where its traffic goes, which certificate it uses and whether visitors sign in first. A change is checked, tried and watched for a minute, and goes back on its own if a host stops answering. Pingora serves, Caddy stands by built from the same routes, and a small Domi certificate authority issues the certificates for home-only hosts and devices.
- hosts: Every host with its health, its certificate and where it sends traffic.
- host: A host in plain words: upstreams, certificate, sign-in and health check.
- engine: Pingora serving, with Caddy built from the same routes and compared host by host.
- history: Every kept version in history, and exactly what restoring one would change.
- certificates: The Domi intermediate and the device certificates for phones, laptops and apps.
+16 -12
View File
@@ -1,13 +1,17 @@
Ianitor 0.2.0 gives Ianitor its own page on Aula.
Ianitor Domi now runs for any small team, not only on a NixOS server, and gives Fabrica a preview address for
every branch.
- **The Domi CA from the shared crate domi-pki.** Ianitor's certificate authority is now the shared crate domi-pki
1.0.0, which Fabrica also uses. It keeps the same certificates, messages and key format.
- **A page on Aula** with a short description, five captioned screenshots, these notes, and the source of the version
as its download. All of them are under a `SHA256SUMS` signed by domi-release.
- **Screenshots and videos from the tests.** The web UI's flows run in a real browser against an invented home
server at a fixed time: add a host, undo, restore, share a link, switch the engine and issue a device certificate.
Each flow is recorded. The same run takes the screenshots, so they are the same in every release.
- **Tested in Fabrica.** The flows are Fabrica's `web` test target and its `e2e` pipeline.
Updates stay a deploy. Fabrica's Deploy moves the server to the new commit and switches back if the health check
does not answer.
- **Install anywhere.** A one-line installer for Linux with systemd, a Docker image with a compose file, and
Windows Server, where Ianitor runs with Caddy as its engine (same screens, same route files; Pingora's Windows
support is still preliminary). The NixOS module stays.
- **Branch previews.** Fabrica asks for `<branch>--<project>.<your preview domain>` and gets it, with a certificate
from the Domi CA or Let's Encrypt; it closes when the branch is merged or its time runs out. Any branch name works:
unusual characters, dots and long names all become a safe address, and two branches never share one.
- **A token that can only do previews.** Fabrica's token opens and closes previews and nothing else, and previews
may only point where you allow, never at Ianitor's own admin ports.
- **Your team, without Authelia.** The installer prints a sign-in link for the first admin; admins invite the rest
with a link. Members change hosts and previews; admins also manage people, tokens, the engine and certificates.
Authelia still works where you have it.
- **Previews screen.** See every open preview in one click, close one in two.
- **Routes on any git host.** Push the routes repository to Gitea, GitHub or GitLab.
- **Tested on Windows too.** The comparison of Pingora and Caddy now also runs on Windows, with Windows paths.
@@ -1,15 +0,0 @@
---
id: j4yav1
title: Turn on the visual gate against v0.2.0
status: todo
priority: normal
labels: [fabrica, release]
created: 2026-11-19T01:25:43+01:00
updated: 2026-11-19T01:25:43+01:00
doc: docs/fabrica.md
---
Add Fabrica's visual step (docs/28_visual.md part 6) to .fabrica/artifex/release.yaml after shots: fabrica visual compare --shots target/aula --out target/visual --before ${{ tag }} --forge https://gitea.marek-novak.cz/mnovak/ianitor, custos: [gitea-token], and approve needs visual. Waits one release because v0.1.0's shots were taken at a moving clock, so every shot would differ (docs/fabrica.md part 5).
## Log
- 2026-11-19T01:25:43+01:00 mnovak: created
@@ -1,15 +0,0 @@
---
id: jd3x1h
title: Publish the showcase videos on Aula
status: todo
priority: normal
labels: [fabrica, aula]
created: 2026-11-19T01:25:17+01:00
updated: 2026-11-19T01:25:17+01:00
doc: docs/fabrica.md
---
The e2e suite records each main flow as target/e2e/videos/<flow>.webm (docs/fabrica.md part 5). Once Fabrica's docs/37 (aula.yaml `videos:`) is on Fabrica main, list them in .fabrica/aula.yaml, add **/aula-*.webm to the release's publish files and to Aula's entry if needed, and check the limits (WebM, at most 8 MiB and 60 s each, at most 6).
## Log
- 2026-11-19T01:25:17+01:00 mnovak: created
-11
View File
@@ -1,11 +0,0 @@
# Ianitor Domi's Playwright tests (docs/fabrica.md part 6; Fabrica docs/20_tests.md): the web UI's main flows on the
# built UI and the demo control plane (apps/web/playwright.config.ts, project `web`), each recorded as a video.
# `fabrica tests run`, or Tests in the Fabrica app; the e2e pipeline (.fabrica/artifex/e2e.yaml) runs the same target
# on the e2e runner. No android target: Ianitor has no Android build. The Rust suites run in WSL2 and the Nix build.
dir: apps/web
gate: [web]
targets:
- name: web
kind: web
title: The web UI's main flows
project: web
-48
View File
@@ -1,48 +0,0 @@
# Ianitor Domi
*Ianitor* (Latin: the doorkeeper) is the reverse proxy of a home server. It decides which name goes to which
service, with which certificate, and who has to sign in first. Every change is tried before it stays.
- **Hosts in plain words.** Add a host, say where its traffic goes, and pick a Domi or Let's Encrypt certificate.
Choose whether visitors sign in first (Authelia forward-auth). Each host is checked for health and shows as
healthy, degraded or down.
- **Changes that undo themselves.** Every change is compiled, tried, and watched for 60 seconds. If a host stops
answering, the change is reverted on its own. Routes live in a git repository, one file per host, with Undo and a
history you can restore any kept version from.
- **Two engines.** Cloudflare's Pingora serves. Caddy is built from the same routes, compared with Pingora host by
host, and can take over at runtime in about two seconds.
- **The Domi certificate authority.** It issues certificates for hosts reached only from home, and device
certificates (mTLS) for phones, computers and Domi apps. They come from an intermediate whose root stays offline.
- **Share links**, signed and time-limited, for a single host.
- **Every action in three clicks or fewer**, in a dark web UI that only the signed-in owner reaches.
## For whom
For someone who runs services at home (a wiki, photos, music, cameras) and wants each one to have a name, a
certificate and a sign-in, without editing a proxy's config by hand and without a change that breaks the house.
## Installing
Ianitor runs on NixOS. There is nothing to download and run: the server builds it from source with Nix.
1. Add the flake `git+https://gitea.marek-novak.cz/mnovak/Ianitor.git` as an input of the server's flake, and
import its module `nixosModules.ianitor`.
2. Set `services.ianitor`: `enable`, the edge's listen addresses, the routes repository, the share-link key file
and, for the Domi CA, `pki`. Keys and passwords come from files the system provides (sops, systemd
credentials), never from the Nix store. Then rebuild.
3. Open the UI's name in a browser and sign in through Authelia.
Ianitor can run beside an existing Caddy first, taking over one host at a time. Updates are a deploy: the server's
flake input moves to the new commit and the system switches, and switches back if the health check does not answer.
## System requirements
- NixOS on x86_64 Linux, with ports 80 and 443 for the edge.
- Authelia for sign-in to the UI and to the hosts that ask for it.
- A git server for the routes repository (any that takes a push over HTTPS).
## The files on this page
`ianitor-<version>-src.tar.gz` is the source of this version: every file in the repository at its tag. The
server's Nix build is made from the same tree. It is listed in `SHA256SUMS`, which verifies with domi-release.
The screenshots show invented hosts on an invented home server.
+4 -2
View File
@@ -14,14 +14,16 @@ tests/diff same requests against Ianitor and Caddy, responses compared.
tests/support shared test fixtures (test CA, upstreams, mock Authelia, clients); test-only.
tests/fuzz cargo-fuzz targets.
deploy/nixos NixOS module + VM tests.
deploy/docker the image (edge + control), compose file, the Linux CI image (target ci). deploy/linux: installer,
systemd units. deploy/windows: Windows Server installer (Caddy mode). docs/deploy/anywhere.md.
scripts the release's version check. Releases (notes, screenshots): docs/release.md.
## Commands
cargo test --workspace # quote test counts per crate; an exit code alone is not green
docker build --load -f deploy/docker/Dockerfile --target ci -t ianitor-ci . && docker run --rm --memory 6g ianitor-ci cargo test --workspace --locked -j 2 # Linux, all suites
cargo run -p ianitor-control -- --dev
pnpm --filter web dev # 127.0.0.1 only, never --host
pnpm --filter web test:e2e # the web UI's flows in Edge on demo data, recorded -> target/e2e/videos (docs/fabrica.md)
pnpm --filter web aula:shots # the Aula screenshots from the same suite -> target/e2e/aula; then `fabrica aula shots`
node apps/web/scripts/shots.mjs # the release's screenshots (demo data, headless Edge) -> target/aula (docs/release.md)
node scripts/check-version.mjs X.Y.Z # Cargo.toml and both package.json carry the version
nix build .#ianitor
nix flake check # includes NixOS VM tests (Linux + KVM)
Generated
+20
View File
@@ -1326,7 +1326,9 @@ dependencies = [
"tokio",
"tokio-rustls",
"toml",
"url",
"utoipa",
"windows-service",
]
[[package]]
@@ -1358,6 +1360,7 @@ dependencies = [
"rustls",
"serde_json",
"tokio",
"toml",
]
[[package]]
@@ -3552,6 +3555,12 @@ dependencies = [
"rustls-pki-types",
]
[[package]]
name = "widestring"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471"
[[package]]
name = "winapi-util"
version = "0.1.11"
@@ -3567,6 +3576,17 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-service"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "857224b3b211c6f3616921f081ee54721ee3ad2ace2fac6a6337e032f7b4dcf2"
dependencies = [
"bitflags",
"widestring",
"windows-sys 0.61.2",
]
[[package]]
name = "windows-sys"
version = "0.52.0"
-6
View File
@@ -1,6 +0,0 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
/** The suite's instant: the demo's answers and the page's Date both read it (a Monday morning in Prague). */
export const CLOCK = "2026-11-16T09:30:00+01:00";
-64
View File
@@ -1,64 +0,0 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// What every e2e test gets: the demo started over, the page's clock at the suite's instant, `open`
// for a page of the UI, and afterwards a check that nothing the page showed looks real
// (tests/demo.ts realLooking: names outside .test, addresses outside the documentation ranges).
// A test with a `video` annotation has its recording kept as target/e2e/videos/<name>.webm.
import { mkdirSync } from "node:fs";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { test as base, expect, type Page } from "@playwright/test";
import { realLooking } from "../tests/demo";
import { CLOCK } from "./clock";
export const REPO = resolve(fileURLToPath(new URL(".", import.meta.url)), "../../..");
export const TARGET = join(REPO, "target", "e2e");
function url(): string {
const u = process.env.IANITOR_E2E_URL;
if (!u) throw new Error("IANITOR_E2E_URL is not set: run the suite through playwright.config.ts (its global setup serves the demo)");
return u;
}
/** Every text, field value and link the page shows (the body: the head's links are the build's own files). */
async function shown(page: Page): Promise<string[]> {
return page.evaluate(() => {
const out: string[] = [];
const walk = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
for (let n = walk.nextNode(); n; n = walk.nextNode()) if (n.textContent?.trim()) out.push(n.textContent);
document.body.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>("input, textarea").forEach((i) => out.push(i.value));
document.body.querySelectorAll("[href]").forEach((a) => out.push(a.getAttribute("href") ?? ""));
return out;
});
}
export const test = base.extend<{ open: (path: string) => Promise<void> }>({
open: async ({ page, request }, use) => {
const res = await request.post(`${url()}/__demo/reset`);
expect(res.status()).toBe(204);
await page.clock.setFixedTime(new Date(CLOCK));
await use(async (path: string) => {
await page.goto(url() + path);
});
},
});
test.afterEach(async ({ page }, info) => {
const video = info.annotations.find((a) => a.type === "video")?.description;
if (!page.isClosed()) {
const seen = (await shown(page)).flatMap(realLooking);
expect(seen, "the page showed something that looks real").toEqual([]);
}
const rec = page.video();
if (video && rec && info.status === info.expectedStatus) {
await page.close();
const dir = join(TARGET, "videos");
mkdirSync(dir, { recursive: true });
await rec.saveAs(join(dir, `${video}.webm`));
}
});
export { expect };
-113
View File
@@ -1,113 +0,0 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// The e2e suite's server (Playwright's global setup): builds the web UI (Vite, production) into a
// fresh temporary folder and serves it on 127.0.0.1 at a free port, with /api/v1 answered by the
// demo control plane (tests/demo.ts) at the suite's fixed instant. Any other path falls back to
// index.html, as in production. POST /__demo/reset starts the demo over (each test starts from the
// same invented server). The address reaches the tests as IANITOR_E2E_URL. Nothing here listens on
// anything but loopback, and the temporary folder is removed when the run ends.
import { existsSync, mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
import { createServer, type IncomingMessage, type Server } from "node:http";
import { tmpdir } from "node:os";
import { extname, join, normalize, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { build } from "vite";
import { demoApi } from "../tests/demo";
import { clock } from "../tests/mockApi";
import { CLOCK } from "./clock";
const web = resolve(fileURLToPath(new URL(".", import.meta.url)), "..");
const TYPES: Record<string, string> = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json",
".svg": "image/svg+xml",
".png": "image/png",
".ico": "image/x-icon",
".woff": "font/woff",
".woff2": "font/woff2",
".txt": "text/plain; charset=utf-8",
};
function body(req: IncomingMessage): Promise<Record<string, unknown>> {
return new Promise((ok) => {
const chunks: Buffer[] = [];
req.on("data", (c: Buffer) => chunks.push(c));
req.on("end", () => {
try {
ok(chunks.length ? (JSON.parse(Buffer.concat(chunks).toString("utf8")) as Record<string, unknown>) : {});
} catch {
ok({});
}
});
});
}
function serve(dist: string): Promise<Server> {
const index = readFileSync(join(dist, "index.html"));
let api = demoApi();
const server = createServer((req, res) => {
const url = new URL(req.url ?? "/", "http://127.0.0.1");
if (url.pathname === "/__demo/reset" && req.method === "POST") {
api = demoApi();
res.writeHead(204).end();
return;
}
if (url.pathname === "/api/v1" || url.pathname.startsWith("/api/v1/")) {
void body(req).then((b) => {
const a = api(req.method ?? "GET", url.pathname.slice("/api/v1".length) + url.search, b);
res.writeHead(a.status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
res.end(a.text ?? undefined);
});
return;
}
let path: string;
try {
path = decodeURIComponent(url.pathname);
} catch {
res.writeHead(400).end();
return;
}
const file = normalize(join(dist, path));
if (file.startsWith(dist + sep) && existsSync(file) && statSync(file).isFile()) {
res.writeHead(200, { "Content-Type": TYPES[extname(file)] ?? "application/octet-stream" });
res.end(readFileSync(file));
return;
}
res.writeHead(200, { "Content-Type": TYPES[".html"], "Cache-Control": "no-store" });
res.end(index);
});
return new Promise((ok, fail) => {
server.once("error", fail);
server.listen(0, "127.0.0.1", () => ok(server));
});
}
export default async function setup(): Promise<() => Promise<void>> {
clock.fixed = Date.parse(CLOCK);
const tmp = mkdtempSync(join(tmpdir(), "ianitor-e2e-"));
const remove = () => rmSync(tmp, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
let server: Server;
try {
const dist = join(tmp, "dist");
await build({ root: web, logLevel: "warn", build: { outDir: dist, emptyOutDir: true } });
server = await serve(dist);
} catch (e) {
remove();
throw e;
}
const addr = server.address();
if (!addr || typeof addr === "string") throw new Error("the demo server has no port");
process.env.IANITOR_E2E_URL = `http://127.0.0.1:${addr.port}`;
console.log(`e2e: the built UI and the demo control plane on ${process.env.IANITOR_E2E_URL}`);
return async () => {
server.closeAllConnections();
await new Promise<void>((r) => server.close(() => r()));
remove();
};
}
-28
View File
@@ -1,28 +0,0 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// The release's screenshots (docs/release.md): each shot of tests/demo.ts SHOTS, 1440 × 900 at
// scale 1, saved as target/e2e/aula/<name>.png. .fabrica/aula.yaml lists the same files, which
// `fabrica aula shots` checks and publishes as aula-<name>.png with aula.json.
import { mkdirSync } from "node:fs";
import { join } from "node:path";
import { SHOTS } from "../../tests/demo";
import { TARGET, expect, test } from "../fixtures";
const dir = join(TARGET, "aula");
for (const shot of SHOTS) {
test(`aula: ${shot.name}`, async ({ page, open }) => {
await open(shot.path);
for (const sel of shot.click ?? []) await page.locator(sel).first().click();
await expect(page.locator(shot.wait).first()).toBeAttached();
// Nothing still loading, the fonts in, two frames drawn and transitions over.
await expect(page.locator("[aria-busy=true]")).toHaveCount(0);
await page.evaluate(() => document.fonts.ready.then(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))));
await page.waitForTimeout(400);
mkdirSync(dir, { recursive: true });
await page.screenshot({ path: join(dir, `${shot.name}.png`), animations: "disabled", caret: "hide" });
});
}
-116
View File
@@ -1,116 +0,0 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// The main flows of ROADMAP §4 in a real browser, on the built UI and the demo control plane, with
// the clicks counted as in the smoke test (tests/flows.test.ts). Each is recorded: the showcase
// videos (docs/fabrica.md part 5) are target/e2e/videos/<name>.webm.
import type { Locator, Page } from "@playwright/test";
import { expect, test } from "../fixtures";
function counter() {
let n = 0;
return {
click: async (l: Locator) => {
n++;
await l.click();
},
get count() {
return n;
},
};
}
/** A beat for the viewer of the video, so a screen is seen before the next click. */
const beat = (page: Page) => page.waitForTimeout(700);
const nav = (page: Page) => page.getByRole("navigation", { name: "Main" }).first();
test("Add a host: + Host → fill → Apply = 2 clicks, kept", { annotation: { type: "video", description: "add-host" } }, async ({ page, open }) => {
const c = counter();
await open("/");
await expect(page.getByRole("button", { name: "More for wiki.home.test" })).toBeVisible();
await beat(page);
await c.click(page.getByRole("button", { name: "Add a host" }));
await page.getByLabel("Hostname").pressSequentially("notes.home.test");
await page.getByLabel("Send traffic to").fill("http://192.0.2.60:8080");
await beat(page);
await c.click(page.getByRole("button", { name: "Apply" }));
await expect(page.locator("dialog.ia-panel")).toHaveCount(0, { timeout: 10_000 });
await expect(page.getByRole("button", { name: "More for notes.home.test" })).toBeVisible();
await beat(page);
expect(c.count).toBe(2);
});
test("Undo the last change = 1 click", { annotation: { type: "video", description: "undo" } }, async ({ page, open }) => {
const c = counter();
await open("/");
const undo = page.getByRole("button", { name: /^Undo: Added recipes\.home\.test/ });
await expect(undo).toBeVisible();
await beat(page);
const sent = page.waitForRequest((r) => r.method() === "POST" && r.url().endsWith("/api/v1/undo"));
await c.click(undo);
expect((await sent).postDataJSON()).toMatchObject({ target_change_id: "ch_0008" });
await beat(page);
expect(c.count).toBe(1);
});
test("Restore: History → pick → Restore = 3 clicks", { annotation: { type: "video", description: "restore" } }, async ({ page, open }) => {
const c = counter();
await open("/");
await expect(page.getByRole("button", { name: "Add a host" })).toBeVisible();
await c.click(nav(page).getByRole("link", { name: "History" }));
await beat(page);
await c.click(page.getByRole("button", { name: /Turned share links on for wiki\.home\.test/ }));
await expect(page.getByRole("button", { name: "Restore this version" })).toBeVisible();
await beat(page);
const sent = page.waitForRequest((r) => r.method() === "POST" && r.url().endsWith("/api/v1/restore"));
await c.click(page.getByRole("button", { name: "Restore this version" }));
await sent;
await beat(page);
expect(c.count).toBe(3);
});
test("Share link: ⋯ → Share link → Copy = 3 clicks, 7 days", { annotation: { type: "video", description: "share-link" } }, async ({ page, context, open }) => {
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
const c = counter();
await open("/");
await c.click(page.getByRole("button", { name: "More for wiki.home.test" }));
const minted = page.waitForRequest((r) => r.method() === "POST" && r.url().endsWith("/share-links"));
await c.click(page.getByRole("menuitem", { name: /Share link/ }));
expect((await minted).postDataJSON()).toMatchObject({ expires_in_s: 604800 });
const copy = page.getByRole("button", { name: "Copy link" });
await expect(copy).not.toHaveAttribute("aria-disabled", /.*/);
await beat(page);
await c.click(copy);
await expect(page.getByText("Copied")).toBeVisible();
await beat(page);
expect(c.count).toBe(3);
});
test("Switch engine: engine chip → Switch to Caddy = 2 clicks", { annotation: { type: "video", description: "engine" } }, async ({ page, open }) => {
const c = counter();
await open("/");
await c.click(page.getByRole("button", { name: /^Engine: Pingora/ }));
await expect(page.getByRole("button", { name: "Switch to Caddy" })).toBeVisible();
await beat(page);
await c.click(page.getByRole("button", { name: "Switch to Caddy" }));
await expect(page.getByText("Now serving with Caddy.")).toBeVisible({ timeout: 10_000 });
await beat(page);
expect(c.count).toBe(2);
});
test("Device certificate: Certificates → + Device → Issue = 3 clicks", { annotation: { type: "video", description: "device-certificate" } }, async ({ page, open }) => {
const c = counter();
await open("/");
await expect(page.getByRole("button", { name: "Add a host" })).toBeVisible();
await c.click(nav(page).getByRole("link", { name: "Certificates" }));
await beat(page);
await c.click(page.getByRole("button", { name: "Add a device certificate" }));
await page.getByLabel("Device name").fill("felix's tablet");
await c.click(page.getByRole("button", { name: "Issue" }));
await expect(page.getByLabel("Match code 47 19 83")).toBeVisible();
expect(c.count).toBe(3);
await expect(page.getByRole("button", { name: "Show QR code" })).toBeVisible({ timeout: 10_000 });
await beat(page);
});
-9
View File
@@ -1,9 +0,0 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"types": ["node"],
"noEmit": true,
"allowImportingTsExtensions": false
},
"include": ["./**/*.ts", "../playwright.config.ts", "../tests/demo.ts", "../tests/mockApi.ts"]
}
+2 -5
View File
@@ -8,21 +8,18 @@
"scripts": {
"dev": "vite",
"build": "vite build",
"check": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings && tsc -p e2e/tsconfig.json",
"check": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings",
"test": "vitest run",
"test:e2e": "playwright test --project=web",
"aula:shots": "playwright test --project=aula"
"shots": "node scripts/shots.mjs"
},
"dependencies": {
"@ianitor/ui": "workspace:*"
},
"devDependencies": {
"@playwright/test": "1.56.1",
"@sveltejs/vite-plugin-svelte": "^5.0.3",
"@testing-library/svelte": "^5.2.6",
"@testing-library/user-event": "^14.6.1",
"@tsconfig/svelte": "^5.0.4",
"@types/node": "^22.20.5",
"jsdom": "^26.0.0",
"svelte": "^5.20.0",
"svelte-check": "^4.1.4",
-51
View File
@@ -1,51 +0,0 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// The web UI's end-to-end suite (docs/fabrica.md, part 5): the built UI in a real browser against
// the demo control plane (tests/demo.ts, invented data only), served on 127.0.0.1 by e2e/serve.ts.
// Two projects:
// web the main flows of ROADMAP §4, each recorded as a video (target/e2e/videos/<flow>.webm);
// Fabrica's `web` target (.fabrica/tests.yaml) and its e2e pipeline run this one.
// aula the release's screenshots (target/e2e/aula/<name>.png), which `fabrica aula shots` checks
// and publishes (.fabrica/aula.yaml, `file:` shots).
// Every page is drawn at a fixed instant in a fixed zone, so two takes of a screen are the same.
// On Windows the browser is the installed Edge (PW_CHANNEL names another, e.g. chrome): nothing is
// downloaded. Elsewhere it is Playwright's own Chromium. Videos need Playwright's ffmpeg, which lives
// in PLAYWRIGHT_BROWSERS_PATH (on F: on Mark's PC, never C:).
import { defineConfig, devices } from "@playwright/test";
const channel = process.env.PW_CHANNEL ?? (process.platform === "win32" ? "msedge" : undefined);
// Fabrica's live view (Fabrica docs/20_tests.md part 3): the port its Tests page watches.
const devtools = process.env.FABRICA_TESTS_DEVTOOLS ? [`--remote-debugging-port=${process.env.FABRICA_TESTS_DEVTOOLS}`] : [];
const desktop = {
...devices["Desktop Chrome"],
...(channel ? { channel } : {}),
viewport: { width: 1440, height: 900 },
deviceScaleFactor: 1,
locale: "en-GB",
timezoneId: "Europe/Prague",
launchOptions: { args: ["--lang=en-GB", ...devtools] },
};
export default defineConfig({
testDir: "e2e/specs",
outputDir: "../../target/e2e/results",
globalSetup: "./e2e/serve.ts",
fullyParallel: false,
workers: 1,
retries: 0,
forbidOnly: !!process.env.CI,
// Generous: the release PC runs several apps' suites at once, and a loaded PC types and draws slowly
// (one Edge start took 45 s there, one flow 72 s). A real hang still ends.
timeout: 180_000,
expect: { timeout: 15_000 },
reporter: [["list"]],
use: { trace: "retain-on-failure" },
projects: [
{ name: "web", testMatch: "flows.spec.ts", use: { ...desktop, video: { mode: "on", size: { width: 1440, height: 900 } } } },
{ name: "aula", testMatch: "aula.spec.ts", use: desktop },
],
});
+418
View File
@@ -0,0 +1,418 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// The release's screenshots of the web UI (docs/release.md):
// node apps/web/scripts/shots.mjs [--out <dir>] (default: <repo>/target/aula)
// Builds the UI, serves it on 127.0.0.1 with /api/v1 answered by the demo control plane
// (tests/demo.ts: invented data only), photographs each shot of demo.ts's SHOTS in headless Edge
// or Chrome over DevTools, and writes aula-<name>.png and aula.json in the format of Fabrica's
// core docs/FORMATS.md ("Fabrica: the Aula page"). On every way out the browser's process tree
// and the server are stopped and the temporary folder is removed.
// Exit codes: 0 done, 1 a problem, 130 cancelled.
import { spawn, spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { createServer as createHttpServer } from "node:http";
import { tmpdir } from "node:os";
import { basename, delimiter, dirname, extname, join, normalize, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { build, createServer as createViteServer } from "vite";
const web = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const repo = resolve(web, "../..");
const WAIT_MS = 20_000;
function usage(msg) {
console.error(`shots: ${msg}\nusage: node apps/web/scripts/shots.mjs [--out <dir>]`);
process.exit(1);
}
let out = join(repo, "target", "aula");
for (let i = 2; i < process.argv.length; i++) {
const a = process.argv[i];
if (a === "--out" && process.argv[i + 1]) out = resolve(process.argv[++i]);
else usage(`unknown argument ${a}`);
}
const log = (m) => console.log(`shots: ${m}`);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// ---------- cleanup on every way out ----------
const cleanups = [];
let cleaning = false;
async function cleanup() {
if (cleaning) return;
cleaning = true;
for (const f of cleanups.reverse()) {
try {
await f();
} catch (e) {
console.error(`shots: cleanup: ${e?.message ?? e}`);
}
}
}
process.on("SIGINT", () => void cleanup().then(() => process.exit(130)));
process.on("SIGTERM", () => void cleanup().then(() => process.exit(130)));
// ---------- the output folder ----------
function clearOutput() {
mkdirSync(out, { recursive: true });
for (const n of readdirSync(out)) {
if (n === "aula.json" || (n.startsWith("aula-") && n.endsWith(".png"))) rmSync(join(out, n), { force: true });
}
}
/** Width and height from the PNG's IHDR, not assumed. */
function pngSize(png) {
const sig = "89504e470d0a1a0a";
if (png.length < 24 || png.subarray(0, 8).toString("hex") !== sig || png.subarray(12, 16).toString("latin1") !== "IHDR") {
throw new Error("the browser's capture is not a PNG");
}
return { width: png.readUInt32BE(16), height: png.readUInt32BE(20) };
}
// ---------- the demo control plane and the built UI on 127.0.0.1 ----------
const TYPES = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json",
".svg": "image/svg+xml",
".png": "image/png",
".ico": "image/x-icon",
".woff": "font/woff",
".woff2": "font/woff2",
".txt": "text/plain; charset=utf-8",
};
function serve(dist, api) {
const index = readFileSync(join(dist, "index.html"));
const server = createHttpServer((req, res) => {
const url = new URL(req.url ?? "/", "http://127.0.0.1");
if (url.pathname.startsWith("/api/v1/") || url.pathname === "/api/v1") {
const chunks = [];
req.on("data", (c) => chunks.push(c));
req.on("end", () => {
let body = {};
try {
body = chunks.length ? JSON.parse(Buffer.concat(chunks).toString("utf8")) : {};
} catch {
body = {};
}
const a = api(req.method ?? "GET", url.pathname.slice("/api/v1".length) + url.search, body);
res.writeHead(a.status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
res.end(a.text ?? undefined);
});
return;
}
// The built files; any other path is the app's own route, answered with index.html.
const file = normalize(join(dist, decodeURIComponent(url.pathname)));
if (file.startsWith(dist + sep) && existsSync(file) && statSync(file).isFile()) {
res.writeHead(200, { "Content-Type": TYPES[extname(file)] ?? "application/octet-stream" });
res.end(readFileSync(file));
return;
}
res.writeHead(200, { "Content-Type": TYPES[".html"], "Cache-Control": "no-store" });
res.end(index);
});
return new Promise((ok, fail) => {
server.once("error", fail);
server.listen(0, "127.0.0.1", () => ok(server));
});
}
// ---------- the browser ----------
function findBrowser() {
const named = process.env.IANITOR_SHOTS_BROWSER;
if (named) {
if (!existsSync(named)) throw new Error(`IANITOR_SHOTS_BROWSER: ${named} does not exist`);
return named;
}
const candidates = [];
if (process.platform === "win32") {
for (const base of [process.env["ProgramFiles(x86)"], process.env.ProgramFiles, process.env.LOCALAPPDATA].filter(Boolean)) {
candidates.push(join(base, "Microsoft", "Edge", "Application", "msedge.exe"), join(base, "Google", "Chrome", "Application", "chrome.exe"));
}
} else {
for (const dir of (process.env.PATH ?? "").split(delimiter).filter(Boolean)) {
for (const n of ["chromium", "chromium-browser", "google-chrome", "google-chrome-stable", "microsoft-edge"]) candidates.push(join(dir, n));
}
candidates.push("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome");
}
const found = candidates.find((c) => existsSync(c));
if (!found) throw new Error("no Microsoft Edge or Chrome found; set IANITOR_SHOTS_BROWSER to a Chromium browser");
return found;
}
/** Only what a program needs to run, the user folders in the temporary folder, nothing of the runner's. */
function cleanEnv(home) {
const keep = /^(SystemRoot|SystemDrive|windir|ComSpec|PATH|PATHEXT|OS|PROCESSOR_.*|NUMBER_OF_PROCESSORS|ProgramFiles.*|ProgramW6432|CommonProgramFiles.*|CommonProgramW6432|ProgramData|ALLUSERSPROFILE|PUBLIC|LANG|TZ)$/i;
const env = {};
for (const [k, v] of Object.entries(process.env)) if (keep.test(k) && v !== undefined) env[k] = v;
for (const d of ["home", "appdata", "local", "temp"]) mkdirSync(join(home, d), { recursive: true });
Object.assign(env, {
HOME: join(home, "home"),
USERPROFILE: join(home, "home"),
APPDATA: join(home, "appdata"),
LOCALAPPDATA: join(home, "local"),
TEMP: join(home, "temp"),
TMP: join(home, "temp"),
TMPDIR: join(home, "temp"),
});
return env;
}
/** Edge may start its browser again as a new process, outside the tree: on Windows, anything still
* running with a profile in the temporary folder is stopped by its command line. */
function sweep(exe, tmp) {
if (process.platform !== "win32") return;
const script = "Get-CimInstance Win32_Process -Filter \"Name='$env:SHOTS_EXE'\" | Where-Object { $_.CommandLine -and $_.CommandLine.Contains($env:SHOTS_TMP) } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }";
spawnSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], {
stdio: "ignore",
windowsHide: true,
env: { ...cleanEnv(join(tmp, "sweep")), SHOTS_EXE: basename(exe), SHOTS_TMP: tmp },
});
}
function killTree(child) {
if (!child.pid || child.exitCode !== null) return;
if (process.platform === "win32") {
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
} else {
try {
process.kill(-child.pid, "SIGKILL");
} catch {
child.kill("SIGKILL");
}
}
}
/** Starts the browser; one that has not opened DevTools after 20 s is killed and started again, twice. */
async function startBrowser(exe, tmp, size) {
for (let attempt = 1; ; attempt++) {
try {
return await launch(exe, join(tmp, `profile-${attempt}`), join(tmp, `user-${attempt}`), size);
} catch (e) {
if (attempt === 3 || e.fatal) throw e;
log(`${e.message}; starting it again`);
}
}
}
async function launch(exe, profile, user, size) {
mkdirSync(profile, { recursive: true });
const args = [
"--headless=new",
"--remote-debugging-port=0",
"--remote-debugging-address=127.0.0.1",
`--user-data-dir=${profile}`,
"--no-first-run",
"--no-default-browser-check",
"--disable-extensions",
"--disable-sync",
"--disable-background-networking",
"--disable-component-update",
"--disable-default-apps",
"--disable-features=Translate,OptimizationHints,MediaRouter,msSmartScreenProtection",
"--hide-scrollbars",
"--mute-audio",
"--force-color-profile=srgb",
"--force-device-scale-factor=1",
`--window-size=${size.width},${size.height}`,
"about:blank",
];
const child = spawn(exe, args, { env: cleanEnv(user), stdio: ["ignore", "ignore", "pipe"], windowsHide: true, detached: process.platform !== "win32" });
const stop = async () => {
killTree(child);
for (let i = 0; i < 50 && child.exitCode === null && child.signalCode === null; i++) await sleep(100);
};
cleanups.push(stop);
let stderr = "";
child.stderr.on("data", (d) => (stderr = (stderr + d).slice(-2000)));
const fail = async (msg, fatal = false) => {
await stop();
const tail = stderr.trim().split(/\r?\n/).slice(-3).join(" | ");
throw Object.assign(new Error(`${msg}${tail ? `; it said: ${tail}` : ""}`), { fatal });
};
let exited = null;
child.on("exit", (code) => (exited = code ?? -1));
child.on("error", (e) => (exited = e.message));
const portFile = join(profile, "DevToolsActivePort");
const deadline = Date.now() + 20_000;
let seen = "no DevToolsActivePort yet";
for (;;) {
if (exited !== null) await fail(`the browser exited before it was ready (${exited})`, typeof exited === "string");
if (existsSync(portFile)) {
const port = Number(readFileSync(portFile, "utf8").split(/\r?\n/)[0]);
if (port > 0) {
try {
const list = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
const page = list.find((t) => t.type === "page" && t.webSocketDebuggerUrl);
if (page) return page.webSocketDebuggerUrl;
seen = `no page among ${list.length} targets on port ${port}`;
await fetch(`http://127.0.0.1:${port}/json/new?about:blank`, { method: "PUT" }).catch(() => {});
} catch (e) {
seen = `port ${port}: ${e.cause?.message ?? e.message}`;
}
}
}
if (Date.now() > deadline) await fail(`the browser's DevTools did not answer within 20 s (${seen})`);
await sleep(200);
}
}
/** A minimal DevTools client over Node's WebSocket. */
async function devtools(url) {
const ws = new WebSocket(url);
await new Promise((ok, fail) => {
ws.onopen = ok;
ws.onerror = () => fail(new Error("cannot open the browser's DevTools socket"));
});
let id = 0;
const pending = new Map();
ws.onmessage = (m) => {
const msg = JSON.parse(String(m.data));
const p = msg.id !== undefined && pending.get(msg.id);
if (!p) return;
pending.delete(msg.id);
if (msg.error) p.fail(new Error(`${p.method}: ${msg.error.message}`));
else p.ok(msg.result);
};
ws.onclose = () => {
for (const p of pending.values()) p.fail(new Error("the browser closed its DevTools socket"));
pending.clear();
};
cleanups.push(() => ws.close());
const send = (method, params = {}) =>
new Promise((ok, fail) => {
const n = ++id;
pending.set(n, { ok, fail, method });
ws.send(JSON.stringify({ id: n, method, params }));
});
/** The value of an expression in the page; a page being replaced answers again later. */
const evaluate = async (expression) => {
const r = await send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true });
if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description ?? r.exceptionDetails.text);
return r.result.value;
};
return { send, evaluate };
}
async function until(what, test) {
const deadline = Date.now() + WAIT_MS;
let last = null;
while (Date.now() < deadline) {
try {
if (await test()) return;
} catch (e) {
last = e;
}
await sleep(100);
}
throw new Error(`waited ${WAIT_MS / 1000} s for ${what}${last ? ` (${last.message})` : ""}`);
}
// ---------- the shots ----------
async function main() {
clearOutput();
const tmp = mkdtempSync(join(tmpdir(), "ianitor-shots-"));
cleanups.push(async () => {
for (let i = 0; i < 20; i++) {
try {
rmSync(tmp, { recursive: true, force: true });
return;
} catch {
await sleep(250);
}
}
console.error(`shots: could not remove ${tmp}`);
});
// The demo's shots and answers, from the TypeScript the tests use.
const loader = await createViteServer({
root: web,
configFile: false,
logLevel: "error",
appType: "custom",
server: { middlewareMode: true, hmr: false, ws: false },
optimizeDeps: { noDiscovery: true, include: [] },
});
let demo;
try {
demo = await loader.ssrLoadModule("/tests/demo.ts");
} finally {
await loader.close();
}
const { SHOTS, SIZE, demoApi } = demo;
log("building the web UI");
const dist = join(tmp, "dist");
await build({ root: web, logLevel: "warn", build: { outDir: dist, emptyOutDir: true } });
const server = await serve(dist, demoApi());
cleanups.push(() => new Promise((r) => server.close(() => r())));
server.closeAllConnections && cleanups.push(() => server.closeAllConnections());
const base = `http://127.0.0.1:${server.address().port}`;
log(`demo control plane and UI on ${base}`);
const exe = findBrowser();
log(`browser: ${exe}`);
cleanups.push(() => sweep(exe, tmp));
const page = await devtools(await startBrowser(exe, tmp, SIZE));
await page.send("Page.enable");
await page.send("Emulation.setDeviceMetricsOverride", { width: SIZE.width, height: SIZE.height, deviceScaleFactor: 1, mobile: false });
const taken = [];
for (const shot of SHOTS) {
const url = base + shot.path;
try {
// A fresh load per shot: mark the old page, so a page that has not been replaced yet does not count.
await page.evaluate("window.__ianitorShotsOld = true").catch(() => {});
await page.send("Page.navigate", { url });
await until(`${url} to load`, () => page.evaluate("!window.__ianitorShotsOld && document.readyState === 'complete'"));
for (const sel of shot.click ?? []) {
const q = JSON.stringify(sel);
await until(`${sel} to click`, () => page.evaluate(`(() => { const e = document.querySelector(${q}); if (!e) return false; e.click(); return true; })()`));
}
const w = JSON.stringify(shot.wait);
await until(shot.wait, () => page.evaluate(`!!document.querySelector(${w})`));
await page.evaluate("document.fonts.ready.then(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r(true)))))");
await sleep(400);
} catch (e) {
try {
const failed = await page.send("Page.captureScreenshot", { format: "png" });
writeFileSync(join(out, `aula-${shot.name}-failed.png`), Buffer.from(failed.data, "base64"));
} catch {
/* nothing to save */
}
throw new Error(`shot ${shot.name}: ${e.message}; the page was ${url}; what it showed is aula-${shot.name}-failed.png`);
}
const png = Buffer.from((await page.send("Page.captureScreenshot", { format: "png" })).data, "base64");
const { width, height } = pngSize(png);
const file = `aula-${shot.name}.png`;
writeFileSync(join(out, file), png);
taken.push({ name: shot.name, title: shot.title, file, width, height, sha256: createHash("sha256").update(png).digest("hex") });
log(`${file} ${width}x${height}`);
}
writeFileSync(join(out, "aula.json"), `${JSON.stringify({ v: 1, shots: taken })}\n`);
log(`${taken.length} shots and aula.json in ${out}`);
}
let code = 0;
try {
await main();
} catch (e) {
console.error(`shots: ${e?.message ?? e}`);
code = 1;
} finally {
await cleanup();
}
process.exit(code);
+43 -4
View File
@@ -15,6 +15,7 @@
import Certificates from "./views/Certificates.svelte";
import History from "./views/History.svelte";
import Hosts from "./views/Hosts.svelte";
import Previews from "./views/Previews.svelte";
import RenewByHand from "./views/RenewByHand.svelte";
import Settings from "./views/Settings.svelte";
import SignedIn from "./views/SignedIn.svelte";
@@ -24,6 +25,7 @@
const p = u.pathname.replace(/\/+$/, "") || "/";
const seg = p.split("/").filter(Boolean).map(decodeURIComponent);
if (p === "/signed-in") return { view: "signed-in" as const };
if (seg[0] === "previews") return { view: "previews" as const };
if (seg[0] === "history") return { view: "history" as const, host: u.searchParams.get("host") ?? undefined, pick: seg[1] };
if (seg[0] === "certificates") return { view: seg[1] === "renew-by-hand" ? ("renew" as const) : ("certs" as const), newDevice: seg[1] === "new" };
if (seg[0] === "settings") return { view: "settings" as const, tab: seg[1] ?? "general" };
@@ -32,18 +34,51 @@
const NAV: { href: string; label: string; icon: IconName; views: string[] }[] = [
{ href: "/", label: "Hosts", icon: "building", views: ["hosts"] },
{ href: "/previews", label: "Previews", icon: "link", views: ["previews"] },
{ href: "/history", label: "History", icon: "history", views: ["history"] },
{ href: "/certificates", label: "Certificates", icon: "shield", views: ["certs", "renew"] },
{ href: "/settings/general", label: "Settings", icon: "gear", views: ["settings"] },
];
const TITLES: Record<string, string> = { hosts: "Hosts", history: "History", certs: "Certificates", renew: "Certificates", settings: "Settings", "signed-in": "Signed in" };
const TITLES: Record<string, string> = { hosts: "Hosts", history: "History", previews: "Previews", certs: "Certificates", renew: "Certificates", settings: "Settings", "signed-in": "Signed in" };
$effect(() => {
document.title = `${TITLES[route.view] ?? "Hosts"} — Ianitor Domi`;
});
// A setup or invite link (`#signin=<code>`, crate::team): one click on the link signs in.
async function signInFromLink(): Promise<void> {
const m = /^#signin=([A-Za-z0-9_-]{8,100})$/.exec(location.hash);
if (!m) return;
history.replaceState(null, "", location.pathname + location.search);
try {
const r = await fetch("/api/v1/session", {
method: "POST",
headers: { "Content-Type": "application/json", "X-Ianitor-UI": "1" },
body: JSON.stringify({ code: m[1], device: navigator.platform || "Browser" }),
credentials: "same-origin",
});
if (!r.ok) {
const j = await r.json().catch(() => null);
app.linkProblem = j?.error?.message ?? "This sign-in link does not work.";
}
} catch {
app.linkProblem = "Ianitor did not answer the sign-in.";
}
}
async function signOutSession() {
try {
await fetch("/api/v1/session/end", { method: "POST", headers: { "X-Ianitor-UI": "1" }, credentials: "same-origin" });
} finally {
location.href = "/";
}
}
onMount(() => {
if (route.view === "signed-in") return;
if (location.hash.startsWith("#signin=")) {
void signInFromLink().then(() => refresh());
}
const stop = startPolling();
// Resume an apply this tab was watching before a reload or a sign-in (§3).
const id = remembered();
@@ -101,7 +136,8 @@
<a href={n.href} class="nav" aria-current={n.views.includes(route.view) ? "page" : undefined} onclick={(e) => go(e, n.href)}><Icon name={n.icon} />{n.label}</a>
{/each}
<div class="foot ia-muted">
<p>{viewer?.via === "authelia" ? `Signed in as ${viewer.name} through Authelia` : viewer ? `Using the API token "${viewer.name}"` : "Signed in through Authelia"}</p>
<p>{viewer?.via === "authelia" ? `Signed in as ${viewer.name} through Authelia` : viewer?.via === "session" ? `Signed in as ${viewer.name}` : viewer ? `Using the API token "${viewer.name}"` : "Not signed in"}</p>
{#if viewer?.via === "session"}<button type="button" class="domi-btn link" onclick={signOutSession}>Sign out</button>{/if}
<p>Control on 127.0.0.1 only</p>
{#if app.overview?.site?.auth_logout_url}<a class="domi-btn link" href={app.overview.site.auth_logout_url}>Sign out</a>{/if}
</div>
@@ -109,8 +145,11 @@
<header class="topbar"><span class="ia-wordmark">IANITOR DOMI</span>{#if app.phone}<EngineChip />{/if}</header>
<main id="main" tabindex="-1">
<TopBanners />
{#if app.linkProblem}<p class="domi-error" role="alert">{app.linkProblem}</p>{/if}
{#if route.view === "hosts"}
<Hosts route={{ newHost: route.newHost, edit: route.edit }} />
{:else if route.view === "previews"}
<Previews />
{:else if route.view === "history"}
{#key route.host}<History host={route.host} pick={route.pick} />{/key}
{:else if route.view === "certs"}
@@ -141,7 +180,7 @@
{#if app.signedOut}
<Dialog title="Your sign-in has ended" role="alertdialog" escape={false} closable={false} onclose={() => {}}>
<p>Sign in again; this page keeps what you typed.</p>
<p>Sign in again; this page keeps what you typed. Without Authelia, open your sign-in link again or ask an admin of your team for a new one.</p>
{#snippet footer()}
<Button onclick={signedInAgain}>I have signed in</Button>
<Button variant="primary" onclick={signIn} data-autofocus>Sign in</Button>
@@ -167,7 +206,7 @@
.topbar { display: flex; align-items: center; justify-content: space-between; background: var(--colonnade); border-bottom: 1px solid var(--hairline); padding: 10px 16px; }
.topbar .ia-wordmark { font-size: 12px; letter-spacing: 0.26em; }
main { padding: 18px 16px calc(90px + env(safe-area-inset-bottom)); gap: 14px; }
.bottombar { display: grid; grid-template-columns: repeat(4, 1fr); position: fixed; left: 0; right: 0; bottom: 0; background: var(--colonnade); border-top: 1px solid var(--hairline); padding: 6px 8px calc(10px + env(safe-area-inset-bottom)); z-index: 40; }
.bottombar { display: grid; grid-template-columns: repeat(5, 1fr); position: fixed; left: 0; right: 0; bottom: 0; background: var(--colonnade); border-top: 1px solid var(--hairline); padding: 6px 8px calc(10px + env(safe-area-inset-bottom)); z-index: 40; }
.bottombar a { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; min-height: var(--phone-bar-h); border-radius: var(--radius-sm); color: var(--text-2); font-weight: 600; font-size: var(--fs-tab-phone); text-decoration: none; }
.bottombar a[aria-current="page"] { background: var(--surface-2); color: var(--text); }
.bottombar a[aria-current="page"] :global(svg) { color: var(--accent); }
+137
View File
@@ -0,0 +1,137 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<script lang="ts">
// T4: the team without Authelia. Invite: Settings → Team → Invite (3 clicks), then Copy link.
import { onMount } from "svelte";
import { Banner, Button, Segmented } from "@ianitor/ui";
import { del, get, post, put, sentence } from "../lib/api";
import { toast } from "../lib/app.svelte";
import { shortDate } from "../lib/format";
import type { TeamView } from "../lib/types";
let team = $state<TeamView | null>(null);
let problem = $state<string | null>(null);
let name = $state("");
let role = $state<"member" | "admin">("member");
let link = $state<string | null>(null);
let confirmRemove = $state<string | null>(null);
let root = $state("");
async function load() {
try {
team = await get<TeamView>("/team");
root = team.me?.tessera_root ?? "";
problem = null;
} catch (e) {
problem = sentence(e);
}
}
onMount(() => void load());
async function invite() {
try {
const r = await post<{ link_fragment: string }>("/team/invites", { name: name.trim(), role });
link = `${location.origin}/${r.link_fragment}`;
name = "";
await load();
} catch (e) {
problem = sentence(e);
}
}
async function copy() {
if (!link) return;
try {
await navigator.clipboard.writeText(link);
toast("Copied. Send it to them; it works once, for 7 days.");
} catch {
problem = "Your browser did not allow copying. Select the link and press Ctrl+C.";
}
}
async function remove(id: string) {
try {
await del(`/team/members/${encodeURIComponent(id)}`);
confirmRemove = null;
toast("Removed and signed out everywhere.");
await load();
} catch (e) {
problem = sentence(e);
}
}
async function saveRoot() {
try {
await put("/team/me/root", { tessera_root: root.trim() || null });
toast("Saved.");
await load();
} catch (e) {
problem = sentence(e);
}
}
const admin = $derived(team?.me ? team.me.role === "admin" : true);
</script>
{#if problem}<Banner tone="notice" live="status" ondismiss={() => (problem = null)}>{#snippet title()}{problem}{/snippet}</Banner>{/if}
{#if team?.authelia}
<p class="ia-hint">Authelia signs people in on this server. Team links work too.</p>
{/if}
<h2 class="ia-h3">People</h2>
<ul class="rows">
{#each team?.members ?? [] as m (m.id)}
<li>
<div class="grow"><strong>{m.name}</strong>{team?.me?.id === m.id ? " (you)" : ""}
<span class="ia-sub" style="display:block">{m.role} · since {shortDate(m.added_at)}{m.match_code ? ` · Domi identity ${m.match_code}` : ""}</span></div>
{#if admin && team?.me?.id !== m.id}
{#if confirmRemove === m.id}
<span>Remove {m.name}? They are signed out everywhere.</span>
<Button small onclick={() => (confirmRemove = null)}>Keep</Button>
<Button small variant="danger" onclick={() => remove(m.id)}>Remove</Button>
{:else}
<Button small variant="danger" onclick={() => (confirmRemove = m.id)}>Remove</Button>
{/if}
{/if}
</li>
{/each}
</ul>
{#if admin}
<div class="row">
<div class="domi-field">
<label class="domi-field-label" for="invite-name">Name</label>
<input id="invite-name" class="domi-input" bind:value={name} placeholder="Petra" />
</div>
<Segmented legend="Role" name="invite-role" bind:value={role} options={[{ value: "member", label: "Member" }, { value: "admin", label: "Admin" }]} />
<Button variant="outline" icon="plus" onclick={invite} disabled={!name.trim()}>Invite</Button>
</div>
<p class="ia-hint">Members change hosts and previews. Admins also manage people, API tokens, the engine and certificates.</p>
{#if link}
<div class="grid">
<input class="ia-secret" readonly value={link} aria-label="Invite link" onfocus={(e) => (e.currentTarget as HTMLInputElement).select()} />
<Button variant="primary" icon="copy" onclick={copy} data-autofocus>Copy link</Button>
</div>
{/if}
{/if}
{#if team?.me}
<h2 class="ia-h3">Your Domi identity</h2>
<div class="row">
<div class="domi-field grow">
<label class="domi-field-label" for="tessera-root">Tessera root (Custos → Domi identity)</label>
<input id="tessera-root" class="domi-input" bind:value={root} spellcheck="false" />
</div>
<Button onclick={saveRoot}>Save</Button>
</div>
<p class="ia-hint">Your teammates see its match code next to your name, the same digits Custos shows.</p>
{/if}
<style>
.rows { list-style: none; margin: 0; padding: 0; }
.rows li { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; min-height: 44px; padding: 8px 0; border-top: 1px solid var(--hairline); }
.grow { flex: 1 1 200px; min-width: 0; }
.row { display: flex; gap: 12px; align-items: flex-end; flex-wrap: wrap; }
.grid { display: grid; grid-template-columns: 1fr auto; gap: 12px; align-items: end; }
@media (max-width: 719.98px) { .grid { grid-template-columns: 1fr; } }
</style>
+1 -1
View File
@@ -139,7 +139,7 @@ export async function call<T>(
await sleep(Math.min(60, env.error.retry_after_s ?? 1) * 1000);
continue;
}
if (res.status === 401 && env.error.code.startsWith("token.")) {
if (res.status === 401 && (env.error.code.startsWith("token.") || env.error.code.startsWith("session."))) {
// The UI holds no token: a token refusal means the sign-in did not reach control.
events.onSignedOut?.();
throw new SignedOut(env.error.message);
+2
View File
@@ -14,6 +14,8 @@ export interface Toast {
}
export const app = $state({
/** Why a `#signin=` link did not sign this browser in. */
linkProblem: null as string | null,
overview: null as Overview | null,
etag: null as string | null,
loadError: false,
+34
View File
@@ -212,6 +212,7 @@ export interface TokenRow {
last_used_at: string | null;
expires_at: string | null;
revoked_at?: string | null;
scope?: "full" | "previews";
}
export interface CreatedToken {
@@ -249,3 +250,36 @@ export interface Bundle {
filename: string;
qr_svg: string | null;
}
// T4: branch previews and the team (docs/previews.md, crate::team).
export interface PreviewView {
hostname: string;
url: string;
project: string;
branch: string;
upstream: string;
expires_at: string;
state: "applying" | "live" | "failed";
problem?: string | null;
}
export interface PreviewList {
items: PreviewView[];
domain: string | null;
}
export interface MemberView {
id: string;
name: string;
role: "admin" | "member";
added_at: string;
tessera_root: string | null;
match_code: string | null;
}
export interface TeamView {
me: MemberView | null;
members: MemberView[];
invites: { id: string; name: string | null; role: string; expires_at: string }[];
authelia: boolean;
}
+103
View File
@@ -0,0 +1,103 @@
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<script lang="ts">
// T4: branch previews Fabrica opens. See them: 1 click (the nav). Close one: 2 clicks
// (Close → Close preview).
import { onMount } from "svelte";
import { Banner, Button, Status } from "@ianitor/ui";
import type { StatusKind } from "@ianitor/ui";
import { del, get, sentence } from "../lib/api";
import { app, toast } from "../lib/app.svelte";
import { whenInline } from "../lib/format";
import type { PreviewList, PreviewView } from "../lib/types";
let list = $state<PreviewList | null>(null);
let problem = $state<string | null>(null);
let confirm = $state<string | null>(null);
let closing = $state<string | null>(null);
async function load() {
try {
list = await get<PreviewList>("/previews");
problem = null;
} catch (e) {
problem = sentence(e);
}
}
async function close(p: PreviewView) {
closing = p.hostname;
try {
await del(`/previews/${encodeURIComponent(p.hostname)}`);
toast(`Closing the preview of ${p.branch}.`);
confirm = null;
await load();
} catch (e) {
problem = sentence(e);
} finally {
closing = null;
}
}
onMount(() => {
void load();
const t = setInterval(() => void load(), 5000);
const f = () => void load();
window.addEventListener("focus", f);
return () => {
clearInterval(t);
window.removeEventListener("focus", f);
};
});
function badge(p: PreviewView): [StatusKind, string] {
if (p.state === "live") return ["healthy", "live"];
if (p.state === "failed") return ["down", "failed"];
return ["running", "opening"];
}
</script>
<h1 class="ia-display">Previews</h1>
{#if problem}<Banner tone="notice" live="status" ondismiss={() => (problem = null)}>{#snippet title()}{problem}{/snippet}</Banner>{/if}
{#if list && !list.domain}
<div class="ia-frame">
<h2 class="ia-h3">Previews are off</h2>
<p class="ia-text2">Set a preview domain in control.toml (<code>[previews] domain</code>) and point a wildcard DNS record at this server. Then every branch Fabrica builds gets its own address here.</p>
</div>
{:else if list && list.items.length === 0}
<div class="ia-frame">
<h2 class="ia-h3">No previews open</h2>
<p class="ia-text2">When Fabrica builds a branch, its preview appears here as <code>&lt;branch&gt;--&lt;project&gt;.{list.domain}</code>. It closes on merge or when its time runs out.</p>
</div>
{:else if list}
<p class="ia-hint">Under {list.domain}. Fabrica opens them with a token that can only manage previews.</p>
<ul class="rows">
{#each list.items as p (p.hostname)}
{@const [kind, label] = badge(p)}
<li>
<Status {kind} word={label} />
<div class="grow">
<a class="host" href={p.url} target="_blank" rel="noreferrer">{p.hostname}</a>
<span class="ia-sub" style="display:block">{p.branch} · {p.project} · to {p.upstream} · closes {whenInline(p.expires_at, app.now)}</span>
{#if p.problem}<span class="domi-error">{p.problem}</span>{/if}
</div>
{#if confirm === p.hostname}
<span>Close the preview of {p.branch}? Its address stops working.</span>
<Button small onclick={() => (confirm = null)}>Keep it</Button>
<Button small variant="danger" pending={closing === p.hostname} onclick={() => close(p)} data-autofocus>Close preview</Button>
{:else}
<Button small variant="danger" onclick={() => (confirm = p.hostname)}>Close</Button>
{/if}
</li>
{/each}
</ul>
{/if}
<style>
.rows { list-style: none; margin: 0; padding: 0; }
.rows li { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; min-height: 52px; padding: 10px 0; border-top: 1px solid var(--hairline); }
.grow { flex: 1 1 260px; min-width: 0; }
.host { font-weight: 600; color: var(--text); overflow-wrap: anywhere; }
</style>
+13 -6
View File
@@ -6,6 +6,7 @@
// accepted 4th), Share links and About.
import { onMount } from "svelte";
import { Banner, Button, Dialog, Segmented } from "@ianitor/ui";
import TeamTab from "../components/TeamTab.svelte";
import { ApiError, call, del, get, newKey, patch, post, sentence } from "../lib/api";
import { app, navigate, toast } from "../lib/app.svelte";
import { longDate, shortDate, whenInline } from "../lib/format";
@@ -14,6 +15,7 @@
let { tab }: { tab: string } = $props();
const TABS = [
{ id: "general", label: "General" },
{ id: "team", label: "Team" },
{ id: "api", label: "API" },
{ id: "share-links", label: "Share links" },
{ id: "about", label: "About" },
@@ -25,6 +27,7 @@
let links = $state<ShareLink[]>([]);
let problem = $state<string | null>(null);
let expiry = $state<"year" | "never">("year");
let scope = $state<"full" | "previews">("full");
let made = $state<CreatedToken | null>(null);
let tokenName = $state("");
let tokenCopied = $state(false);
@@ -69,8 +72,8 @@
async function newToken() {
creating = true;
try {
const name = `Token made ${shortDate(new Date().toISOString())}`;
const body = expiry === "never" ? { name, never_expires: true } : { name, expires_in_days: 365 };
const name = scope === "previews" ? `Fabrica previews ${shortDate(new Date().toISOString())}` : `Token made ${shortDate(new Date().toISOString())}`;
const body = expiry === "never" ? { name, never_expires: true, scope } : { name, expires_in_days: 365, scope };
made = await post<CreatedToken>("/tokens", body);
tokenName = made.name;
tokenCopied = false;
@@ -164,18 +167,22 @@
<div role="tabpanel" id="panel-{tab}" aria-labelledby="tab-{tab}" class="panel">
{#if tab === "general"}
<p class="ia-label">Routes repository</p>
<p>{settings?.repo ? `${settings.repo.name} on Gitea · ${settings.repo.last_push_at ? "pushed " + whenInline(settings.repo.last_push_at, app.now) : "not pushed yet"}` : "No place to push to is set up."}</p>
<p>{settings?.repo ? `${settings.repo.name} · ${settings.repo.last_push_at ? "pushed " + whenInline(settings.repo.last_push_at, app.now) : "not pushed yet"}` : "No place to push to is set up."}</p>
<p class="ia-label">Health watch after apply</p>
<p>{settings?.watch_seconds ?? app.overview?.site?.watch_seconds ?? 60} seconds</p>
<p class="ia-label">Signed in</p>
<p>{viewer ? (viewer.via === "authelia" ? `${viewer.name} through Authelia` : `API token "${viewer.name}"`) : "Through Authelia"}</p>
<p>{viewer ? (viewer.via === "authelia" ? `${viewer.name} through Authelia` : viewer.via === "session" ? viewer.name : `API token "${viewer.name}"`) : "Not signed in"}</p>
{#if app.overview?.site?.auth_logout_url}<p><a class="domi-btn link" href={app.overview.site.auth_logout_url}>Sign out</a></p>{/if}
{:else if tab === "team"}
<TeamTab />
{:else if tab === "api"}
<div class="row">
<h2 class="ia-h3">API tokens</h2>
<Button variant="outline" icon="plus" onclick={newToken} pending={creating}>New token</Button>
<Segmented legend="New tokens expire after" name="token-expiry" bind:value={expiry} options={[{ value: "year", label: "1 year" }, { value: "never", label: "Never" }]} />
<Segmented legend="New tokens may" name="token-scope" bind:value={scope} options={[{ value: "full", label: "Do everything" }, { value: "previews", label: "Previews only" }]} />
</div>
<p class="ia-hint">Fabrica needs a previews-only token: it can open and close branch previews and touch nothing else. Keep it in the Custos team vault.</p>
<p class="ia-hint">The API listens on 127.0.0.1 only. Ianitor keeps a hash of each token, never the token.</p>
{#if tokens.length === 0}
<div class="ia-frame"><h2 class="ia-h3">No API tokens</h2><p class="ia-text2">Scripts and other Domi apps use a token to talk to Ianitor.</p></div>
@@ -184,7 +191,7 @@
{#each tokens as t (t.id)}
<li>
<div class="grow">
<span class="tname" class:struck={!!revoked[t.id] || !!t.revoked_at}>{t.name}</span>
<span class="tname" class:struck={!!revoked[t.id] || !!t.revoked_at}>{t.name}</span>{#if t.scope === "previews"} <span class="ia-sub">previews only</span>{/if}
<span class="ia-sub" style="display:block">
{#if revoked[t.id]}Revoked {whenInline(revoked[t.id], app.now)}{:else}Made {shortDate(t.created_at)} · {t.last_used_at ? `last used ${whenInline(t.last_used_at, app.now)}` : "never used"} · {t.expires_at ? `expires ${shortDate(t.expires_at)}` : "never expires"}{/if}
</span>
@@ -233,7 +240,7 @@
{/if}
{/if}
{:else}
<p>Ianitor Domi 0.1.0</p>
<p>Ianitor Domi 0.2.0</p>
<p>MPL-2.0</p>
<p>Built, tested and signed by Fabrica Domi</p>
<p><a class="domi-btn link" href="https://gitea.marek-novak.cz/mnovak/Ianitor" rel="noreferrer">Source on Gitea</a></p>
+18 -1
View File
@@ -10,7 +10,24 @@ import { cleanup, render, waitFor } from "@testing-library/svelte";
import { afterEach, describe, expect, it } from "vitest";
import App from "../src/App.svelte";
import { app } from "../src/lib/app.svelte";
import { SHOTS, demoApi, realLooking } from "./demo";
import { SHOTS, demoApi } from "./demo";
const ALLOWED_TLDS = new Set(["test", "example", "invalid"]);
const DOC_NETS = ["192.0.2.", "198.51.100.", "203.0.113."];
const FORBIDDEN = ["mark", "marek", "novak", "flowers", "esp32", "hyperv"];
/** What in a text could be real: addresses outside the documentation ranges, names outside .test. */
function realLooking(text: string): string[] {
const found: string[] = [];
for (const m of text.matchAll(/(?<![\w.])\d{1,3}(?:\.\d{1,3}){3}(?![\w.])/g)) {
if (m[0] !== "127.0.0.1" && !DOC_NETS.some((n) => m[0].startsWith(n))) found.push(m[0]);
}
for (const m of text.matchAll(/(?<![\w.-])(?:[a-z0-9-]+\.)+([a-z][a-z0-9-]*)(?![\w-])/gi)) {
if (!ALLOWED_TLDS.has(m[1].toLowerCase())) found.push(m[0]);
}
for (const w of FORBIDDEN) if (new RegExp(`\\b${w}\\b`, "i").test(text)) found.push(w);
return found;
}
let served: { status: number; path: string; text: string | null }[] = [];
+7 -62
View File
@@ -9,7 +9,7 @@
// and felix, made-up commits and fingerprints. demo.test.ts renders every shot from it and fails
// on any other name or address.
import { apply, host, mockRoutes, newMock, nowMs, respond, type Route } from "./mockApi";
import { apply, host, mockRoutes, newMock, respond, type Route } from "./mockApi";
/** One screenshot: the page, the selectors clicked in order, and the selector that means "drawn". */
export interface Shot {
@@ -34,7 +34,7 @@ export const SHOTS: Shot[] = [
type Json = Record<string, unknown>;
const DAY = 86_400;
const at = (s: number) => new Date(nowMs() + s * 1000).toISOString();
const at = (s: number) => new Date(Date.now() + s * 1000).toISOString();
interface Health {
state: string;
@@ -97,8 +97,8 @@ function intermediate(): Json {
return { state: "ok", subject: "Demo Intermediate CA", not_after: at(212 * DAY), days_left: 212, renewal: null, banner: null };
}
function overview(added: Json[] = []): Json {
const list = [...hosts(), ...added];
function overview(): Json {
const list = hosts();
const count = (s: string) => list.filter((h) => (h.health as Json).state === s).length;
return {
counts: { hosts: list.length, healthy: count("healthy"), degraded: count("degraded"), down: count("down"), unknown: count("unknown") },
@@ -213,47 +213,10 @@ function certs(): Json {
};
}
/** The demo's own answers, first; the smoke test's stand-in answers the rest. A host added in the
* demo (the e2e suite's Add host flow) is listed from then on, healthy, with the upstream it was
* given; a device certificate request carries the name it was asked with. */
/** The demo's own answers, first; the smoke test's stand-in answers the rest. */
export function demoRoutes(): Route[] {
const m = newMock();
const added: Json[] = [];
let device = "";
const request = (state: "waiting" | "approved"): Json => ({
request_id: "pr_dev",
kind: "device",
state,
match_code: "47 19 83",
created_at: at(-5),
expires_at: at(600),
approved_at: state === "approved" ? at(0) : null,
device_id: state === "approved" ? "dv_1" : null,
name: device,
csr_pem: null,
not_after: state === "approved" ? at(365 * DAY) : null,
message_code: state === "approved" ? "pki.issued" : "pki.waiting.manual",
message: state === "approved" ? `${device} has a certificate.` : "Approve it on the server with the match code.",
approve_command: state === "approved" ? null : "ianitor-control pki approve 47 19 83",
problem: null,
});
return [
["GET", /^\/overview$/, () => [200, overview(added)]],
["POST", /^\/hosts$/, (_, b) => {
const h = b.host as Json;
const name = String(h.hostname);
m.state.hostsAdded.push(name);
const ups = Array.isArray(h.upstreams) ? h.upstreams.map(String) : [];
added.push(demoHost(name, ups, { state: "healthy", latency: 11 }, { added_at: at(0) }));
return [202, { apply: apply("ch_new", "queued", `Added ${name}`, [name]) }];
}],
["POST", /^\/certs\/devices$/, (_, b) => {
device = String(b.name ?? "");
return [202, request("waiting")];
}],
["GET", /^\/pki-requests\/pr_dev$/, () => [200, request("approved")]],
// A share link whose token cannot be read as a name (the stand-in's `ish1.abc` would be).
["POST", /^\/hosts\/([^/]+)\/share-links$/, (mm) => [201, { id: "sl_demo", url: `https://${decodeURIComponent(mm[1])}/?share=ish1.4f9c2a7e1b0d`, expires_at: at(7 * DAY), path_prefix: "/", has_password: false, warning: null }]],
["GET", /^\/overview$/, () => [200, overview()]],
["GET", /^\/hosts\/([^/?]+)$/, (mm) => {
const s = spec(decodeURIComponent(mm[1]));
return s ? [200, { host: s, rev: "rev-demo-8" }] : [404, { error: { code: "host.not_found", message: "There is no such host.", field: null, params: {}, retry_after_s: null, detail: null }, errors: [], request_id: "demo" }];
@@ -262,7 +225,7 @@ export function demoRoutes(): Route[] {
["GET", /^\/history\/([^/]+)\/restore-preview$/, (mm) => [200, restorePreview(decodeURIComponent(mm[1]))]],
["GET", /^\/certs$/, () => [200, certs()]],
["GET", /^\/settings$/, () => [200, { repo: { name: "home-routes", last_push_at: at(-2 * 3600) }, watch_seconds: 60 }]],
...mockRoutes(m),
...mockRoutes(newMock()),
];
}
@@ -271,21 +234,3 @@ export function demoApi(): (method: string, path: string, body: Json) => { statu
const routes = demoRoutes();
return (method, path, body) => respond(routes, method.toUpperCase(), path, body);
}
// What the demo may show (demo.test.ts, and the e2e suite on every page it visits).
const ALLOWED_TLDS = new Set(["test", "example", "invalid"]);
const DOC_NETS = ["192.0.2.", "198.51.100.", "203.0.113."];
const FORBIDDEN = ["mark", "marek", "novak", "flowers", "esp32", "hyperv"];
/** What in a text could be real: addresses outside the documentation ranges, names outside .test. */
export function realLooking(text: string): string[] {
const found: string[] = [];
for (const m of text.matchAll(/(?<![\w.])\d{1,3}(?:\.\d{1,3}){3}(?![\w.])/g)) {
if (m[0] !== "127.0.0.1" && !DOC_NETS.some((n) => m[0].startsWith(n))) found.push(m[0]);
}
for (const m of text.matchAll(/(?<![\w.-])(?:[a-z0-9-]+\.)+([a-z][a-z0-9-]*)(?![\w-])/gi)) {
if (!ALLOWED_TLDS.has(m[1].toLowerCase())) found.push(m[0]);
}
for (const w of FORBIDDEN) if (new RegExp(`\\b${w}\\b`, "i").test(text)) found.push(w);
return found;
}
+31
View File
@@ -170,6 +170,37 @@ describe("ROADMAP §4 flows, clicks counted", () => {
});
});
describe("T4 flows, clicks counted", () => {
it("See active previews = 1 click", async () => {
start();
const nav = (await screen.findAllByRole("navigation", { name: "Main" }, T))[0];
await click(within(nav).getByRole("link", { name: "Previews" }));
await screen.findByRole("link", { name: "fix-42--shop.preview.home.test" }, T);
expect(clicks).toBe(1);
});
it("Kill a preview = 2 clicks (Close → Close preview)", async () => {
start("/previews");
await click(await screen.findByRole("button", { name: "Close" }, T));
await click(await screen.findByRole("button", { name: "Close preview" }));
await waitFor(() => expect(called("DELETE", "/previews/fix-42--shop.preview.home.test")).toBe(true), T);
await screen.findByRole("heading", { name: "No previews open" }, T);
expect(clicks).toBe(2);
});
it("Invite a teammate: Settings → Team → Invite = 3 clicks, the link shown", async () => {
start();
const nav = (await screen.findAllByRole("navigation", { name: "Main" }, T))[0];
await click(within(nav).getByRole("link", { name: "Settings" }));
await click(await screen.findByRole("tab", { name: "Team" }));
await user.type(await screen.findByLabelText("Name"), "Petra");
await click(screen.getByRole("button", { name: "Invite" }));
const link = (await screen.findByLabelText("Invite link", {}, T)) as HTMLInputElement;
expect(link.value).toMatch(/\/#signin=iin_testcode$/);
expect(clicks).toBe(3);
});
});
describe("focus", () => {
it("+ Host puts the cursor in Hostname, so typing right after the click lands there", async () => {
start();
+15 -6
View File
@@ -12,6 +12,7 @@ export interface Mock {
calls: { method: string; path: string; body: unknown }[];
state: {
engine: "pingora" | "caddy";
previewClosed: boolean;
switching: number;
intermediate: "ok" | "due";
renewal: boolean;
@@ -20,11 +21,8 @@ export interface Mock {
};
}
/** The stand-in's clock: the real one, or a fixed instant (the e2e suite's, so two takes of a screen match). */
export const clock: { fixed: number | null } = { fixed: null };
export const nowMs = () => clock.fixed ?? Date.now();
const now = () => new Date(nowMs()).toISOString();
const later = (s: number) => new Date(nowMs() + s * 1000).toISOString();
const now = () => new Date().toISOString();
const later = (s: number) => new Date(Date.now() + s * 1000).toISOString();
export function host(hostname: string, share: boolean) {
return {
@@ -68,7 +66,7 @@ export type Route = [string, RegExp, (mm: RegExpMatchArray, body: Json) => [numb
export function newMock(): Mock {
return {
calls: [],
state: { engine: "pingora", switching: 0, intermediate: "due", renewal: false, requestPolls: 0, hostsAdded: [] },
state: { engine: "pingora", switching: 0, intermediate: "due", renewal: false, requestPolls: 0, hostsAdded: [], previewClosed: false },
};
}
@@ -173,6 +171,17 @@ export function mockRoutes(m: Mock): Route[] {
["GET", /^\/tokens$/, () => [200, { items: [] }]],
["POST", /^\/tokens$/, (_, b) => [201, { id: "tk_1", name: b.name, token: "ian_tk1_secretvalue", expires_at: later(365 * 86400) }]],
["GET", /^\/share-links$/, () => [200, { items: [], epoch: 0 }]],
// T4: previews and the team (invented .test names only).
["GET", /^\/previews$/, () => [200, {
domain: "preview.home.test",
items: m.state.previewClosed ? [] : [{ hostname: "fix-42--shop.preview.home.test", url: "https://fix-42--shop.preview.home.test/", project: "team/shop", branch: "fix-42", upstream: "http://10.0.0.7:8080", expires_at: later(86400), state: "live" }],
}]],
["DELETE", /^\/previews\/fix-42--shop\.preview\.home\.test$/, () => {
m.state.previewClosed = true;
return [202, { apply: apply("ch_pv", "queued", "Closed the preview of fix-42 (team/shop)", ["fix-42--shop.preview.home.test"]) }];
}],
["GET", /^\/team$/, () => [200, { me: { id: "m1", name: "Mark", role: "admin", added_at: now(), tessera_root: null, match_code: null }, members: [{ id: "m1", name: "Mark", role: "admin", added_at: now(), tessera_root: null, match_code: null }], invites: [], authelia: false }]],
["POST", /^\/team\/invites$/, (_, b) => [201, { invite: { id: "iv1", name: b.name, role: b.role, expires_at: later(7 * 86400) }, link_fragment: "#signin=iin_testcode" }]],
];
}
+5
View File
@@ -23,6 +23,7 @@ test-hooks = []
[dependencies]
ianitor-core.workspace = true
url.workspace = true
rustls.workspace = true
rustls-pki-types.workspace = true
tokio-rustls.workspace = true
@@ -44,6 +45,10 @@ qrcode = { version = "0.14", default-features = false, features = ["svg"] }
# The offline root CLI asks for its passphrase without echo.
rpassword = "7"
# Windows Server, Caddy mode: the service control manager starts control and the guard.
[target.'cfg(windows)'.dependencies]
windows-service = "0.8"
[dev-dependencies]
ianitor-testkit.workspace = true
p12-keystore = "0.4"
+29 -4
View File
@@ -300,6 +300,8 @@ pub async fn overview(
viewer: Some(Viewer {
via: if actor.token_id.starts_with("user:") {
"authelia".into()
} else if actor.member.is_some() {
"session".into()
} else {
"token".into()
},
@@ -935,6 +937,9 @@ pub struct TokenCreate {
pub expires_in_days: Option<u64>,
#[serde(default)]
pub never_expires: bool,
/// `full` (default) or `previews`: a token for Fabrica that may only use `/api/v1/previews`.
#[serde(default)]
pub scope: Option<String>,
}
/// Make a token. Its value is in this response only.
@@ -966,7 +971,19 @@ pub async fn create_token(
let name = b
.name
.unwrap_or_else(|| format!("Token {}", ianitor_core::time::long_date(now())));
let (rec, value) = st.ctl.tokens.create(&name, expires).map_err(|e| {
let scope = match b.scope.as_deref() {
None => crate::tokens::Scope::Full,
Some(s) => crate::tokens::Scope::parse(s).ok_or_else(|| {
let mut e = ApiError::new(
StatusCode::UNPROCESSABLE_ENTITY,
"token.scope_value",
Params::new(),
);
e.body.field = Some("scope".into());
e
})?,
};
let (rec, value) = st.ctl.tokens.create(&name, expires, scope).map_err(|e| {
if e == "token.name" {
let mut err = ApiError::new(
StatusCode::UNPROCESSABLE_ENTITY,
@@ -1384,7 +1401,11 @@ impl Modify for Bearer {
mint_share_link, list_share_links, stop_share_link, stop_all_share_links, health, openapi,
super::pki::get_certs, super::pki::request_device, super::pki::get_request, super::pki::cancel_request,
super::pki::get_csr, super::pki::get_ext, super::pki::put_certificate, super::pki::renew, super::pki::revoke_device,
super::pki::make_bundle, super::pki::download_bundle, super::pki::get_engine, super::pki::switch_engine
super::pki::make_bundle, super::pki::download_bundle, super::pki::get_engine, super::pki::switch_engine,
super::previews::list_previews, super::previews::open_preview, super::previews::get_preview,
super::previews::kill_preview, super::previews::close_preview,
super::team::sign_out, super::team::get_team, super::team::invite, super::team::cancel_invite,
super::team::remove_member, super::team::set_root
),
components(schemas(
HostSpec, HealthCheckSpec, HeaderRuleSpec, HostWrite, HostPatch, UndoBody, RestoreBody, TokenCreate,
@@ -1394,13 +1415,17 @@ impl Modify for Bearer {
HealthReport, Done, super::pki::CertsView, super::pki::PkiRequestView, super::pki::IntermediateView,
super::pki::RootView, super::pki::DeviceView, super::pki::DeviceRequestBody, super::pki::CertificateBody,
super::pki::BundleBody, super::pki::BundleView, super::pki::EngineSwitchView, super::pki::EngineBody,
FallbackReady
FallbackReady, crate::hostspec::PreviewSpec, super::previews::PreviewOpen, super::previews::PreviewClose,
super::previews::PreviewView, super::previews::PreviewOpened, super::previews::PreviewOne,
super::previews::PreviewList, super::previews::PreviewClosed,
super::team::SignIn, super::team::SignedIn, super::team::MemberView, super::team::TeamView,
super::team::InviteBody, super::team::InviteMade, super::team::InviteView, super::team::RootBody
)),
modifiers(&Bearer),
tags(
(name = "overview"), (name = "hosts"), (name = "applies"), (name = "history"),
(name = "repo"), (name = "settings"), (name = "tokens"), (name = "share-links"),
(name = "certs"), (name = "engine")
(name = "certs"), (name = "engine"), (name = "previews"), (name = "team")
)
)]
pub struct ApiDoc;
+117 -4
View File
@@ -17,6 +17,8 @@
pub mod handlers;
pub mod pki;
pub mod previews;
pub mod team;
pub mod ui;
pub mod views;
@@ -45,11 +47,36 @@ use views::{ErrorBody, ErrorEnvelope};
pub const MAX_BODY: usize = 64 * 1024;
const RATE_PER_MINUTE: u32 = 120;
/// Who is calling: the API token's id and name.
/// Who is calling: the API token's id and name, and what the token may do.
#[derive(Debug, Clone)]
pub struct Actor {
pub token_id: String,
pub name: String,
pub scope: crate::tokens::Scope,
/// A team member signed in with a session (`crate::team`): their id, session and role.
/// `None` for API tokens and Authelia sign-ins, which may do everything.
pub member: Option<String>,
pub session: Option<String>,
pub role: Option<crate::team::Role>,
}
/// What only an admin may do (a `member` session gets 403 `team.admin_only`): API tokens,
/// the team, the engine and the CA.
fn admin_only(method: &str, path: &str) -> bool {
let write = !matches!(method, "GET" | "HEAD" | "OPTIONS");
path.starts_with("/api/v1/tokens")
|| (path.starts_with("/api/v1/team/") && !path.starts_with("/api/v1/team/me/"))
|| (write && path == "/api/v1/engine")
|| (write && path.starts_with("/api/v1/certs/intermediate"))
|| path.starts_with("/api/v1/pki-requests")
}
/// The only routes a `previews` token may call (T4: it can never touch another host).
fn in_preview_scope(path: &str) -> bool {
path == "/api/v1/previews"
|| path
.strip_prefix("/api/v1/previews/")
.is_some_and(|rest| !rest.is_empty() && !rest.contains('/'))
}
pub enum Stored {
@@ -330,11 +357,16 @@ pub(crate) fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool {
format!("127.0.0.1:{port}"),
format!("[::1]:{port}"),
];
// The admin host edge forwards the UI on, with or without edge's HTTPS port.
// The admin host the engine forwards the UI on, with any port: behind Docker's or a
// router's port mapping the visitor's port is not the engine's (T4). The name is what
// keeps a rebound DNS name out.
let ui = ctl.cfg.ui.as_ref().and_then(|u| u.hostname.as_deref());
let ui_ok = ui.is_some_and(|u| {
let edge_port = ctl.cfg.compile.https_listen.port();
host.eq_ignore_ascii_case(u) || host.eq_ignore_ascii_case(&format!("{u}:{edge_port}"))
let name = match host.rsplit_once(':') {
Some((n, p)) if !p.is_empty() && p.bytes().all(|c| c.is_ascii_digit()) => n,
_ => host,
};
name.eq_ignore_ascii_case(u)
});
ui_ok
|| ok.iter().any(|o| o.eq_ignore_ascii_case(host))
@@ -461,10 +493,65 @@ async fn guard(State(st): State<Arc<AppState>>, mut req: Request, next: Next) ->
req.extensions_mut().insert(Actor {
token_id: format!("user:{user}"),
name: display,
scope: crate::tokens::Scope::Full,
member: None,
session: None,
role: None,
});
return Ok(next.run(req).await);
}
}
// A team session (crate::team): the cookie, when no API token is given.
if !req.headers().contains_key(header::AUTHORIZATION)
&& let Some(value) = team::session_cookie(req.headers())
{
let ctl = st.ctl.clone();
let found = tokio::task::spawn_blocking(move || ctl.team.check(&value))
.await
.ok()
.flatten();
let Some((member, session)) = found else {
return Err(ApiError::new(
StatusCode::UNAUTHORIZED,
"session.unknown",
Params::new(),
));
};
let same_site = req
.headers()
.get("sec-fetch-site")
.is_none_or(|v| matches!(v.as_bytes(), b"same-origin" | b"none"));
if write && (!ui || !same_site) {
return Err(ApiError::new(
StatusCode::FORBIDDEN,
"request.csrf",
Params::new(),
));
}
if member.role != crate::team::Role::Admin
&& admin_only(method.as_str(), req.uri().path())
{
return Err(ApiError::new(
StatusCode::FORBIDDEN,
"team.admin_only",
Params::new(),
));
}
st.limit(&format!("member:{}", member.id), RATE_PER_MINUTE, 60)
.map_err(|s| {
ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new())
.retry(s)
})?;
req.extensions_mut().insert(Actor {
token_id: format!("member:{}", member.id),
name: member.name.clone(),
scope: crate::tokens::Scope::Full,
member: Some(member.id),
session: Some(session.id),
role: Some(member.role),
});
return Ok(next.run(req).await);
}
let auth = req
.headers()
.get(header::AUTHORIZATION)
@@ -490,6 +577,13 @@ async fn guard(State(st): State<Arc<AppState>>, mut req: Request, next: Next) ->
};
ApiError::new(StatusCode::UNAUTHORIZED, code, params)
})?;
if tok.scope == crate::tokens::Scope::Previews && !in_preview_scope(req.uri().path()) {
return Err(ApiError::new(
StatusCode::FORBIDDEN,
"token.scope",
Params::new(),
));
}
st.limit(&format!("token:{}", tok.id), RATE_PER_MINUTE, 60)
.map_err(|s| {
ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s)
@@ -497,6 +591,10 @@ async fn guard(State(st): State<Arc<AppState>>, mut req: Request, next: Next) ->
req.extensions_mut().insert(Actor {
token_id: tok.id,
name: tok.name,
scope: tok.scope,
member: None,
session: None,
role: None,
});
Ok(next.run(req).await)
}
@@ -620,6 +718,21 @@ pub fn router(st: Arc<AppState>) -> Router {
"/api/v1/engine",
get(pki::get_engine).post(pki::switch_engine),
)
.route(
"/api/v1/previews",
get(previews::list_previews).post(previews::open_preview),
)
.route("/api/v1/previews/close", post(previews::close_preview))
.route(
"/api/v1/previews/{hostname}",
get(previews::get_preview).delete(previews::kill_preview),
)
.route("/api/v1/team", get(team::get_team))
.route("/api/v1/team/invites", post(team::invite))
.route("/api/v1/team/invites/{id}", delete(team::cancel_invite))
.route("/api/v1/team/members/{id}", delete(team::remove_member))
.route("/api/v1/team/me/root", axum::routing::put(team::set_root))
.route("/api/v1/session/end", post(team::sign_out))
.route("/api/v1/health", get(h::health))
.route("/api/v1/openapi.json", get(h::openapi))
.method_not_allowed_fallback(method_not_allowed)
+265
View File
@@ -0,0 +1,265 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! `/api/v1/previews`: Fabrica's branch previews (T4). The only routes a `previews` token may
//! call (the guard in `api` refuses every other route for it).
// An error answer is built once per failed request; boxing it buys nothing.
#![allow(clippy::result_large_err)]
use std::sync::Arc;
use axum::Extension;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use super::views::{ApplyView, apply_view};
use super::{Actor, ApiError, AppState, Body};
use crate::messages::Params;
use crate::util::rfc3339;
type Shared = State<Arc<AppState>>;
fn json<T: Serialize>(status: StatusCode, v: &T) -> Response {
(status, axum::Json(v)).into_response()
}
#[derive(Debug, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct PreviewOpen {
/// Fabrica's project, e.g. `mnovak/Arca` or `github:acme/web`.
pub project: String,
/// The git branch, as the git host names it.
pub branch: String,
/// Where the branch's build runs, e.g. `http://10.0.0.5:8080` (must be in `[previews] upstreams`).
pub upstream: String,
/// Seconds until the preview closes by itself (default from `[previews]`).
pub ttl: Option<u64>,
}
#[derive(Debug, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct PreviewClose {
pub project: String,
pub branch: String,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct PreviewView {
pub hostname: String,
/// `https://<hostname>/`
pub url: String,
pub project: String,
pub branch: String,
pub upstream: String,
pub expires_at: String,
/// `applying`, `live` or `failed`.
pub state: String,
/// Why it failed, in plain English.
#[serde(skip_serializing_if = "Option::is_none")]
pub problem: Option<String>,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct PreviewOpened {
pub preview: PreviewView,
pub apply: ApplyView,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct PreviewOne {
pub preview: PreviewView,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct PreviewList {
pub items: Vec<PreviewView>,
/// The domain previews live under; absent when previews are off.
pub domain: Option<String>,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct PreviewClosed {
pub apply: ApplyView,
}
fn view(st: &AppState, p: &crate::previews::Listed) -> PreviewView {
let (state, problem) = st
.ctl
.preview_state(&p.hostname)
.unwrap_or(("live".into(), None));
PreviewView {
url: format!("https://{}/", p.hostname),
hostname: p.hostname.clone(),
project: p.project.clone(),
branch: p.branch.clone(),
upstream: p.upstream.clone(),
expires_at: rfc3339(p.expires_at),
state,
problem,
}
}
/// Every open preview.
#[utoipa::path(get, path = "/api/v1/previews", tag = "previews",
responses((status = 200, body = PreviewList)), security(("bearer" = [])))]
pub async fn list_previews(State(st): Shared) -> Result<Response, ApiError> {
let domain = st.ctl.cfg.previews.as_ref().map(|p| p.domain.clone());
let items = if domain.is_some() {
st.ctl.previews()?.iter().map(|p| view(&st, p)).collect()
} else {
Vec::new()
};
Ok(json(StatusCode::OK, &PreviewList { items, domain }))
}
/// Open a branch's preview, or move it to a new upstream and lifetime. The host is
/// `<branch>--<project>.<preview domain>`; it is live when its apply is kept.
#[utoipa::path(post, path = "/api/v1/previews", tag = "previews", request_body = PreviewOpen,
responses((status = 202, body = PreviewOpened), (status = 403, body = super::views::ErrorEnvelope),
(status = 409, body = super::views::ErrorEnvelope), (status = 422, body = super::views::ErrorEnvelope)),
security(("bearer" = [])))]
pub async fn open_preview(
State(st): Shared,
Extension(actor): Extension<Actor>,
body: Body<PreviewOpen>,
) -> Result<Response, ApiError> {
let b = body.value;
let (hostname, expires_at, rec) =
st.ctl
.open_preview(&b.project, &b.branch, &b.upstream, b.ttl, &actor.name)?;
let preview = PreviewView {
url: format!("https://{hostname}/"),
hostname,
project: b.project,
branch: b.branch,
upstream: b.upstream,
expires_at: rfc3339(expires_at),
state: "applying".into(),
problem: None,
};
Ok(json(
StatusCode::ACCEPTED,
&PreviewOpened {
preview,
apply: apply_view(&st.ctl, &rec),
},
))
}
/// One preview and where it stands (Fabrica polls this after opening one).
#[utoipa::path(get, path = "/api/v1/previews/{hostname}", tag = "previews",
params(("hostname" = String, Path)),
responses((status = 200, body = PreviewOne), (status = 404, body = super::views::ErrorEnvelope)),
security(("bearer" = [])))]
pub async fn get_preview(
State(st): Shared,
Path(hostname): Path<String>,
) -> Result<Response, ApiError> {
st.ctl.previews_cfg()?;
let not_found = || ApiError::new(StatusCode::NOT_FOUND, "preview.not_found", Params::new());
if let Some(p) = st
.ctl
.previews()?
.into_iter()
.find(|p| p.hostname == hostname)
{
return Ok(json(
StatusCode::OK,
&PreviewOne {
preview: view(&st, &p),
},
));
}
// Not at the head: a preview whose apply is still running or failed.
let (state, problem) = st.ctl.preview_state(&hostname).ok_or_else(not_found)?;
let rec = st
.ctl
.records()
.into_iter()
.rev()
.find(|r| r.hosts.contains(&hostname))
.ok_or_else(not_found)?;
let pv = rec
.attempted_host
.as_ref()
.and_then(|h| h.preview.clone())
.ok_or_else(not_found)?;
Ok(json(
StatusCode::OK,
&PreviewOne {
preview: PreviewView {
url: format!("https://{hostname}/"),
hostname,
project: pv.project,
branch: pv.branch,
upstream: rec
.attempted_host
.as_ref()
.and_then(|h| h.upstreams.first().cloned())
.unwrap_or_default(),
expires_at: rfc3339(u64::try_from(pv.expires_at).unwrap_or(0)),
state,
problem,
},
},
))
}
/// Close a preview now (the previews screen's Close, or Fabrica after a merge).
#[utoipa::path(delete, path = "/api/v1/previews/{hostname}", tag = "previews",
params(("hostname" = String, Path)),
responses((status = 202, body = PreviewClosed), (status = 404, body = super::views::ErrorEnvelope)),
security(("bearer" = [])))]
pub async fn kill_preview(
State(st): Shared,
Extension(actor): Extension<Actor>,
Path(hostname): Path<String>,
) -> Result<Response, ApiError> {
let rec = st.ctl.close_preview(&hostname, &actor.name, "Closed the")?;
Ok(json(
StatusCode::ACCEPTED,
&PreviewClosed {
apply: apply_view(&st.ctl, &rec),
},
))
}
/// Close a branch's preview by project and branch (Fabrica, when the branch is merged or
/// deleted).
#[utoipa::path(post, path = "/api/v1/previews/close", tag = "previews", request_body = PreviewClose,
responses((status = 202, body = PreviewClosed), (status = 404, body = super::views::ErrorEnvelope)),
security(("bearer" = [])))]
pub async fn close_preview(
State(st): Shared,
Extension(actor): Extension<Actor>,
body: Body<PreviewClose>,
) -> Result<Response, ApiError> {
let b = body.value;
let p = st.ctl.previews_cfg()?;
let hostname = ianitor_core::preview::hostname(&b.project, &b.branch, &p.domain)
.map_err(crate::previews::name_fail)?;
let mine = st
.ctl
.previews()?
.into_iter()
.any(|x| x.hostname == hostname && x.project == b.project && x.branch == b.branch);
if !mine {
return Err(ApiError::new(
StatusCode::NOT_FOUND,
"preview.not_found",
Params::new(),
));
}
let rec = st.ctl.close_preview(&hostname, &actor.name, "Closed the")?;
Ok(json(
StatusCode::ACCEPTED,
&PreviewClosed {
apply: apply_view(&st.ctl, &rec),
},
))
}
+351
View File
@@ -0,0 +1,351 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Team sign-in and the team list (`crate::team`). `POST /api/v1/session` is the one call
//! without a token or session: it redeems a setup or invite link. Everything else here goes
//! through the guard; inviting and removing people needs the admin role.
// An error answer is built once per failed request; boxing it buys nothing.
#![allow(clippy::result_large_err)]
use std::sync::Arc;
use axum::Extension;
use axum::extract::{Path, Request, State};
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use super::{Actor, ApiError, AppState, Body};
use crate::messages::Params;
use crate::team::{COOKIE, Member, Role, SESSION_SECS, match_code};
use crate::util::rfc3339;
type Shared = State<Arc<AppState>>;
fn json<T: Serialize>(status: StatusCode, v: &T) -> Response {
(status, axum::Json(v)).into_response()
}
fn refused(code: &'static str) -> ApiError {
let status = match code {
"internal" => StatusCode::INTERNAL_SERVER_ERROR,
"session.code" => StatusCode::UNAUTHORIZED,
"team.not_found" => StatusCode::NOT_FOUND,
"team.last_admin" | "team.full" => StatusCode::CONFLICT,
_ => StatusCode::UNPROCESSABLE_ENTITY,
};
ApiError::new(status, code, Params::new())
}
/// The session cookie's value from a request, if any.
pub fn session_cookie(headers: &HeaderMap) -> Option<String> {
headers
.get_all(header::COOKIE)
.iter()
.filter_map(|v| v.to_str().ok())
.flat_map(|v| v.split(';'))
.filter_map(|kv| kv.trim().split_once('='))
.find(|(k, _)| *k == COOKIE)
.map(|(_, v)| v.to_owned())
}
#[derive(Debug, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct SignIn {
/// The code from a setup or invite link (`#signin=<code>`).
pub code: String,
/// Your name (setup links only; an invite already names you).
pub name: Option<String>,
/// What to call this browser in the sessions list.
pub device: Option<String>,
}
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct MemberView {
pub id: String,
pub name: String,
/// `admin` or `member`.
pub role: String,
pub added_at: String,
/// The member's Tessera root and its match code, when they recorded it.
pub tessera_root: Option<String>,
pub match_code: Option<String>,
}
impl From<&Member> for MemberView {
fn from(m: &Member) -> Self {
MemberView {
id: m.id.clone(),
name: m.name.clone(),
role: m.role.as_str().into(),
added_at: rfc3339(m.added_at),
tessera_root: m.tessera_root.clone(),
match_code: m.tessera_root.as_deref().and_then(match_code),
}
}
}
#[derive(Debug, Serialize, ToSchema)]
pub struct SignedIn {
pub member: MemberView,
}
/// Redeem a setup or invite link: sets the session cookie. No token needed (this is the
/// door). At most 20 tries a minute for the whole server.
pub async fn sign_in(st: Arc<AppState>, req: Request) -> Response {
async {
if st.limit("signin", 20, 60).is_err() {
return Err(ApiError::new(
StatusCode::TOO_MANY_REQUESTS,
"rate.limited",
Params::new(),
)
.retry(60));
}
// Only the UI's own page signs in (the custom header needs a CORS preflight that
// control never answers), and never a cross-site page.
let h = req.headers();
let ui = h.get("x-ianitor-ui").is_some_and(|v| v.as_bytes() == b"1");
let site_ok = h
.get("sec-fetch-site")
.is_none_or(|v| matches!(v.as_bytes(), b"same-origin" | b"none"));
if !ui || !site_ok {
return Err(ApiError::new(
StatusCode::FORBIDDEN,
"request.csrf",
Params::new(),
));
}
let body = <Body<SignIn> as axum::extract::FromRequest<()>>::from_request(req, &()).await?;
let b = body.value;
let team = st.ctl.team.clone();
let device = b.device.unwrap_or_else(|| "Browser".into());
let (member, value) =
tokio::task::spawn_blocking(move || team.redeem(&b.code, b.name.as_deref(), &device))
.await
.map_err(|_| ApiError::internal("sign-in"))?
.map_err(|r| refused(r.0))?;
log::info!(target: "ianitor::team", "{} ({}) signed in", member.name, member.role.as_str());
let mut resp = json(
StatusCode::OK,
&SignedIn {
member: MemberView::from(&member),
},
);
let cookie = format!(
"{COOKIE}={value}; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age={SESSION_SECS}"
);
if let Ok(v) = HeaderValue::from_str(&cookie) {
resp.headers_mut().insert(header::SET_COOKIE, v);
}
resp.headers_mut()
.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
Ok(resp)
}
.await
.unwrap_or_else(IntoResponse::into_response)
}
/// Sign this browser out.
#[utoipa::path(post, path = "/api/v1/session/end", tag = "team",
responses((status = 200, body = super::views::Done)), security(("bearer" = [])))]
pub async fn sign_out(
State(st): Shared,
Extension(actor): Extension<Actor>,
) -> Result<Response, ApiError> {
if let Some(id) = &actor.session {
st.ctl.team.end_session(id).map_err(ApiError::internal)?;
}
let mut resp = json(
StatusCode::OK,
&super::views::Done {
message: "Done.".into(),
},
);
if let Ok(v) = HeaderValue::from_str(&format!(
"{COOKIE}=; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=0"
)) {
resp.headers_mut().insert(header::SET_COOKIE, v);
}
Ok(resp)
}
#[derive(Debug, Serialize, ToSchema)]
pub struct InviteView {
pub id: String,
pub name: Option<String>,
pub role: String,
pub expires_at: String,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct TeamView {
/// Who is asking; absent for an API token.
pub me: Option<MemberView>,
pub members: Vec<MemberView>,
pub invites: Vec<InviteView>,
/// Whether Authelia signs people in on this server instead.
pub authelia: bool,
}
/// The team: members, open invites, and who you are.
#[utoipa::path(get, path = "/api/v1/team", tag = "team",
responses((status = 200, body = TeamView)), security(("bearer" = [])))]
pub async fn get_team(
State(st): Shared,
Extension(actor): Extension<Actor>,
) -> Result<Response, ApiError> {
let members = st.ctl.team.members().map_err(ApiError::internal)?;
let invites = st
.ctl
.team
.codes()
.map_err(ApiError::internal)?
.into_iter()
.filter(|c| c.kind == "invite")
.map(|c| InviteView {
id: c.id,
name: c.name,
role: c.role.as_str().into(),
expires_at: rfc3339(c.expires_at),
})
.collect();
let me = actor
.member
.as_ref()
.and_then(|id| members.iter().find(|m| &m.id == id))
.map(MemberView::from);
Ok(json(
StatusCode::OK,
&TeamView {
me,
members: members.iter().map(MemberView::from).collect(),
invites,
authelia: st.ctl.ui_proof.is_some(),
},
))
}
#[derive(Debug, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct InviteBody {
pub name: String,
/// `admin` or `member` (default).
pub role: Option<String>,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct InviteMade {
pub invite: InviteView,
/// Send this to the person: `<the UI's address>/#signin=<code>`. Shown once.
pub link_fragment: String,
}
/// Invite someone (admin). The link is shown once.
#[utoipa::path(post, path = "/api/v1/team/invites", tag = "team", request_body = InviteBody,
responses((status = 201, body = InviteMade), (status = 403, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
pub async fn invite(
State(st): Shared,
Extension(actor): Extension<Actor>,
body: Body<InviteBody>,
) -> Result<Response, ApiError> {
let role = match body.value.role.as_deref() {
None => Role::Member,
Some(r) => Role::parse(r).ok_or_else(|| refused("team.role"))?,
};
let (code, value) = st
.ctl
.team
.invite(&body.value.name, role, &actor.name)
.map_err(|r| refused(r.0))?;
log::info!(target: "ianitor::team", "{} invited {} as {}", actor.name, code.name.clone().unwrap_or_default(), role.as_str());
Ok(json(
StatusCode::CREATED,
&InviteMade {
invite: InviteView {
id: code.id,
name: code.name,
role: role.as_str().into(),
expires_at: rfc3339(code.expires_at),
},
link_fragment: format!("#signin={value}"),
},
))
}
/// Cancel an invite that was not used (admin).
#[utoipa::path(delete, path = "/api/v1/team/invites/{id}", tag = "team", params(("id" = String, Path)),
responses((status = 200, body = super::views::Done)), security(("bearer" = [])))]
pub async fn cancel_invite(
State(st): Shared,
Path(id): Path<String>,
) -> Result<Response, ApiError> {
if !st.ctl.team.cancel_invite(&id).map_err(ApiError::internal)? {
return Err(refused("team.not_found"));
}
Ok(json(
StatusCode::OK,
&super::views::Done {
message: "Done.".into(),
},
))
}
/// Remove a member and sign them out everywhere (admin). The last admin stays.
#[utoipa::path(delete, path = "/api/v1/team/members/{id}", tag = "team", params(("id" = String, Path)),
responses((status = 200, body = super::views::Done), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
pub async fn remove_member(
State(st): Shared,
Extension(actor): Extension<Actor>,
Path(id): Path<String>,
) -> Result<Response, ApiError> {
match st.ctl.team.remove(&id).map_err(|r| refused(r.0))? {
Some(m) => {
log::info!(target: "ianitor::team", "{} removed {}", actor.name, m.name);
Ok(json(
StatusCode::OK,
&super::views::Done {
message: "Done.".into(),
},
))
}
None => Err(refused("team.not_found")),
}
}
#[derive(Debug, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct RootBody {
/// Your Tessera root (base64url, as Custos shows it under Domi identity), or null.
pub tessera_root: Option<String>,
}
/// Record your own Tessera root, so the team list shows its match code.
#[utoipa::path(put, path = "/api/v1/team/me/root", tag = "team", request_body = RootBody,
responses((status = 200, body = super::views::Done)), security(("bearer" = [])))]
pub async fn set_root(
State(st): Shared,
Extension(actor): Extension<Actor>,
body: Body<RootBody>,
) -> Result<Response, ApiError> {
let Some(me) = &actor.member else {
return Err(ApiError::new(
StatusCode::FORBIDDEN,
"team.session_only",
Params::new(),
));
};
st.ctl
.team
.set_root(me, body.value.tessera_root.as_deref())
.map_err(|r| refused(r.0))?;
Ok(json(
StatusCode::OK,
&super::views::Done {
message: "Done.".into(),
},
))
}
+16
View File
@@ -43,6 +43,22 @@ pub async fn front(State(st): State<Arc<AppState>>, req: Request, next: Next) ->
.into_response(),
};
}
// The door: redeeming a setup or invite link needs no token (crate::team).
if path == "/api/v1/session" {
if !host_allowed(&st.ctl, req.headers()) {
return ApiError::new(StatusCode::FORBIDDEN, "request.host", Params::new())
.into_response();
}
if req.method() != "POST" {
return ApiError::new(
StatusCode::METHOD_NOT_ALLOWED,
"request.method",
Params::new(),
)
.into_response();
}
return super::team::sign_in(st, req).await;
}
if path.starts_with("/api/") || path == "/api" {
return next.run(req).await;
}
+3
View File
@@ -746,6 +746,8 @@ pub struct TokenView {
pub last_used_at: Option<String>,
pub expires_at: Option<String>,
pub revoked_at: Option<String>,
/// `full` or `previews`.
pub scope: String,
}
impl From<&crate::tokens::TokenRecord> for TokenView {
@@ -757,6 +759,7 @@ impl From<&crate::tokens::TokenRecord> for TokenView {
last_used_at: t(r.last_used_at),
expires_at: t(r.expires_at),
revoked_at: t(r.revoked_at),
scope: r.scope.as_str().into(),
}
}
}
+4 -7
View File
@@ -127,15 +127,12 @@ async fn revert(cfg: &Config, why: &str) -> Result<bool, String> {
return Ok(false);
}
let loaded = async {
let sock = cfg
.caddy_compile()
.caddy_admin_socket
.clone()
.ok_or("no caddy_admin_socket is configured")?;
let sock = crate::caddy_link::Admin::from_compile(cfg.caddy_compile())
.ok_or("no caddy_admin_socket (or loopback caddy_admin) is configured")?;
let text = std::fs::read(&cfg.caddy.config)
.map_err(|e| format!("cannot read {}: {e}", cfg.caddy.config.display()))?;
crate::caddy_link::load(Path::new(&sock), &text).await?;
if !crate::caddy_link::runs(Path::new(&sock), &text).await? {
crate::caddy_link::load(&sock, &text).await?;
if !crate::caddy_link::runs(&sock, &text).await? {
return Err("Caddy took caddy.json but does not run it".to_owned());
}
Ok::<_, String>(())
+92 -36
View File
@@ -3,60 +3,116 @@
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Control's side of the Caddy fallback while it serves (Mark, 2026-11-08: changes keep
//! working under Caddy): loading a config through Caddy's admin API on its Unix socket
//! working under Caddy): loading a config through Caddy's admin API on its Unix socket, or on
//! loopback TCP where there are no Unix sockets (Windows Caddy mode, T4)
//! (`POST /load`, the whole JSON) and reading back what runs (`GET /config/`), probing a host
//! *through* Caddy ("does Caddy answer at all") and its upstreams directly (the health watch,
//! judged like edge's), and the certificate Caddy serves.
use std::net::SocketAddr;
use std::path::Path;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
const TIMEOUT: Duration = Duration::from_secs(10);
/// One request to Caddy's admin API (HTTP/1.0: the answer is never chunked).
async fn admin(socket: &Path, request: &[u8]) -> Result<(u16, Vec<u8>), String> {
#[cfg(unix)]
{
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let exchange = async {
let mut s = tokio::net::UnixStream::connect(socket).await?;
/// Where Caddy's admin API listens: a Unix socket (Linux, mode 0660), or loopback TCP
/// (Windows, where control and Caddy are the only services and the port is on 127.0.0.1).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Admin {
Unix(PathBuf),
Tcp(SocketAddr),
}
impl Admin {
/// From the compile facts: the socket when there is one, else a loopback TCP address.
pub fn from_compile(c: &crate::config::Compile) -> Option<Admin> {
match (&c.caddy_admin_socket, c.caddy_admin) {
(Some(s), _) => Some(Admin::Unix(PathBuf::from(s))),
(None, Some(a)) if a.ip().is_loopback() => Some(Admin::Tcp(a)),
_ => None,
}
}
/// The `Host` header Caddy's admin API accepts (its origin check).
fn host(&self) -> String {
match self {
Admin::Unix(_) => "localhost".into(),
Admin::Tcp(a) => a.to_string(),
}
}
}
impl From<&Path> for Admin {
fn from(p: &Path) -> Admin {
Admin::Unix(p.to_owned())
}
}
async fn exchange(admin: &Admin, request: &[u8]) -> std::io::Result<Vec<u8>> {
let mut buf = Vec::new();
match admin {
#[cfg(unix)]
Admin::Unix(p) => {
let mut s = tokio::net::UnixStream::connect(p).await?;
s.write_all(request).await?;
let mut buf = Vec::new();
s.read_to_end(&mut buf).await?;
Ok::<_, std::io::Error>(buf)
};
let buf = tokio::time::timeout(TIMEOUT, exchange)
.await
.map_err(|_| "Caddy's admin API did not answer within 10 s".to_owned())?
.map_err(|e| format!("Caddy's admin API cannot be reached: {e}"))?;
let split = buf
}
#[cfg(not(unix))]
Admin::Unix(_) => {
return Err(std::io::Error::other(
"Caddy's admin socket needs Unix; set caddy_admin = \"127.0.0.1:2019\" instead",
));
}
Admin::Tcp(a) => {
let mut s = tokio::net::TcpStream::connect(a).await?;
s.write_all(request).await?;
s.read_to_end(&mut buf).await?;
}
}
Ok(buf)
}
/// One request to Caddy's admin API (HTTP/1.0: the answer is never chunked). `request` has
/// `{host}` where the Host header value goes.
async fn admin(admin: &Admin, request: &[u8]) -> Result<(u16, Vec<u8>), String> {
let host = admin.host();
let request = {
let split = request
.windows(4)
.position(|w| w == b"\r\n\r\n")
.ok_or("no answer from Caddy's admin API")?;
let head = String::from_utf8_lossy(&buf[..split]);
let status: u16 = head
.split(' ')
.nth(1)
.and_then(|s| s.parse().ok())
.ok_or("no answer from Caddy's admin API")?;
Ok((status, buf[split + 4..].to_vec()))
}
#[cfg(not(unix))]
{
let _ = (socket, request);
Err("Caddy's admin socket needs Unix".into())
}
.unwrap_or(request.len());
let head = String::from_utf8_lossy(&request[..split]).replace("{host}", &host);
let mut r = head.into_bytes();
r.extend_from_slice(&request[split..]);
r
};
let buf = tokio::time::timeout(TIMEOUT, exchange(admin, &request))
.await
.map_err(|_| "Caddy's admin API did not answer within 10 s".to_owned())?
.map_err(|e| format!("Caddy's admin API cannot be reached: {e}"))?;
let split = buf
.windows(4)
.position(|w| w == b"\r\n\r\n")
.ok_or("no answer from Caddy's admin API")?;
let head = String::from_utf8_lossy(&buf[..split]);
let status: u16 = head
.split(' ')
.nth(1)
.and_then(|s| s.parse().ok())
.ok_or("no answer from Caddy's admin API")?;
Ok((status, buf[split + 4..].to_vec()))
}
/// Load a full Caddy JSON config. Caddy swaps it in gracefully or refuses it (and keeps the
/// old one). `Cache-Control: must-revalidate` makes Caddy load it even when it is the same as
/// the running one, so certificate and device files are read again (without it an identical
/// config is a no-op: QC round 2, B1; `qc_reloading_the_same_caddy_json_rereads_the_certificate_files`).
pub async fn load(socket: &Path, config: &[u8]) -> Result<(), String> {
pub async fn load(socket: &Admin, config: &[u8]) -> Result<(), String> {
let mut req = format!(
"POST /load HTTP/1.0\r\nHost: localhost\r\nContent-Type: application/json\r\nCache-Control: must-revalidate\r\nContent-Length: {}\r\n\r\n",
"POST /load HTTP/1.0\r\nHost: {{host}}\r\nContent-Type: application/json\r\nCache-Control: must-revalidate\r\nContent-Length: {}\r\n\r\n",
config.len()
)
.into_bytes();
@@ -77,8 +133,8 @@ pub async fn load(socket: &Path, config: &[u8]) -> Result<(), String> {
}
/// The config Caddy runs now.
pub async fn running_config(socket: &Path) -> Result<serde_json::Value, String> {
let (status, body) = admin(socket, b"GET /config/ HTTP/1.0\r\nHost: localhost\r\n\r\n").await?;
pub async fn running_config(socket: &Admin) -> Result<serde_json::Value, String> {
let (status, body) = admin(socket, b"GET /config/ HTTP/1.0\r\nHost: {host}\r\n\r\n").await?;
if status != 200 {
return Err(format!(
"Caddy's admin API answered {status} to GET /config/"
@@ -88,7 +144,7 @@ pub async fn running_config(socket: &Path) -> Result<serde_json::Value, String>
}
/// Whether Caddy runs exactly this config (as JSON values, so formatting does not matter).
pub async fn runs(socket: &Path, config: &[u8]) -> Result<bool, String> {
pub async fn runs(socket: &Admin, config: &[u8]) -> Result<bool, String> {
let want: serde_json::Value =
serde_json::from_slice(config).map_err(|e| format!("not JSON: {e}"))?;
Ok(running_config(socket).await? == want)
+69 -4
View File
@@ -58,6 +58,61 @@ pub struct Config {
/// Switching between Pingora and the Caddy fallback at runtime.
#[serde(default)]
pub engine: Option<EngineConfig>,
/// Branch previews for Fabrica (`POST /api/v1/previews`); off without it.
#[serde(default)]
pub previews: Option<PreviewsConfig>,
}
/// `[previews]`: where branch previews live and what they may point at.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PreviewsConfig {
/// Previews are `<branch>--<project>.<domain>`; a wildcard DNS record points here.
pub domain: String,
/// `domi` (the Domi CA, internal) or `letsencrypt` (public; one certificate per preview).
#[serde(default = "default_preview_tls")]
pub tls: String,
/// `none` (anyone with the address) or `forward-auth` (behind the site's sign-in).
#[serde(default = "default_preview_auth")]
pub auth: String,
/// Where previews may send traffic: `10.0.0.0/8`, `127.0.0.1:20000-29999`, `app.internal`,
/// `*.svc.internal:8080`. Nothing else is accepted; control's own port and Caddy's admin
/// port never are. Empty: every preview is refused.
#[serde(default)]
pub upstreams: Vec<String>,
#[serde(default = "default_preview_ttl")]
pub default_ttl_secs: u64,
#[serde(default = "default_preview_min_ttl")]
pub min_ttl_secs: u64,
#[serde(default = "default_preview_max_ttl")]
pub max_ttl_secs: u64,
#[serde(default = "default_preview_max")]
pub max_previews: usize,
/// How often expired previews are looked for.
#[serde(default = "default_preview_sweep")]
pub sweep_secs: u64,
}
fn default_preview_tls() -> String {
"domi".into()
}
fn default_preview_auth() -> String {
"none".into()
}
fn default_preview_ttl() -> u64 {
72 * 3600
}
fn default_preview_min_ttl() -> u64 {
300
}
fn default_preview_max_ttl() -> u64 {
30 * 86_400
}
fn default_preview_max() -> usize {
100
}
fn default_preview_sweep() -> u64 {
30
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -120,13 +175,14 @@ pub struct Compile {
impl Compile {
pub fn options(&self) -> CompileOptions {
use ianitor_core::compile::windows_path as w;
CompileOptions {
http_listen: self.http_listen,
https_listen: self.https_listen,
cert_dir: self.cert_dir.clone(),
state_dir: self.state_dir.clone(),
access_log: self.access_log.clone(),
caddy_credentials_dir: self.caddy_credentials_dir.clone(),
cert_dir: w(&self.cert_dir),
state_dir: w(&self.state_dir),
access_log: w(&self.access_log),
caddy_credentials_dir: w(&self.caddy_credentials_dir),
caddy_admin: self.caddy_admin,
caddy_admin_socket: self.caddy_admin_socket.clone(),
trusted_proxies: self.trusted_proxies.clone(),
@@ -240,6 +296,9 @@ impl Config {
"pki.kdf_iterations must be at least {MIN_KDF_ITERATIONS}"
)));
}
if let Some(p) = &self.previews {
crate::previews::check_config(p, self).map_err(ConfigError::Invalid)?;
}
if let Some(m) = empty_model() {
for c in std::iter::once(&self.compile).chain(self.compile_caddy.as_ref()) {
ianitor_core::compile::edge(&m, &c.options())
@@ -344,6 +403,12 @@ pub struct UiConfig {
/// Authelia's logout address (e.g. `https://auth.example/logout`), shown as "Sign out".
#[serde(default)]
pub logout_url: Option<String>,
/// Without Authelia (T4): control keeps the admin host in the routes repository itself,
/// as a plain host to this API with this certificate (`letsencrypt` or `domi`); people
/// sign in with team links (crate::team). Unset: the admin host is managed by hand
/// (the NixOS module's Authelia setup).
#[serde(default)]
pub admin_tls: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
+14 -1
View File
@@ -168,13 +168,26 @@ pub async fn run(args: &[String]) -> Result<(), String> {
proof_credential: None,
static_dir: Some(PathBuf::from(d)),
logout_url: None,
admin_tls: None,
}),
engine: None,
// Branch previews on a name nobody can own (RFC 2606), from loopback test upstreams.
previews: Some(ianitor_control::config::PreviewsConfig {
domain: "preview.dev.test".into(),
tls: "domi".into(),
auth: "none".into(),
upstreams: vec!["127.0.0.1:20000-29999".into(), "10.0.0.0/8".into()],
default_ttl_secs: 72 * 3600,
min_ttl_secs: 60,
max_ttl_secs: 30 * 86_400,
max_previews: 100,
sweep_secs: 10,
}),
};
cfg.check().map_err(|e| e.to_string())?;
Repo::open_seeded(&cfg.git, &cfg.routes.repo, &cfg.state_dir, "main", SITE)
.map_err(|e| e.to_string())?;
let (_, token) = Tokens::new(&cfg.state_dir).create("dev", None)?;
let (_, token) = Tokens::new(&cfg.state_dir).create("dev", None, Default::default())?;
// Control writes edge.json first; then edge can start from it.
let ctl_cfg = cfg.clone();
+33 -4
View File
@@ -39,8 +39,9 @@ use crate::util::{
write_json,
};
/// What a user asked for.
/// What a user asked for. Built once per request; boxing the host body buys nothing.
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum Change {
Put { spec: HostSpec, create: bool },
ShareLinks { hostname: String, on: bool },
@@ -53,6 +54,8 @@ struct Job {
id: String,
change: Change,
base_rev: Option<String>,
/// Replaces the plan's summary (and so the commit message), e.g. for previews.
summary: Option<String>,
}
/// A refusal, before or during an apply.
@@ -141,6 +144,8 @@ pub struct Control {
pub repo: Repo,
pub edge: EdgeLink,
pub tokens: Tokens,
/// Team members and their sessions (sign-in without Authelia).
pub team: Arc<crate::team::Team>,
pub shares: Shares,
pub share_key: Option<ShareKey>,
/// The Domi CA, when `[pki]` is configured.
@@ -245,6 +250,7 @@ impl Control {
let paused: Option<Reason> = read_json(&cfg.state_dir.join("paused.json"))?;
let c = Arc::new(Control {
tokens: Tokens::new(&cfg.state_dir),
team: Arc::new(crate::team::Team::new(&cfg.state_dir)),
shares: Shares::new(&cfg.state_dir, &cfg.edge.share_revocations),
repo,
edge,
@@ -740,6 +746,18 @@ impl Control {
change: Change,
base_rev: Option<String>,
actor: &str,
) -> Result<ApplyRecord, Fail> {
self.submit_as(change, base_rev, actor, None)
}
/// [`Control::submit`] with a summary of the caller's own (the history line and commit
/// message), e.g. "Opened the preview of fix-42 (shop)".
pub fn submit_as(
&self,
change: Change,
base_rev: Option<String>,
actor: &str,
summary: Option<String>,
) -> Result<ApplyRecord, Fail> {
if let Some(p) = self.paused_for(&change, false) {
return Err(Fail::new(
@@ -749,7 +767,10 @@ impl Control {
));
}
let (head, tree) = self.head_and_tree()?;
let plan = self.plan(&change, &head, &tree, base_rev.as_deref())?;
let mut plan = self.plan(&change, &head, &tree, base_rev.as_deref())?;
if let Some(s) = &summary {
plan.summary = s.clone();
}
self.compile(&plan.model)?;
let id = format!(
"ch_{}",
@@ -792,6 +813,7 @@ impl Control {
id,
change,
base_rev,
summary,
});
}
self.wake.notify_one();
@@ -930,7 +952,14 @@ impl Control {
Ok(x) => x,
Err(f) => return self.finish(&id, "failed", Some(f.reason), f.errors),
};
let plan = match self.plan(&job.change, &head, &tree, job.base_rev.as_deref()) {
let plan = match self
.plan(&job.change, &head, &tree, job.base_rev.as_deref())
.map(|mut p| {
if let Some(s) = &job.summary {
p.summary = s.clone();
}
p
}) {
Ok(p) => p,
Err(f) => return self.finish(&id, "failed", Some(f.reason), f.errors),
};
@@ -1000,7 +1029,7 @@ impl Control {
}
crash::point("committed");
if !self.edge.attached() {
if !self.edge.attached() && self.engine_running() != "caddy" {
// Development without an edge: write the files directly, nothing to watch.
let r = write_atomic(&self.cfg.edge.config, edge_text.as_bytes(), 0o644)
.and_then(|_| write_atomic(&self.cfg.caddy.config, caddy_text.as_bytes(), 0o644));
+6 -9
View File
@@ -42,13 +42,10 @@ struct Rule {
}
impl Control {
/// Caddy's admin socket, from `[compile_caddy]` (or `[compile]`).
pub fn caddy_socket(&self) -> Option<std::path::PathBuf> {
self.cfg
.caddy_compile()
.caddy_admin_socket
.as_ref()
.map(std::path::PathBuf::from)
/// Caddy's admin API, from `[compile_caddy]` (or `[compile]`): its Unix socket, or its
/// loopback TCP address on Windows.
pub fn caddy_socket(&self) -> Option<caddy_link::Admin> {
caddy_link::Admin::from_compile(self.cfg.caddy_compile())
}
/// Load caddy.json (the last good config) into the running Caddy, even when it is the
@@ -56,7 +53,7 @@ impl Control {
pub async fn caddy_reload(&self) -> Result<(), String> {
let sock = self
.caddy_socket()
.ok_or("no caddy_admin_socket is configured, so Caddy cannot be told")?;
.ok_or("no caddy_admin_socket (or loopback caddy_admin) is configured, so Caddy cannot be told")?;
let text = std::fs::read(&self.cfg.caddy.config)
.map_err(|e| format!("cannot read {}: {e}", self.cfg.caddy.config.display()))?;
caddy_link::load(&sock, &text).await?;
@@ -334,7 +331,7 @@ impl Control {
async fn caddy_watch(
&self,
id: &str,
sock: &std::path::Path,
sock: &caddy_link::Admin,
trial: &str,
judged: &[String],
rules: &BTreeMap<String, Rule>,
+13
View File
@@ -38,6 +38,18 @@ pub struct HostSpec {
pub request_headers: Vec<HeaderRuleSpec>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub response_headers: Vec<HeaderRuleSpec>,
/// Set on a branch preview (Fabrica); written by `/api/v1/previews`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub preview: Option<PreviewSpec>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct PreviewSpec {
pub project: String,
pub branch: String,
/// Unix seconds.
pub expires_at: i64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
@@ -178,6 +190,7 @@ mod tests {
secret: None,
}],
response_headers: vec![],
preview: None,
};
let text = h.to_toml().unwrap();
assert_eq!(HostSpec::from_toml(&text).unwrap(), h);
+7
View File
@@ -18,10 +18,12 @@ pub mod logger;
pub mod messages;
pub mod pki;
pub mod pki_ctl;
pub mod previews;
pub mod records;
pub mod repo;
pub mod shares;
pub mod switch;
pub mod team;
pub mod tokens;
pub mod util;
@@ -42,6 +44,11 @@ pub async fn serve(
tokio::spawn(ctl.clone().health_poller());
tokio::spawn(ctl.clone().pusher());
tokio::spawn(ctl.clone().pki_poller());
tokio::spawn(ctl.clone().preview_sweeper());
ctl.ensure_admin_host();
if ctl.cfg.ui.is_some() && !ctl.team.has_members() && ctl.ui_proof.is_none() {
log::warn!(target: "ianitor::team", "nobody is in the team yet: run `ianitor-control team setup-link --config <control.toml>` and open the link it prints");
}
let app = api::router(api::AppState::new(ctl.clone()));
if !listen.ip().is_loopback() {
return Err("ianitor-control only listens on loopback".into());
+40 -7
View File
@@ -12,6 +12,8 @@ use log::{Level, LevelFilter, Log, Metadata, Record};
struct Stderr {
own: LevelFilter,
/// `$IANITOR_LOG_FILE` or `--log-file`: append here instead of stderr (Windows services).
file: Option<std::sync::Mutex<std::fs::File>>,
}
impl Log for Stderr {
@@ -33,12 +35,27 @@ impl Log for Stderr {
Level::Debug => "DEBUG",
Level::Trace => "TRACE",
};
let _ = writeln!(
std::io::stderr().lock(),
"{lvl} {}: {}",
r.target(),
r.args()
);
match &self.file {
Some(f) => {
if let Ok(mut f) = f.lock() {
let _ = writeln!(
f,
"{} {lvl} {}: {}",
crate::util::rfc3339(crate::util::now()),
r.target(),
r.args()
);
}
}
None => {
let _ = writeln!(
std::io::stderr().lock(),
"{lvl} {}: {}",
r.target(),
r.args()
);
}
}
}
}
@@ -48,6 +65,22 @@ impl Log for Stderr {
}
pub fn init(level: Option<&str>) {
init_to(
level,
std::env::var_os("IANITOR_LOG_FILE").map(std::path::PathBuf::from),
);
}
/// Like [`init`], appending to `file` when given.
pub fn init_to(level: Option<&str>, file: Option<std::path::PathBuf>) {
let file = file.and_then(|p| {
std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(p)
.ok()
.map(std::sync::Mutex::new)
});
let own = match level.map(str::to_ascii_lowercase).as_deref() {
Some("error") => LevelFilter::Error,
Some("warn") => LevelFilter::Warn,
@@ -55,7 +88,7 @@ pub fn init(level: Option<&str>) {
Some("trace") => LevelFilter::Trace,
_ => LevelFilter::Info,
};
if log::set_boxed_logger(Box::new(Stderr { own })).is_ok() {
if log::set_boxed_logger(Box::new(Stderr { own, file })).is_ok() {
log::set_max_level(own);
}
}
+76 -5
View File
@@ -5,7 +5,7 @@
//! ```text
//! ianitor-control --config <control.toml> run the control plane
//! ianitor-control --dev [--edge-bin <ianitor-edge>] temporary everything on 127.0.0.1
//! ianitor-control token create --name <name> [--expires-days <n> | --never] (--config <c> | --state-dir <d>)
//! ianitor-control token create --name <name> [--scope full|previews] [--expires-days <n> | --never] (--config <c> | --state-dir <d>)
//! ianitor-control token list (--config <c> | --state-dir <d>)
//! ianitor-control token revoke <id> (--config <c> | --state-dir <d>)
//! ianitor-control openapi print the OpenAPI document
@@ -15,6 +15,8 @@
//! ianitor-control ca init --out <dir> [--passphrase-file <f>] the offline root (never on the server)
//! ianitor-control ca sign --root <dir> --csr <f> --out <f> [--yes] sign an intermediate offline
//! ianitor-control check --config <control.toml> check the config and exit
//! ianitor-control team setup-link|list --config <c> the first admin's sign-in link
//! ianitor-control service control|caddy-guard --config <c> [--log-file <f>] Windows service
//! ```
//! The log level comes from `$IANITOR_LOG`. As `GIT_ASKPASS` (with `$IANITOR_ASKPASS=1`),
//! the binary answers git's prompt from the push credential file.
@@ -25,6 +27,8 @@ use std::process::ExitCode;
use ianitor_control::{Config, logger, tokens::Tokens};
mod dev;
#[cfg(windows)]
mod winsvc;
fn usage() -> ExitCode {
eprintln!(
@@ -139,12 +143,19 @@ fn token(args: &[String]) -> Result<(), String> {
match args.first().map(String::as_str) {
Some("create") => {
let mut name = None;
let mut scope = ianitor_control::tokens::Scope::Full;
let mut expires = Some(ianitor_control::util::now() + 365 * 86_400);
let mut it = args.iter().skip(1);
while let Some(a) = it.next() {
match a.as_str() {
"--name" => name = it.next().cloned(),
"--never" => expires = None,
"--scope" => {
scope = it
.next()
.and_then(|s| ianitor_control::tokens::Scope::parse(s))
.ok_or("--scope must be full or previews")?;
}
"--expires-days" => {
let d: u64 = it
.next()
@@ -157,7 +168,7 @@ fn token(args: &[String]) -> Result<(), String> {
}
}
let name = name.ok_or("--name <name> is required")?;
let (rec, value) = tokens.create(&name, expires).map_err(|e| {
let (rec, value) = tokens.create(&name, expires, scope).map_err(|e| {
if e == "token.name" {
"the name must be 1 to 64 letters, digits, spaces, dots, dashes or underscores"
.to_owned()
@@ -166,8 +177,10 @@ fn token(args: &[String]) -> Result<(), String> {
}
})?;
eprintln!(
"Token {} ({}) created. It is shown once; save it in Custos now:",
rec.id, rec.name
"Token {} ({}, scope {}) created. It is shown once; save it in Custos now:",
rec.id,
rec.name,
rec.scope.as_str()
);
println!("{value}");
Ok(())
@@ -186,6 +199,9 @@ fn token(args: &[String]) -> Result<(), String> {
.map(|e| format!(" REVOKED {}", ianitor_control::util::rfc3339(e)))
.unwrap_or_default()
);
if t.scope != ianitor_control::tokens::Scope::Full {
println!(" scope {}", t.scope.as_str());
}
}
Ok(())
}
@@ -371,12 +387,66 @@ fn pki_cli(args: &[String]) -> Result<(), String> {
}
}
/// `team setup-link | list` on the server, as the user control runs as.
fn team_cli(args: &[String]) -> Result<(), String> {
let path = arg_after(args, "--config").ok_or("team setup-link|list --config <control.toml>")?;
let cfg = Config::load(&PathBuf::from(path)).map_err(|e| e.to_string())?;
same_owner(&cfg.state_dir)?;
let team = ianitor_control::team::Team::new(&cfg.state_dir);
match args.first().map(String::as_str) {
Some("setup-link") => {
let (code, until) = team.setup_code()?;
let base = match cfg.ui.as_ref().and_then(|u| u.hostname.as_ref()) {
Some(h) => format!("https://{h}/"),
None => format!("http://{}/", cfg.listen),
};
eprintln!(
"Open this link to sign in as the team's first admin. It works once, until {}:",
ianitor_control::util::rfc3339(until)
);
println!("{base}#signin={code}");
Ok(())
}
Some("list") => {
for m in team.members()? {
println!("{} {} {}", m.id, m.role.as_str(), m.name);
}
Ok(())
}
_ => Err("team setup-link|list --config <control.toml>".into()),
}
}
fn main() -> ExitCode {
if std::env::var("IANITOR_ASKPASS").as_deref() == Ok("1") {
return askpass();
}
logger::init(std::env::var("IANITOR_LOG").ok().as_deref());
let args: Vec<String> = std::env::args().skip(1).collect();
let log_file = args
.iter()
.position(|a| a == "--log-file")
.and_then(|i| args.get(i + 1))
.map(PathBuf::from);
match log_file {
Some(f) => logger::init_to(std::env::var("IANITOR_LOG").ok().as_deref(), Some(f)),
None => logger::init(std::env::var("IANITOR_LOG").ok().as_deref()),
}
// Windows Server, Caddy mode: started by the service control manager.
if args.first().map(String::as_str) == Some("service") {
#[cfg(windows)]
return match winsvc::run(&args[1..]) {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("ianitor-control: {e}");
ExitCode::FAILURE
}
};
#[cfg(not(windows))]
{
eprintln!("ianitor-control: `service` is for Windows; use the systemd units on Linux");
return ExitCode::FAILURE;
}
}
let rt = match tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
@@ -390,6 +460,7 @@ fn main() -> ExitCode {
let result = match args.first().map(String::as_str) {
Some("token") => token(&args[1..]),
Some("pki") => pki_cli(&args[1..]),
Some("team") => team_cli(&args[1..]),
Some("ca") => ca(&args[1..]),
Some("openapi") => {
println!("{}", ianitor_control::api::openapi_json());
+37
View File
@@ -205,6 +205,43 @@ fn template(code: &str) -> &'static str {
"token.not_found" => "There is no API token with that id.",
"token.name" => "Use 1 to 64 letters, digits, spaces, dots, dashes or underscores.",
"token.expiry" => "Choose between 1 and 3650 days, or never.",
"token.scope" => {
"This API token may only open and close branch previews (/api/v1/previews)."
}
"token.scope_value" => "A token's scope is full or previews.",
"session.code" => {
"This sign-in link does not work: it was used, it expired, or it was mistyped. Ask an admin for a new one."
}
"session.unknown" => {
"You are signed out. Open your sign-in link again, or ask an admin for one."
}
"team.admin_only" => "Only an admin of this team can do that.",
"team.last_admin" => "The team needs at least one admin. Make someone else an admin first.",
"team.full" => "The team is full (64 people, 100 open invites).",
"team.name" => "Enter a name of 1 to 64 characters.",
"team.role" => "A role is admin or member.",
"team.root" => "That is not a Tessera root. Copy it from Custos, Domi identity.",
"team.not_found" => "There is no such member or invite.",
"team.session_only" => "Only a signed-in person can do that, not an API token.",
"preview.off" => {
"Previews are off on this server: set a preview domain under [previews] in control.toml."
}
"preview.taken" => {
"{hostname} is already used by another host or branch, so this branch's preview cannot have it."
}
"preview.not_found" => "There is no preview at that address.",
"preview.branch" => "The branch name {problem}.",
"preview.project" => "The project name {problem}.",
"preview.domain" => "The preview address is not usable: {problem}.",
"preview.ttl" => "Choose a lifetime between {min} and {max} seconds.",
"preview.upstream" => {
"Write the preview's address as http://host:port or https://host:port, without a path, user or password."
}
"preview.upstream_not_allowed" => {
"{upstream} is not an address previews may use. Allowed: {allowed}."
}
"preview.too_many" => "There are already {max} previews. Close some first.",
"preview.expired" => "Preview of {branch} expired",
"rate.limited" => "Too many requests in a short time. Try again in {seconds} s.",
"control.files_unwritten" => {
"The change is live, but Ianitor could not save the proxy settings to disk. Changes are paused until Ianitor restarts and saves them."
+598
View File
@@ -0,0 +1,598 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Branch previews for Fabrica (Fabrica docs/32_coherence.md, T4). A preview is an ordinary
//! host file in the routes repository with a `[preview]` table, so it goes through the same
//! validation, compilers, differential tests and commit-confirmed apply as any host. This
//! module holds what is preview-only: the host body control writes, the upstream allow list
//! (a preview token is hostile: it must not be able to publish this machine's admin ports),
//! and the sweeper that closes expired previews.
// A refusal is built once per failed request; boxing it buys nothing (as in `engine`).
#![allow(clippy::result_large_err)]
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::sync::Arc;
use std::time::Duration;
use crate::config::{Config, PreviewsConfig};
use crate::engine::{Change, Control, Fail};
use crate::hostspec::{HeaderRuleSpec, HostSpec, PreviewSpec};
use crate::messages::{self, Params};
use crate::util::now;
/// The actor name the sweeper's removals carry in the history.
pub const EXPIRY_ACTOR: &str = "Preview expiry";
/// One entry of `[previews] upstreams`.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Target {
Net(IpAddr, u8),
Name(String),
/// `*.suffix`: any name ending in `.suffix`.
Suffix(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Allowed {
target: Target,
ports: Option<(u16, u16)>,
}
fn parse_ports(p: &str) -> Option<(u16, u16)> {
let (lo, hi) = match p.split_once('-') {
Some((a, b)) => (a.parse().ok()?, b.parse().ok()?),
None => {
let x: u16 = p.parse().ok()?;
(x, x)
}
};
(lo >= 1 && lo <= hi).then_some((lo, hi))
}
fn parse_entry(e: &str) -> Option<Allowed> {
let e = e.trim();
// IPv6 networks carry no port (`fd00::/8`); everything else may end in `:port[-port]`.
if e.matches(':').count() > 1 {
let (ip, bits) = e.split_once('/').unwrap_or((e, "128"));
let ip: Ipv6Addr = ip.parse().ok()?;
let bits: u8 = bits.parse().ok().filter(|b| *b <= 128)?;
return Some(Allowed {
target: Target::Net(IpAddr::V6(ip), bits),
ports: None,
});
}
let (host, ports) = match e.rsplit_once(':') {
Some((h, p)) => (h, Some(parse_ports(p)?)),
None => (e, None),
};
if let Some((ip, bits)) = host.split_once('/') {
let ip: Ipv4Addr = ip.parse().ok()?;
let bits: u8 = bits.parse().ok().filter(|b| *b <= 32)?;
return Some(Allowed {
target: Target::Net(IpAddr::V4(ip), bits),
ports,
});
}
if let Ok(ip) = host.parse::<Ipv4Addr>() {
return Some(Allowed {
target: Target::Net(IpAddr::V4(ip), 32),
ports,
});
}
let name = host.to_ascii_lowercase();
let plain = |n: &str| {
!n.is_empty()
&& n.len() <= 253
&& n.split('.').all(|l| {
!l.is_empty()
&& l.len() <= 63
&& l.bytes()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
})
};
if let Some(suffix) = name.strip_prefix("*.") {
return plain(suffix).then(|| Allowed {
target: Target::Suffix(suffix.to_owned()),
ports,
});
}
if !plain(&name) {
return None;
}
Some(Allowed {
target: Target::Name(name),
ports,
})
}
fn in_net(ip: IpAddr, net: IpAddr, bits: u8) -> bool {
match (ip, net) {
(IpAddr::V4(a), IpAddr::V4(n)) => {
let mask = if bits == 0 {
0
} else {
u32::MAX << (32 - u32::from(bits))
};
u32::from(a) & mask == u32::from(n) & mask
}
(IpAddr::V6(a), IpAddr::V6(n)) => {
let mask = if bits == 0 {
0
} else {
u128::MAX << (128 - u32::from(bits))
};
u128::from(a) & mask == u128::from(n) & mask
}
_ => false,
}
}
/// Addresses no preview may ever use, whatever the allow list says.
fn never(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(v) => {
v.is_unspecified() || v.is_link_local() || v.is_multicast() || v.is_broadcast()
}
IpAddr::V6(v) => {
v.is_unspecified()
|| v.is_multicast()
|| (v.segments()[0] & 0xffc0) == 0xfe80
|| v.to_ipv4_mapped().is_some()
}
}
}
/// Check the `[previews]` section at start.
pub fn check_config(p: &PreviewsConfig, cfg: &Config) -> Result<(), String> {
ianitor_core::preview::hostname("p", "main", &p.domain)
.map_err(|e| format!("previews.domain: {e}"))?;
if !["domi", "letsencrypt"].contains(&p.tls.as_str()) {
return Err("previews.tls must be domi or letsencrypt".into());
}
if !["none", "forward-auth"].contains(&p.auth.as_str()) {
return Err("previews.auth must be none or forward-auth".into());
}
for u in &p.upstreams {
if parse_entry(u).is_none() {
return Err(format!(
"previews.upstreams: {u:?} is not a network (10.0.0.0/8), an address with ports (127.0.0.1:20000-29999) or a name (app.internal, *.svc.internal)"
));
}
}
if p.min_ttl_secs == 0
|| p.min_ttl_secs > p.max_ttl_secs
|| !(p.min_ttl_secs..=p.max_ttl_secs).contains(&p.default_ttl_secs)
{
return Err(
"previews: min_ttl_secs ≤ default_ttl_secs ≤ max_ttl_secs, and min_ttl_secs > 0".into(),
);
}
if !(1..=3600).contains(&p.sweep_secs) || !(1..=10_000).contains(&p.max_previews) {
return Err("previews: sweep_secs 1 to 3600, max_previews 1 to 10000".into());
}
let _ = cfg;
Ok(())
}
fn fail(status: u16, code: &str, params: Params) -> Fail {
Fail::new(status, code, params)
}
/// Whether a preview may send traffic to `upstream`; the parsed URL's host and port.
pub fn check_upstream(cfg: &Config, p: &PreviewsConfig, upstream: &str) -> Result<(), Fail> {
let bad = || fail(422, "preview.upstream", Params::new());
if upstream.is_empty()
|| upstream.len() > 512
|| !upstream.bytes().all(|c| c.is_ascii_graphic())
{
return Err(bad());
}
let u = url::Url::parse(upstream).map_err(|_| bad())?;
if !["http", "https"].contains(&u.scheme())
|| !u.username().is_empty()
|| u.password().is_some()
|| u.query().is_some()
|| u.fragment().is_some()
|| !(u.path().is_empty() || u.path() == "/")
{
return Err(bad());
}
let port = u.port_or_known_default().ok_or_else(bad)?;
let host = u.host().ok_or_else(bad)?;
let shown = || {
messages::params([
("upstream", upstream.to_owned()),
("allowed", {
if p.upstreams.is_empty() {
"nothing yet (set [previews] upstreams)".to_owned()
} else {
p.upstreams.join(", ")
}
}),
])
};
let not_allowed = || fail(403, "preview.upstream_not_allowed", shown());
let ip = match &host {
url::Host::Ipv4(v) => Some(IpAddr::V4(*v)),
url::Host::Ipv6(v) => Some(IpAddr::V6(*v)),
url::Host::Domain(_) => None,
};
if let Some(ip) = ip {
if never(ip) {
return Err(not_allowed());
}
// This machine's own control API and Caddy admin API, whatever the list says.
if ip.is_loopback() {
let admin_ports = std::iter::once(cfg.listen.port()).chain(
[cfg.compile.caddy_admin, cfg.caddy_compile().caddy_admin]
.into_iter()
.flatten()
.map(|a| a.port()),
);
if admin_ports.into_iter().any(|a| a == port) || port == 2019 {
return Err(not_allowed());
}
}
}
let name = match &host {
url::Host::Domain(d) => Some(d.to_ascii_lowercase()),
_ => None,
};
let ok = p.upstreams.iter().filter_map(|e| parse_entry(e)).any(|a| {
let port_ok = a.ports.is_none_or(|(lo, hi)| (lo..=hi).contains(&port));
let host_ok = match (&a.target, ip, &name) {
(Target::Net(net, bits), Some(ip), _) => in_net(ip, *net, *bits),
(Target::Name(n), _, Some(h)) => n == h,
(Target::Suffix(s), _, Some(h)) => h.ends_with(&format!(".{s}")),
_ => false,
};
port_ok && host_ok
});
if ok { Ok(()) } else { Err(not_allowed()) }
}
/// The host body of a branch's preview.
pub fn spec(
p: &PreviewsConfig,
hostname: &str,
project: &str,
branch: &str,
upstream: &str,
expires_at: u64,
) -> HostSpec {
HostSpec {
hostname: hostname.to_owned(),
upstreams: vec![upstream.trim_end_matches('/').to_owned()],
tls: p.tls.clone(),
auth: p.auth.clone(),
websockets: true,
share_links: false,
device_certs: false,
access_log: "off".into(),
health_check: None,
request_headers: Vec::new(),
// A preview is not for search engines.
response_headers: vec![HeaderRuleSpec {
action: "set".into(),
name: "X-Robots-Tag".into(),
value: Some("noindex, nofollow".into()),
secret: None,
}],
preview: Some(PreviewSpec {
project: project.to_owned(),
branch: branch.to_owned(),
expires_at: i64::try_from(expires_at).unwrap_or(i64::MAX),
}),
}
}
/// A preview's field problem as an API refusal.
pub fn name_fail(e: ianitor_core::preview::PreviewError) -> Fail {
use ianitor_core::preview::PreviewError as P;
let (code, problem) = match &e {
P::Branch(r) => ("preview.branch", (*r).to_owned()),
P::Project(r) => ("preview.project", (*r).to_owned()),
P::Domain(r) => ("preview.domain", r.clone()),
};
let mut f = fail(422, code, messages::params([("problem", problem)]));
f.reason.field = Some(
match e {
P::Branch(_) => "branch",
P::Project(_) => "project",
P::Domain(_) => "domain",
}
.into(),
);
f
}
/// What the previews screen and Fabrica see.
#[derive(Debug, Clone)]
pub struct Listed {
pub hostname: String,
pub project: String,
pub branch: String,
pub upstream: String,
pub expires_at: u64,
}
impl Control {
/// With `[ui] hostname` and `admin_tls`: make sure the admin host (the web UI and this
/// API, through the engine) is in the routes repository; queue it at start if not.
pub fn ensure_admin_host(&self) {
let Some(ui) = &self.cfg.ui else { return };
let (Some(host), Some(tls)) = (&ui.hostname, &ui.admin_tls) else {
return;
};
let Ok((_, tree, _)) = self.head_model() else {
return;
};
if tree.host(host).is_some() {
return;
}
let spec = HostSpec {
hostname: host.clone(),
upstreams: vec![format!("http://{}", self.cfg.listen)],
tls: tls.clone(),
auth: "none".into(),
websockets: false,
share_links: false,
device_certs: false,
access_log: "off".into(),
// No health path: every API path needs a sign-in, so a probe would see 401 and
// the apply would be reverted. Any answer from control counts as up.
health_check: None,
request_headers: Vec::new(),
response_headers: vec![
HeaderRuleSpec {
action: "set".into(),
name: "X-Robots-Tag".into(),
value: Some("noindex, nofollow".into()),
secret: None,
},
HeaderRuleSpec {
action: "set".into(),
name: "Strict-Transport-Security".into(),
value: Some("max-age=31536000".into()),
secret: None,
},
],
preview: None,
};
match self.submit_as(
Change::Put { spec, create: true },
None,
"Setup",
Some(format!("Added the admin host {host} (the web UI)")),
) {
Ok(_) => log::info!(target: "ianitor::control", "adding the admin host {host}"),
Err(f) => {
log::error!(target: "ianitor::control", "cannot add the admin host {host}: {}", f.reason.message)
}
}
}
pub fn previews_cfg(&self) -> Result<&PreviewsConfig, Fail> {
self.cfg
.previews
.as_ref()
.ok_or_else(|| fail(409, "preview.off", Params::new()))
}
/// Every preview at the branch head, by host name.
pub fn previews(&self) -> Result<Vec<Listed>, Fail> {
let (_, _, model) = self.head_model()?;
Ok(model
.hosts()
.iter()
.filter_map(|h| {
let p = h.preview.as_ref()?;
Some(Listed {
hostname: h.hostname.to_string(),
project: p.project.clone(),
branch: p.branch.clone(),
upstream: h
.upstreams
.first()
.map(ToString::to_string)
.unwrap_or_default(),
expires_at: p.expires_at,
})
})
.collect())
}
/// Open (or move) a branch's preview.
pub fn open_preview(
&self,
project: &str,
branch: &str,
upstream: &str,
ttl: Option<u64>,
actor: &str,
) -> Result<(String, u64, crate::records::ApplyRecord), Fail> {
let p = self.previews_cfg()?;
let hostname =
ianitor_core::preview::hostname(project, branch, &p.domain).map_err(name_fail)?;
let ttl = ttl.unwrap_or(p.default_ttl_secs);
if !(p.min_ttl_secs..=p.max_ttl_secs).contains(&ttl) {
let mut f = fail(
422,
"preview.ttl",
messages::params([
("min", p.min_ttl_secs.to_string()),
("max", p.max_ttl_secs.to_string()),
]),
);
f.reason.field = Some("ttl".into());
return Err(f);
}
check_upstream(&self.cfg, p, upstream)?;
let previews = self.previews()?;
let (_, tree, model) = self.head_model()?;
let existing = model
.hosts()
.iter()
.find(|h| h.hostname.as_str() == hostname);
let create = match existing {
None => {
if previews.len() >= p.max_previews {
return Err(fail(
409,
"preview.too_many",
messages::params([("max", p.max_previews.to_string())]),
));
}
true
}
Some(h) => match &h.preview {
Some(pv) if pv.project == project && pv.branch == branch => false,
_ => {
return Err(fail(
409,
"preview.taken",
messages::params([("hostname", hostname.clone())]),
));
}
},
};
drop(tree);
let expires_at = now().saturating_add(ttl);
let spec = spec(p, &hostname, project, branch, upstream, expires_at);
let summary = format!(
"{} the preview of {branch} ({project})",
if create { "Opened" } else { "Moved" }
);
let rec = self.submit_as(Change::Put { spec, create }, None, actor, Some(summary))?;
Ok((hostname, expires_at, rec))
}
/// Close a preview by its host name. Only preview hosts.
pub fn close_preview(
&self,
hostname: &str,
actor: &str,
why: &str,
) -> Result<crate::records::ApplyRecord, Fail> {
self.previews_cfg()?;
let pv = self
.previews()?
.into_iter()
.find(|p| p.hostname == hostname)
.ok_or_else(|| fail(404, "preview.not_found", Params::new()))?;
let summary = format!("{why} preview of {} ({})", pv.branch, pv.project);
self.submit_as(
Change::Delete {
hostname: hostname.to_owned(),
},
None,
actor,
Some(summary),
)
}
/// Where a preview stands: `applying`, `live`, `failed` (with why), or not a preview.
pub fn preview_state(&self, hostname: &str) -> Option<(String, Option<String>)> {
let live = self.previews().ok()?.iter().any(|p| p.hostname == hostname);
let last = self
.records()
.into_iter()
.rev()
.find(|r| r.hosts.iter().any(|h| h == hostname));
let pending = last
.as_ref()
.is_some_and(|r| !["kept", "reverted", "failed"].contains(&r.state.as_str()));
if pending {
return Some(("applying".into(), None));
}
if live {
return Some(("live".into(), None));
}
let r = last?;
// A preview that never went live because its apply failed.
(r.summary.contains("the preview of") && r.state != "kept").then(|| {
(
"failed".into(),
r.reason.as_ref().map(|x| x.message.clone()),
)
})
}
/// Close expired previews, every `sweep_secs`.
pub async fn preview_sweeper(self: Arc<Self>) {
let Some(p) = self.cfg.previews.clone() else {
return;
};
loop {
tokio::time::sleep(Duration::from_secs(p.sweep_secs)).await;
let Ok(list) = self.previews() else {
continue;
};
let t = now();
let busy: Vec<String> = self
.records()
.into_iter()
.filter(|r| !["kept", "reverted", "failed"].contains(&r.state.as_str()))
.flat_map(|r| r.hosts)
.collect();
for pv in list.iter().filter(|p| p.expires_at <= t) {
if busy.contains(&pv.hostname) {
continue;
}
match self.close_preview(&pv.hostname, EXPIRY_ACTOR, "Closed the expired") {
Ok(_) => {
log::info!(target: "ianitor::previews", "the preview {} expired; closing it", pv.hostname)
}
Err(f) => {
log::warn!(target: "ianitor::previews", "cannot close the expired preview {}: {}", pv.hostname, f.reason.message)
}
}
}
}
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn allow_list_entries_parse() {
for ok in [
"10.0.0.0/8",
"127.0.0.1:20000-29999",
"192.168.1.5:8080",
"app.internal",
"app.internal:3000",
"*.svc.internal",
"fd00::/8",
] {
assert!(parse_entry(ok).is_some(), "{ok}");
}
for bad in [
"",
"10.0.0.0/33",
"a b",
"x:0",
"x:9-1",
"*.",
"http://x",
"1.2.3.4/8:70000",
] {
assert!(parse_entry(bad).is_none(), "{bad}");
}
}
#[test]
fn networks_match() {
let n = |s: &str| s.parse::<IpAddr>().unwrap();
assert!(in_net(n("10.1.2.3"), n("10.0.0.0"), 8));
assert!(!in_net(n("11.1.2.3"), n("10.0.0.0"), 8));
assert!(in_net(n("fd12::1"), n("fd00::"), 8));
assert!(in_net(n("1.2.3.4"), n("0.0.0.0"), 0));
assert!(never(n("0.0.0.0")) && never(n("169.254.169.254")) && never(n("::ffff:127.0.0.1")));
}
}
+470
View File
@@ -0,0 +1,470 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Team sign-in without Authelia (T4: Ianitor on any server, for a small team). Authelia stays
//! an option (`[ui] proof_credential`, docs/api.md "Sign-in"); this is the default elsewhere.
//!
//! - **The founding admin** signs in with a one-time **setup link** (`#signin=isc_…`): made at
//! the first start of a server with no member, printed by the installer
//! (`ianitor-control team setup-link`), valid 7 days, one use.
//! - **Teammates** get an **invite link** from an admin (Settings → Team → Invite), for a role:
//! `admin` (everything) or `member` (hosts, previews, history; not tokens, the team, the
//! engine or the CA). One use, 7 days.
//! - Redeeming a link makes a **session**: `ise_` + 32 random bytes in an `HttpOnly`,
//! `Secure`, `SameSite=Strict`, `__Host-` cookie, 30 days, no sliding. Control stores only
//! SHA-256 of codes and sessions (in `team.json`, 0600), so a copy of the state directory
//! signs no one in. Signing out ends the session; removing a member ends all of theirs.
//! - A member may record their **Tessera root** (the Domi identity's public key, as Custos
//! shows it) so the team list shows its match code. Signing in *with* the Tessera key (a
//! browser Domi key) and Custos approval of admin changes need operations Custos does not
//! have yet (docs/custos-ticket.md, T4 part); until then admin changes need the admin role.
use std::path::{Path, PathBuf};
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use serde::{Deserialize, Serialize};
use crate::util::{ct_eq, hex, now, random, read_json, sha256_hex, write_json};
pub const COOKIE: &str = "__Host-ianitor";
pub const SESSION_SECS: u64 = 30 * 86_400;
pub const CODE_SECS: u64 = 7 * 86_400;
const MAX_MEMBERS: usize = 64;
const MAX_SESSIONS: usize = 400;
const MAX_CODES: usize = 100;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Role {
Admin,
Member,
}
impl Role {
pub fn as_str(self) -> &'static str {
match self {
Role::Admin => "admin",
Role::Member => "member",
}
}
pub fn parse(s: &str) -> Option<Role> {
match s {
"admin" => Some(Role::Admin),
"member" => Some(Role::Member),
_ => None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Member {
pub id: String,
pub name: String,
pub role: Role,
/// The member's Tessera root public key (base64url, 32 bytes), when they gave it.
#[serde(default)]
pub tessera_root: Option<String>,
pub added_at: u64,
pub added_by: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Session {
pub id: String,
pub sha256: String,
pub member: String,
/// What the browser was called at sign-in (`Laptop`, `Phone`).
pub device: String,
pub created_at: u64,
pub expires_at: u64,
pub last_used_at: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Code {
pub id: String,
pub sha256: String,
/// `setup` (the founding admin) or `invite`.
pub kind: String,
pub role: Role,
/// The invitee's name, as the admin typed it.
pub name: Option<String>,
pub expires_at: u64,
pub created_by: String,
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct TeamFile {
members: Vec<Member>,
sessions: Vec<Session>,
codes: Vec<Code>,
}
/// Why a sign-in or a team change was refused (an API error code).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Refused(pub &'static str);
pub struct Team {
path: PathBuf,
lock: std::sync::Mutex<()>,
}
struct Guard<'a> {
_m: std::sync::MutexGuard<'a, ()>,
_f: std::fs::File,
}
pub fn valid_name(n: &str) -> bool {
let n = n.trim();
!n.is_empty() && n.chars().count() <= 64 && !n.chars().any(char::is_control)
}
/// A Tessera root as Custos shows it: base64url of 32 bytes.
pub fn valid_root(r: &str) -> bool {
URL_SAFE_NO_PAD
.decode(r.trim())
.is_ok_and(|b| b.len() == 32)
}
/// The 6-digit match code of a Tessera key, exactly as Fundamentum's `tessera::match_code`
/// (docs/TESSERA.md §5): SHA-256 of `"tessera match v1"` and the key, first 4 bytes
/// big-endian, mod 10^6; shown as `474 719`.
pub fn match_code(root: &str) -> Option<String> {
let b = URL_SAFE_NO_PAD.decode(root.trim()).ok()?;
let mut ctx = ring::digest::Context::new(&ring::digest::SHA256);
ctx.update(b"tessera match v1");
ctx.update(&b);
let d = ctx.finish();
let n = u32::from_be_bytes([d.as_ref()[0], d.as_ref()[1], d.as_ref()[2], d.as_ref()[3]]);
let c = n % 1_000_000;
Some(format!("{:03} {:03}", c / 1000, c % 1000))
}
fn secret(prefix: &str) -> Result<String, String> {
Ok(format!(
"{prefix}_{}",
URL_SAFE_NO_PAD.encode(random::<32>().map_err(|e| e.to_string())?)
))
}
fn new_id() -> Result<String, String> {
Ok(hex(&random::<8>().map_err(|e| e.to_string())?))
}
impl Team {
pub fn new(state_dir: &Path) -> Team {
Team {
path: state_dir.join("team.json"),
lock: std::sync::Mutex::new(()),
}
}
fn guard(&self) -> Result<Guard<'_>, String> {
let m = self
.lock
.lock()
.map_err(|_| "team store unavailable".to_owned())?;
let path = self.path.with_file_name("team.lock");
if let Some(d) = path.parent() {
std::fs::create_dir_all(d)
.map_err(|e| format!("cannot create {}: {e}", d.display()))?;
}
let f = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(&path)
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
f.lock()
.map_err(|e| format!("cannot lock {}: {e}", path.display()))?;
Ok(Guard { _m: m, _f: f })
}
fn load(&self) -> Result<TeamFile, String> {
let mut f: TeamFile = read_json(&self.path)?.unwrap_or_default();
let t = now();
f.sessions.retain(|s| s.expires_at > t);
f.codes.retain(|c| c.expires_at > t);
Ok(f)
}
fn save(&self, f: &TeamFile) -> Result<(), String> {
write_json(&self.path, f)
}
pub fn members(&self) -> Result<Vec<Member>, String> {
let _g = self.guard()?;
Ok(self.load()?.members)
}
/// Open invites (never their values).
pub fn codes(&self) -> Result<Vec<Code>, String> {
let _g = self.guard()?;
Ok(self.load()?.codes)
}
pub fn has_members(&self) -> bool {
self.members().is_ok_and(|m| !m.is_empty())
}
/// A new setup code for the founding admin, while the team has no member. Older setup
/// codes stop working.
pub fn setup_code(&self) -> Result<(String, u64), String> {
let _g = self.guard()?;
let mut f = self.load()?;
if !f.members.is_empty() {
return Err(
"the team already has members; an admin invites people from Settings → Team".into(),
);
}
f.codes.retain(|c| c.kind != "setup");
let value = secret("isc")?;
let expires_at = now() + CODE_SECS;
f.codes.push(Code {
id: new_id()?,
sha256: sha256_hex(value.as_bytes()),
kind: "setup".into(),
role: Role::Admin,
name: None,
expires_at,
created_by: "setup".into(),
});
self.save(&f)?;
Ok((value, expires_at))
}
/// An invite for one person (admin only, checked by the caller).
pub fn invite(&self, name: &str, role: Role, by: &str) -> Result<(Code, String), Refused> {
let _g = self.guard().map_err(|_| Refused("internal"))?;
let mut f = self.load().map_err(|_| Refused("internal"))?;
if !valid_name(name) {
return Err(Refused("team.name"));
}
if f.codes.len() >= MAX_CODES || f.members.len() >= MAX_MEMBERS {
return Err(Refused("team.full"));
}
let value = secret("iin").map_err(|_| Refused("internal"))?;
let code = Code {
id: new_id().map_err(|_| Refused("internal"))?,
sha256: sha256_hex(value.as_bytes()),
kind: "invite".into(),
role,
name: Some(name.trim().to_owned()),
expires_at: now() + CODE_SECS,
created_by: by.to_owned(),
};
f.codes.push(code.clone());
self.save(&f).map_err(|_| Refused("internal"))?;
Ok((code, value))
}
pub fn cancel_invite(&self, id: &str) -> Result<bool, String> {
let _g = self.guard()?;
let mut f = self.load()?;
let before = f.codes.len();
f.codes.retain(|c| !(c.id == id && c.kind == "invite"));
let gone = f.codes.len() != before;
self.save(&f)?;
Ok(gone)
}
/// Redeem a setup or invite code: the member (made now) and a new session's value.
pub fn redeem(
&self,
code: &str,
name: Option<&str>,
device: &str,
) -> Result<(Member, String), Refused> {
let _g = self.guard().map_err(|_| Refused("internal"))?;
let mut f = self.load().map_err(|_| Refused("internal"))?;
let presented = sha256_hex(code.trim().as_bytes());
let Some(pos) = f
.codes
.iter()
.position(|c| ct_eq(c.sha256.as_bytes(), presented.as_bytes()))
else {
return Err(Refused("session.code"));
};
let c = f.codes.remove(pos);
if c.kind == "setup" && !f.members.is_empty() {
return Err(Refused("session.code"));
}
let name = match (c.name.as_deref(), name) {
(Some(n), _) => n.to_owned(),
(None, Some(n)) if valid_name(n) => n.trim().to_owned(),
(None, _) => "Admin".to_owned(),
};
if f.members.len() >= MAX_MEMBERS {
return Err(Refused("team.full"));
}
let member = Member {
id: new_id().map_err(|_| Refused("internal"))?,
name,
role: c.role,
tessera_root: None,
added_at: now(),
added_by: c.created_by.clone(),
};
f.members.push(member.clone());
let value = self.push_session(&mut f, &member.id, device)?;
self.save(&f).map_err(|_| Refused("internal"))?;
Ok((member, value))
}
fn push_session(
&self,
f: &mut TeamFile,
member: &str,
device: &str,
) -> Result<String, Refused> {
let value = secret("ise").map_err(|_| Refused("internal"))?;
let t = now();
if f.sessions.len() >= MAX_SESSIONS {
// The oldest one goes.
f.sessions.sort_by_key(|s| s.created_at);
f.sessions.remove(0);
}
let device = if valid_name(device) {
device.trim().to_owned()
} else {
"Browser".to_owned()
};
f.sessions.push(Session {
id: new_id().map_err(|_| Refused("internal"))?,
sha256: sha256_hex(value.as_bytes()),
member: member.to_owned(),
device,
created_at: t,
expires_at: t + SESSION_SECS,
last_used_at: Some(t),
});
Ok(value)
}
/// The member and session behind a cookie value.
pub fn check(&self, value: &str) -> Option<(Member, Session)> {
if !value.starts_with("ise_") || value.len() > 100 {
return None;
}
let _g = self.guard().ok()?;
let mut f = self.load().ok()?;
let presented = sha256_hex(value.as_bytes());
let s = f
.sessions
.iter_mut()
.find(|s| ct_eq(s.sha256.as_bytes(), presented.as_bytes()))?;
let t = now();
let touch = s.last_used_at.is_none_or(|l| t.saturating_sub(l) >= 60);
if touch {
s.last_used_at = Some(t);
}
let s = s.clone();
let m = f.members.iter().find(|m| m.id == s.member)?.clone();
if touch {
let _ = self.save(&f);
}
Some((m, s))
}
pub fn end_session(&self, id: &str) -> Result<(), String> {
let _g = self.guard()?;
let mut f = self.load()?;
f.sessions.retain(|s| s.id != id);
self.save(&f)
}
/// Remove a member and every session of theirs. The last admin stays.
pub fn remove(&self, id: &str) -> Result<Option<Member>, Refused> {
let _g = self.guard().map_err(|_| Refused("internal"))?;
let mut f = self.load().map_err(|_| Refused("internal"))?;
let Some(m) = f.members.iter().find(|m| m.id == id).cloned() else {
return Ok(None);
};
let admins = f.members.iter().filter(|m| m.role == Role::Admin).count();
if m.role == Role::Admin && admins <= 1 {
return Err(Refused("team.last_admin"));
}
f.members.retain(|x| x.id != id);
f.sessions.retain(|s| s.member != id);
self.save(&f).map_err(|_| Refused("internal"))?;
Ok(Some(m))
}
/// Record (or clear) a member's own Tessera root.
pub fn set_root(&self, member: &str, root: Option<&str>) -> Result<(), Refused> {
if root.is_some_and(|r| !valid_root(r)) {
return Err(Refused("team.root"));
}
let _g = self.guard().map_err(|_| Refused("internal"))?;
let mut f = self.load().map_err(|_| Refused("internal"))?;
let m = f
.members
.iter_mut()
.find(|m| m.id == member)
.ok_or(Refused("team.not_found"))?;
m.tessera_root = root.map(|r| r.trim().to_owned());
self.save(&f).map_err(|_| Refused("internal"))
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
fn dir(n: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("ianitor-team-{n}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
d
}
#[test]
fn setup_then_invite_then_sessions() {
let d = dir("flow");
let t = Team::new(&d);
let (setup, _) = t.setup_code().unwrap();
assert!(t.redeem("isc_wrong", Some("Mark"), "Laptop").is_err());
let (mark, s1) = t.redeem(&setup, Some("Mark"), "Laptop").unwrap();
assert_eq!(mark.role, Role::Admin);
// One use only, and no second setup once there is a member.
assert_eq!(
t.redeem(&setup, Some("Eve"), "x").unwrap_err(),
Refused("session.code")
);
assert!(t.setup_code().is_err());
let (who, _) = t.check(&s1).unwrap();
assert_eq!(who.name, "Mark");
// Only hashes on disk.
let stored = std::fs::read_to_string(d.join("team.json")).unwrap();
assert!(!stored.contains(&s1) && !stored.contains(&setup));
let (_, inv) = t.invite("Petra", Role::Member, &mark.id).unwrap();
let (petra, s2) = t.redeem(&inv, Some("Someone else"), "Phone").unwrap();
assert_eq!((petra.name.as_str(), petra.role), ("Petra", Role::Member));
// The last admin cannot go; a member can, with their sessions.
assert_eq!(t.remove(&mark.id).unwrap_err(), Refused("team.last_admin"));
t.remove(&petra.id).unwrap();
assert!(t.check(&s2).is_none());
let (_, s) = t.check(&s1).unwrap();
t.end_session(&s.id).unwrap();
assert!(t.check(&s1).is_none());
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn tessera_roots_are_checked() {
assert!(valid_root(&URL_SAFE_NO_PAD.encode([7u8; 32])));
assert!(!valid_root("not base64!"));
assert!(!valid_root(&URL_SAFE_NO_PAD.encode([7u8; 31])));
// Fundamentum's vector (crates/tessera/tests/mandatory.rs, MATCH_SEVENS = "016810").
assert_eq!(
match_code(&URL_SAFE_NO_PAD.encode([7u8; 32])).unwrap(),
"016 810"
);
}
}
+34 -2
View File
@@ -23,6 +23,34 @@ use serde::{Deserialize, Serialize};
use crate::util::{ct_eq, hex, now, random, read_json, sha256_hex, write_json};
/// What a token may do. `full` (the default, and every token made before T4) may do
/// everything the API offers; `previews` may only use `/api/v1/previews` (Fabrica's branch
/// previews), so a leaked preview token can never touch another host.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Scope {
#[default]
Full,
Previews,
}
impl Scope {
pub fn as_str(self) -> &'static str {
match self {
Scope::Full => "full",
Scope::Previews => "previews",
}
}
pub fn parse(s: &str) -> Option<Scope> {
match s {
"full" => Some(Scope::Full),
"previews" => Some(Scope::Previews),
_ => None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TokenRecord {
@@ -33,6 +61,8 @@ pub struct TokenRecord {
pub expires_at: Option<u64>,
pub last_used_at: Option<u64>,
pub revoked_at: Option<u64>,
#[serde(default)]
pub scope: Scope,
}
#[derive(Debug, Default, Serialize, Deserialize)]
@@ -117,6 +147,7 @@ impl Tokens {
&self,
name: &str,
expires_at: Option<u64>,
scope: Scope,
) -> Result<(TokenRecord, String), String> {
let _g = self.guard()?;
if !valid_name(name) {
@@ -137,6 +168,7 @@ impl Tokens {
expires_at,
last_used_at: None,
revoked_at: None,
scope,
};
f.tokens.push(rec.clone());
self.save(&f)?;
@@ -231,7 +263,7 @@ mod tests {
fn create_check_revoke() {
let d = std::env::temp_dir().join(format!("ianitor-tokens-{}", std::process::id()));
let t = Tokens::new(&d);
let (rec, value) = t.create("laptop", None).unwrap();
let (rec, value) = t.create("laptop", None, Scope::Full).unwrap();
assert!(value.starts_with("ian_"));
let stored = std::fs::read_to_string(d.join("tokens.json")).unwrap();
assert!(!stored.contains(&value[21..]), "only the hash is stored");
@@ -253,7 +285,7 @@ mod tests {
t.check(Some(&format!("Bearer {value}"))).unwrap_err(),
Refusal::Revoked(_)
));
let (_, v2) = t.create("old", Some(1)).unwrap();
let (_, v2) = t.create("old", Some(1), Scope::Full).unwrap();
assert_eq!(
t.check(Some(&format!("Bearer {v2}"))).unwrap_err(),
Refusal::Expired(1)
+109
View File
@@ -0,0 +1,109 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Windows Server, Caddy mode (Fabrica docs/32_coherence.md §2.5, T4): what the service
//! control manager starts. `ianitor-control service control --config <c>` is the control
//! plane, `ianitor-control service caddy-guard --config <c>` the Caddy trial deadline guard
//! (its own service, so a hung or crashed control cannot leave Caddy on an unconfirmed
//! trial). Both stop cleanly on the SCM's Stop. `deploy/windows/install.ps1` registers them.
//! Logs go to the file given with `--log-file` (stderr goes nowhere under the SCM).
use std::ffi::OsString;
use std::sync::OnceLock;
use std::time::Duration;
use windows_service::service::{
ServiceControl, ServiceControlAccept, ServiceExitCode, ServiceState, ServiceStatus, ServiceType,
};
use windows_service::service_control_handler::{self, ServiceControlHandlerResult};
use windows_service::{define_windows_service, service_dispatcher};
static ARGS: OnceLock<Vec<String>> = OnceLock::new();
define_windows_service!(ffi_service_main, service_main);
/// Hand this process to the service control manager (blocks until the service stops).
pub fn run(args: &[String]) -> Result<(), String> {
let _ = ARGS.set(args.to_vec());
// The name is ignored for a service in its own process.
service_dispatcher::start("IanitorControl", ffi_service_main)
.map_err(|e| format!("not started by the service control manager ({e}); run it as a service, or use --config to run it in a console"))
}
fn status(state: ServiceState, code: u32) -> ServiceStatus {
ServiceStatus {
service_type: ServiceType::OWN_PROCESS,
current_state: state,
controls_accepted: if state == ServiceState::Running {
ServiceControlAccept::STOP | ServiceControlAccept::SHUTDOWN
} else {
ServiceControlAccept::empty()
},
exit_code: ServiceExitCode::Win32(code),
checkpoint: 0,
wait_hint: Duration::from_secs(10),
process_id: None,
}
}
fn service_main(_: Vec<OsString>) {
let args = ARGS.get().cloned().unwrap_or_default();
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
let tx = std::sync::Mutex::new(Some(tx));
let handler = move |c| match c {
ServiceControl::Stop | ServiceControl::Shutdown => {
if let Ok(mut t) = tx.lock()
&& let Some(t) = t.take()
{
let _ = t.send(());
}
ServiceControlHandlerResult::NoError
}
ServiceControl::Interrogate => ServiceControlHandlerResult::NoError,
_ => ServiceControlHandlerResult::NotImplemented,
};
let Ok(h) = service_control_handler::register("IanitorControl", handler) else {
return;
};
let _ = h.set_service_status(status(ServiceState::Running, 0));
let result = serve(&args, rx);
if let Err(e) = &result {
log::error!(target: "ianitor::service", "{e}");
}
let _ = h.set_service_status(status(ServiceState::Stopped, u32::from(result.is_err())));
}
fn serve(args: &[String], stop: tokio::sync::oneshot::Receiver<()>) -> Result<(), String> {
let what = args.first().map(String::as_str).unwrap_or("control");
let config = args
.iter()
.position(|a| a == "--config")
.and_then(|i| args.get(i + 1))
.ok_or("service: --config <control.toml> is required")?;
let cfg =
ianitor_control::Config::load(std::path::Path::new(config)).map_err(|e| e.to_string())?;
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.map_err(|e| e.to_string())?;
rt.block_on(async move {
match what {
"control" => {
ianitor_control::serve(cfg, async {
let _ = stop.await;
})
.await
}
"caddy-guard" => {
tokio::select! {
r = ianitor_control::caddy_guard::run(cfg) => r,
_ = stop => Ok(()),
}
}
other => Err(format!(
"service: unknown part {other:?} (control or caddy-guard)"
)),
}
})
}
+280
View File
@@ -0,0 +1,280 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Caddy mode end to end (T4: Windows Server runs control with Caddy as the data plane, no
//! edge). Control runs with `engine = caddy`, Caddy's admin API on loopback TCP (as on
//! Windows), and the Domi CA. A previews-only token opens a branch preview; the apply goes
//! through Caddy (trial, watch, confirm); the preview's address then answers through Caddy
//! with a Domi certificate; closing it takes it away again. Runs on Windows and on Linux.
//! Needs `caddy` on PATH or `$IANITOR_CADDY_BIN` (else it fails, unless IANITOR_ALLOW_SKIP=1).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::net::SocketAddr;
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::time::{Duration, Instant};
use ianitor_control::Config;
use ianitor_control::tokens::{Scope, Tokens};
use ianitor_testkit::client::{self, Req};
use ianitor_testkit::more::{JsonResp, tcp_json};
use ianitor_testkit::proc::{ChildGuard, TempDir, free_port, local, require_binary, wait_for_port};
use ianitor_testkit::upstream::Echo;
use serde_json::{Value, json};
fn s(p: &std::path::Path) -> String {
p.to_string_lossy().replace('\\', "/")
}
async fn call(
api: SocketAddr,
token: &str,
method: &str,
path: &str,
body: Option<Value>,
) -> JsonResp {
let auth = format!("Bearer {token}");
tcp_json(
api,
method,
path,
&[("Authorization", &auth)],
body.as_ref(),
)
.await
.unwrap()
}
async fn settle(api: SocketAddr, token: &str, apply: &Value) -> Value {
let id = apply["id"].as_str().unwrap().to_owned();
let t = Instant::now();
loop {
let r = call(api, token, "GET", &format!("/api/v1/applies/{id}"), None).await;
if ["kept", "reverted", "failed"].contains(&r.json["state"].as_str().unwrap_or("")) {
return r.json;
}
assert!(
t.elapsed() < Duration::from_secs(90),
"apply stuck: {}",
r.text
);
tokio::time::sleep(Duration::from_millis(700)).await;
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_branch_preview_answers_through_caddy_without_an_edge() {
let Some(caddy) = require_binary("caddy") else {
return;
};
let dir = TempDir::new("caddy-mode");
for d in [
"state",
"edge",
"caddy",
"certs",
"creds",
"caddy-state",
"root",
"xdg",
] {
std::fs::create_dir_all(dir.join(d)).unwrap();
}
// The offline root (a test one) and the intermediate's password.
let now = ianitor_control::util::now();
let (root_pem, root_key) = ianitor_core::pki::create_root(now as i64).unwrap();
std::fs::write(dir.join("root/domi-root.crt"), &root_pem).unwrap();
std::fs::write(
dir.join("creds/pki-password"),
"caddy-mode-test-password-0123456789",
)
.unwrap();
let api = local(free_port());
let admin = local(free_port());
let (http, https) = (free_port(), free_port());
// Caddy starts with only its admin API, as the installer starts it; control loads the rest.
let boot = json!({"admin": {"listen": admin.to_string()}}).to_string();
std::fs::write(dir.join("caddy/boot.json"), &boot).unwrap();
let log = std::fs::File::create(dir.join("caddy.log")).unwrap();
let _caddy = ChildGuard(
Command::new(&caddy)
.args(["run", "--config"])
.arg(dir.join("caddy/boot.json"))
.env("HOME", dir.join("xdg"))
.env("XDG_CONFIG_HOME", dir.join("xdg"))
.env("XDG_DATA_HOME", dir.join("xdg"))
.env("APPDATA", dir.join("xdg"))
.stdout(Stdio::from(log.try_clone().unwrap()))
.stderr(Stdio::from(log))
.spawn()
.unwrap(),
);
assert!(
wait_for_port(admin, Duration::from_secs(60)),
"Caddy's admin API did not start"
);
std::fs::write(dir.join("state/engine"), "caddy\n").unwrap();
let text = format!(
r#"listen = "{api}"
state_dir = "{state}"
credentials_dir = "{creds}"
watch_secs = 2
watch_every_secs = 1
trial_margin_secs = 5
[routes]
repo = "{repo}"
[edge]
config = "{edge}/edge.json"
share_revocations = "{edge}/share-revocations.json"
[caddy]
config = "{caddy_dir}/caddy.json"
[compile]
http_listen = "127.0.0.1:{http}"
https_listen = "127.0.0.1:{https}"
cert_dir = "{certs}"
state_dir = "{caddy_state}"
access_log = "{caddy_state}/access.log"
caddy_credentials_dir = "{creds}"
caddy_admin = "{admin}"
[pki]
root_cert = "{root}/domi-root.crt"
kdf_iterations = 10000
[engine]
file = "{state}/engine"
units = "none"
[previews]
domain = "pv.test"
tls = "domi"
upstreams = ["127.0.0.1:1024-65535"]
min_ttl_secs = 60
"#,
state = s(&dir.join("state")),
creds = s(&dir.join("creds")),
repo = s(&dir.join("routes.git")),
edge = s(&dir.join("edge")),
caddy_dir = s(&dir.join("caddy")),
certs = s(&dir.join("certs")),
caddy_state = s(&dir.join("caddy-state")),
root = s(&dir.join("root")),
);
std::fs::write(dir.join("control.toml"), text).unwrap();
let cfg = Config::load(&dir.join("control.toml")).unwrap();
// The intermediate, signed by the test root (the offline step of docs/pki.md).
{
let c = ianitor_control::Control::open(cfg.clone()).await.unwrap();
let p = c.pki.as_ref().unwrap();
let r = p.request_renewal(now, "test").unwrap();
let signed = ianitor_core::pki::sign_intermediate(
&root_pem,
&root_key,
r.csr_pem.as_deref().unwrap(),
now as i64,
)
.unwrap();
p.install_intermediate(&r.id, &signed, now).unwrap();
}
let tokens = Tokens::new(&dir.join("state"));
let (_, admin_tok) = tokens.create("admin", None, Scope::Full).unwrap();
let (_, fabrica) = tokens.create("fabrica", None, Scope::Previews).unwrap();
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
tokio::spawn(ianitor_control::serve(cfg, async {
let _ = rx.await;
}));
assert!(wait_for_port(api, Duration::from_secs(20)));
let r = call(api, &admin_tok, "GET", "/api/v1/overview", None).await;
assert_eq!(r.json["engine"]["running"], "caddy", "{}", r.text);
assert_eq!(r.json["engine"]["switchable"], false, "{}", r.text);
// Fabrica opens the branch's preview.
let app = Echo::start("preview-app").await;
let r = call(
api,
&fabrica,
"POST",
"/api/v1/previews",
Some(json!({"project": "shop", "branch": "fix-42", "upstream": app.url(), "ttl": 3600})),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
let host = r.json["preview"]["hostname"].as_str().unwrap().to_owned();
assert_eq!(host, "fix-42--shop.pv.test");
let done = settle(api, &admin_tok, &r.json["apply"]).await;
assert_eq!(done["state"], "kept", "{done}");
let steps: Vec<String> = done["steps"]
.as_array()
.unwrap()
.iter()
.map(|s| {
format!(
"{}={}",
s["key"].as_str().unwrap(),
s["state"].as_str().unwrap()
)
})
.collect();
assert!(
steps.contains(&"watch=done".to_owned()),
"watched through Caddy: {steps:?}"
);
// The preview answers through Caddy, with a certificate from the Domi CA.
let mut roots = rustls::RootCertStore::empty();
for der in ianitor_core::pki::chain_der(&root_pem).unwrap() {
roots
.add(rustls_pki_types::CertificateDer::from(der))
.unwrap();
}
let roots = Arc::new(roots);
let https_addr = local(https);
let resp = client::https(https_addr, &host, roots.clone(), &Req::get(&host, "/hello"))
.await
.unwrap();
assert_eq!(resp.status, 200);
assert_eq!(resp.header("x-robots-tag"), Some("noindex, nofollow"));
assert!(String::from_utf8_lossy(&resp.body).contains("preview-app"));
let r = call(
api,
&fabrica,
"GET",
&format!("/api/v1/previews/{host}"),
None,
)
.await;
assert_eq!(r.json["preview"]["state"], "live", "{}", r.text);
// Closed on merge: Caddy stops serving it.
let r = call(
api,
&fabrica,
"POST",
"/api/v1/previews/close",
Some(json!({"project": "shop", "branch": "fix-42"})),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
assert_eq!(
settle(api, &admin_tok, &r.json["apply"]).await["state"],
"kept"
);
let gone = client::https(https_addr, &host, roots, &Req::get(&host, "/hello")).await;
assert!(
gone.as_ref()
.map_or(true, |r| r.status == 404 || r.status == 421),
"{:?}",
gone.map(|r| r.status)
);
let _ = tx.send(());
}
+23 -10
View File
@@ -533,7 +533,11 @@ esac
std::fs::write(env.dir.join("certs/a.test.crt"), &leaf.chain_pem).unwrap();
// What control does in devices_changed / reload_serving_engine under Caddy.
let text = std::fs::read(env.dir.join("caddy/caddy.json")).unwrap();
let r = ianitor_control::caddy_link::load(&env.dir.join("caddy/admin.sock"), &text).await;
let r = ianitor_control::caddy_link::load(
&ianitor_control::caddy_link::Admin::Unix(env.dir.join("caddy/admin.sock")),
&text,
)
.await;
assert!(r.is_ok(), "{r:?}");
let after = visit(env, ce.https, "a.test").await;
eprintln!(
@@ -690,9 +694,12 @@ esac
);
// What a device change or a Caddy restart does: Caddy gets the last good config.
let good = std::fs::read(env.dir.join("caddy/caddy.json")).unwrap();
ianitor_control::caddy_link::load(&env.dir.join("caddy/admin.sock"), &good)
.await
.unwrap();
ianitor_control::caddy_link::load(
&ianitor_control::caddy_link::Admin::Unix(env.dir.join("caddy/admin.sock")),
&good,
)
.await
.unwrap();
let rec = env.wait_apply(&id).await;
assert_ne!(rec["state"], "kept", "{rec}");
assert_eq!(rec["reason"]["code"], "apply.reverted.edge_lost", "{rec}");
@@ -841,13 +848,19 @@ esac
std::fs::write(env.dir.join("certs/domi-devices.pem"), &laptop.cert_pem).unwrap();
let sock = env.dir.join("caddy/admin.sock");
let text = std::fs::read(env.dir.join("caddy/caddy.json")).unwrap();
ianitor_control::caddy_link::load(&sock, &text)
.await
.unwrap();
ianitor_control::caddy_link::load(
&ianitor_control::caddy_link::Admin::Unix(sock.clone()),
&text,
)
.await
.unwrap();
assert!(
ianitor_control::caddy_link::runs(&sock, &text)
.await
.unwrap()
ianitor_control::caddy_link::runs(
&ianitor_control::caddy_link::Admin::Unix(sock.clone()),
&text
)
.await
.unwrap()
);
let phone_after = visit_as(&phone).await;
let laptop_after = visit_as(&laptop).await;
+539
View File
@@ -0,0 +1,539 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Branch previews for Fabrica (T4, tests first). `POST /api/v1/previews {project, branch,
//! upstream, ttl}` gives the branch the host `<branch>--<project>.<preview domain>`; a token
//! scoped to previews may do that and nothing else. These tests run control in this process
//! without an edge (applies are kept at once), so they run on Windows too; the end-to-end
//! runs through Pingora and Caddy are in tests/diff and scripts/preview-smoke.*.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::net::SocketAddr;
use std::time::{Duration, Instant};
use ianitor_control::Config;
use ianitor_control::tokens::{Scope, Tokens};
use ianitor_testkit::more::{JsonResp, tcp_json};
use ianitor_testkit::proc::{TempDir, free_port, local, wait_for_port};
use serde_json::{Value, json};
const DOMAIN: &str = "pv.example.test";
struct Ctl {
_dir: TempDir,
api: SocketAddr,
admin: String,
preview: String,
stop: Option<tokio::sync::oneshot::Sender<()>>,
}
impl Drop for Ctl {
fn drop(&mut self) {
if let Some(s) = self.stop.take() {
let _ = s.send(());
}
}
}
fn s(p: &std::path::Path) -> String {
p.to_string_lossy().replace('\\', "/")
}
impl Ctl {
async fn start(extra: &str) -> Ctl {
let dir = TempDir::new("pv");
for d in ["state", "edge", "caddy", "certs", "creds", "edge-state"] {
std::fs::create_dir_all(dir.join(d)).unwrap();
}
let api = local(free_port());
let text = format!(
r#"listen = "{api}"
state_dir = "{state}"
credentials_dir = "{creds}"
[routes]
repo = "{repo}"
[edge]
config = "{edge}/edge.json"
share_revocations = "{edge}/share-revocations.json"
[caddy]
config = "{caddy}/caddy.json"
[compile]
http_listen = "127.0.0.1:{http}"
https_listen = "127.0.0.1:{https}"
cert_dir = "{certs}"
state_dir = "{edge_state}"
access_log = "{edge_state}/access.log"
caddy_credentials_dir = "{creds}"
[previews]
domain = "{DOMAIN}"
tls = "letsencrypt"
upstreams = ["10.0.0.0/8", "127.0.0.1:20000-29999", "app.internal"]
min_ttl_secs = 1
sweep_secs = 1
{extra}
"#,
state = s(&dir.join("state")),
creds = s(&dir.join("creds")),
repo = s(&dir.join("routes.git")),
edge = s(&dir.join("edge")),
caddy = s(&dir.join("caddy")),
certs = s(&dir.join("certs")),
edge_state = s(&dir.join("edge-state")),
http = free_port(),
https = free_port(),
);
let path = dir.join("control.toml");
std::fs::write(&path, text).unwrap();
let cfg = Config::load(&path).unwrap();
let tokens = Tokens::new(&dir.join("state"));
let (_, admin) = tokens.create("admin", None, Scope::Full).unwrap();
let (_, preview) = tokens
.create("fabrica previews", None, Scope::Previews)
.unwrap();
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
tokio::spawn(async move {
if let Err(e) = ianitor_control::serve(cfg, async {
let _ = rx.await;
})
.await
{
panic!("control stopped: {e}");
}
});
assert!(
wait_for_port(api, Duration::from_secs(20)),
"control did not listen"
);
Ctl {
_dir: dir,
api,
admin,
preview,
stop: Some(tx),
}
}
async fn call(&self, token: &str, method: &str, path: &str, body: Option<Value>) -> JsonResp {
let auth = format!("Bearer {token}");
tcp_json(
self.api,
method,
path,
&[("Authorization", &auth)],
body.as_ref(),
)
.await
.unwrap()
}
async fn admin(&self, method: &str, path: &str, body: Option<Value>) -> JsonResp {
self.call(&self.admin, method, path, body).await
}
async fn fabrica(&self, method: &str, path: &str, body: Option<Value>) -> JsonResp {
self.call(&self.preview, method, path, body).await
}
/// Wait for an apply to end; returns its final state.
async fn settle(&self, apply: &Value) -> String {
let id = apply["id"].as_str().expect("an apply id").to_owned();
let t = Instant::now();
loop {
let r = self
.admin("GET", &format!("/api/v1/applies/{id}"), None)
.await;
let state = r.json["state"].as_str().unwrap_or("").to_owned();
if ["kept", "reverted", "failed"].contains(&state.as_str()) {
return state;
}
assert!(
t.elapsed() < Duration::from_secs(30),
"apply {id} stuck: {}",
r.text
);
tokio::time::sleep(Duration::from_millis(700)).await;
}
}
async fn host_names(&self) -> Vec<String> {
let r = self.admin("GET", "/api/v1/hosts", None).await;
assert_eq!(r.status, 200, "{}", r.text);
r.json["hosts"]
.as_array()
.unwrap()
.iter()
.map(|h| h["hostname"].as_str().unwrap().to_owned())
.collect()
}
async fn add_plain_host(&self, hostname: &str) {
let r = self
.admin(
"POST",
"/api/v1/hosts",
Some(json!({"host": {"hostname": hostname, "upstreams": ["http://10.0.0.9:80"]}})),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
assert_eq!(self.settle(&r.json["apply"]).await, "kept");
}
async fn open_preview(&self, project: &str, branch: &str, upstream: &str) -> JsonResp {
self.fabrica(
"POST",
"/api/v1/previews",
Some(json!({"project": project, "branch": branch, "upstream": upstream, "ttl": 3600})),
)
.await
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_preview_token_cannot_touch_non_preview_hosts() {
let c = Ctl::start("").await;
c.add_plain_host("www.example.test").await;
let www =
json!({"host": {"hostname": "www.example.test", "upstreams": ["http://10.6.6.6:80"]}});
// Everything outside /api/v1/previews is refused, reads included.
let refused: Vec<(&str, &str, Option<Value>)> = vec![
("GET", "/api/v1/overview", None),
("GET", "/api/v1/hosts", None),
("GET", "/api/v1/hosts/www.example.test", None),
(
"POST",
"/api/v1/hosts",
Some(
json!({"host": {"hostname": "evil.example.test", "upstreams": ["http://10.6.6.6:80"]}}),
),
),
("PUT", "/api/v1/hosts/www.example.test", Some(www.clone())),
(
"PATCH",
"/api/v1/hosts/www.example.test",
Some(json!({"share_links": true})),
),
("DELETE", "/api/v1/hosts/www.example.test", None),
("POST", "/api/v1/hosts/validate", Some(www["host"].clone())),
("POST", "/api/v1/undo", Some(json!({}))),
("POST", "/api/v1/restore", Some(json!({"change_id": "x"}))),
("GET", "/api/v1/history", None),
("GET", "/api/v1/applies", None),
("GET", "/api/v1/tokens", None),
("POST", "/api/v1/tokens", Some(json!({"name": "escalate"}))),
(
"POST",
"/api/v1/hosts/www.example.test/share-links",
Some(json!({})),
),
("POST", "/api/v1/share-links/stop-all", None),
("GET", "/api/v1/certs", None),
("POST", "/api/v1/engine", Some(json!({"target": "caddy"}))),
("POST", "/api/v1/repo/push", None),
("GET", "/api/v1/settings", None),
("GET", "/api/v1/team", None),
];
for (m, p, b) in refused {
let r = c.fabrica(m, p, b).await;
assert_eq!(r.status, 403, "{m} {p}: {}", r.text);
assert_eq!(
r.json["error"]["code"], "token.scope",
"{m} {p}: {}",
r.text
);
}
// The previews API refuses a host that is not a preview.
let r = c
.fabrica("DELETE", "/api/v1/previews/www.example.test", None)
.await;
assert_eq!(r.status, 404, "{}", r.text);
assert_eq!(r.json["error"]["code"], "preview.not_found");
let r = c
.fabrica("GET", "/api/v1/previews/www.example.test", None)
.await;
assert_eq!(r.status, 404, "{}", r.text);
// A non-preview host at exactly the name a preview would get is not taken over.
let taken = format!("main--shop.{DOMAIN}");
c.add_plain_host(&taken).await;
let r = c.open_preview("shop", "main", "http://10.0.0.5:8080").await;
assert_eq!(r.status, 409, "{}", r.text);
assert_eq!(r.json["error"]["code"], "preview.taken");
let r = c
.admin("GET", &format!("/api/v1/hosts/{taken}"), None)
.await;
assert_eq!(
r.json["host"]["upstreams"][0], "http://10.0.0.9:80",
"{}",
r.text
);
let r = c
.fabrica(
"POST",
"/api/v1/previews/close",
Some(json!({"project": "shop", "branch": "main"})),
)
.await;
assert_eq!(r.status, 404, "{}", r.text);
// A preview the token made touches only its own file, and the list holds only previews.
let r = c
.open_preview("shop", "fix-1", "http://10.0.0.5:8080")
.await;
assert_eq!(r.status, 202, "{}", r.text);
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
let hosts = r.json["apply"]["hosts"].as_array().unwrap().clone();
assert_eq!(hosts, vec![json!(format!("fix-1--shop.{DOMAIN}"))]);
let r = c.fabrica("GET", "/api/v1/previews", None).await;
assert_eq!(r.status, 200, "{}", r.text);
let listed: Vec<&str> = r.json["items"]
.as_array()
.unwrap()
.iter()
.map(|p| p["hostname"].as_str().unwrap())
.collect();
assert_eq!(listed, vec![format!("fix-1--shop.{DOMAIN}").as_str()]);
let mut names = c.host_names().await;
names.sort();
assert_eq!(
names,
vec![
format!("fix-1--shop.{DOMAIN}"),
taken.clone(),
"www.example.test".into()
]
);
// An admin can still kill a preview; the scoped token was never needed for that.
let r = c
.admin(
"DELETE",
&format!("/api/v1/previews/fix-1--shop.{DOMAIN}"),
None,
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
assert!(
!c.host_names()
.await
.iter()
.any(|h| h.starts_with("fix-1--"))
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_preview_token_cannot_point_a_preview_at_this_machine_s_admin_ports() {
let c = Ctl::start("").await;
let control_port = c.api.port();
for upstream in [
// control itself, Caddy's admin API, anything on loopback outside the allowed range
format!("http://127.0.0.1:{control_port}"),
"http://127.0.0.1:2019".to_owned(),
"http://localhost:20001".to_owned(),
"http://[::1]:20001".to_owned(),
"http://0.0.0.0:20001".to_owned(),
"http://169.254.169.254:80".to_owned(),
// not in the allow list
"http://192.168.1.10:8080".to_owned(),
"http://other.internal:8080".to_owned(),
// not an upstream at all
"http://user:pw@10.0.0.5:8080".to_owned(),
"http://10.0.0.5:8080/path".to_owned(),
"file:///etc/passwd".to_owned(),
"".to_owned(),
] {
let r = c.open_preview("shop", "main", &upstream).await;
assert!(
r.status == 422 || r.status == 403,
"{upstream}: {} {}",
r.status,
r.text
);
assert!(
r.json["error"]["code"].as_str().is_some_and(
|c| c.starts_with("preview.upstream") || c.starts_with("host.upstream")
),
"{upstream}: {}",
r.text
);
}
assert!(c.host_names().await.is_empty());
// Allowed: the private range, the loopback port range, the listed name.
for (b, u) in [
("a", "http://10.1.2.3:8080"),
("b", "http://127.0.0.1:20001"),
("c", "http://app.internal:3000"),
] {
let r = c.open_preview("shop", b, u).await;
assert_eq!(r.status, 202, "{u}: {}", r.text);
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_preview_lives_until_closed_or_expired() {
let c = Ctl::start("").await;
// Open, with a hostile branch name: the host is safe and the API says where it is.
let r = c
.open_preview(
"github:acme/Web.App",
"feature/Ünï ../../etc",
"http://10.0.0.5:8080",
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
let host = r.json["preview"]["hostname"].as_str().unwrap().to_owned();
assert!(host.ends_with(&format!(".{DOMAIN}")), "{host}");
assert!(host.split('.').next().unwrap().contains("--"));
assert_eq!(r.json["preview"]["url"], format!("https://{host}/"));
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
let r = c
.fabrica("GET", &format!("/api/v1/previews/{host}"), None)
.await;
assert_eq!(r.status, 200, "{}", r.text);
assert_eq!(r.json["preview"]["branch"], "feature/Ünï ../../etc");
assert_eq!(r.json["preview"]["state"], "live", "{}", r.text);
// A new deploy of the same branch moves the same host, it does not add one.
let r = c
.open_preview(
"github:acme/Web.App",
"feature/Ünï ../../etc",
"http://10.0.0.6:8080",
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
assert_eq!(r.json["preview"]["hostname"], host.as_str());
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
let r = c.admin("GET", &format!("/api/v1/hosts/{host}"), None).await;
assert_eq!(r.json["host"]["upstreams"][0], "http://10.0.0.6:8080");
assert_eq!(c.host_names().await.len(), 1);
// Closed on merge, by project and branch.
let r = c
.fabrica(
"POST",
"/api/v1/previews/close",
Some(json!({"project": "github:acme/Web.App", "branch": "feature/Ünï ../../etc"})),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
assert!(c.host_names().await.is_empty());
// Expired: removed by control by itself.
let r = c
.fabrica(
"POST",
"/api/v1/previews",
Some(json!({"project": "shop", "branch": "short", "upstream": "http://10.0.0.5:80", "ttl": 2})),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
assert_eq!(c.settle(&r.json["apply"]).await, "kept");
let t = Instant::now();
while !c.host_names().await.is_empty() {
assert!(
t.elapsed() < Duration::from_secs(30),
"the expired preview stayed"
);
tokio::time::sleep(Duration::from_millis(700)).await;
}
let r = c.admin("GET", "/api/v1/history", None).await;
assert!(r.text.contains("expired"), "{}", r.text);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn bad_preview_requests_are_refused_with_a_reason() {
let c = Ctl::start(
"max_ttl_secs = 86400
default_ttl_secs = 3600",
)
.await;
for (body, code) in [
(
json!({"project": "shop", "branch": "a\nb", "upstream": "http://10.0.0.5:80"}),
"preview.branch",
),
(
json!({"project": "shop", "branch": "", "upstream": "http://10.0.0.5:80"}),
"preview.branch",
),
(
json!({"project": "sh op", "branch": "main", "upstream": "http://10.0.0.5:80"}),
"preview.project",
),
(
json!({"project": "shop", "branch": "main", "upstream": "http://10.0.0.5:80", "ttl": 0}),
"preview.ttl",
),
(
json!({"project": "shop", "branch": "main", "upstream": "http://10.0.0.5:80", "ttl": 864000}),
"preview.ttl",
),
(
json!({"project": "shop", "branch": "main", "upstream": "http://10.0.0.5:80", "auth": "none"}),
"request.body_unknown_field",
),
] {
let r = c
.fabrica("POST", "/api/v1/previews", Some(body.clone()))
.await;
assert_eq!(r.json["error"]["code"], code, "{body}: {}", r.text);
assert!(r.status == 422 || r.status == 400, "{body}: {}", r.text);
}
assert!(c.host_names().await.is_empty());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn without_a_preview_domain_the_api_says_previews_are_off() {
let c = Ctl::start("").await;
// Replace the config with one that has no [previews] section, then restart.
drop(c);
let c2 = {
let dir = TempDir::new("pv-off");
std::fs::create_dir_all(dir.join("state")).unwrap();
let api = local(free_port());
let text = format!(
"listen = \"{api}\"\nstate_dir = \"{st}\"\n\n[routes]\nrepo = \"{repo}\"\n\n[edge]\nconfig = \"{d}/edge.json\"\nshare_revocations = \"{d}/rev.json\"\n\n[caddy]\nconfig = \"{d}/caddy.json\"\n\n[compile]\nhttp_listen = \"127.0.0.1:{h}\"\nhttps_listen = \"127.0.0.1:{hs}\"\ncert_dir = \"{d}\"\nstate_dir = \"{d}\"\naccess_log = \"{d}/a.log\"\ncaddy_credentials_dir = \"{d}\"\n",
st = s(&dir.join("state")),
repo = s(&dir.join("routes.git")),
d = s(dir.path()),
h = free_port(),
hs = free_port(),
);
std::fs::write(dir.join("control.toml"), text).unwrap();
let cfg = Config::load(&dir.join("control.toml")).unwrap();
let (_, tok) = Tokens::new(&dir.join("state"))
.create("fabrica", None, Scope::Previews)
.unwrap();
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
tokio::spawn(ianitor_control::serve(cfg, async {
let _ = rx.await;
}));
assert!(wait_for_port(api, Duration::from_secs(20)));
(dir, api, tok, tx)
};
let auth = format!("Bearer {}", c2.2);
let r = tcp_json(
c2.1,
"POST",
"/api/v1/previews",
&[("Authorization", &auth)],
Some(&json!({"project": "shop", "branch": "main", "upstream": "http://10.0.0.5:80"})),
)
.await
.unwrap();
assert_eq!(r.status, 409, "{}", r.text);
assert_eq!(r.json["error"]["code"], "preview.off");
let _ = c2.3.send(());
}
+8 -2
View File
@@ -27,7 +27,11 @@ fn a_cli_revoke_is_not_lost_while_the_server_records_token_use() {
let d = TempDir::new("tok-race");
let server = Tokens::new(d.path());
let values: Vec<_> = (0..150)
.map(|i| server.create(&format!("t{i}"), None).unwrap())
.map(|i| {
server
.create(&format!("t{i}"), None, Default::default())
.unwrap()
})
.collect();
let victim = values[75].0.id.clone();
let mut cli = std::process::Command::new(bin)
@@ -77,7 +81,9 @@ fn concurrent_creates_from_the_cli_and_the_server_all_survive() {
})
.collect();
for i in 0..40 {
server.create(&format!("srv{i}"), None).unwrap();
server
.create(&format!("srv{i}"), None, Default::default())
.unwrap();
}
for c in &mut clis {
assert!(c.wait().unwrap().success());
+257
View File
@@ -0,0 +1,257 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Team sign-in without Authelia (T4): the setup link makes the founding admin, invites make
//! members, a session cookie identifies them, members cannot do admin things, and browser
//! writes need the UI header. Runs on Windows and Linux (control in this process, no edge).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::net::SocketAddr;
use std::time::Duration;
use ianitor_control::Config;
use ianitor_control::team::Team;
use ianitor_testkit::more::{JsonResp, tcp_json};
use ianitor_testkit::proc::{TempDir, free_port, local, wait_for_port};
use serde_json::{Value, json};
fn s(p: &std::path::Path) -> String {
p.to_string_lossy().replace('\\', "/")
}
async fn start() -> (TempDir, SocketAddr, tokio::sync::oneshot::Sender<()>) {
let dir = TempDir::new("team");
std::fs::create_dir_all(dir.join("state")).unwrap();
let api = local(free_port());
let text = format!(
"listen = \"{api}\"\nstate_dir = \"{st}\"\n\n[routes]\nrepo = \"{repo}\"\n\n[edge]\nconfig = \"{d}/edge.json\"\nshare_revocations = \"{d}/rev.json\"\n\n[caddy]\nconfig = \"{d}/caddy.json\"\n\n[compile]\nhttp_listen = \"127.0.0.1:{h}\"\nhttps_listen = \"127.0.0.1:{hs}\"\ncert_dir = \"{d}\"\nstate_dir = \"{d}\"\naccess_log = \"{d}/a.log\"\ncaddy_credentials_dir = \"{d}\"\n",
st = s(&dir.join("state")),
repo = s(&dir.join("routes.git")),
d = s(dir.path()),
h = free_port(),
hs = free_port(),
);
std::fs::write(dir.join("control.toml"), text).unwrap();
let cfg = Config::load(&dir.join("control.toml")).unwrap();
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
tokio::spawn(ianitor_control::serve(cfg, async {
let _ = rx.await;
}));
assert!(wait_for_port(api, Duration::from_secs(20)));
(dir, api, tx)
}
async fn req(api: SocketAddr, m: &str, p: &str, h: &[(&str, &str)], b: Option<Value>) -> JsonResp {
tcp_json(api, m, p, h, b.as_ref()).await.unwrap()
}
fn cookie_of(r: &JsonResp) -> String {
let set = r
.headers
.iter()
.find(|(n, _)| n == "set-cookie")
.map(|(_, v)| v.clone())
.expect("a Set-Cookie");
for part in ["HttpOnly", "Secure", "SameSite=Strict", "Path=/"] {
assert!(set.contains(part), "{set}");
}
assert!(set.starts_with("__Host-ianitor=ise_"), "{set}");
set.split(';').next().unwrap().to_owned()
}
async fn sign_in(api: SocketAddr, code: &str, name: &str) -> (JsonResp, String) {
let r = req(
api,
"POST",
"/api/v1/session",
&[("X-Ianitor-UI", "1"), ("Sec-Fetch-Site", "same-origin")],
Some(json!({"code": code, "name": name, "device": "Laptop"})),
)
.await;
assert_eq!(r.status, 200, "{}", r.text);
let c = cookie_of(&r);
(r, c)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_setup_link_then_invites_sign_a_team_in() {
let (dir, api, _stop) = start().await;
let (setup, _) = Team::new(&dir.join("state")).setup_code().unwrap();
// The door refuses bad codes, other sites and pages that are not the UI.
for (headers, code) in [
(vec![("X-Ianitor-UI", "1")], "isc_wrong"),
(vec![], setup.as_str()),
(
vec![("X-Ianitor-UI", "1"), ("Sec-Fetch-Site", "cross-site")],
setup.as_str(),
),
] {
let r = req(
api,
"POST",
"/api/v1/session",
&headers,
Some(json!({"code": code})),
)
.await;
assert!(
r.status == 401 || r.status == 403,
"{headers:?}: {}",
r.text
);
assert!(!r.headers.iter().any(|(n, _)| n == "set-cookie"));
}
let (r, mark) = sign_in(api, &setup, "Mark").await;
assert_eq!(r.json["member"]["role"], "admin");
let ov = req(api, "GET", "/api/v1/overview", &[("Cookie", &mark)], None).await;
assert_eq!(ov.status, 200, "{}", ov.text);
assert_eq!(ov.json["viewer"]["via"], "session");
assert_eq!(ov.json["viewer"]["name"], "Mark");
// The setup link worked once.
let r = req(
api,
"POST",
"/api/v1/session",
&[("X-Ianitor-UI", "1")],
Some(json!({"code": setup})),
)
.await;
assert_eq!(r.status, 401, "{}", r.text);
// A browser write without the UI header is refused (CSRF), with it it works.
let r = req(
api,
"POST",
"/api/v1/team/invites",
&[("Cookie", &mark)],
Some(json!({"name": "Petra"})),
)
.await;
assert_eq!(r.status, 403, "{}", r.text);
assert_eq!(r.json["error"]["code"], "request.csrf");
let r = req(
api,
"POST",
"/api/v1/team/invites",
&[("Cookie", &mark), ("X-Ianitor-UI", "1")],
Some(json!({"name": "Petra", "role": "member"})),
)
.await;
assert_eq!(r.status, 201, "{}", r.text);
let code = r.json["link_fragment"]
.as_str()
.unwrap()
.strip_prefix("#signin=")
.unwrap()
.to_owned();
// Petra is a member: hosts yes, tokens, the team and the engine no.
let (_, petra) = sign_in(api, &code, "Not Petra").await;
let team = req(api, "GET", "/api/v1/team", &[("Cookie", &petra)], None).await;
assert_eq!(team.json["me"]["name"], "Petra", "{}", team.text);
for (m, p, b) in [
("GET", "/api/v1/tokens", None),
("POST", "/api/v1/tokens", Some(json!({"name": "x"}))),
(
"POST",
"/api/v1/team/invites",
Some(json!({"name": "Eve", "role": "admin"})),
),
("POST", "/api/v1/engine", Some(json!({"target": "caddy"}))),
] {
let r = req(api, m, p, &[("Cookie", &petra), ("X-Ianitor-UI", "1")], b).await;
assert_eq!(r.status, 403, "{m} {p}: {}", r.text);
assert_eq!(r.json["error"]["code"], "team.admin_only", "{m} {p}");
}
let r = req(
api,
"POST",
"/api/v1/hosts",
&[("Cookie", &petra), ("X-Ianitor-UI", "1")],
Some(
json!({"host": {"hostname": "wiki.example.test", "upstreams": ["http://10.0.0.2:80"]}}),
),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
// A member records their Tessera root; the list shows its match code.
let root = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc";
let r = req(
api,
"PUT",
"/api/v1/team/me/root",
&[("Cookie", &petra), ("X-Ianitor-UI", "1")],
Some(json!({"tessera_root": root})),
)
.await;
assert_eq!(r.status, 200, "{}", r.text);
let team = req(api, "GET", "/api/v1/team", &[("Cookie", &mark)], None).await;
let p = team.json["members"]
.as_array()
.unwrap()
.iter()
.find(|m| m["name"] == "Petra")
.unwrap()
.clone();
assert_eq!(p["match_code"], "016 810");
// Removing Petra signs her out; a forged cookie gets nothing; the last admin stays.
let id = p["id"].as_str().unwrap();
let r = req(
api,
"DELETE",
&format!("/api/v1/team/members/{id}"),
&[("Cookie", &mark), ("X-Ianitor-UI", "1")],
None,
)
.await;
assert_eq!(r.status, 200, "{}", r.text);
let r = req(api, "GET", "/api/v1/overview", &[("Cookie", &petra)], None).await;
assert_eq!(r.status, 401, "{}", r.text);
let r = req(
api,
"GET",
"/api/v1/overview",
&[("Cookie", "__Host-ianitor=ise_forged")],
None,
)
.await;
assert_eq!(r.status, 401);
let me = team.json["members"]
.as_array()
.unwrap()
.iter()
.find(|m| m["name"] == "Mark")
.unwrap()["id"]
.as_str()
.unwrap()
.to_owned();
let r = req(
api,
"DELETE",
&format!("/api/v1/team/members/{me}"),
&[("Cookie", &mark), ("X-Ianitor-UI", "1")],
None,
)
.await;
assert_eq!(r.status, 409, "{}", r.text);
assert_eq!(r.json["error"]["code"], "team.last_admin");
// Signing out ends this browser's session.
let r = req(
api,
"POST",
"/api/v1/session/end",
&[("Cookie", &mark), ("X-Ianitor-UI", "1")],
None,
)
.await;
assert_eq!(r.status, 200, "{}", r.text);
let r = req(api, "GET", "/api/v1/overview", &[("Cookie", &mark)], None).await;
assert_eq!(r.status, 401);
}
+19 -2
View File
@@ -109,9 +109,13 @@ fn check_options(o: &CompileOptions) -> Result<(), CompileError> {
Ok(())
}
/// Paths end up inside JSON strings and Caddy `{file.*}` placeholders.
/// Paths end up inside JSON strings and Caddy `{file.*}` placeholders. Absolute: `/…` on
/// Linux, or a drive path with forward slashes on Windows (`C:/ProgramData/Ianitor/…`, which
/// Caddy and Go read as is; control writes backslashes as `/`, see [`windows_path`]).
fn check_path(p: &str) -> Result<(), &'static str> {
if !p.starts_with('/') {
let drive =
p.len() >= 3 && p.as_bytes()[0].is_ascii_alphabetic() && &p.as_bytes()[1..3] == b":/";
if !p.starts_with('/') && !drive {
return Err("it must be an absolute path");
}
if p.len() > 1024 {
@@ -126,6 +130,19 @@ fn check_path(p: &str) -> Result<(), &'static str> {
Ok(())
}
/// A Windows path as the compilers take it: `C:\ProgramData\Ianitor` → `C:/ProgramData/Ianitor`.
/// Anything that is not a drive path is returned unchanged (and a Linux path with a backslash
/// is still refused by the option check).
pub fn windows_path(p: &str) -> String {
let b = p.as_bytes();
if b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b[2] == b'\\' || b[2] == b'/')
{
p.replace('\\', "/")
} else {
p.to_owned()
}
}
/// Identity headers never accepted from clients on forward-auth hosts: Authelia's four, then
/// any other configured copy header (case-insensitive, no duplicates).
fn strip_headers(fa: &crate::ForwardAuth) -> Vec<String> {
+6 -1
View File
@@ -178,6 +178,8 @@ pub enum ValidationError {
BadForwardAuth { file: String, reason: &'static str },
#[error("{file}: acme is not usable: {reason}")]
BadAcme { file: String, reason: &'static str },
#[error("{file}: the preview is not usable: {reason}")]
BadPreview { file: String, reason: String },
}
fn line_suffix(line: Option<usize>) -> String {
@@ -217,7 +219,8 @@ impl ValidationError {
| E::ForwardAuthNotConfigured { file }
| E::ProofWithoutSignIn { file }
| E::BadForwardAuth { file, .. }
| E::BadAcme { file, .. } => file,
| E::BadAcme { file, .. }
| E::BadPreview { file, .. } => file,
E::DuplicateHostname { second, .. } => second,
}
}
@@ -304,6 +307,7 @@ impl ValidationError {
E::ProofWithoutSignIn { .. } => "host.header.proof",
E::BadForwardAuth { .. } => "site.forward_auth",
E::BadAcme { .. } => "site.acme",
E::BadPreview { .. } => "host.preview",
}
}
@@ -338,6 +342,7 @@ impl ValidationError {
E::BadHealthCheck { .. } => Some("health_check.path".into()),
E::ForwardAuthNotConfigured { .. } => Some("auth".into()),
E::ProofWithoutSignIn { .. } => Some("auth".into()),
E::BadPreview { .. } => Some("preview".into()),
_ => None,
}
}
+2 -1
View File
@@ -13,6 +13,7 @@ pub mod edge_config;
mod error;
mod model;
pub mod pki;
pub mod preview;
pub mod routes;
pub mod share;
pub mod time;
@@ -22,7 +23,7 @@ pub use error::{ValidationError, ValidationErrors};
pub use model::{
AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue,
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING, MAX_FILE_BYTES,
MAX_UPSTREAMS, Model, Scheme, SecretName, Site, TlsMode, UI_PROOF_SECRET, Upstream,
MAX_UPSTREAMS, Model, Preview, Scheme, SecretName, Site, TlsMode, UI_PROOF_SECRET, Upstream,
UpstreamHost,
};
pub use validate::{SourceFile, load};
+14
View File
@@ -173,6 +173,20 @@ pub struct Host {
pub access_log: AccessLog,
/// Visitors must present a Domi device certificate (mTLS) that is on the allow list.
pub device_certs: bool,
/// Set when this host is a branch preview (see [`crate::preview`]). Control uses it; the
/// compilers never read it.
pub preview: Option<Preview>,
}
/// The `[preview]` table of a preview host: which branch of which project it shows, and
/// until when. Its host name's first label is always `preview::label(project, branch)`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Preview {
pub project: String,
pub branch: String,
/// Unix seconds; control removes the host after this.
pub expires_at: u64,
}
/// The forward-auth endpoint (Authelia's `/api/authz/forward-auth`).
+2 -2
View File
@@ -32,8 +32,8 @@ use ring::rand::{SecureRandom, SystemRandom};
pub use domi_pki::{
CertInfo, DEVICE_DAYS, EkuInfo, INTERMEDIATE_DAYS, INTERMEDIATE_OPENSSL_EXT, KeyPair,
KeyUsageInfo, ORG, ROOT_CN, ROOT_DAYS, SERVER_DAYS, SERVER_RENEW_DAYS, der_to_pem,
match_code, openssl_sign_command, sha256_hex,
KeyUsageInfo, ORG, ROOT_CN, ROOT_DAYS, SERVER_DAYS, SERVER_RENEW_DAYS, der_to_pem, match_code,
openssl_sign_command, sha256_hex,
};
/// Subject CN of the intermediate. Signers refuse a CSR whose CN does not start with this.
+149
View File
@@ -0,0 +1,149 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Branch previews (Fabrica docs/32_coherence.md, T4): every branch of a project gets the host
//! `<branch>--<project>.<preview domain>`. Branch and project names come from a git host and
//! are hostile input; this module turns them into one safe DNS label.
//!
//! The label is `<branch part>--<project part>`, at most 62 characters:
//! - each part is the name lowercased, with every run of other characters than `a-z0-9`
//! turned into one `-`, trimmed of dashes (the project part uses only the repository name,
//! the text after the last `/` or `:`);
//! - when that lost anything (case, a character, the owner, length) the part gets `-` and 6
//! hex digits of SHA-256 of the whole original name, so two names that would read the same
//! never share a host (`feature/login` and `feature-login`, `Main` and `main`);
//! - a branch part shorter than 3 characters is also suffixed, so `--` never lands in the
//! label's positions 3 and 4 (reserved for IDNA; Let's Encrypt refuses such labels).
//!
//! Parts never contain `--`, so the separator is unambiguous. Names that cannot be a git
//! branch or a Fabrica project (control characters, too long, empty) are refused, not mangled.
use std::fmt;
/// Longest branch name accepted, in bytes (git allows more; no real branch is near this).
pub const MAX_BRANCH_BYTES: usize = 255;
/// Longest project name accepted (Fabrica's `project` field).
pub const MAX_PROJECT_CHARS: usize = 128;
/// The branch part of the label is at most this long.
pub const BRANCH_PART: usize = 40;
/// The project part of the label is at most this long.
pub const PROJECT_PART: usize = 20;
const HASH_HEX: usize = 6;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PreviewError {
Branch(&'static str),
Project(&'static str),
Domain(String),
}
impl fmt::Display for PreviewError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PreviewError::Branch(r) => write!(f, "the branch name {r}"),
PreviewError::Project(r) => write!(f, "the project name {r}"),
PreviewError::Domain(r) => write!(f, "the preview host name is not usable: {r}"),
}
}
}
impl std::error::Error for PreviewError {}
fn check_branch(b: &str) -> Result<(), PreviewError> {
if b.is_empty() {
return Err(PreviewError::Branch("is empty"));
}
if b.len() > MAX_BRANCH_BYTES {
return Err(PreviewError::Branch("is longer than 255 bytes"));
}
if b.chars().any(char::is_control) {
return Err(PreviewError::Branch("contains a control character"));
}
Ok(())
}
fn check_project(p: &str) -> Result<(), PreviewError> {
if p.is_empty() || p.chars().count() > MAX_PROJECT_CHARS {
return Err(PreviewError::Project("must be 1 to 128 characters"));
}
if !p
.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"._/:-".contains(&c))
{
return Err(PreviewError::Project(
"may only use letters, digits, '.', '_', '/', ':' and '-'",
));
}
if repo_name(p).bytes().all(|c| !c.is_ascii_alphanumeric()) {
return Err(PreviewError::Project("has no repository name"));
}
Ok(())
}
/// The repository name: what follows the last `/` or `:` (`github:acme/web` → `web`).
fn repo_name(p: &str) -> &str {
p.rsplit(['/', ':']).next().unwrap_or(p)
}
/// Lowercase LDH with dash runs collapsed and trimmed.
fn slug(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
if c.is_ascii_alphanumeric() {
out.push(c.to_ascii_lowercase());
} else if !out.is_empty() && !out.ends_with('-') {
out.push('-');
}
}
while out.ends_with('-') {
out.pop();
}
out
}
fn short_hash(s: &str) -> String {
let d = ring::digest::digest(&ring::digest::SHA256, s.as_bytes());
let mut h = String::with_capacity(HASH_HEX);
for b in d.as_ref().iter().take(HASH_HEX / 2) {
h.push_str(&format!("{b:02x}"));
}
h
}
/// `slug` cut to `max`, with the hash of `original` appended when the slug is not exactly
/// `shown` or is shorter than `min`.
fn part(shown: &str, original: &str, max: usize, min: usize) -> String {
let s = slug(shown);
if s == shown && s.len() <= max && s.len() >= min && original == shown {
return s;
}
let keep = max - HASH_HEX - 1;
let mut cut: String = s.chars().take(keep).collect();
while cut.ends_with('-') {
cut.pop();
}
let h = short_hash(original);
if cut.is_empty() {
h
} else {
format!("{cut}-{h}")
}
}
/// The DNS label of a branch's preview.
pub fn label(project: &str, branch: &str) -> Result<String, PreviewError> {
check_branch(branch)?;
check_project(project)?;
let b = part(branch, branch, BRANCH_PART, 3);
let p = part(repo_name(project), project, PROJECT_PART, 1);
Ok(format!("{b}--{p}"))
}
/// The preview's host name under `domain`, checked like any host name.
pub fn hostname(project: &str, branch: &str, domain: &str) -> Result<String, PreviewError> {
crate::validate::check_hostname(domain).map_err(|r| PreviewError::Domain(r.to_owned()))?;
let h = format!("{}.{domain}", label(project, branch)?);
crate::validate::check_hostname(&h).map_err(|r| PreviewError::Domain(r.to_owned()))?;
Ok(h)
}
+42 -1
View File
@@ -15,7 +15,7 @@ use crate::error::{ValidationError as E, ValidationErrors, reason as r};
use crate::model::{
AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue,
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, MAX_FILE_BYTES, MAX_UPSTREAMS, Model,
Scheme, SecretName, Site, TlsMode, UI_PROOF_SECRET, Upstream, UpstreamHost,
Preview, Scheme, SecretName, Site, TlsMode, UI_PROOF_SECRET, Upstream, UpstreamHost,
};
/// One route file handed in by the caller (core does no I/O).
@@ -129,6 +129,16 @@ struct RawHost {
request_headers: Vec<RawRule>,
#[serde(default)]
response_headers: Vec<RawRule>,
preview: Option<RawPreview>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawPreview {
project: String,
branch: String,
/// Signed so that 0 and negative numbers get a typed error instead of a serde one.
expires_at: i64,
}
// ------------------------------------------------------------------ entry point
@@ -511,6 +521,36 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
errors.push(E::ProofWithoutSignIn { file: f() });
}
let preview = raw.preview.and_then(|p| {
let bad = |reason: String| E::BadPreview { file: f(), reason };
let expires_at = match u64::try_from(p.expires_at) {
Ok(e) if e > 0 => e,
_ => {
errors.push(bad("expires_at must be a time in Unix seconds".into()));
return None;
}
};
match crate::preview::label(&p.project, &p.branch) {
Ok(label) => {
if raw.hostname.split('.').next() != Some(label.as_str()) {
errors.push(bad(format!(
"the host name of this branch's preview must start with \"{label}.\""
)));
return None;
}
}
Err(e) => {
errors.push(bad(e.to_string()));
return None;
}
}
Some(Preview {
project: p.project,
branch: p.branch,
expires_at,
})
});
if errors.len() != before {
return None;
}
@@ -533,6 +573,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
RawAccessLog::Off => AccessLog::Off,
RawAccessLog::Truncated => AccessLog::Truncated,
},
preview,
})
}
+301
View File
@@ -0,0 +1,301 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Preview host names (T4, written before the code): `<branch>--<project>.<preview domain>`.
//! Branch and project names come from a git host and are hostile: every one must map to a
//! safe DNS label, two different branches must never share a host, and the preview table of
//! a host file must agree with its host name.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::collections::BTreeMap;
use ianitor_core::preview::{self, PreviewError};
use ianitor_core::{SourceFile, load};
/// A label a public CA and every resolver accept: LDH, 1–63, no leading or trailing dash, and
/// no `--` in positions 3 and 4 (reserved for IDNA A-labels, refused by Let's Encrypt).
fn assert_safe_label(l: &str) {
assert!(!l.is_empty() && l.len() <= 63, "length of {l:?}");
assert!(
l.bytes()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-'),
"{l:?} is not lowercase LDH"
);
assert!(
!l.starts_with('-') && !l.ends_with('-'),
"{l:?} has an edge dash"
);
assert!(
l.get(2..4) != Some("--"),
"{l:?} has -- in positions 3 and 4"
);
}
#[test]
fn plain_names_stay_readable() {
assert_eq!(
preview::label("mnovak/Arca", "main").unwrap(),
"main--arca-4a93cc"
);
assert_eq!(preview::label("shop", "fix-42").unwrap(), "fix-42--shop");
assert_eq!(
preview::hostname("shop", "fix-42", "preview.example.org").unwrap(),
"fix-42--shop.preview.example.org"
);
}
#[test]
fn hostile_branch_names_map_to_safe_labels() {
let long = "a".repeat(250);
let dots = "x.".repeat(100);
let hostile: &[&str] = &[
"main",
"Main",
"feature/login",
"feature//login",
"feature.login",
"..",
"...hidden",
"v1.2.3",
"ab",
"xn",
"a",
"-",
"--",
"_",
"fix/ünïcødé",
"日本語のブランチ",
"emoji-🦊-branch",
"Ⅻ-roman",
"fi-ligature",
"\u{200b}zero-width",
"right-to-left-\u{202e}gnp.exe",
"has space and ~^:?*[",
"semi;colon&amp<script>",
"../../etc/passwd",
"%2e%2e%2f",
"CAPS_AND_UNDERSCORES",
&long,
&dots,
"xn--80ak6aa92e",
"a--b",
"end-",
"-start",
];
for b in hostile {
let l = preview::label("team/web-app", b).unwrap_or_else(|e| panic!("{b:?}: {e}"));
assert_safe_label(&l);
let host = preview::hostname("team/web-app", b, "preview.example.org").unwrap();
assert!(host.ends_with(".preview.example.org"));
// The host is a valid host-file name: core accepts a preview file for it.
let text = preview_file(&host, "team/web-app", b);
load_one(&host, &text).unwrap_or_else(|e| panic!("{b:?}: {e}"));
}
}
#[test]
fn different_branches_never_share_a_label() {
// Pairs a naive slug would merge.
let pairs = [
("feature/login", "feature-login"),
("feature.login", "feature-login"),
("Main", "main"),
("fix/ü", "fix/ö"),
("a/b", "a_b"),
("x", "X"),
];
for (a, b) in pairs {
assert_ne!(
preview::label("p", a).unwrap(),
preview::label("p", b).unwrap(),
"{a:?} and {b:?}"
);
}
// Long branches that differ only after the cut.
let a = format!("{}-one", "release".repeat(10));
let b = format!("{}-two", "release".repeat(10));
assert_ne!(
preview::label("p", &a).unwrap(),
preview::label("p", &b).unwrap()
);
// And a broad sweep: many similar names, all distinct.
let mut seen = BTreeMap::new();
for i in 0..2000 {
for b in [
format!("feature/{i}"),
format!("feature-{i}"),
format!("Feature/{i}"),
] {
let l = preview::label("p", &b).unwrap();
assert_safe_label(&l);
if let Some(prev) = seen.insert(l.clone(), b.clone()) {
panic!("{prev:?} and {b:?} both map to {l}");
}
}
}
}
#[test]
fn same_input_same_label() {
for b in ["main", "feature/ünï", "x".repeat(300).as_str()] {
if b.len() > preview::MAX_BRANCH_BYTES {
continue;
}
assert_eq!(
preview::label("p/q", b).unwrap(),
preview::label("p/q", b).unwrap()
);
}
}
#[test]
fn unusable_names_are_refused_not_mangled() {
let too_long = "b".repeat(preview::MAX_BRANCH_BYTES + 1);
let bad_branches = [
"",
"tab\there",
"with\nnewline",
"nul\0byte",
"bell\u{7}",
too_long.as_str(),
];
for b in bad_branches {
assert!(
matches!(preview::label("p", b), Err(PreviewError::Branch(_))),
"{b:?}"
);
}
let bad_projects = [
"",
"/",
"owner/",
"has space",
"semi;colon",
"ü/name",
&"p".repeat(129),
];
for p in bad_projects {
assert!(
matches!(preview::label(p, "main"), Err(PreviewError::Project(_))),
"{p:?}"
);
}
// A preview domain must be a hostname, and the whole name must fit DNS.
assert!(matches!(
preview::hostname("p", "main", "bad domain"),
Err(PreviewError::Domain(_))
));
let deep = format!("{}.example.org", "d".repeat(60) + &".d".repeat(90));
assert!(preview::hostname("p", "main", &deep).is_err());
}
#[test]
fn project_names_from_every_git_host_work() {
for p in [
"mnovak/Arca",
"github:acme/web",
"gitlab-work:group/sub/app",
"app",
"Org.Name/repo.js",
] {
let l = preview::label(p, "main").unwrap();
assert_safe_label(&l);
}
// Same repo name under two owners: different hosts.
assert_ne!(
preview::label("alice/app", "main").unwrap(),
preview::label("bob/app", "main").unwrap()
);
}
fn preview_file(host: &str, project: &str, branch: &str) -> String {
let mut t = toml::Table::new();
t.insert("hostname".into(), host.into());
t.insert(
"upstreams".into(),
toml::Value::Array(vec!["http://10.0.0.5:8080".into()]),
);
t.insert("tls".into(), "domi".into());
let mut p = toml::Table::new();
p.insert("project".into(), project.into());
p.insert("branch".into(), branch.into());
p.insert("expires_at".into(), toml::Value::Integer(1_900_000_000));
t.insert("preview".into(), toml::Value::Table(p));
toml::to_string(&t).unwrap()
}
fn load_one(host: &str, text: &str) -> Result<ianitor_core::Model, ianitor_core::ValidationErrors> {
let name = format!("hosts/{host}.toml");
load(
&SourceFile {
name: "ianitor.toml",
contents: "",
},
&[SourceFile {
name: &name,
contents: text,
}],
)
}
#[test]
fn the_model_carries_the_preview() {
let host = preview::hostname("shop", "fix-42", "pv.example.org").unwrap();
let m = load_one(&host, &preview_file(&host, "shop", "fix-42")).unwrap();
let p = m.hosts()[0].preview.as_ref().expect("a preview");
assert_eq!(
(p.project.as_str(), p.branch.as_str(), p.expires_at),
("shop", "fix-42", 1_900_000_000)
);
}
#[test]
fn a_preview_table_must_match_its_host_name() {
// A file cannot claim to be another branch's preview, or name a host its label does not.
let host = preview::hostname("shop", "fix-42", "pv.example.org").unwrap();
let e = load_one(&host, &preview_file(&host, "shop", "other")).unwrap_err();
assert!(e.to_string().contains("preview"), "{e}");
let e = load_one(
"plain.pv.example.org",
&preview_file("plain.pv.example.org", "shop", "fix-42"),
)
.unwrap_err();
assert!(e.to_string().contains("preview"), "{e}");
// Unknown keys and bad values in the table are refused like everywhere else.
let text = preview_file(&host, "shop", "fix-42").replace("expires_at", "expires");
assert!(load_one(&host, &text).is_err());
let text = preview_file(&host, "shop", "fix-42").replace("1900000000", "0");
assert!(load_one(&host, &text).is_err());
}
#[test]
fn compilers_ignore_the_preview_table() {
// The preview metadata never reaches an engine: both outputs equal those of the same
// host without it.
let host = preview::hostname("shop", "fix-42", "pv.example.org").unwrap();
let with = load_one(&host, &preview_file(&host, "shop", "fix-42")).unwrap();
let text = preview_file(&host, "shop", "fix-42");
let without_text: String = text.split("[preview]").next().unwrap().to_owned();
let without = load_one(&host, &without_text).unwrap();
let o = ianitor_core::compile::CompileOptions {
http_listen: "0.0.0.0:80".parse().unwrap(),
https_listen: "0.0.0.0:443".parse().unwrap(),
cert_dir: "/var/lib/ianitor/certs".into(),
state_dir: "/var/lib/ianitor".into(),
access_log: "/var/log/ianitor/access.log".into(),
caddy_credentials_dir: "/run/credentials/caddy-fallback.service".into(),
caddy_admin: None,
caddy_admin_socket: None,
trusted_proxies: Vec::new(),
};
assert_eq!(
ianitor_core::compile::edge(&with, &o).unwrap(),
ianitor_core::compile::edge(&without, &o).unwrap()
);
assert_eq!(
ianitor_core::compile::caddy(&with, &o).unwrap(),
ianitor_core::compile::caddy(&without, &o).unwrap()
);
}
+9
View File
@@ -180,6 +180,15 @@ pub fn server(shared: Arc<Shared>, opts: &Options) -> Result<Server, EdgeError>
Ok(server)
}
/// For running edge inside a test process on Windows (the differential suite with Windows
/// paths, T4). Pingora on Windows stops only on Ctrl-C, so `stop` is ignored and the server
/// lives until the test process ends. Ianitor does not ship edge on Windows (Caddy mode).
#[cfg(windows)]
pub fn run_until(server: Server, stop: tokio::sync::oneshot::Receiver<()>) {
drop(stop);
server.run(pingora::server::RunArgs::default());
}
/// Run until `stop` resolves (or is dropped). For running edge inside a test process.
#[cfg(unix)]
pub fn run_until(server: Server, stop: tokio::sync::oneshot::Receiver<()>) {
+13 -8
View File
@@ -391,15 +391,20 @@ impl ProxyHttp for EdgeProxy {
ctx: &mut Ctx,
) -> Result<()> {
let Some(host) = &ctx.host else { return Ok(()) };
apply(&host.response_ops, |n, v| {
match v {
Some(v) => resp.insert_header(n.clone(), v.clone())?,
None => {
resp.remove_header(n);
// Response rules are for HTTP answers, not the switch to a websocket: Caddy leaves a
// `101` as the upstream sent it, and so does edge (found by the T4 preview fixture in
// the differential suite: `X-Robots-Tag` on a websocket upgrade).
if resp.status.as_u16() != 101 {
apply(&host.response_ops, |n, v| {
match v {
Some(v) => resp.insert_header(n.clone(), v.clone())?,
None => {
resp.remove_header(n);
}
}
}
Ok(())
})?;
Ok(())
})?;
}
// Defence in depth: never hand a secret back to a client, even if the upstream echoes it.
if !host.secret_values.is_empty() {
let leaking: Vec<http::HeaderName> = resp
+110
View File
@@ -0,0 +1,110 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
#
# Ianitor Domi on Docker (T4): one image with both programs; deploy/docker/compose.yaml runs
# it twice (edge, and control in edge's network so the API stays on loopback).
#
# docker build -f deploy/docker/Dockerfile -t ianitor . the image
# docker build -f deploy/docker/Dockerfile --target ci -t ianitor-ci . Linux test runner
#
# Build context: the repository (see .dockerignore: no target/, node_modules/ or .git/).
ARG RUST=1.99-bookworm
ARG CADDY=2.11.7
ARG PEBBLE=v2.6.0
# ------------------------------------------------------------------ Rust toolchain + native deps
FROM rust:${RUST} AS rust
RUN apt-get update \
&& apt-get install -y --no-install-recommends cmake git ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# ------------------------------------------------------------------ Caddy (the fallback, and the diff suite's other engine)
FROM debian:bookworm-slim AS caddy
ARG CADDY
RUN apt-get update && apt-get install -y --no-install-recommends curl ca-certificates \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /caddy
RUN curl -fsSLo caddy.tar.gz "https://github.com/caddyserver/caddy/releases/download/v${CADDY}/caddy_${CADDY}_linux_amd64.tar.gz" \
&& curl -fsSLo sums.txt "https://github.com/caddyserver/caddy/releases/download/v${CADDY}/caddy_${CADDY}_checksums.txt" \
&& grep " caddy_${CADDY}_linux_amd64.tar.gz\$" sums.txt | sed "s/caddy_${CADDY}_linux_amd64.tar.gz/caddy.tar.gz/" | sha512sum -c - \
&& tar -xzf caddy.tar.gz caddy && ./caddy version
# ------------------------------------------------------------------ the Linux test runner (layers 1–3 in CI)
FROM rust AS ci
ARG PEBBLE
RUN apt-get update && apt-get install -y --no-install-recommends curl unzip \
&& rm -rf /var/lib/apt/lists/*
COPY --from=caddy /caddy/caddy /usr/local/bin/caddy
RUN set -e; cd /tmp; for b in pebble pebble-challtestsrv; do \
curl -fsSLo "$b.tar.gz" "https://github.com/letsencrypt/pebble/releases/download/${PEBBLE}/$b-linux-amd64.tar.gz"; \
mkdir "$b.d"; tar -xzf "$b.tar.gz" -C "$b.d"; \
install -m 0755 "$(find "$b.d" -type f -name "$b" | head -n1)" "/usr/local/bin/$b"; \
done; rm -rf /tmp/*; pebble -version || true
ENV CARGO_TARGET_DIR=/target
WORKDIR /src
COPY . .
CMD ["cargo", "test", "--workspace", "--locked"]
# ------------------------------------------------------------------ release build
FROM rust AS build
# Two jobs: the default (every core) runs Docker Desktop out of memory on Pingora's crates.
ARG JOBS=2
ENV CARGO_BUILD_JOBS=${JOBS}
WORKDIR /src
COPY . .
RUN cargo build --release --locked -p ianitor-edge \
&& cargo build --release --locked -p ianitor-control --no-default-features \
&& strip target/release/ianitor-edge target/release/ianitor-control
FROM node:22-bookworm-slim AS web
RUN corepack enable && corepack prepare pnpm@10.28.0 --activate
WORKDIR /src
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY apps/web/package.json apps/web/package.json
COPY packages/ui/package.json packages/ui/package.json
RUN pnpm install --frozen-lockfile
COPY apps/web apps/web
COPY packages/ui packages/ui
RUN pnpm --filter web build
# ------------------------------------------------------------------ the Linux release files
# docker build -f deploy/docker/Dockerfile --target dist --output type=local,dest=target/dist .
FROM debian:bookworm-slim AS dist-files
WORKDIR /out
COPY --from=build /src/target/release/ianitor-edge /src/target/release/ianitor-control /tmp/bin/
COPY --from=web /src/apps/web/dist /tmp/web
COPY deploy/linux /tmp/linux
COPY Cargo.toml /tmp/Cargo.toml
RUN set -e; v=$(sed -n 's/^version = "\(.*\)"/\1/p' /tmp/Cargo.toml | head -n1); d="ianitor-$v"; \
mkdir -p "$d/bin" "$d/lib"; cp /tmp/bin/* "$d/bin/"; cp -r /tmp/web "$d/web"; \
cp /tmp/linux/setup.sh /tmp/linux/*.service "$d/lib/"; \
tar --owner=0 --group=0 --numeric-owner --sort=name --mtime=@0 -czf "ianitor-$v-linux-x86_64.tar.gz" "$d"; \
sed "s/__VERSION__/$v/" /tmp/linux/install.sh > install.sh; rm -rf "$d"
FROM scratch AS dist
COPY --from=dist-files /out/ /
# ------------------------------------------------------------------ the image
FROM debian:bookworm-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends git ca-certificates tini \
&& rm -rf /var/lib/apt/lists/* \
&& useradd --system --uid 10001 --home-dir /var/lib/ianitor --shell /usr/sbin/nologin ianitor \
&& mkdir -p /var/lib/ianitor /run/ianitor /usr/share/ianitor \
&& chown ianitor:ianitor /var/lib/ianitor /run/ianitor
COPY --from=build /src/target/release/ianitor-edge /src/target/release/ianitor-control /usr/local/bin/
COPY --from=web /src/apps/web/dist /usr/share/ianitor/web
COPY deploy/docker/entrypoint.sh /usr/local/bin/ianitor-entrypoint
COPY deploy/linux/setup.sh /usr/local/lib/ianitor/setup.sh
LABEL org.opencontainers.image.title="Ianitor Domi" \
org.opencontainers.image.description="Reverse proxy on Pingora with the Domi CA, a web UI and branch previews for Fabrica" \
org.opencontainers.image.licenses="MPL-2.0" \
org.opencontainers.image.source="https://gitea.marek-novak.cz/mnovak/Ianitor"
USER ianitor
VOLUME ["/var/lib/ianitor"]
# Docker lets an unprivileged user bind 80 and 443 inside the container
# (net.ipv4.ip_unprivileged_port_start = 0 by default since Docker 20.10).
EXPOSE 80 443
ENTRYPOINT ["tini", "--", "/usr/local/bin/ianitor-entrypoint"]
CMD ["edge"]
+57
View File
@@ -0,0 +1,57 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
#
# Ianitor Domi on Docker (T4). Set the variables in .env next to this file (see
# deploy/linux/setup.sh for all of them), then:
#
# docker compose up -d && docker compose exec control ianitor-entrypoint setup-link
#
# and open the link it prints. Edge serves 80/443; control runs in edge's network namespace,
# so its API stays on 127.0.0.1 and only edge (the admin host) reaches it.
name: ianitor
x-common: &common
image: ${IANITOR_IMAGE:-ianitor:latest}
restart: unless-stopped
environment: &env
IANITOR_LOG: info
CREDENTIALS_DIRECTORY: /var/lib/ianitor/credentials
IANITOR_ADMIN_HOST: ${IANITOR_ADMIN_HOST:?set IANITOR_ADMIN_HOST in .env (the web UI's address)}
IANITOR_TLS: ${IANITOR_TLS:-letsencrypt}
IANITOR_DOMI_ROOT: ${IANITOR_DOMI_ROOT:-}
IANITOR_PREVIEW_DOMAIN: ${IANITOR_PREVIEW_DOMAIN:-}
IANITOR_PREVIEW_UPSTREAMS: ${IANITOR_PREVIEW_UPSTREAMS:-}
IANITOR_PREVIEW_TLS: ${IANITOR_PREVIEW_TLS:-}
IANITOR_ROUTES_REMOTE: ${IANITOR_ROUTES_REMOTE:-}
IANITOR_ROUTES_HOST: ${IANITOR_ROUTES_HOST:-gitea}
volumes:
- state:/var/lib/ianitor
- run:/run/ianitor
read_only: true
tmpfs: [/tmp]
cap_drop: [ALL]
security_opt: ["no-new-privileges:true"]
services:
edge:
<<: *common
command: ["edge"]
ports:
- "${IANITOR_HTTP_PORT:-80}:80"
- "${IANITOR_HTTPS_PORT:-443}:443"
# Unprivileged port binding inside the container (Docker's default since 20.10, set here
# so a daemon with another default works too).
sysctls:
net.ipv4.ip_unprivileged_port_start: "0"
control:
<<: *common
command: ["control"]
network_mode: "service:edge"
depends_on: [edge]
volumes:
state:
run:
+39
View File
@@ -0,0 +1,39 @@
#!/bin/sh
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
#
# The image's entrypoint (deploy/docker/compose.yaml runs it twice):
# control write control.toml from the environment once (deploy/linux/setup.sh), then
# run the control plane on 127.0.0.1:7878 (in edge's network namespace)
# edge wait for control's first edge.json, then serve 80 and 443
# setup-link print the first admin's sign-in link
# <anything> run it (ianitor-control token create ..., a shell)
set -eu
ROOT=/var/lib/ianitor
export IANITOR_ROOT=$ROOT IANITOR_CONFIG=$ROOT/control.toml IANITOR_EDGE_SOCKET=/run/ianitor/admin.sock
case "${1:-edge}" in
control)
sh /usr/local/lib/ianitor/setup.sh
exec ianitor-control --config "$IANITOR_CONFIG"
;;
edge)
i=0
while [ ! -s "$ROOT/edge/edge.json" ]; do
i=$((i + 1))
[ $i -le 120 ] || { echo "edge: no edge.json from control after 120 s" >&2; exit 1; }
sleep 1
done
exec ianitor-edge --config "$ROOT/edge/edge.json" \
--admin-socket /run/ianitor/admin.sock \
--share-revocations "$ROOT/edge/share-revocations.json"
;;
setup-link)
exec ianitor-control team setup-link --config "$IANITOR_CONFIG"
;;
*)
exec "$@"
;;
esac
+34
View File
@@ -0,0 +1,34 @@
# Ianitor control: API and web UI on 127.0.0.1:7878 (deploy/linux/install.sh writes this).
[Unit]
Description=Ianitor control (API and UI on loopback)
After=network-online.target
Wants=network-online.target
[Service]
User=ianitor
Group=ianitor
Environment=IANITOR_LOG=info
ExecStart=/usr/local/bin/ianitor-control --config /etc/ianitor/control.toml
# After every stop, a crash included: a trial still loaded into Caddy goes back at once.
ExecStopPost=/usr/local/bin/ianitor-control caddy-revert --config /etc/ianitor/control.toml
Restart=on-failure
RestartSec=2
ReadWritePaths=/var/lib/ianitor
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
RestrictNamespaces=yes
LockPersonality=yes
MemoryDenyWriteExecute=yes
SystemCallArchitectures=native
CapabilityBoundingSet=
UMask=0027
[Install]
WantedBy=multi-user.target
+39
View File
@@ -0,0 +1,39 @@
# Ianitor edge: the Pingora data plane on 80 and 443 (deploy/linux/install.sh writes this).
# Header-rule secrets: add one LoadCredential=<name>:/var/lib/ianitor/credentials/<name> each
# (systemctl edit ianitor-edge).
[Unit]
Description=Ianitor edge (Pingora)
After=network-online.target ianitor-control.service
Wants=network-online.target
StartLimitIntervalSec=0
[Service]
User=ianitor-edge
Group=ianitor
Environment=IANITOR_LOG=info
ExecStart=/usr/local/bin/ianitor-edge --config /var/lib/ianitor/edge/edge.json --admin-socket /run/ianitor-edge/admin.sock --share-revocations /var/lib/ianitor/edge/share-revocations.json
LoadCredential=share-link-key:/var/lib/ianitor/credentials/share-link-key
RuntimeDirectory=ianitor-edge
RuntimeDirectoryMode=0750
ReadWritePaths=/var/lib/ianitor/edge-state /var/lib/ianitor/logs
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
# The first start may come before control has written edge.json.
Restart=always
RestartSec=2
LimitNOFILE=65536
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
RestrictNamespaces=yes
LockPersonality=yes
SystemCallArchitectures=native
[Install]
WantedBy=multi-user.target
+81
View File
@@ -0,0 +1,81 @@
#!/bin/sh
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
#
# Ianitor Domi on plain Linux with systemd (T4), in one line:
#
# curl -fsSL https://gitea.marek-novak.cz/mnovak/Ianitor/releases/download/vX.Y.Z/install.sh \
# | sudo IANITOR_ADMIN_HOST=ianitor.example.org sh
#
# It downloads the release tarball and SHA256SUMS of the same release, checks the sum, installs
# the binaries, the web UI and two systemd units (ianitor-control, ianitor-edge), writes
# /etc/ianitor/control.toml once (deploy/linux/setup.sh: every IANITOR_* variable), starts both,
# and prints the first admin's sign-in link. Running it again upgrades the binaries and keeps
# the config and the state. IANITOR_TARBALL=<file> installs a local tarball instead (no download).
set -eu
VERSION="${IANITOR_VERSION:-__VERSION__}"
BASE="${IANITOR_RELEASES:-https://gitea.marek-novak.cz/mnovak/Ianitor/releases/download}/v$VERSION"
ARCH="$(uname -m)"
NAME="ianitor-$VERSION-linux-$ARCH.tar.gz"
die() { echo "ianitor install: $*" >&2; exit 1; }
[ "$(id -u)" = 0 ] || die "run it as root (sudo)"
command -v systemctl >/dev/null || die "this installer needs systemd; use the Docker image otherwise (deploy/docker)"
command -v git >/dev/null || die "install git first (apt install git / dnf install git)"
[ "$ARCH" = x86_64 ] || die "only x86_64 builds are published so far"
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT
if [ -n "${IANITOR_TARBALL:-}" ]; then
cp "$IANITOR_TARBALL" "$work/$NAME"
else
command -v curl >/dev/null || die "install curl first"
curl -fsSLo "$work/$NAME" "$BASE/$NAME"
curl -fsSLo "$work/SHA256SUMS" "$BASE/SHA256SUMS"
(cd "$work" && grep " $NAME\$" SHA256SUMS | sha256sum -c -) || die "the download does not match SHA256SUMS"
fi
tar -xzf "$work/$NAME" -C "$work"
src="$work/ianitor-$VERSION"
[ -x "$src/bin/ianitor-control" ] || die "the tarball has no bin/ianitor-control"
getent group ianitor >/dev/null || groupadd --system ianitor
id ianitor >/dev/null 2>&1 || useradd --system --gid ianitor --home-dir /var/lib/ianitor --shell /usr/sbin/nologin ianitor
id ianitor-edge >/dev/null 2>&1 || useradd --system --gid ianitor --no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin ianitor-edge
install -m 0755 "$src/bin/ianitor-control" "$src/bin/ianitor-edge" /usr/local/bin/
install -d -m 0755 /usr/local/lib/ianitor /usr/share/ianitor
install -m 0755 "$src/lib/setup.sh" /usr/local/lib/ianitor/setup.sh
rm -rf /usr/share/ianitor/web && cp -r "$src/web" /usr/share/ianitor/web
install -m 0644 "$src/lib/ianitor-control.service" "$src/lib/ianitor-edge.service" /etc/systemd/system/
IANITOR_ROOT=/var/lib/ianitor IANITOR_CONFIG=/etc/ianitor/control.toml \
IANITOR_EDGE_SOCKET=/run/ianitor-edge/admin.sock sh /usr/local/lib/ianitor/setup.sh
# Who may read what (as the NixOS module's tmpfiles): control owns the state, edge reads its
# config and the certificates through the group and writes only its own state and logs.
chown -R ianitor:ianitor /var/lib/ianitor
chmod 0755 /var/lib/ianitor
chmod 0700 /var/lib/ianitor/control /var/lib/ianitor/credentials
chmod 0750 /var/lib/ianitor/edge /var/lib/ianitor/certs /var/lib/ianitor/caddy
chown -R ianitor-edge:ianitor /var/lib/ianitor/edge-state /var/lib/ianitor/logs
chmod 0700 /var/lib/ianitor/edge-state
chmod 0770 /var/lib/ianitor/logs
chown root:ianitor /etc/ianitor /etc/ianitor/control.toml
chmod 0750 /etc/ianitor
chmod 0640 /etc/ianitor/control.toml
systemctl daemon-reload
systemctl enable --now ianitor-control.service ianitor-edge.service
systemctl restart ianitor-control.service ianitor-edge.service
i=0
until curl -s -o /dev/null http://127.0.0.1:7878/api/v1/health 2>/dev/null; do
i=$((i + 1)); [ $i -le 30 ] || die "control did not start; see journalctl -u ianitor-control"
sleep 1
done
echo
echo "Ianitor $VERSION is running. Open this link to sign in as the first admin:"
runuser -u ianitor -- /usr/local/bin/ianitor-control team setup-link --config /etc/ianitor/control.toml 2>/dev/null \
|| echo "(the team already has an admin; they invite you from Settings → Team)"
+144
View File
@@ -0,0 +1,144 @@
#!/bin/sh
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
#
# Writes Ianitor's control.toml and its first secrets from environment variables, once.
# Shared by the Linux installer (deploy/linux/install.sh) and the Docker image's entrypoint.
# An existing control.toml is never touched; secrets are random files (0600), never values in
# the config, the image or a log.
#
# IANITOR_ADMIN_HOST the web UI's address, e.g. ianitor.example.org (required)
# IANITOR_TLS letsencrypt (default) or domi, for the admin host
# IANITOR_DOMI_ROOT the Domi root certificate (public) for tls = domi (docs/pki.md)
# IANITOR_PREVIEW_DOMAIN branch previews live under it, e.g. preview.example.org
# IANITOR_PREVIEW_UPSTREAMS comma list of what previews may point at (10.0.0.0/8,app.internal)
# IANITOR_PREVIEW_TLS letsencrypt or domi (default: IANITOR_TLS)
# IANITOR_ROUTES_REMOTE where the routes repository is pushed (https URL on Gitea, GitHub, GitLab)
# IANITOR_ROUTES_HOST gitea (default), github or gitlab: the push user name and the UI's label
# IANITOR_ROUTES_USER overrides the push user name
# IANITOR_ROOT state root (default /var/lib/ianitor)
# IANITOR_CONFIG where control.toml goes (default /etc/ianitor/control.toml)
# IANITOR_CREDENTIALS the credentials folder (default $IANITOR_ROOT/credentials)
# IANITOR_EDGE_SOCKET edge's admin socket (default /run/ianitor/admin.sock)
# IANITOR_WEB the built web UI (default /usr/share/ianitor/web)
# IANITOR_HTTP, IANITOR_HTTPS listen addresses (default 0.0.0.0:80, 0.0.0.0:443)
set -eu
ROOT="${IANITOR_ROOT:-/var/lib/ianitor}"
CONFIG="${IANITOR_CONFIG:-/etc/ianitor/control.toml}"
CREDS="${IANITOR_CREDENTIALS:-$ROOT/credentials}"
SOCKET="${IANITOR_EDGE_SOCKET:-/run/ianitor/admin.sock}"
WEB="${IANITOR_WEB:-/usr/share/ianitor/web}"
TLS="${IANITOR_TLS:-letsencrypt}"
die() { echo "ianitor setup: $*" >&2; exit 1; }
# Only plain values reach the TOML: no quotes, backslashes, dollars or newlines.
plain() {
case "$1" in
*[\"\\\'\`\$]*) die "$2 contains a character that is not allowed" ;;
esac
if [ "$(printf '%s' "$1" | wc -l)" -ne 0 ]; then die "$2 must be one line"; fi
}
for d in "$ROOT" "$ROOT/control" "$ROOT/edge" "$ROOT/caddy" "$ROOT/certs" "$ROOT/edge-state" \
"$ROOT/caddy-state" "$ROOT/logs" "$CREDS"; do
mkdir -p "$d"
done
chmod 0700 "$CREDS" "$ROOT/control"
# Secrets: made here once, random, readable by their owner only.
umask 077
[ -s "$CREDS/share-link-key" ] || head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n' > "$CREDS/share-link-key"
[ -s "$CREDS/pki-password" ] || head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n' > "$CREDS/pki-password"
umask 022
[ -f "$ROOT/edge/share-revocations.json" ] || echo '{"epoch":0,"deny":[]}' > "$ROOT/edge/share-revocations.json"
[ -f "$ROOT/engine" ] || echo pingora > "$ROOT/engine"
if [ -f "$CONFIG" ]; then
echo "ianitor setup: $CONFIG exists; leaving it as it is." >&2
exit 0
fi
[ -n "${IANITOR_ADMIN_HOST:-}" ] || die "IANITOR_ADMIN_HOST is required (the web UI's address, e.g. ianitor.example.org)"
plain "$IANITOR_ADMIN_HOST" IANITOR_ADMIN_HOST
case "$TLS" in letsencrypt|domi) ;; *) die "IANITOR_TLS must be letsencrypt or domi" ;; esac
PTLS="${IANITOR_PREVIEW_TLS:-$TLS}"
case "$PTLS" in letsencrypt|domi) ;; *) die "IANITOR_PREVIEW_TLS must be letsencrypt or domi" ;; esac
routes_remote=""
if [ -n "${IANITOR_ROUTES_REMOTE:-}" ]; then
plain "$IANITOR_ROUTES_REMOTE" IANITOR_ROUTES_REMOTE
case "${IANITOR_ROUTES_HOST:-gitea}" in
github) user=x-access-token; label=GitHub ;;
gitlab) user=oauth2; label=GitLab ;;
gitea) user=ianitor; label=Gitea ;;
*) die "IANITOR_ROUTES_HOST must be gitea, github or gitlab" ;;
esac
user="${IANITOR_ROUTES_USER:-$user}"
plain "$user" IANITOR_ROUTES_USER
routes_remote="remote = \"$IANITOR_ROUTES_REMOTE\"
remote_name = \"$label\"
push_username = \"$user\"
push_credential = \"routes-token\""
fi
pki=""
if [ "$TLS" = domi ] || [ "$PTLS" = domi ]; then
[ -n "${IANITOR_DOMI_ROOT:-}" ] || die "tls = domi needs IANITOR_DOMI_ROOT (the Domi root certificate; docs/pki.md)"
plain "$IANITOR_DOMI_ROOT" IANITOR_DOMI_ROOT
pki="[pki]
root_cert = \"$IANITOR_DOMI_ROOT\""
fi
previews=""
if [ -n "${IANITOR_PREVIEW_DOMAIN:-}" ]; then
plain "$IANITOR_PREVIEW_DOMAIN" IANITOR_PREVIEW_DOMAIN
plain "${IANITOR_PREVIEW_UPSTREAMS:-}" IANITOR_PREVIEW_UPSTREAMS
list=$(printf '%s\n' "${IANITOR_PREVIEW_UPSTREAMS:-}" | tr ',' '\n' | sed '/^ *$/d; s/^ *//; s/ *$//; s/.*/"&"/' | paste -sd, -)
previews="[previews]
domain = \"$IANITOR_PREVIEW_DOMAIN\"
tls = \"$PTLS\"
upstreams = [$list]"
fi
mkdir -p "$(dirname "$CONFIG")"
cat > "$CONFIG.new" <<EOF
# Written by Ianitor's setup on $(date -u +%Y-%m-%d). Edit freely; setup never rewrites it.
# Secrets are files in $CREDS, never values here.
listen = "127.0.0.1:7878"
state_dir = "$ROOT/control"
credentials_dir = "$CREDS"
[routes]
repo = "$ROOT/routes.git"
$routes_remote
[edge]
config = "$ROOT/edge/edge.json"
admin_socket = "$SOCKET"
share_revocations = "$ROOT/edge/share-revocations.json"
[caddy]
config = "$ROOT/caddy/caddy.json"
[compile]
http_listen = "${IANITOR_HTTP:-0.0.0.0:80}"
https_listen = "${IANITOR_HTTPS:-0.0.0.0:443}"
cert_dir = "$ROOT/certs"
state_dir = "$ROOT/edge-state"
access_log = "$ROOT/logs/access.log"
caddy_credentials_dir = "$CREDS"
[ui]
hostname = "$IANITOR_ADMIN_HOST"
static_dir = "$WEB"
admin_tls = "$TLS"
$pki
$previews
EOF
mv "$CONFIG.new" "$CONFIG"
echo "ianitor setup: wrote $CONFIG" >&2
+40
View File
@@ -90,6 +90,16 @@ let
password_credential = "pki-password";
};
}
// lib.optionalAttrs (cfg.previews.domain != null) {
# Branch previews for Fabrica (T4, docs/previews.md).
previews = {
domain = cfg.previews.domain;
tls = cfg.previews.tls;
auth = cfg.previews.auth;
upstreams = cfg.previews.upstreams;
default_ttl_secs = cfg.previews.defaultTtlSeconds;
};
}
);
hardening = {
@@ -222,6 +232,36 @@ in
};
};
previews = {
domain = mkOption {
type = types.nullOr types.str;
default = null;
example = "preview.example.org";
description = "Branch previews for Fabrica live under this domain (`<branch>--<project>.<domain>`); a wildcard DNS record must point here. Null: previews are off.";
};
tls = mkOption {
type = types.enum [ "domi" "letsencrypt" ];
default = "domi";
description = "Certificates for previews: the Domi CA (internal) or Let's Encrypt (public, one certificate per preview).";
};
auth = mkOption {
type = types.enum [ "none" "forward-auth" ];
default = "forward-auth";
description = "Whether previews are behind Authelia (forward-auth) or open to anyone with the address.";
};
upstreams = mkOption {
type = types.listOf types.str;
default = [ ];
example = [ "10.0.0.0/8" "127.0.0.1:20000-29999" ];
description = "What previews may send traffic to (networks, address:port ranges, names). Control's own port and Caddy's admin are never allowed.";
};
defaultTtlSeconds = mkOption {
type = types.ints.positive;
default = 72 * 3600;
description = "How long a preview lives when Fabrica does not say.";
};
};
ui = {
hostname = mkOption {
type = types.nullOr types.str;
+216
View File
@@ -0,0 +1,216 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
#
# Ianitor Domi on Windows Server, Caddy mode (Fabrica docs/32_coherence.md §2.5, T4).
# Pingora's Windows support is preliminary upstream, so Windows runs ianitor-control with Caddy
# as the data plane: same UI, same TOML, compiled to Caddy JSON, kept honest by the
# differential suite (which runs on Windows with Windows paths).
#
# From the unpacked release zip, in an elevated PowerShell:
#
# .\install.ps1 -AdminHost ianitor.example.org [-Tls letsencrypt|domi] [-DomiRoot <crt>]
# [-PreviewDomain preview.example.org -PreviewUpstreams "10.0.0.0/8,127.0.0.1:20000-29999"]
# [-RoutesRemote https://github.com/team/routes.git -RoutesHost github]
#
# It installs the binaries to %ProgramFiles%\Ianitor, Caddy (pinned, SHA-512 checked) next to
# them, the state to %ProgramData%\Ianitor (ACL: Administrators, SYSTEM, LocalService), writes
# control.toml once, registers three services as LocalService (IanitorCaddy, IanitorControl,
# IanitorGuard; restart on failure), starts them and prints the first admin's sign-in link.
# -NoService runs the same setup but starts nothing (tests, or a manual start).
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)][string]$AdminHost,
[ValidateSet('letsencrypt', 'domi')][string]$Tls = 'letsencrypt',
[string]$DomiRoot = '',
[string]$PreviewDomain = '',
[string]$PreviewUpstreams = '',
[ValidateSet('', 'letsencrypt', 'domi')][string]$PreviewTls = '',
[string]$RoutesRemote = '',
[ValidateSet('gitea', 'github', 'gitlab')][string]$RoutesHost = 'gitea',
[string]$Root = (Join-Path $env:ProgramData 'Ianitor'),
[string]$Bin = (Join-Path $env:ProgramFiles 'Ianitor'),
[int]$HttpPort = 80,
[int]$HttpsPort = 443,
[int]$ApiPort = 7878,
[int]$CaddyAdminPort = 2019,
[string]$Caddy = '',
[switch]$NoService
)
$ErrorActionPreference = 'Stop'
$CaddyVersion = '2.11.7'
$CaddySha512 = 'c308154504e53755958ffc62d8a2657ab17eefd6dd25c45dbb2c3d93d29519971f77ca652f7d0f2bcb7f980b9ba3822478865e29969d0272d7613550a43152b1'
function Fail($m) { Write-Error "ianitor install: $m"; exit 1 }
function Plain($v, $name) {
if ($v -match '["\\''`$\r\n]') { Fail "$name contains a character that is not allowed" }
}
# A path may have backslashes (they become '/' in the TOML), nothing else that TOML would read.
function PlainPath($v, $name) {
if ($v -match '["''`$\r\n]') { Fail "$name contains a character that is not allowed" }
}
# Paths in TOML with forward slashes (control and Caddy read C:/ProgramData/... as is).
function Fwd($p) { return ($p -replace '\\', '/') }
if (-not $NoService) {
$me = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
if (-not $me.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { Fail 'run it in an elevated PowerShell (Run as administrator)' }
}
Plain $AdminHost 'AdminHost'; Plain $PreviewDomain 'PreviewDomain'; Plain $PreviewUpstreams 'PreviewUpstreams'
Plain $RoutesRemote 'RoutesRemote'; PlainPath $DomiRoot 'DomiRoot'; PlainPath $Root 'Root'; PlainPath $Bin 'Bin'
$git = (Get-Command git.exe -ErrorAction SilentlyContinue)
if (-not $git) { Fail 'install Git for Windows first (https://git-scm.com/download/win); control keeps the routes in git' }
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
if (-not (Test-Path (Join-Path $here 'ianitor-control.exe'))) { Fail "ianitor-control.exe is not next to install.ps1 ($here)" }
# ---------------------------------------------------------------- files
New-Item -ItemType Directory -Force $Bin | Out-Null
Copy-Item (Join-Path $here 'ianitor-control.exe') $Bin -Force
if (Test-Path (Join-Path $here 'web')) {
if (Test-Path (Join-Path $Bin 'web')) { Remove-Item -Recurse -Force (Join-Path $Bin 'web') }
Copy-Item -Recurse (Join-Path $here 'web') (Join-Path $Bin 'web')
}
$caddyExe = Join-Path $Bin 'caddy.exe'
if ($Caddy) {
Copy-Item $Caddy $caddyExe -Force
} elseif (-not (Test-Path $caddyExe)) {
$zip = Join-Path $env:TEMP "caddy_$CaddyVersion.zip"
$url = "https://github.com/caddyserver/caddy/releases/download/v$CaddyVersion/caddy_${CaddyVersion}_windows_amd64.zip"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $zip
$got = (Get-FileHash -Algorithm SHA512 $zip).Hash.ToLower()
if ($got -ne $CaddySha512) { Remove-Item $zip; Fail "Caddy $CaddyVersion does not match its pinned SHA-512" }
$x = Join-Path $env:TEMP "caddy_$CaddyVersion"
Expand-Archive -Force $zip $x
Copy-Item (Join-Path $x 'caddy.exe') $caddyExe -Force
Remove-Item -Recurse -Force $zip, $x
}
foreach ($d in 'control', 'edge', 'caddy', 'certs', 'caddy-state', 'logs', 'credentials') {
New-Item -ItemType Directory -Force (Join-Path $Root $d) | Out-Null
}
# Only Administrators, SYSTEM and the services' account (LocalService) see the state.
$grants = @('*S-1-5-32-544:(OI)(CI)F', '*S-1-5-18:(OI)(CI)F', '*S-1-5-19:(OI)(CI)M')
# -NoService runs everything as the person who ran it, who then needs the folder too.
if ($NoService) { $grants += "*$([Security.Principal.WindowsIdentity]::GetCurrent().User.Value):(OI)(CI)F" }
icacls $Root /inheritance:r /grant:r @grants | Out-Null
if ($LASTEXITCODE -ne 0) { Fail "could not set the folder's permissions on $Root" }
function Secret($name) {
$f = Join-Path $Root "credentials\$name"
if (-not (Test-Path $f) -or (Get-Item $f).Length -eq 0) {
$b = New-Object byte[] 32
[Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($b)
[IO.File]::WriteAllText($f, (($b | ForEach-Object { $_.ToString('x2') }) -join ''))
}
}
Secret 'share-link-key'; Secret 'pki-password'
$engine = Join-Path $Root 'engine'
if (-not (Test-Path $engine)) { [IO.File]::WriteAllText($engine, "caddy`n") }
$rev = Join-Path $Root 'edge\share-revocations.json'
if (-not (Test-Path $rev)) { [IO.File]::WriteAllText($rev, '{"epoch":0,"deny":[]}') }
# Caddy starts with only its admin API; control loads the rest and keeps caddy.json current.
$caddyJson = Join-Path $Root 'caddy\caddy.json'
if (-not (Test-Path $caddyJson)) {
[IO.File]::WriteAllText($caddyJson, "{`"admin`":{`"listen`":`"127.0.0.1:$CaddyAdminPort`"}}")
}
# ---------------------------------------------------------------- control.toml (once)
$config = Join-Path $Root 'control.toml'
if (Test-Path $config) {
Write-Host "ianitor install: $config exists; leaving it as it is."
} else {
$R = Fwd $Root
if (-not $PreviewTls) { $PreviewTls = $Tls }
$routes = ''
if ($RoutesRemote) {
$user = @{ github = 'x-access-token'; gitlab = 'oauth2'; gitea = 'ianitor' }[$RoutesHost]
$label = @{ github = 'GitHub'; gitlab = 'GitLab'; gitea = 'Gitea' }[$RoutesHost]
$routes = "remote = `"$RoutesRemote`"`nremote_name = `"$label`"`npush_username = `"$user`"`npush_credential = `"routes-token`""
}
$pki = ''
if ($Tls -eq 'domi' -or $PreviewTls -eq 'domi') {
if (-not $DomiRoot) { Fail 'tls domi needs -DomiRoot (the Domi root certificate; docs/pki.md)' }
$pki = "[pki]`nroot_cert = `"$(Fwd $DomiRoot)`""
}
$previews = ''
if ($PreviewDomain) {
$list = ($PreviewUpstreams -split ',' | Where-Object { $_.Trim() } | ForEach-Object { "`"$($_.Trim())`"" }) -join ', '
$previews = "[previews]`ndomain = `"$PreviewDomain`"`ntls = `"$PreviewTls`"`nupstreams = [$list]"
}
$text = @"
# Written by Ianitor's Windows installer on $(Get-Date -Format yyyy-MM-dd). Edit freely; the
# installer never rewrites it. Secrets are files in $R/credentials, never values here.
listen = "127.0.0.1:$ApiPort"
state_dir = "$R/control"
credentials_dir = "$R/credentials"
git = "$(Fwd $git.Source)"
[routes]
repo = "$R/routes.git"
$routes
[edge]
config = "$R/edge/edge.json"
share_revocations = "$R/edge/share-revocations.json"
[caddy]
config = "$R/caddy/caddy.json"
[compile]
http_listen = "0.0.0.0:$HttpPort"
https_listen = "0.0.0.0:$HttpsPort"
cert_dir = "$R/certs"
state_dir = "$R/caddy-state"
access_log = "$R/logs/access.log"
caddy_credentials_dir = "$R/credentials"
caddy_admin = "127.0.0.1:$CaddyAdminPort"
[engine]
file = "$R/engine"
units = "none"
[ui]
hostname = "$AdminHost"
static_dir = "$(Fwd (Join-Path $Bin 'web'))"
admin_tls = "$Tls"
$pki
$previews
"@
[IO.File]::WriteAllText($config, $text)
Write-Host "ianitor install: wrote $config"
}
& (Join-Path $Bin 'ianitor-control.exe') check --config $config
if ($LASTEXITCODE -ne 0) { Fail "the config does not check out: $config" }
if ($NoService) {
Write-Host "ianitor install: set up in $Root; no services started (-NoService)."
exit 0
}
# ---------------------------------------------------------------- services
$ctl = Join-Path $Bin 'ianitor-control.exe'
$log = Join-Path $Root 'logs'
$services = @(
@{ Name = 'IanitorCaddy'; Display = 'Ianitor Caddy (data plane)'; Path = "`"$caddyExe`" run --config `"$caddyJson`"" },
@{ Name = 'IanitorControl'; Display = 'Ianitor control (API and UI on loopback)'; Path = "`"$ctl`" service control --config `"$config`" --log-file `"$log\control.log`"" },
@{ Name = 'IanitorGuard'; Display = 'Ianitor Caddy trial guard'; Path = "`"$ctl`" service caddy-guard --config `"$config`" --log-file `"$log\guard.log`"" }
)
foreach ($s in $services) {
if (Get-Service $s.Name -ErrorAction SilentlyContinue) {
Stop-Service $s.Name -Force -ErrorAction SilentlyContinue
sc.exe config $s.Name binPath= $s.Path | Out-Null
} else {
sc.exe create $s.Name binPath= $s.Path start= auto obj= 'NT AUTHORITY\LocalService' DisplayName= $s.Display | Out-Null
}
sc.exe failure $s.Name reset= 86400 actions= restart/2000/restart/5000/restart/30000 | Out-Null
}
foreach ($s in $services) { Start-Service $s.Name }
Write-Host ''
Write-Host 'Ianitor is running (Caddy mode). Open this link to sign in as the first admin:'
& $ctl team setup-link --config $config
+50 -33
View File
@@ -145,44 +145,61 @@ Identity gate, tunnel, Domi templates, ACME server, HTTP/3, migrating public sit
| 1 Core and engine | Done | Merged to main 2026-11-07. Tests run in WSL2; ACME checked only against Pebble. The Let's Encrypt staging check moved to phase 3 (Mark, 2026-11-07). |
| 2 Control plane | Done | Merged to main 2026-11-07 (PR 3): routes repo, journaled apply with trial/watch/revert, undo, restore, share links, API tokens, REST API + OpenAPI, `--dev`. Four QC rounds; every finding fixed or listed in Handover. Real Gitea, systemd credentials and Authelia not exercised. |
| 3 Web UI, PKI, NixOS | Built and merged; Done criteria pending Mark | Merged to main 2026-11-08 (PR 5): web UI (murex palette), Domi CA and device mTLS, UI sign-in behind Authelia, runtime engine switch with changes under Caddy, NixOS flake, module and VM tests. Click smoke test green. Not yet done: VM tests run on a KVM host, Mark's nixos-rebuild on the staging mirror, deploy/test-access.sh there, the LE staging check. |
| 4 Hardening and release | Started: the release kit, Fabrica onboarding | A `v*` tag's Gitea release carries the source archive, the notes, screenshots of the web UI and the Aula page under a signed SHA256SUMS (docs/release.md). Fabrica onboarding (docs/fabrica.md, 2026-11-19): `aula: true`, AULA.md and the brief, a Playwright e2e suite that takes the shots and records the main flows, `tests.yaml` and the `e2e` pipeline; updates stay `fabrica-deploy`; no Canalis (a device-local layer). The rest of phase 4 is not started; known gaps carried here: see Handover. |
| 4 Hardening and release | Started: the release kit | A `v*` tag's Gitea release carries the notes and screenshots of the web UI under a signed SHA256SUMS (docs/release.md, 2026-11-09). The rest of phase 4 is not started; known gaps carried here: see Handover. |
| T4 Anywhere, previews, team (Fabrica docs/32_coherence.md) | Built and merged; release prepared | 2026-11-17: Ianitor off NixOS (Linux installer, Docker image, Windows Server in Caddy mode), branch previews for Fabrica with previews-only tokens, team sign-in without Authelia, the diff suite on Windows. 0.2.0 prepared (pipeline, notes), not tagged. See Handover. |
## 10. Handover
(Rewritten at the end of every session: what changed, what was not verified, which build is deployed, the next step.)
**2026-11-19: Ianitor onboarded to Fabrica (docs/fabrica.md; Fabrica docs/36_app_onboarding.md).**
**2026-11-17: T4, Ianitor anywhere, previews for Fabrica, team sign-in (Fabrica docs/32_coherence.md).**
- **Changed:**
- `.fabrica/app.yaml` has `aula: true` and `tagPrefix: v`, with one server part.
- The release pipeline publishes the source archive (`scripts/pack-source.mjs`, the Aula download), the notes,
five `file:` shots and `aula-page.json`.
- `.fabrica/aula.yaml`, `.fabrica/aula/brief.md`, `AULA.md`, `.fabrica/notes/0.2.0.md`.
- `.fabrica/tests.yaml` (target `web`) and `.fabrica/artifex/e2e.yaml` (`windows-e2e`).
- A Playwright suite in apps/web (`e2e/`, `playwright.config.ts`): the six §4 flows with their clicks counted, each
recorded as a video, and the five Aula shots. It runs on the built UI and the demo control plane, at a fixed
instant, with every page checked for real-looking names.
- `apps/web/scripts/shots.mjs` is removed.
- The demo keeps the hosts it is given and names device requests by what was asked.
- Version 0.2.0.
- Pensum: `#jd3x1h` (the videos on Aula, when Fabrica's `videos:` lands) and `#j4yav1` (the visual gate against
v0.2.0).
- **Decided:**
- Canalis does not apply (docs/fabrica.md part 4).
- There is no android target: no Android build.
- The visual gate waits one release, because v0.1.0's shots were taken at a moving clock.
- **Verified on this PC (Windows, Edge):**
- Playwright: web 6/6 and aula 5/5, under heavy load (the slowest flow took 72 s).
- vitest 21 (smoke 15, demo 6); svelte-check: 0 errors.
- `fabrica artifex check`: 0 problems (3 pipelines, app.yaml, aula.yaml, tests.yaml, brief). `fabrica pensum check`:
0 problems. `fabrica preflight ianitor`: 0 blockers.
- `fabrica aula shots` (5 × 1440×900), `fabrica notes`, `fabrica aula page`. Each PNG was looked at.
- No Rust file changed.
- **Not verified:**
- The `e2e` pipeline on the `windows-e2e` runner.
- The Linux suites and the Nix build (as in the 2026-11-17 entry).
- **Deployed:** nothing.
- **Next step:**
- Tag `v0.2.0` and start `release` at it. Mark approves and signs on Custos.
- Configuration_Server adds the Aula entry (docs/fabrica.md, Handover).
- core: `preview` (branch and project → one safe label, `<branch>--<project>.<domain>`, hashed where anything was
lost; refuses control characters and over-long names) and a `[preview]` table in host files, checked against the
host name; compilers ignore it. Compile options take Windows drive paths (`C:/…`).
- control: `/api/v1/previews` (open/move, get, list, close by project and branch, kill by host), tokens with
`scope = previews` that get `403 token.scope` everywhere else, the upstream allow list (`[previews] upstreams`;
control's port, Caddy's admin, unspecified/link-local/multicast never), expiry sweeper. Caddy's admin API over
loopback TCP (Windows), applies through Caddy without an edge, `ianitor-control service control|caddy-guard`
(Windows services), `--log-file`. Team sign-in (`team.rs`): setup link, invites, `__Host-ianitor` sessions,
admin/member roles, Tessera roots with Fundamentum's match code; `ianitor-control team setup-link`; control keeps
the admin host itself with `[ui] admin_tls`; the admin host is accepted with any port.
- edge: a websocket `101` keeps the upstream's headers (response rules apply to HTTP answers only), as Caddy does;
found by the preview fixture in the diff suite. `run_until` on Windows (tests only).
- tests/diff runs on Windows (Pingora in-process vs Windows Caddy 2.11.7, drive paths), two preview hosts in the
fixtures and five preview cases in the corpus.
- web: Previews screen (see 1 click, close 2), sign-in from `#signin=` links, Settings → Team (invite 3 clicks),
previews-only tokens; version 0.2.0.
- deploy: `deploy/docker` (image, compose, CI target, Linux dist target), `deploy/linux` (install.sh, setup.sh,
systemd units), `deploy/windows/install.ps1`, NixOS `services.ianitor.previews.*`. scripts: `preview.sh|.ps1`
(Fabrica's client), `package-windows.mjs`, `smoke-windows.ps1`, `smoke-docker.sh`, `smoke-linux.sh`.
- docs: previews.md, deploy/anywhere.md, api.md (team, previews), custos-ticket.md (T4 part); release pipeline
builds and tests the Linux tarball, the Windows zip and the image; `.fabrica/notes/0.2.0.md`.
- **Verified:**
- Windows (this PC, Windows 10, not Server): core 112, control 14 unit + api 1, apply 1, caddy_mode 1,
engine_switch 1, pki 1, previews 5, stores 6, team 1, ui_auth 1 (the Linux-only targets are skip stubs), diff 3
(the real suite, Windows Caddy), apply_sequence 1 (stub), edge 16 unit + stubs, testkit 1. vitest 24, svelte-check
0 errors, `fabrica artifex check` 0 problems.
- Linux (Docker, `--target ci`, Pebble 2.6.0, Caddy 2.11.7): core 112; control 14 + api 5, apply 25, caddy_mode 1,
engine_switch 16, pki 8, previews 5, stores 6, team 1, ui_auth 5; diff 3 + apply_sequence 1; edge 16 + acme 1,
device_certs 7, forward_auth 5, qc_sni_stale 4, reload 5, secrets 3, share_links 7, share_throttle 3,
trusted_proxies 2, upstreams 4; testkit 1. `pki::device_certificate_needs_the_match_code_and_installs_once`
failed once under the full parallel run and passed twice alone (a load flake, not T4 code). The ACME test needs
Pebble 2.6.0: with 2.10.3 Pebble cannot resolve the test name.
- Smoke, previews end to end with the previews-only token and Fabrica's client: Windows Caddy mode through
`install.ps1 -NoService` (`scripts/smoke-windows.ps1`): PASSED. Docker and Linux (systemd): see below.
- **Not verified:** the Windows services under the SCM (registration, LocalService ACLs, ports 80/443) and Windows
Server itself; `nix build .#ianitor` and the VM tests (no Nix/KVM here); a real browser on the sign-in link; Let's
Encrypt for previews; a push of the routes repository to GitHub or GitLab.
- **Deployed:** nothing. No tag, no release run.
- **Server (Mark):** nothing is required for T4; previews on the NixOS server are opt-in:
`services.ianitor.previews = { domain = "preview.<domain>"; upstreams = [ … ]; };` in hyperv-infra's
modules/ianitor.nix (the module from docs/deploy/configuration-server.patch, if it is applied by then), a wildcard
DNS record, then in hyperv-infra: `nix flake update ianitor && sudo nixos-rebuild switch --flake .#hyperv-vm`.
- **Open:** Custos `http-token` target kind, a generic team approval for admin changes, a browser Domi key
(docs/custos-ticket.md, T4); Fabrica's `preview:` step and close-on-merge (Fabrica docs/handover/t4-previews.md);
the Docker image is not pushed to a registry; plain Linux has no Caddy fallback; Caddy's admin API on Windows is
loopback TCP (any local process can reach it).
- **Next step:** the main session tags v0.2.0 and starts `release`; Fabrica wires its preview step.
**2026-11-17: The Domi CA moved to the shared crate domi-pki (Fabrica docs/32_coherence.md, T3a).**
- **Changed:** `crates/core/src/pki.rs` is now Ianitor's view of [domi-pki](https://gitea.marek-novak.cz/mnovak/domi-pki)
+18
View File
@@ -272,6 +272,24 @@ secret = "ui-proof" # listed in ianitor.toml: secrets = ["ui-proof"]
Why not the Unix socket now: edge's upstreams are `host:port` in the schema; a socket upstream is a
schema and compiler change in both engines, and the proof header needs neither.
## Team sign-in without Authelia (T4)
On a server without Authelia, people sign in with links (crates/control/src/team.rs):
- `ianitor-control team setup-link --config <c>` prints the first admin's link, `https://<admin host>/#signin=isc_…`
(one use, 7 days, only while the team has nobody). The UI posts the code to `POST /api/v1/session` (no token; the
`X-Ianitor-UI: 1` header and a same-origin page are required) and gets the `__Host-ianitor` cookie (HttpOnly,
Secure, SameSite=Strict, 30 days).
- Admins invite: `POST /api/v1/team/invites {name, role}` → `{link_fragment}` (Settings → Team → Invite).
- `GET /api/v1/team`, `DELETE /api/v1/team/members/{id}` (the last admin stays), `PUT /api/v1/team/me/root`
(your Tessera root), `POST /api/v1/session/end`.
- A `member` gets `403 team.admin_only` on tokens, the team, the engine switch and the CA's renewal and requests.
Browser writes need `X-Ianitor-UI: 1` (`403 request.csrf`).
## Branch previews (T4)
`/api/v1/previews`, and tokens with `"scope": "previews"` that may call nothing else: docs/previews.md.
## Certificates (the Domi CA)
Everything is in [pki.md](pki.md); the calls:
+18
View File
@@ -92,3 +92,21 @@ against the `domi-approve` public key before issuing. No new crypto in Custos.
with `pathlen:0`, after a match-code approval on the phone.
- A CSR with another CN, a bad signature or a request for a CA without pathLen 0 is refused.
- An `x509_csr` request against any other key is `out_of_scope`.
## T4 (2026-11-17): what Ianitor on any server needs from Custos
Not filed; written for the Custos session that picks it up. Each item has a working stand-in in Ianitor today.
1. **A target kind for an HTTP API token** (`http-token`: `host`, `secret`), so the team vault can hold Ianitor's
previews-only token and hand it to Fabrica per preview deployment through `target.request` (CustosPublic
`docs/TEAM.md`, "Target credentials"). Stand-in: the `registry` kind (a token with a host), docs/previews.md.
2. **A generic team approval** (`approve.request`: a canonical statement, the request's match code on every
member's card, an answer that carries the existing `custos team approval v1` statements and a proof
`verify_proof` can check), so Ianitor can ask a teammate to approve an admin change (a new API token, a member,
the engine switch, a renewal) without asking the team's release key to sign anything. Signing a dummy artifact
with `sign.request` is not a stand-in: Ianitor would choose the digest the release key signs. Stand-in: admin
changes need the admin role (crates/control/src/team.rs).
3. **A browser Domi key** (Fundamentum's web client): a WebCrypto key certified by the member's Tessera root, so a
sign-in is a signed challenge, not a link. Stand-in: one-time setup and invite links that make a session cookie;
members may record their Tessera root, and the team list shows its match code (`tessera match v1`, the same
digits Custos shows).
+80
View File
@@ -0,0 +1,80 @@
# Ianitor anywhere (T4)
Four ways to run Ianitor, one config model. Fabrica's coherence roadmap (`docs/32_coherence.md`, §2.5 and T4).
| | Engine | Package | Install | Secrets |
| :-- | :-- | :-- | :-- | :-- |
| Linux with systemd | Pingora (edge) | `ianitor-X.Y.Z-linux-x86_64.tar.gz` + `install.sh` | one line, below | `/var/lib/ianitor/credentials` (0700, random, made by setup) |
| Docker | Pingora (edge) | the image from `deploy/docker/Dockerfile`, `deploy/docker/compose.yaml` | `docker compose up -d` | the `state` volume's `credentials/` |
| Windows Server | **Caddy** (Caddy mode) | `ianitor-X.Y.Z-windows-x86_64.zip` | `install.ps1` | `%ProgramData%\Ianitor\credentials` (ACL: Administrators, SYSTEM, LocalService) |
| NixOS | Pingora, Caddy fallback | the flake (`nixosModules.ianitor`) | `nixos-rebuild` | systemd credentials (`LoadCredential`) |
Everywhere: control listens on 127.0.0.1:7878 only; only the engine binds 80 and 443; the web UI is the admin host
(`IANITOR_ADMIN_HOST`) through the engine. Without Authelia, people sign in with team links (Settings → Team,
docs/api.md); the installer prints the first admin's link (`ianitor-control team setup-link`).
## Linux (systemd)
```bash
curl -fsSL https://gitea.marek-novak.cz/mnovak/Ianitor/releases/download/v0.2.0/install.sh | sudo IANITOR_ADMIN_HOST=ianitor.example.org IANITOR_PREVIEW_DOMAIN=preview.example.org IANITOR_PREVIEW_UPSTREAMS=10.0.0.0/8 sh
```
It checks the tarball against the release's `SHA256SUMS`, installs `/usr/local/bin/ianitor-{control,edge}`, the web
UI, `ianitor-control.service` and `ianitor-edge.service` (users `ianitor` and `ianitor-edge`, the NixOS module's
hardening), writes `/etc/ianitor/control.toml` once (`deploy/linux/setup.sh`: every `IANITOR_*` variable is
listed there), starts both and prints the sign-in link. Running it again upgrades and keeps config and state. No
Caddy fallback here (the engine switch is NixOS-only); header-rule secrets need a `LoadCredential=` line each.
## Docker
```bash
cd deploy/docker && printf 'IANITOR_ADMIN_HOST=ianitor.example.org\nIANITOR_PREVIEW_DOMAIN=preview.example.org\nIANITOR_PREVIEW_UPSTREAMS=app\n' > .env && docker compose up -d && docker compose exec control ianitor-entrypoint setup-link
```
Two services from one image: `edge` (ports 80/443) and `control` in edge's network namespace, so the API stays on
loopback. Read-only root, no capabilities, `no-new-privileges`, user 10001. Previews of other containers: attach them
to the compose network and list their names in `IANITOR_PREVIEW_UPSTREAMS`.
## Windows Server (Caddy mode)
Pingora's Windows support is preliminary upstream, so Windows runs control with Caddy as the data plane: same UI,
same TOML, compiled to Caddy JSON; the differential suite runs on Windows with Windows paths to keep that honest.
From the unpacked zip, in an elevated PowerShell (Git for Windows installed):
```bash
powershell -ExecutionPolicy Bypass -File install.ps1 -AdminHost ianitor.example.org -PreviewDomain preview.example.org -PreviewUpstreams "10.0.0.0/8,127.0.0.1:20000-29999"
```
Three services as LocalService, restarted on failure: `IanitorCaddy` (`caddy run` on the last good `caddy.json`),
`IanitorControl` (`ianitor-control service control`) and `IanitorGuard` (the Caddy trial deadline, its own process
so a hung control cannot leave Caddy on an unconfirmed change). Caddy 2.11.7 is fetched by the installer and its
SHA-512 checked against the pinned value. Caddy's admin API listens on 127.0.0.1:2019 (Windows has no Unix socket
for it); any local process could reach it, so the machine should run nothing untrusted. Logs:
`%ProgramData%\Ianitor\logs`. Domi certificates have no revocation list, so Windows' own TLS (Schannel, curl.exe)
needs `--ssl-no-revoke`; browsers accept them once the Domi root is trusted.
## NixOS
Unchanged (`nixosModules.ianitor`, docs/deploy/beside-caddy.md), plus `services.ianitor.previews.{domain, tls, auth,
upstreams, defaultTtlSeconds}`.
## The Domi CA anywhere
With `tls = domi` the root stays offline (`ianitor-control ca init` on another machine). Start the intermediate in
the UI (Certificates → banner Renew) or `POST /api/v1/certs/intermediate/renewal`, sign the CSR offline
(`ianitor-control ca sign`), install it (`ianitor-control pki install <crt> --config <c>`), then restart control so
it adds the admin host with a certificate it can now issue. `scripts/smoke-windows.ps1` does all of it with a
throw-away root.
## Routes on any git host
`IANITOR_ROUTES_REMOTE` (an `https://` URL on Gitea, GitHub or GitLab) and `IANITOR_ROUTES_HOST`
(`gitea`, `github` → user `x-access-token`, `gitlab` → `oauth2`); the token goes in the credentials folder as
`routes-token`. Kept changes are pushed there, as on NixOS.
## Smoke tests (what was run for T4, 2026-11-17)
- Windows: `scripts/smoke-windows.ps1` (installer with `-NoService`, Caddy and control in the console, PKI, the
preview client, the preview through Caddy, close). The services themselves (SCM start, LocalService ACLs, ports 80
and 443) were not exercised on this PC.
- Docker and Linux: see the T4 handover in docs/ROADMAP.md.
-231
View File
@@ -1,231 +0,0 @@
# Ianitor in Fabrica: release, Aula page, updates, showcase, tests
Mark, 2026-11-19: every Domi app is released and updated through Fabrica. Each app gets its own Aula Domi page,
updates in its own way, gets Canalis, gets showcase screenshots and videos from its e2e tests with demo data, and is
tested on Fabrica's Playwright runner.
This page says what each of those means for Ianitor. The checklist is Fabrica `docs/36_app_onboarding.md`. The
formats are in Fabrica core `docs/FORMATS.md`, and Calenda's `.fabrica/` is the reference app.
docs/release.md describes the release pipeline step by step.
## Why
Ianitor is a server app. What runs is built by Nix on the server and switched in by the `deploy` pipeline. Its only
screens are the web UI, served by control on loopback behind edge and Authelia.
Three of the six items fit an app like that. Three do not:
- Ianitor has no installer and no updater.
- It has no Canalis, because Canalis is for apps on one device.
- It has no phone build.
Each item below says which case it is and why.
## The six items
| # | Item | Ianitor | Where |
| :-- | :-- | :-- | :-- |
| 1 | Fabrica app | `app.yaml` with `aula: true`. One `server` part (pipeline `deploy`, flake input `ianitor`). A `release` pipeline started by a `v*` tag. | `.fabrica/app.yaml`, `.fabrica/artifex/{release,deploy}.yaml` |
| 2 | Aula page | `AULA.md`, the brief, the shots, the release's highlights. The release publishes the source archive (the page's download), `aula-*.png`, `aula.json`, `aula-page.json` and the notes under a `SHA256SUMS` signed by `domi-release`. | `AULA.md`, `.fabrica/aula/brief.md`, `.fabrica/aula.yaml`, `.fabrica/notes/<version>.md` |
| 3 | Auto-update | `fabrica-deploy@ianitor` on the server (part 3). | `.fabrica/artifex/deploy.yaml` |
| 4 | Canalis | Not applicable (part 4). | this page |
| 5 | Showcase | A Playwright suite on the built UI and the demo control plane, at a fixed instant. It takes the Aula screenshots and records a video of each main flow. The videos wait for Fabrica's `videos:` (part 5). | `apps/web/e2e/`, `apps/web/playwright.config.ts` |
| 6 | Test targets | `tests.yaml` with the `web` target, and the `e2e` pipeline on Fabrica's `windows-e2e` runner. No `android` target, because Ianitor has no Android build. | `.fabrica/tests.yaml`, `.fabrica/artifex/e2e.yaml` |
## 1. The Fabrica app
`.fabrica/app.yaml` has:
- `name`, `icon` and `color` (the murex accent);
- `aula: true` and `tagPrefix: v`;
- one part, `server: {pipeline: deploy, input: ianitor}`.
**No `desktop` part.** A desktop part's Deploy bumps the version, tags and pushes, and that tag starts an installer
release. Ianitor has no installer. Fabrica allows `aula: true` on an app with a server part only (FORMATS, *Fabrica:
the app*).
**The release comes from a tag.** The version is changed by hand (`[repo] Release: X.Y.Z`, checked by
`scripts/check-version.mjs`). Then the `vX.Y.Z` tag is pushed and the hub is asked for a run of `release` at that
tag (`POST /api/runs`, `ref: vX.Y.Z`). No Gitea webhook reaches the hub yet.
`fabrica artifex check` checks every file of this page except `AULA.md`. `fabrica preflight ianitor` checks the
server part's pipeline: the hub and the NixOS runner. The release pipeline runs on the Windows runner, which runs
its own preflight before each run (Fabrica `docs/23_preflight.md`).
## 2. The Aula page
- **`AULA.md`**: the project's text, as Calenda's: what Ianitor is, for whom, what it does, how it is installed (the
NixOS module, not a download), and what the release's files are.
- **`.fabrica/aula/brief.md`**: the card's line, a short about, and one caption per shot. `fabrica aula page` turns it
into `aula-page.json`.
- **`.fabrica/aula.yaml`**: five `file:` shots, the PNGs the e2e suite took (part 5). `fabrica aula shots` checks each
one (a PNG, at most 2560 × 1600 and 3 MB) and writes `target/aula/aula-<name>.png` and `aula.json`. It starts no
browser for them.
- **`.fabrica/notes/<version>.md`**: the highlights a person writes. `fabrica notes` adds the merges since the
previous tag.
**What Aula shows.** Aula's server config lists each project with:
- its download globs;
- whether it must be signed.
That config is `modules/aula.nix` on the server, owned by the Configuration_Server session. Aula publishes a release
only when a file matches the download globs. So Ianitor's download is the source archive of the tag
(`ianitor-<version>-src.tar.gz`, `scripts/pack-source.mjs`). Ianitor's entry is in the Handover below.
v0.1.0 is already a signed release with the shots and the notes. It has no `aula-page.json`, because `aula: true`
came later. Aula keeps a file only when it is in the verified `SHA256SUMS`.
## 3. Updates: `fabrica-deploy`
Ianitor updates the way a server part does (Fabrica docs/36 part 3, "a server only: `deploy.yaml`"):
1. Fabrica's Apps → Ianitor → Deploy, or `fabrica deploy ianitor`, starts the `deploy` pipeline on the NixOS runner.
2. Mark approves it on his Custos card.
3. `fabrica-deploy@ianitor` fast-forwards the server's clone, updates the flake input `ianitor`, switches the system,
and asks the health check.
4. If the health check does not answer, it rolls the switch back.
That is the right way for Ianitor because:
- The code that runs is whatever the server's flake builds. A downloaded binary would be a second, unsigned path
around the Nix build.
- The web UI is part of the same Nix package (`.#ianitor-web`), served by control. A deploy replaces it with the
binaries, so there is nothing for a browser-side updater to do.
- A service worker would cache an admin UI that sits behind Authelia and must never be served stale. The UI has
none, on purpose.
A release does not deploy, and a deploy does not need a release. The deploy takes the server's chosen commit; the
release is the signed record of a version, with its pictures and notes. After a deploy, `deploy/test-access.sh` is
run from a LAN machine (CLAUDE.md).
## 4. Canalis: not applicable
Canalis is Fundamentum's layer for app-to-app calls **on one device** (Fundamentum `docs/CANALIS.md`):
- A caller and a target are both local processes. They are authenticated by Tessera subkeys and signed manifests,
and connected over a Noise channel.
- Part A registers `domi-<app-id>://open` with the operating system, under the user's own classes.
- Part B serves capabilities behind the app's own consent prompt, in the app's window.
- The template is for a Tauri 2 + Rust desktop app (a .NET one for Tabula).
Ianitor has none of the pieces this needs:
- No process on Mark's PC or phone.
- No window to show a consent prompt in.
- No scheme to register.
- No Tessera identity.
Its UI is a page served by a server, reached through the browser behind Authelia. Its control API listens on the
server's loopback only and never serves public traffic (CLAUDE.md), so no app on a device can reach it.
A capability another app could want ("give this new service a host") would be a call from a device to a server.
That is a remote API with its own authentication (control's API tokens, docs/api.md), not Canalis.
So Ianitor stops before Part A. If a Domi app ever needs to ask Ianitor for something, the answer is a scoped API
token and a documented call, written in its own design doc.
## 5. Showcase: the e2e suite, screenshots and videos
`apps/web/playwright.config.ts`, `apps/web/e2e/`:
**The server.** The suite's global setup (`e2e/serve.ts`):
- builds the UI (Vite, production) into a fresh temporary folder;
- serves it on `127.0.0.1` at a free port, with `/api/v1` answered by the demo control plane (`tests/demo.ts`: hosts
under `.test`, addresses in the documentation ranges, people *ada* and *felix*);
- sends any other path to `index.html`, as production does.
`POST /__demo/reset` starts the demo over. Every test starts from the same invented server.
**The clock.** The instant is `2026-11-16T09:30:00+01:00`, a Monday in `Europe/Prague`, with locale `en-GB`. Two
things read it:
- the demo's answers (`tests/mockApi.ts` `clock`);
- the page's `Date` (`page.clock.setFixedTime`).
So "2 h ago", "today 07:30" and every expiry date read the same in every take. This is what Fabrica's visual
comparison needs (docs/28).
**The checks on every page.** After each test, every text, field and link the page shows is checked with
`realLooking` (tests/demo.ts), which the vitest demo test already uses. A name outside `.test`, an address outside the
documentation ranges, or a forbidden word fails the test.
**The browser.** On Windows it is the installed Edge (`PW_CHANNEL` names another), so nothing is downloaded.
Elsewhere it is Playwright's own Chromium. Video recording needs Playwright's ffmpeg in `PLAYWRIGHT_BROWSERS_PATH`,
which is on F: on Mark's PC and never on C:.
**The projects.**
| Project | Command | What it does | Writes |
| :-- | :-- | :-- | :-- |
| `web` | `pnpm --filter web test:e2e` | The main flows of ROADMAP §4, with the clicks counted as in the smoke test: Add a host (2), Undo (1), Restore (3), Share link (3), Switch engine (2), Device certificate (3). Each is recorded at 1440 × 900. | `target/e2e/videos/<flow>.webm` |
| `aula` | `pnpm --filter web aula:shots` | The five screenshots of `tests/demo.ts` SHOTS at 1440 × 900, scale 1, once nothing is busy and the fonts and two frames are in. | `target/e2e/aula/<name>.png` |
**Videos.** The flows' recordings are WebM, a few seconds each. Fabrica's `videos:` in `aula.yaml` is planned (its
docs/36, docs/37) but not on Fabrica `main`, where the key still fails as unknown. Until it lands:
- the release publishes the screenshots only;
- the videos are artifacts of the e2e run;
- Pensum ticket "Publish the showcase videos on Aula" holds the change. That change is a `videos:` list in
`aula.yaml` naming `target/e2e/videos/*.webm`, and the release's file globs.
**The visual gate waits one release.** Fabrica's `visual` step compares the shots with the last signed release's.
v0.1.0's shots were taken by the old DevTools script at a moving clock, so every shot would differ, and the first
release would stop for an approval of a change that is only the clock. So:
- this release (v0.2.0) publishes the fixed-clock shots;
- the `visual` step comes with the next release, against v0.2.0;
- Pensum ticket "Turn on the visual gate against v0.2.0" holds it.
`apps/web/scripts/shots.mjs` is removed: the suite takes the same five pictures, and `fabrica aula shots` writes
`aula.json`.
## 6. Test targets
- **`.fabrica/tests.yaml`**: `dir: apps/web`, one target `web` (kind `web`, project `web`), which is also the merge
gate. `fabrica tests run --target web` runs it off-screen, and the record, traces and videos go under
`.fabrica/runs/tests/`. The Playwright config passes `FABRICA_TESTS_DEVTOOLS` to the browser for the Tests page's
live view.
- **`.fabrica/artifex/e2e.yaml`**: Fabrica's own e2e pipeline with `fabrica` for `cargo run`. It is manual, on
`windows-e2e`, and runs `pnpm install --frozen-lockfile` then `fabrica tests run --target web`, with
`.fabrica/runs/tests/**` as the artifacts.
- **No `android` target.** Ianitor has no Android build. Its UI on a phone is the same page in the phone's browser,
which a `web` target with a phone viewport would test. That is a gap (below), not a phone queue item.
- **The Rust suites** (core, edge, control, diff) are not Playwright. They run in WSL2 and in the Nix build
(ROADMAP §8.3). Edge, diff and ACME are Linux-only and need caddy and pebble, which the Windows e2e runner does
not have.
## Risks
| Risk | Answer |
| :-- | :-- |
| A picture or video shows Mark's network | The UI talks only to the demo control plane. `realLooking` checks every page every test visits. The PNGs are looked at in the review. |
| The demo server is reachable from the LAN | It listens on `127.0.0.1` only, at a free port, for the length of the run. |
| A secret reaches the browser | The demo serves no token, key or certificate. The demo API token answer is the stand-in's invented `ian_tk1_…`, which no flow shows. |
| Two takes of a screen differ | A fixed instant and zone, the demo reset before each test, fonts and two frames awaited, animations disabled in the screenshot. |
| A video grows too large | Each flow is under 15 s at 1440 × 900. docs/37's limits (8 MiB, 60 s, 6 videos) are checked when `videos:` lands. |
| The release is held by the visual gate on the clock change | The gate comes one release later (part 5). |
## Gaps
- The videos are not on Aula until Fabrica's `videos:` is on `main` (Pensum ticket).
- There is no visual gate in v0.2.0 (Pensum ticket).
- There are no phone-width shots or tests, and no tests in WebKit or Firefox.
- The `e2e` pipeline has not run on the `windows-e2e` runner from this repo. The suite was run here, with Playwright
directly and with `fabrica tests run`.
- There is no Canalis (part 4).
## Handover
**Aula entry** for the server's `modules/aula.nix` (the Configuration_Server session adds it). `files` lists the
downloads only. Aula reads the kit (`aula-*.png`, `aula.json`, `aula-page.json`, `release-notes.md`) by itself and
never offers it as a download.
Aula publishes no release that has no file matching `files` (Aula `src/aula_sync.py`). That is why v0.1.0, with the
default `*-setup.exe`, shows nothing. v0.2.0 is the first release with a download.
```nix
{
name = "Ianitor";
repo = "mnovak/ianitor";
files = [ "ianitor-*-src.tar.gz" ];
signed = true;
}
```
**Releasing 0.2.0** (docs/release.md, "Handover"):
1. `[repo] Release: 0.2.0` on main.
2. Tag `v0.2.0` and push it.
3. Start `release` at `v0.2.0` on the hub.
4. Mark approves on the Custos card, then signs `SHA256SUMS` with `domi-release`.
+107
View File
@@ -0,0 +1,107 @@
# Branch previews (T4)
Every branch Fabrica builds can get its own address: `<branch>--<project>.<preview domain>`, with a certificate
from the Domi CA (internal) or Let's Encrypt (public). It closes when the branch is merged, or when its lifetime
runs out. Fabrica's coherence roadmap, `docs/32_coherence.md` in Fabrica, phase T4.
## Set up (once per server)
1. A wildcard DNS record for the preview domain points at the server: `*.preview.example.org`.
2. `[previews]` in control.toml (the installers write it from `IANITOR_PREVIEW_DOMAIN` and
`IANITOR_PREVIEW_UPSTREAMS`; NixOS: `services.ianitor.previews`):
```toml
[previews]
domain = "preview.example.org"
tls = "domi" # or "letsencrypt" (one certificate per preview; mind the rate limits)
auth = "none" # or "forward-auth" (behind the site's Authelia)
upstreams = ["10.0.0.0/8", "127.0.0.1:20000-29999", "app.internal", "*.svc.internal:8080"]
default_ttl_secs = 259200 # 72 h; min_ttl_secs 300, max_ttl_secs 30 days, max_previews 100, sweep_secs 30
```
`upstreams` is the allow list of where previews may send traffic: a network (`10.0.0.0/8`, `fd00::/8`), an
address with a port or port range (`127.0.0.1:20000-29999`), a name (`app.internal`) or every name under a suffix
(`*.svc.internal`), each with an optional port. Nothing else is accepted. Whatever the list says, a preview can never
point at control's own port, Caddy's admin port (2019 and the configured one), an unspecified, link-local or
multicast address, or an IPv4-mapped IPv6 address. A name is checked as written, not as it resolves: list only names
you control.
3. A token for Fabrica that may only manage previews:
`ianitor-control token create --name "Fabrica previews" --scope previews --config <control.toml>`, or
Settings → API → *Previews only* → New token. It goes into the Custos team vault (see *The token* below).
## The API
All calls carry `Authorization: Bearer <token>`; the token may be a full one or a previews-only one. A previews-only
token gets `403 token.scope` on every other route, reads included.
| Call | Body | Answer |
| :-- | :-- | :-- |
| `POST /api/v1/previews` | `{project, branch, upstream, ttl?}` | `202 {preview, apply}`: opens the branch's preview, or moves it (new upstream, new lifetime) |
| `GET /api/v1/previews/{hostname}` | | `200 {preview}` with `state`: `applying`, `live` or `failed` (with `problem`) |
| `GET /api/v1/previews` | | `200 {items, domain}` |
| `POST /api/v1/previews/close` | `{project, branch}` | `202 {apply}`: on merge or branch deletion; `404` when there is none |
| `DELETE /api/v1/previews/{hostname}` | | `202 {apply}`; `404 preview.not_found` for any host that is not a preview |
- `project` is Fabrica's project name (`mnovak/Arca`, `github:acme/web`): 1–128 of `A-Za-z0-9._/:-`.
- `branch` is the branch as the git host names it, any characters except control characters, up to 255 bytes.
- `upstream` is `http(s)://host:port` with no path, user or query, and must be in the allow list.
- `ttl` is seconds (default `default_ttl_secs`).
- A preview is an ordinary host file in the routes repository (`hosts/<name>.toml` with a `[preview]` table),
so it goes through the same validation, compilers, differential tests and commit-confirmed apply (trial, watch,
revert) as any host, and shows in History. Its answers carry `X-Robots-Tag: noindex, nofollow`.
- The apply is live when `GET /api/v1/previews/{hostname}` says `live`; poll every 2 s. A failed apply (the branch
build did not answer during the watch) says `failed` with Ianitor's reason, and the preview is not served.
- Errors: `preview.off` (no `[previews]`), `preview.taken` (another host or branch has that name),
`preview.branch`, `preview.project`, `preview.ttl`, `preview.upstream`, `preview.upstream_not_allowed`,
`preview.too_many`, `token.scope`.
## Names
The label is `<branch part>--<project part>` (core `preview::label`, tests in `crates/core/tests/preview.rs`):
- each part is lowercased, every run of other characters than `a-z0-9` becomes one `-`, dashes trimmed; the project
part is the repository name only (after the last `/` or `:`);
- if that lost anything (case, a character, the owner, length), the part gets `-` and 6 hex digits of SHA-256 of
the whole original, so `feature/login` and `feature-login`, or `alice/app` and `bob/app`, never share a host;
- the branch part is 3–40 characters, the project part 1–20, so the label is at most 62 and never has `--` in
positions 3–4 (reserved for IDNA; Let's Encrypt refuses those).
| Project | Branch | Host |
| :-- | :-- | :-- |
| `shop` | `fix-42` | `fix-42--shop.preview.example.org` |
| `mnovak/Arca` | `main` | `main--arca-4a93cc.preview.example.org` |
| `github:acme/Web.App` | `feature/Ünï ../../etc` | `feature-n-etc-50d099--web-app-4ff2e1.preview.example.org` |
Two branches can still collide only by a 24-bit hash collision; control then answers `409 preview.taken` instead of
taking the other branch's host.
## The token, from the Custos team vault
The previews-only token is a secret: it lives in the team vault, and Fabrica gets it per deployment, the way it
gets any target credential (Custos `docs/27_team_vault.md`, Fabrica `docs/handover/t1-sign-request.md`): the preview
build is signed under the team's `preview` environment (0 approvals: the test key signs at once), the sign reply's
ticket authorises one `target.request` for the Ianitor target of that project and environment, and the token comes
back sealed to Fabrica's one-time key. Fabrica uses it for that deployment and drops it.
Custos's target kinds today are `ssh-key`, `winrm`, `openssh`, `registry` and `kubeconfig`; an API token for an HTTP
service has no kind of its own yet. Until Custos adds one (`http-token`, written up in docs/custos-ticket.md), keep
it as `registry` (a token with a host), which carries the same fields.
## A client
`scripts/preview.sh` (curl and jq) and `scripts/preview.ps1` are what a Fabrica pipeline step runs until Fabrica has
a preview step of its own:
```bash
IANITOR_URL=https://ianitor.example.org IANITOR_PREVIEW_TOKEN=… scripts/preview.sh open mnovak/Arca "$BRANCH" http://10.0.0.7:8080 86400
```
```bash
scripts/preview.sh close mnovak/Arca "$BRANCH"
```
## Screens
Previews (the nav): every open preview with its state, branch, project, upstream and when it closes (1 click);
Close → Close preview (2 clicks).
+63 -71
View File
@@ -1,70 +1,69 @@
# Releases: the source, the notes and the Aula page on the Gitea release
# Releases: notes and screenshots on the Gitea release
Ianitor is server-only. What runs is built by Nix on the server and switched in by the `deploy` pipeline
(`.fabrica/artifex/deploy.yaml`, `fabrica-deploy@ianitor`).
Ianitor is server-only: what runs is built by Nix on the server and switched in by the `deploy` pipeline
(`.fabrica/artifex/deploy.yaml`, `fabrica-deploy@ianitor`). A release adds what a deploy does not leave behind: a
Gitea release for the `vX.Y.Z` tag with the release notes and screenshots of the web UI, under a `SHA256SUMS`
signed by `domi-release`. It ships no binary; the deploy stays the deploy.
A release adds what a deploy does not leave behind: a Gitea release for the `vX.Y.Z` tag with these files, all under
a `SHA256SUMS` signed by `domi-release`:
- the source archive of the tag;
- the release notes;
- the screenshots of the web UI;
- the Aula landing page.
The release ships no binary, and the deploy stays the deploy. docs/fabrica.md says how the six Fabrica items (Aula,
updates, Canalis, showcase, tests) fit Ianitor.
The release kit is Fabrica's (Fabrica `docs/12_release_kit.md`, `docs/19_web_shots.md`; core `docs/FORMATS.md`,
"Fabrica: release notes" and "Fabrica: the Aula page"). The screenshots are `file:` shots, PNGs taken by the web UI's
own Playwright suite. `fabrica aula shots` checks them and writes `aula.json`.
The release kit is Fabrica's (Fabrica `docs/12_release_kit.md`, core `docs/FORMATS.md`, "Fabrica: release notes"
and "Fabrica: the Aula page"). Ianitor uses it as it is, with one difference: Fabrica's `fabrica aula shots`
drives a built Windows WebView2 exe, which Ianitor does not have, so a repo script takes the same files from the
web UI in a headless browser.
## The pipeline: `.fabrica/artifex/release.yaml`
`on: tag "v*"` and `manual: true`, on the Windows runner. That is the Fabrica app on Mark's PC: `fabrica`, node and
pnpm are on every step's PATH.
`on: tag "v*"` and `manual: true`, on the Windows runner (the Fabrica app on Mark's PC: `fabrica`, node and pnpm
are on every step's PATH).
| Step | Does | Produces |
| :-- | :-- | :-- |
| `version` | `node scripts/check-version.mjs <version>`: the tag's version must be the workspace `Cargo.toml`'s and both `package.json`s' | |
| `install` | `pnpm install --frozen-lockfile` | |
| `check`, `test` | `svelte-check` and vitest (the click smoke test and the demo data test) | |
| `e2e` | `pnpm --filter web test:e2e`: the main flows in Edge on the built UI and the demo control plane, each recorded (docs/fabrica.md part 5) | `target/e2e/videos/*.webm` (not published yet) |
| `pictures` | `pnpm --filter web aula:shots`: the five screens from the same suite | `target/e2e/aula/<name>.png` |
| `source` | `node scripts/pack-source.mjs <version>`: `git archive` of the tag | `target/release/ianitor-<version>-src.tar.gz` |
| `notes` | `fabrica notes`: the range since the previous `v*` tag | `target/notes/release-notes.md`, `release-notes.json` |
| `shots` | `fabrica aula shots`: checks the five PNGs (`.fabrica/aula.yaml`) and copies them | `target/aula/aula-<name>.png`, `aula.json` |
| `page` | `fabrica aula page`: the brief (`.fabrica/aula/brief.md`), the shots and the notes | `target/aula/aula-page.json` |
| `check`, `test` | `svelte-check` and the vitest click smoke test of the web UI the shots show | |
| `notes` | `fabrica notes` (the range since the previous `v*` tag; the first release covers the whole history) | `target/notes/release-notes.md`, `release-notes.json` |
| `shots` | `node apps/web/scripts/shots.mjs` (below) | `target/aula/aula-<name>.png`, `aula.json` |
| `approve` | the run's Custos approval, before anything is published | |
| `publish` | the Gitea release of the tag with the files above. `sums: domi-release` adds `SHA256SUMS` and `SHA256SUMS.minisig`. `release-notes.md` becomes the release's text. | |
| `publish` | the Gitea release of the tag: the notes, the shots and `aula.json`; `sums: domi-release` adds `SHA256SUMS` and `SHA256SUMS.minisig`; `release-notes.md` becomes the release's text | |
The Rust tests are not in it. The edge, diff and ACME tests are Linux-only (ROADMAP §8.3), and the release builds
The Rust tests are not in it: the edge, diff and ACME tests are Linux-only (ROADMAP §8.3) and the release builds
nothing. They run in WSL2 and in the Nix build.
**The download.** Aula offers a project's release only when it has a file to download, and kit files (the shots,
the notes, the page) never count. Ianitor's download is its source archive. The archive is every tracked file at the
tag, under `ianitor-<version>/`. `git archive` of one tree gives the same bytes every time.
**No landing page.** `fabrica aula page` and `aula-page.json` are left out while `.fabrica/app.yaml` has no
`aula: true`. Turning Aula on later is two lines: `aula: true` in `app.yaml` and a `page` step (`fabrica aula
page`, after `notes` and `shots`) whose `aula-page.json` is published; a brief (`.fabrica/aula/brief.md`) is
optional, its caption names are the shot names below.
**app.yaml** has `aula: true` and one `server` part. There is no desktop part: a desktop part's Deploy bumps the
version and pushes a tag for an installer release, and Ianitor has no installer. The release is started by its tag.
**app.yaml stays as it is.** Its parts are `desktop` (a release pipeline started by the tag the card's Deploy
bumps and pushes, with installers) and `server` (a deploy pipeline). Ianitor has no installer and no version bump to
make, so it keeps its one `server` part; the release is started by its tag.
## Release notes
`fabrica notes` writes them from:
- the first-parent commit subjects;
- the Pensum tickets done;
- `.fabrica/notes/<version>.md`, the highlights a person writes.
`fabrica notes` writes them from the first-parent commit subjects, the Pensum tickets done (Ianitor has none) and
`.fabrica/notes/<version>.md`, the highlights a person writes. The merges of PR 3 to 5 predate the
`[repo] Merge: <branch> (<title>, PR #n)` form and come out as bare "PR #n" lines; history is not rewritten, so
`.fabrica/notes/0.1.0.md` says in a few sentences what 0.1.0 is, and goes first.
The highlights go first.
## Screenshots: `apps/web/scripts/shots.mjs`
## Screenshots
`node apps/web/scripts/shots.mjs [--out <dir>]` (default `target/aula` at the repo root):
`apps/web/e2e/specs/aula.spec.ts`, project `aula` of `apps/web/playwright.config.ts` (docs/fabrica.md part 5). For
each shot of `apps/web/tests/demo.ts` SHOTS, it:
1. loads the page at 1440 × 900, scale 1, at the suite's fixed instant;
2. clicks the shot's selectors;
3. waits for its selector, for no `aria-busy` element, for the fonts, two frames and 400 ms;
4. saves `target/e2e/aula/<name>.png`.
The suite's global setup builds the UI and serves it on `127.0.0.1` with `/api/v1` answered by the demo control plane.
1. empties the output folder of `aula-*.png` and `aula.json`;
2. builds the web UI (Vite, production) into a fresh temporary folder;
3. serves it on `127.0.0.1` (a free port), with `/api/v1` answered by the demo control plane
(`apps/web/tests/demo.ts`), and every other path falling back to `index.html` as in production;
4. starts headless Microsoft Edge (or Chrome; `IANITOR_SHOTS_BROWSER` names another) with a fresh profile in the
temporary folder, its DevTools port on loopback only, and a cleared environment (the system variables and the
temporary folder, nothing of the runner's: no `GITEA_TOKEN`, no hub token); a browser whose DevTools do not
answer within 20 s is stopped and started again, at most three times;
5. for each shot: sets the viewport (1440 × 900, scale 1), loads its page, clicks its selectors, waits for its
selector, the fonts, two frames and 400 ms, and saves `aula-<name>.png`; a wait that runs out (20 s) saves
`aula-<name>-failed.png` and fails;
6. writes `aula.json` in the format of core `docs/FORMATS.md` ("Fabrica: the Aula page"): `{"v":1,"shots":[…]}`,
each shot's `name`, `title`, `file`, `width` and `height` read from the PNG, and `sha256`;
7. on every way out kills the browser's process tree and, on Windows, any process left with a profile in the
temporary folder (Edge can start its browser again as a new process, outside the tree), stops the server, and
removes the temporary folder.
| Name | Page | Shows |
| :-- | :-- | :-- |
@@ -79,39 +78,32 @@ test's stand-in (`apps/web/tests/mockApi.ts`: the same host and apply shapes and
replace). Its data is invented: hostnames under `.test`, upstream addresses in the documentation ranges
(192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24), people *ada* and *felix*, made-up commits, match codes and
fingerprints. A vitest test (`apps/web/tests/demo.test.ts`) asks every page's calls and fails on any other
hostname or address, and the e2e suite checks every page it visits the same way (`realLooking`), so a real name
cannot slip in through a later fixture.
hostname or address, so a real name cannot slip in through a later fixture.
## Risks
| Risk | Answer |
| :-- | :-- |
| A screenshot or video shows Mark's network | The UI talks only to the demo control plane. The demo data test and the e2e suite's `realLooking` check refuse names outside `.test` and addresses outside the documentation ranges. The PNGs are looked at in the review. |
| The browser reaches out | It loads only `127.0.0.1`, and the UI's own CSP allows no outside requests. Playwright's profile is temporary. |
| A secret reaches the browser | The demo serves no token, key or certificate. |
| A forged screenshot, note or archive | They are release assets under `SHA256SUMS`, signed by `domi-release` through Custos. The Gitea text is not signed; the asset is. |
| The source archive is not the tag | It is `git archive` of the run's HEAD, the tag's commit in the run's clean worktree. Anyone can repeat it and compare the SHA-256. |
| A shot of a half-drawn screen | Each `wait` selector exists only once the screen's data is there. The page has no `aria-busy` element, and the fonts and two frames are awaited. |
| A screenshot shows Mark's network | The UI talks only to the demo control plane; the demo data test refuses names outside `.test` and addresses outside the documentation ranges; the PNGs are looked at in the review. |
| The browser reaches out | It loads only `127.0.0.1`; the UI's own CSP allows no outside requests; background networking, sync and component updates are off; its profile is thrown away. |
| A secret reaches the browser | Its environment is cleared to the system variables. The demo serves no token, key or certificate. |
| A forged screenshot or note | They are release assets under `SHA256SUMS`, signed by `domi-release` through Custos; the Gitea text is not signed, the asset is. |
| The browser outlives the run | Its process tree is killed on every way out (`taskkill /T` on Windows). |
| A shot of a half-drawn screen | Each `wait` selector exists only once the screen's data is there; fonts and two frames are awaited. |
## Gaps
- Tested on Windows with Edge only. The suite is plain Playwright and should work in Chromium on Linux, but that is
untested.
- One size (desktop). There is no phone layout shot.
- Windows and Edge or Chrome only as tested; the script is plain Node and DevTools, so Linux with Chromium should
work, untested.
- One size (desktop); no phone layout shot.
- The release does not run the Rust tests (see above).
- No `[repo] Release:` step: the version in `Cargo.toml`, `Cargo.lock` and the `package.json`s is changed by hand
before tagging.
- The flows' videos are not published yet (docs/fabrica.md part 5).
- No `[repo] Release:` bump: the version in `Cargo.toml` and the `package.json`s is changed by hand before tagging.
## Handover: releasing a version
## Handover: releasing 0.1.0
1. On main, set the version in `Cargo.toml`, `Cargo.lock` and both `package.json`s. `node scripts/check-version.mjs
X.Y.Z` must pass. Write `.fabrica/notes/X.Y.Z.md`.
2. Tag and push: `git tag vX.Y.Z && git push origin vX.Y.Z`.
3. Start the `release` pipeline at `vX.Y.Z` from Fabrica. No Gitea webhook reaches the hub yet, so use the hub's
`POST /api/runs` with ref `vX.Y.Z`.
4. Approve on the Custos card, then sign `SHA256SUMS` on Custos (`domi-release`).
5. Check the Gitea release `vX.Y.Z`. Its text is the notes. Its files are `ianitor-X.Y.Z-src.tar.gz`,
`release-notes.md`, `release-notes.json`, five `aula-*.png`, `aula.json`, `aula-page.json`, `SHA256SUMS` and
`SHA256SUMS.minisig`.
6. Deploy as before: Fabrica's *Apps* → Ianitor → *Deploy*, then run deploy/test-access.sh from a LAN machine.
1. On main: `git tag v0.1.0 && git push origin v0.1.0`.
2. Start the `release` pipeline at `v0.1.0` from Fabrica (no Gitea webhook to the hub yet: the hub's
`POST /api/runs`, ref `v0.1.0`). Approve on the Custos card, then sign `SHA256SUMS` on Custos (`domi-release`).
3. The Gitea release `v0.1.0` has the notes as its text and `release-notes.md`, `release-notes.json`, five
`aula-*.png`, `aula.json`, `SHA256SUMS` and `SHA256SUMS.minisig`.
4. Deploy as before: Fabrica's *Apps* → Ianitor → *Deploy*, then deploy/test-access.sh from a LAN machine.
+25 -80
View File
@@ -14,24 +14,18 @@ importers:
specifier: workspace:*
version: link:../../packages/ui
devDependencies:
'@playwright/test':
specifier: 1.56.1
version: 1.56.1
'@sveltejs/vite-plugin-svelte':
specifier: ^5.0.3
version: 5.1.1(svelte@5.57.3)(vite@6.4.5(@types/node@22.20.5))
version: 5.1.1(svelte@5.57.3)(vite@6.4.5)
'@testing-library/svelte':
specifier: ^5.2.6
version: 5.4.2(svelte@5.57.3)(vite@6.4.5(@types/node@22.20.5))(vitest@3.2.7(@types/node@22.20.5)(jsdom@26.1.0))
version: 5.4.2(svelte@5.57.3)(vite@6.4.5)(vitest@3.2.7(jsdom@26.1.0))
'@testing-library/user-event':
specifier: ^14.6.1
version: 14.6.8(@testing-library/dom@10.4.2)
'@tsconfig/svelte':
specifier: ^5.0.4
version: 5.0.8
'@types/node':
specifier: ^22.20.5
version: 22.20.5
jsdom:
specifier: ^26.0.0
version: 26.1.0
@@ -46,10 +40,10 @@ importers:
version: 5.9.3
vite:
specifier: ^6.1.0
version: 6.4.5(@types/node@22.20.5)
version: 6.4.5
vitest:
specifier: ^3.0.5
version: 3.2.7(@types/node@22.20.5)(jsdom@26.1.0)
version: 3.2.7(jsdom@26.1.0)
packages/ui:
dependencies:
@@ -292,11 +286,6 @@ packages:
'@jridgewell/trace-mapping@0.3.31':
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
'@playwright/test@1.56.1':
resolution: {integrity: sha512-vSMYtL/zOcFpvJCW71Q/OEGQb7KYBPAdKh35WNSkaZA75JlAO8ED8UN6GUNTm3drWomcbcqRPFqQbLae8yBTdg==}
engines: {node: '>=18'}
hasBin: true
'@rollup/rollup-android-arm-eabi@4.68.0':
resolution: {integrity: sha512-Ta2n0ntLfzP0LqwwcXOIh2z0mnHjlxMS+h4Y9lo+w33Quyf9KFKEi9QZ2IKqeEBKr0qxNpXc/DQjz5KVIs8AEA==}
cpu: [arm]
@@ -495,9 +484,6 @@ packages:
'@types/estree@1.0.10':
resolution: {integrity: sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==}
'@types/node@22.20.5':
resolution: {integrity: sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==}
'@vitest/expect@3.2.7':
resolution: {integrity: sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==}
@@ -656,11 +642,6 @@ packages:
picomatch:
optional: true
fsevents@2.3.2:
resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
os: [darwin]
fsevents@2.3.3:
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
@@ -755,16 +736,6 @@ packages:
resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==}
engines: {node: '>=12'}
playwright-core@1.56.1:
resolution: {integrity: sha512-hutraynyn31F+Bifme+Ps9Vq59hKuUCz7H1kDOcBs+2oGguKkWTU50bBWrtz34OUWmIwpBTWDxaRPXrIXkgvmQ==}
engines: {node: '>=18'}
hasBin: true
playwright@1.56.1:
resolution: {integrity: sha512-aFi5B0WovBHTEvpM3DzXTUaeN6eN0qWnTkKx4NQaH4Wvcmc153PdaY2UBdSYKaGYw+UyWXSVyxDUg5DoPEttjw==}
engines: {node: '>=18'}
hasBin: true
postcss@8.5.32:
resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==}
engines: {node: ^10 || ^12 || >=14}
@@ -876,9 +847,6 @@ packages:
engines: {node: '>=14.17'}
hasBin: true
undici-types@6.21.0:
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
vite-node@3.2.4:
resolution: {integrity: sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==}
engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}
@@ -1151,10 +1119,6 @@ snapshots:
'@jridgewell/resolve-uri': 3.1.2
'@jridgewell/sourcemap-codec': 1.6.0
'@playwright/test@1.56.1':
dependencies:
playwright: 1.56.1
'@rollup/rollup-android-arm-eabi@4.68.0':
optional: true
@@ -1239,25 +1203,25 @@ snapshots:
'@sveltejs/load-config@0.2.3': {}
'@sveltejs/vite-plugin-svelte-inspector@4.0.1(@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.57.3)(vite@6.4.5(@types/node@22.20.5)))(svelte@5.57.3)(vite@6.4.5(@types/node@22.20.5))':
'@sveltejs/vite-plugin-svelte-inspector@4.0.1(@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.57.3)(vite@6.4.5))(svelte@5.57.3)(vite@6.4.5)':
dependencies:
'@sveltejs/vite-plugin-svelte': 5.1.1(svelte@5.57.3)(vite@6.4.5(@types/node@22.20.5))
'@sveltejs/vite-plugin-svelte': 5.1.1(svelte@5.57.3)(vite@6.4.5)
debug: 4.4.3
svelte: 5.57.3
vite: 6.4.5(@types/node@22.20.5)
vite: 6.4.5
transitivePeerDependencies:
- supports-color
'@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.57.3)(vite@6.4.5(@types/node@22.20.5))':
'@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.57.3)(vite@6.4.5)':
dependencies:
'@sveltejs/vite-plugin-svelte-inspector': 4.0.1(@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.57.3)(vite@6.4.5(@types/node@22.20.5)))(svelte@5.57.3)(vite@6.4.5(@types/node@22.20.5))
'@sveltejs/vite-plugin-svelte-inspector': 4.0.1(@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.57.3)(vite@6.4.5))(svelte@5.57.3)(vite@6.4.5)
debug: 4.4.3
deepmerge: 4.3.1
kleur: 4.1.5
magic-string: 0.30.21
svelte: 5.57.3
vite: 6.4.5(@types/node@22.20.5)
vitefu: 1.1.3(vite@6.4.5(@types/node@22.20.5))
vite: 6.4.5
vitefu: 1.1.3(vite@6.4.5)
transitivePeerDependencies:
- supports-color
@@ -1276,14 +1240,14 @@ snapshots:
dependencies:
svelte: 5.57.3
'@testing-library/svelte@5.4.2(svelte@5.57.3)(vite@6.4.5(@types/node@22.20.5))(vitest@3.2.7(@types/node@22.20.5)(jsdom@26.1.0))':
'@testing-library/svelte@5.4.2(svelte@5.57.3)(vite@6.4.5)(vitest@3.2.7(jsdom@26.1.0))':
dependencies:
'@testing-library/dom': 10.4.2
'@testing-library/svelte-core': 1.1.3(svelte@5.57.3)
svelte: 5.57.3
optionalDependencies:
vite: 6.4.5(@types/node@22.20.5)
vitest: 3.2.7(@types/node@22.20.5)(jsdom@26.1.0)
vite: 6.4.5
vitest: 3.2.7(jsdom@26.1.0)
'@testing-library/user-event@14.6.8(@testing-library/dom@10.4.2)':
dependencies:
@@ -1302,10 +1266,6 @@ snapshots:
'@types/estree@1.0.10': {}
'@types/node@22.20.5':
dependencies:
undici-types: 6.21.0
'@vitest/expect@3.2.7':
dependencies:
'@types/chai': 5.2.3
@@ -1314,13 +1274,13 @@ snapshots:
chai: 5.3.3
tinyrainbow: 2.0.0
'@vitest/mocker@3.2.7(vite@6.4.5(@types/node@22.20.5))':
'@vitest/mocker@3.2.7(vite@6.4.5)':
dependencies:
'@vitest/spy': 3.2.7
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
vite: 6.4.5(@types/node@22.20.5)
vite: 6.4.5
'@vitest/pretty-format@3.2.7':
dependencies:
@@ -1459,9 +1419,6 @@ snapshots:
optionalDependencies:
picomatch: 4.0.7
fsevents@2.3.2:
optional: true
fsevents@2.3.3:
optional: true
@@ -1558,14 +1515,6 @@ snapshots:
picomatch@4.0.7: {}
playwright-core@1.56.1: {}
playwright@1.56.1:
dependencies:
playwright-core: 1.56.1
optionalDependencies:
fsevents: 2.3.2
postcss@8.5.32:
dependencies:
nanoid: 3.3.20
@@ -1706,15 +1655,13 @@ snapshots:
typescript@5.9.3: {}
undici-types@6.21.0: {}
vite-node@3.2.4(@types/node@22.20.5):
vite-node@3.2.4:
dependencies:
cac: 6.7.14
debug: 4.4.3
es-module-lexer: 1.7.0
pathe: 2.0.3
vite: 6.4.5(@types/node@22.20.5)
vite: 6.4.5
transitivePeerDependencies:
- '@types/node'
- jiti
@@ -1729,7 +1676,7 @@ snapshots:
- tsx
- yaml
vite@6.4.5(@types/node@22.20.5):
vite@6.4.5:
dependencies:
esbuild: 0.25.12
fdir: 6.5.0(picomatch@4.0.7)
@@ -1738,18 +1685,17 @@ snapshots:
rollup: 4.68.0
tinyglobby: 0.2.17
optionalDependencies:
'@types/node': 22.20.5
fsevents: 2.3.3
vitefu@1.1.3(vite@6.4.5(@types/node@22.20.5)):
vitefu@1.1.3(vite@6.4.5):
optionalDependencies:
vite: 6.4.5(@types/node@22.20.5)
vite: 6.4.5
vitest@3.2.7(@types/node@22.20.5)(jsdom@26.1.0):
vitest@3.2.7(jsdom@26.1.0):
dependencies:
'@types/chai': 5.2.3
'@vitest/expect': 3.2.7
'@vitest/mocker': 3.2.7(vite@6.4.5(@types/node@22.20.5))
'@vitest/mocker': 3.2.7(vite@6.4.5)
'@vitest/pretty-format': 3.2.7
'@vitest/runner': 3.2.7
'@vitest/snapshot': 3.2.7
@@ -1767,11 +1713,10 @@ snapshots:
tinyglobby: 0.2.17
tinypool: 1.1.1
tinyrainbow: 2.0.0
vite: 6.4.5(@types/node@22.20.5)
vite-node: 3.2.4(@types/node@22.20.5)
vite: 6.4.5
vite-node: 3.2.4
why-is-node-running: 2.3.0
optionalDependencies:
'@types/node': 22.20.5
jsdom: 26.1.0
transitivePeerDependencies:
- jiti
-35
View File
@@ -1,35 +0,0 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// The release's one download (docs/release.md): the source of the commit being released, as
// target/release/ianitor-X.Y.Z-src.tar.gz (every file git tracks, under ianitor-X.Y.Z/)
// Ianitor ships no binary: the server builds it with Nix (docs/fabrica.md part 3). The archive is
// listed in the release's SHA256SUMS, signed by domi-release, so the source a version names can be
// checked. `git archive` of one tree gives the same bytes every time.
// node scripts/pack-source.mjs X.Y.Z
// Exit codes: 0 written, 1 git failed, 2 usage.
import { spawnSync } from "node:child_process";
import { mkdirSync, readdirSync, rmSync, statSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const repo = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const version = process.argv[2];
if (process.argv.length !== 3 || !/^\d+\.\d+\.\d+$/.test(version)) {
console.error("usage: node scripts/pack-source.mjs X.Y.Z");
process.exit(2);
}
const out = join(repo, "target", "release");
mkdirSync(out, { recursive: true });
for (const n of readdirSync(out)) if (/^ianitor-.*-src\.tar\.gz$/.test(n)) rmSync(join(out, n), { force: true });
const file = join(out, `ianitor-${version}-src.tar.gz`);
const git = spawnSync("git", ["archive", "--format=tar.gz", `--prefix=ianitor-${version}/`, "-o", file, "HEAD"], { cwd: repo, stdio: "inherit" });
if (git.error || git.status !== 0) {
console.error(`pack-source: git archive failed${git.error ? `: ${git.error.message}` : ` (exit ${git.status})`}`);
process.exit(1);
}
console.log(`pack-source: ${file} (${statSync(file).size} bytes)`);
+39
View File
@@ -0,0 +1,39 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// The Windows Server release zip (Caddy mode, T4): ianitor-control.exe (release build without
// the test hooks), the built web UI and deploy/windows/install.ps1, in
// target/dist/ianitor-<version>-windows-x86_64.zip. Caddy is not in it: install.ps1 fetches the
// pinned version and checks its SHA-512.
//
// cargo build --release -p ianitor-control --no-default-features
// pnpm --filter web build
// node scripts/package-windows.mjs
import { cpSync, existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
import { join } from "node:path";
import { execFileSync } from "node:child_process";
const root = new URL("..", import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, "$1");
const version = /^version = "([^"]+)"/m.exec(readFileSync(join(root, "Cargo.toml"), "utf8"))?.[1];
if (!version) throw new Error("no version in Cargo.toml");
const target = process.env.CARGO_TARGET_DIR || join(root, "target");
const exe = join(target, "release", "ianitor-control.exe");
const web = join(root, "apps", "web", "dist");
for (const p of [exe, web]) if (!existsSync(p)) throw new Error(`missing ${p}: build it first`);
const name = `ianitor-${version}-windows-x86_64`;
const out = join(root, "target", "dist");
const stage = join(out, name);
rmSync(stage, { recursive: true, force: true });
mkdirSync(stage, { recursive: true });
cpSync(exe, join(stage, "ianitor-control.exe"));
cpSync(web, join(stage, "web"), { recursive: true });
cpSync(join(root, "deploy", "windows", "install.ps1"), join(stage, "install.ps1"));
cpSync(join(root, "LICENSE"), join(stage, "LICENSE"));
const zip = join(out, `${name}.zip`);
rmSync(zip, { force: true });
execFileSync("powershell", ["-NoProfile", "-Command", `Compress-Archive -Path '${stage}\\*' -DestinationPath '${zip}'`], { stdio: "inherit" });
rmSync(stage, { recursive: true, force: true });
console.log(zip);
+60
View File
@@ -0,0 +1,60 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
#
# The Windows twin of scripts/preview.sh (a Fabrica runner on Windows):
#
# scripts\preview.ps1 open -Project shop -Branch fix-42 -Upstream http://10.0.0.5:8080 [-Ttl 86400]
# scripts\preview.ps1 close -Project shop -Branch fix-42
# scripts\preview.ps1 list
#
# $env:IANITOR_URL, $env:IANITOR_PREVIEW_TOKEN (a `--scope previews` token from the Custos team
# vault). An internal (Domi) admin host needs the Domi root in the machine's trusted roots.
param(
[Parameter(Mandatory = $true, Position = 0)][ValidateSet('open', 'close', 'list')][string]$Action,
[string]$Project, [string]$Branch, [string]$Upstream, [int]$Ttl = 0
)
$ErrorActionPreference = 'Stop'
if (-not $env:IANITOR_URL -or -not $env:IANITOR_PREVIEW_TOKEN) { throw 'set IANITOR_URL and IANITOR_PREVIEW_TOKEN' }
$base = $env:IANITOR_URL.TrimEnd('/')
$headers = @{ Authorization = "Bearer $($env:IANITOR_PREVIEW_TOKEN)" }
function Call($method, $path, $body) {
$p = @{ Method = $method; Uri = "$base$path"; Headers = $headers; UseBasicParsing = $true; ContentType = 'application/json' }
if ($body) { $p.Body = [Text.Encoding]::UTF8.GetBytes(($body | ConvertTo-Json -Compress)) }
try {
$r = Invoke-WebRequest @p
return @{ Code = [int]$r.StatusCode; Json = ($r.Content | ConvertFrom-Json) }
} catch [System.Net.WebException] {
$resp = $_.Exception.Response
if (-not $resp) { throw }
$text = (New-Object IO.StreamReader($resp.GetResponseStream())).ReadToEnd()
return @{ Code = [int]$resp.StatusCode; Json = ($text | ConvertFrom-Json) }
}
}
switch ($Action) {
'open' {
$body = @{ project = $Project; branch = $Branch; upstream = $Upstream }
if ($Ttl -gt 0) { $body.ttl = $Ttl }
$r = Call POST '/api/v1/previews' $body
if ($r.Code -ne 202) { throw "preview: $($r.Json.error.message)" }
$host_ = $r.Json.preview.hostname
for ($i = 0; $i -lt 150; $i++) {
$s = Call GET "/api/v1/previews/$host_" $null
if ($s.Code -ne 200) { throw "preview: $($s.Json.error.message)" }
if ($s.Json.preview.state -eq 'live') { Write-Output $r.Json.preview.url; exit 0 }
if ($s.Json.preview.state -eq 'failed') { throw "preview: $($s.Json.preview.problem)" }
Start-Sleep -Seconds 2
}
throw 'preview: not live after 5 minutes'
}
'close' {
$r = Call POST '/api/v1/previews/close' @{ project = $Project; branch = $Branch }
if ($r.Code -eq 202) { 'closing' } elseif ($r.Code -eq 404) { 'no preview' } else { throw "preview: $($r.Json.error.message)" }
}
'list' {
$r = Call GET '/api/v1/previews' $null
$r.Json.items | ForEach-Object { "$($_.url)`t$($_.project)`t$($_.branch)`t$($_.state)`tuntil $($_.expires_at)" }
}
}
+78
View File
@@ -0,0 +1,78 @@
#!/bin/sh
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
#
# A client of Ianitor's preview API (docs/previews.md) for a Fabrica pipeline step or a script:
#
# scripts/preview.sh open <project> <branch> <upstream> [ttl-seconds] prints the preview's URL
# scripts/preview.sh close <project> <branch>
# scripts/preview.sh list
#
# IANITOR_URL Ianitor's admin address, e.g. https://ianitor.example.org
# IANITOR_PREVIEW_TOKEN a token made with `ianitor-control token create --scope previews`
# (kept in the Custos team vault; never in the repository or a log)
# IANITOR_CA optional: a CA file for curl (a Domi root, for an internal admin host)
#
# `open` waits until the preview is live (its apply kept) and fails with Ianitor's reason
# otherwise. Needs curl and jq.
set -eu
: "${IANITOR_URL:?set IANITOR_URL}"
: "${IANITOR_PREVIEW_TOKEN:?set IANITOR_PREVIEW_TOKEN}"
command -v jq >/dev/null || { echo "preview: needs jq" >&2; exit 2; }
api() {
# The token goes in a header read from stdin, so it never shows in `ps`.
method=$1; path=$2; body=${3:-}
set -- -sS -X "$method" -H "Content-Type: application/json" -H @- -w '\n%{http_code}'
[ -n "${IANITOR_CA:-}" ] && set -- "$@" --cacert "$IANITOR_CA"
[ -n "$body" ] && set -- "$@" --data "$body"
printf 'Authorization: Bearer %s\n' "$IANITOR_PREVIEW_TOKEN" | curl "$@" "${IANITOR_URL%/}$path"
}
split() { # sets BODY and CODE from api's output
CODE=$(printf '%s' "$1" | tail -n1)
BODY=$(printf '%s' "$1" | sed '$d')
}
fail() {
echo "preview: $(printf '%s' "$BODY" | jq -r '.error.message // .' 2>/dev/null || printf '%s' "$BODY")" >&2
exit 1
}
case "${1:-}" in
open)
[ $# -ge 4 ] || { echo "usage: $0 open <project> <branch> <upstream> [ttl]" >&2; exit 2; }
body=$(jq -cn --arg p "$2" --arg b "$3" --arg u "$4" --arg t "${5:-}" \
'{project:$p, branch:$b, upstream:$u} + (if $t == "" then {} else {ttl: ($t|tonumber)} end)')
split "$(api POST /api/v1/previews "$body")"
[ "$CODE" = 202 ] || fail
host=$(printf '%s' "$BODY" | jq -r .preview.hostname)
url=$(printf '%s' "$BODY" | jq -r .preview.url)
i=0
while :; do
split "$(api GET "/api/v1/previews/$host")"
[ "$CODE" = 200 ] || fail
state=$(printf '%s' "$BODY" | jq -r .preview.state)
case "$state" in
live) echo "$url"; exit 0 ;;
failed) echo "preview: $(printf '%s' "$BODY" | jq -r '.preview.problem // "the apply failed"')" >&2; exit 1 ;;
esac
i=$((i + 1)); [ $i -le 150 ] || { echo "preview: not live after 5 minutes" >&2; exit 1; }
sleep 2
done
;;
close)
[ $# -eq 3 ] || { echo "usage: $0 close <project> <branch>" >&2; exit 2; }
split "$(api POST /api/v1/previews/close "$(jq -cn --arg p "$2" --arg b "$3" '{project:$p, branch:$b}')")"
case "$CODE" in 202) echo "closing"; ;; 404) echo "no preview"; ;; *) fail ;; esac
;;
list)
split "$(api GET /api/v1/previews)"
[ "$CODE" = 200 ] || fail
printf '%s' "$BODY" | jq -r '.items[] | "\(.url)\t\(.project)\t\(.branch)\t\(.state)\tuntil \(.expires_at)"'
;;
*)
echo "usage: $0 open|close|list ..." >&2; exit 2 ;;
esac
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env bash
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
#
# Docker end to end (T4): deploy/docker/compose.yaml with the image, a throw-away Domi root,
# a branch build in another container, Fabrica's client (scripts/preview.sh) with a
# previews-only token, the preview through edge (Pingora) from the host, close. Ports 28080 and
# 28443 on 127.0.0.1; everything is removed at the end (containers, volumes, the network).
#
# scripts/smoke-docker.sh <image> <ianitor-control binary for the offline root> <work dir>
set -euo pipefail
# Git Bash on Windows rewrites /paths in arguments and the environment of Windows programs
# (docker.exe); the paths here are the container's.
export MSYS_NO_PATHCONV=1 MSYS2_ENV_CONV_EXCL='*'
IMAGE=$1 CTL=$2 WORK=$3
REPO=$(cd "$(dirname "$0")/.." && (pwd -W 2>/dev/null || pwd))
P=ianitor-smoke
export COMPOSE_PROJECT_NAME=$P IANITOR_IMAGE=$IMAGE IANITOR_HTTP_PORT=28080 IANITOR_HTTPS_PORT=28443
export IANITOR_ADMIN_HOST=ianitor.smoke.test IANITOR_TLS=domi IANITOR_DOMI_ROOT=/var/lib/ianitor/domi-root.crt
export IANITOR_PREVIEW_DOMAIN=pv.smoke.test IANITOR_PREVIEW_UPSTREAMS=app:8080
DC=(docker compose -f "$REPO/deploy/docker/compose.yaml")
step() { echo "== $*"; }
ok() { echo " ok: $*"; }
fail() { echo "FAILED: $*" >&2; "${DC[@]}" logs --tail 40 control edge >&2 2>&1 || true; exit 1; }
cleanup() {
"${DC[@]}" down -v --remove-orphans >/dev/null 2>&1 || true
docker rm -f $P-app >/dev/null 2>&1 || true
docker volume rm ${P}_state >/dev/null 2>&1 || true
}
trap cleanup EXIT
[ ! -e "$WORK" ] || fail "$WORK exists; give a new folder"
mkdir -p "$WORK"
# A drive path (F:/…) on Windows, which both Git Bash and the Windows ianitor-control read.
WORK=$(cd "$WORK" && (pwd -W 2>/dev/null || pwd))
# In edge's network namespace: the loopback API (curl and jq from a throw-away Alpine).
inside() { docker run --rm -i --network container:$P-edge-1 alpine:3.20 sh -c "apk add -q curl jq >/dev/null && $1"; }
step "a throw-away Domi root (offline step)"
printf 'smoke-test-offline-passphrase' > "$WORK/pass"
"$CTL" ca init --out "$WORK/root" --passphrase-file "$WORK/pass" >/dev/null 2>&1 || fail "ca init"
docker volume create ${P}_state >/dev/null
docker run --rm -i -v ${P}_state:/v alpine:3.20 sh -c 'cat > /v/domi-root.crt && chown 10001:10001 /v /v/domi-root.crt' < "$WORK/root/domi-root.crt"
ok "root in the state volume"
step "docker compose up"
"${DC[@]}" up -d > "$WORK/compose-up.log" 2>&1 || { cat "$WORK/compose-up.log"; fail "compose up"; }
for i in $(seq 60); do inside "curl -s -o /dev/null http://127.0.0.1:7878/" 2>/dev/null && break; sleep 2; done
ADMIN=$("${DC[@]}" exec -T control ianitor-control token create --name smoke --config /var/lib/ianitor/control.toml 2>/dev/null | tail -n1)
FABRICA=$("${DC[@]}" exec -T control ianitor-control token create --name fabrica --scope previews --config /var/lib/ianitor/control.toml 2>/dev/null | tail -n1)
[ -n "$ADMIN" ] && [ -n "$FABRICA" ] || fail "tokens"
ok "control up, tokens made"
step "the intermediate, signed offline"
rid=$(inside "curl -s -X POST -H 'Authorization: Bearer $ADMIN' http://127.0.0.1:7878/api/v1/certs/intermediate/renewal | jq -r .request_id")
inside "curl -s -H 'Authorization: Bearer $ADMIN' http://127.0.0.1:7878/api/v1/pki-requests/$rid/csr" > "$WORK/int.csr"
"$CTL" ca sign --root "$WORK/root" --csr "$WORK/int.csr" --out "$WORK/int.crt" --yes --passphrase-file "$WORK/pass" >/dev/null 2>&1 || fail "ca sign"
"${DC[@]}" exec -T control sh -c 'cat > /tmp/int.crt && ianitor-control pki install /tmp/int.crt --config /var/lib/ianitor/control.toml' < "$WORK/int.crt" >/dev/null 2>&1 || fail "pki install"
"${DC[@]}" restart control >/dev/null 2>&1
for i in $(seq 60); do
inside "curl -s -H 'Authorization: Bearer $ADMIN' http://127.0.0.1:7878/api/v1/hosts" 2>/dev/null | grep -q ianitor.smoke.test && break
sleep 2
done
ok "intermediate installed; admin host added"
step "a branch build in its own container"
docker run -d --name $P-app --network ${P}_default --network-alias app python:3.12-alpine \
sh -c 'mkdir /s && echo "hello from fix-42" > /s/index.html && python -m http.server 8080 --directory /s' >/dev/null
sleep 3
step "Fabrica opens the preview (scripts/preview.sh, previews-only token)"
url=$(inside "IANITOR_URL=http://127.0.0.1:7878 IANITOR_PREVIEW_TOKEN=$FABRICA sh -s -- open shop fix-42 http://app:8080 3600" < "$REPO/scripts/preview.sh")
[ "$url" = "https://fix-42--shop.pv.smoke.test/" ] || fail "preview URL: $url"
ok "preview URL $url"
body=$(curl -sS --ssl-no-revoke --cacert "$WORK/root/domi-root.crt" --resolve fix-42--shop.pv.smoke.test:28443:127.0.0.1 https://fix-42--shop.pv.smoke.test:28443/ || true)
[ "$body" = "hello from fix-42" ] || fail "the preview through edge: $body"
ok "the preview answers through edge (Pingora) from the host, with a Domi certificate"
code=$(curl -s -o /dev/null -w '%{http_code}' --ssl-no-revoke --cacert "$WORK/root/domi-root.crt" --resolve ianitor.smoke.test:28443:127.0.0.1 https://ianitor.smoke.test:28443/api/v1/team || true)
[ "$code" = 401 ] || fail "admin host: $code"
ok "the admin host reaches control and needs a sign-in (401)"
code=$(inside "curl -s -o /dev/null -w '%{http_code}' -H 'Authorization: Bearer $FABRICA' http://127.0.0.1:7878/api/v1/hosts")
[ "$code" = 403 ] || fail "preview token on hosts: $code"
ok "the preview token cannot read the hosts (403)"
step "closed on merge"
inside "IANITOR_URL=http://127.0.0.1:7878 IANITOR_PREVIEW_TOKEN=$FABRICA sh -s -- close shop fix-42" < "$REPO/scripts/preview.sh" >/dev/null
for i in $(seq 45); do
code=$(curl -s -o /dev/null -w '%{http_code}' --ssl-no-revoke --cacert "$WORK/root/domi-root.crt" --resolve fix-42--shop.pv.smoke.test:28443:127.0.0.1 https://fix-42--shop.pv.smoke.test:28443/ || true)
[ "$code" != 200 ] && break
sleep 2
done
[ "$code" != 200 ] || fail "still served after close"
ok "gone after close ($code)"
echo "SMOKE PASSED"
+105
View File
@@ -0,0 +1,105 @@
#!/usr/bin/env bash
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
#
# Plain Linux with systemd, end to end (T4): a Debian container with systemd as PID 1 stands in
# for a fresh server. deploy/linux/install.sh installs the release tarball (IANITOR_TARBALL, no
# download), a throw-away Domi root signs the intermediate, a branch build runs on 127.0.0.1,
# Fabrica's client (scripts/preview.sh) opens the preview with a previews-only token, and the
# preview answers through edge (Pingora, under systemd) on a published port; then it is closed.
# The container and its image are removed at the end.
#
# scripts/smoke-linux.sh <dist dir with the tarball and install.sh> <ianitor-control binary> <work dir>
set -euo pipefail
# Git Bash on Windows rewrites /paths for Windows programs (docker.exe); the paths here are the container's.
export MSYS_NO_PATHCONV=1 MSYS2_ENV_CONV_EXCL='*'
DIST=$1 CTL=$2 WORK=$3
REPO=$(cd "$(dirname "$0")/.." && (pwd -W 2>/dev/null || pwd))
C=ianitor-smoke-linux
step() { echo "== $*"; }
ok() { echo " ok: $*"; }
fail() { echo "FAILED: $*" >&2; docker exec $C journalctl --no-pager -n 60 -u ianitor-control -u ianitor-edge 2>/dev/null || true; exit 1; }
cleanup() { docker rm -f $C >/dev/null 2>&1 || true; docker rmi -f $C:latest >/dev/null 2>&1 || true; }
trap cleanup EXIT
[ ! -e "$WORK" ] || fail "$WORK exists; give a new folder"
mkdir -p "$WORK"
# A drive path (F:/...) on Windows, which both Git Bash and the Windows ianitor-control read.
WORK=$(cd "$WORK" && (pwd -W 2>/dev/null || pwd))
DIST=$(cd "$DIST" && (pwd -W 2>/dev/null || pwd))
tarball=$(ls "$DIST"/ianitor-*-linux-x86_64.tar.gz | head -n1)
[ -f "$tarball" ] && [ -f "$DIST/install.sh" ] || fail "no tarball or install.sh in $DIST"
version=$(basename "$tarball" | sed 's/^ianitor-\(.*\)-linux-x86_64.tar.gz$/\1/')
step "a fresh Debian with systemd"
docker build -q -t $C:latest - >/dev/null <<'EOF'
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends systemd systemd-sysv dbus git curl jq python3 ca-certificates \
&& rm -rf /var/lib/apt/lists/*
STOPSIGNAL SIGRTMIN+3
CMD ["/sbin/init"]
EOF
docker run -d --name $C --privileged --cgroupns=host -v /sys/fs/cgroup:/sys/fs/cgroup:rw \
--tmpfs /run --tmpfs /run/lock -p 127.0.0.1:38443:443 $C:latest >/dev/null
for i in $(seq 30); do docker exec $C systemctl is-system-running 2>/dev/null | grep -qE 'running|degraded' && break; sleep 1; done
ok "systemd is up"
step "a throw-away Domi root (offline step)"
printf 'smoke-test-offline-passphrase' > "$WORK/pass"
"$CTL" ca init --out "$WORK/root" --passphrase-file "$WORK/pass" >/dev/null 2>&1 || fail "ca init"
docker exec $C mkdir -p /etc/ianitor
docker cp "$WORK/root/domi-root.crt" $C:/etc/ianitor/domi-root.crt
docker cp "$tarball" $C:/tmp/
docker cp "$DIST/install.sh" $C:/tmp/install.sh
step "install.sh (the one line, with the tarball given instead of downloaded)"
docker exec -e IANITOR_TARBALL=/tmp/$(basename "$tarball") -e IANITOR_ADMIN_HOST=ianitor.smoke.test -e IANITOR_TLS=domi \
-e IANITOR_DOMI_ROOT=/etc/ianitor/domi-root.crt -e IANITOR_PREVIEW_DOMAIN=pv.smoke.test \
-e IANITOR_PREVIEW_UPSTREAMS=127.0.0.1:20000-29999 $C sh /tmp/install.sh > "$WORK/install.log" 2>&1 \
|| { cat "$WORK/install.log"; fail "install.sh"; }
grep -q '#signin=isc_' "$WORK/install.log" || { cat "$WORK/install.log"; fail "no sign-in link printed"; }
ok "installed $version; both units active: $(docker exec $C systemctl is-active ianitor-control ianitor-edge | tr '\n' ' ')"
as_ianitor() { docker exec $C runuser -u ianitor -- "$@"; }
ADMIN=$(as_ianitor ianitor-control token create --name smoke --config /etc/ianitor/control.toml 2>/dev/null | tail -n1)
FABRICA=$(as_ianitor ianitor-control token create --name fabrica --scope previews --config /etc/ianitor/control.toml 2>/dev/null | tail -n1)
api() { docker exec $C curl -s -H "Authorization: Bearer $1" "${@:2}"; }
step "the intermediate, signed offline"
rid=$(api "$ADMIN" -X POST http://127.0.0.1:7878/api/v1/certs/intermediate/renewal | jq -r .request_id)
api "$ADMIN" "http://127.0.0.1:7878/api/v1/pki-requests/$rid/csr" > "$WORK/int.csr"
"$CTL" ca sign --root "$WORK/root" --csr "$WORK/int.csr" --out "$WORK/int.crt" --yes --passphrase-file "$WORK/pass" >/dev/null 2>&1 || fail "ca sign"
docker cp "$WORK/int.crt" $C:/tmp/int.crt
docker exec $C chmod 0644 /tmp/int.crt
as_ianitor ianitor-control pki install /tmp/int.crt --config /etc/ianitor/control.toml >/dev/null 2>&1 || fail "pki install"
docker exec $C systemctl restart ianitor-control
for i in $(seq 60); do api "$ADMIN" http://127.0.0.1:7878/api/v1/hosts 2>/dev/null | grep -q ianitor.smoke.test && break; sleep 2; done
ok "intermediate installed; admin host added"
step "a branch build on 127.0.0.1:23456"
docker exec -d $C sh -c 'mkdir -p /srv/app && echo "hello from fix-42" > /srv/app/index.html && python3 -m http.server 23456 --bind 127.0.0.1 --directory /srv/app'
sleep 2
step "Fabrica opens the preview (scripts/preview.sh, previews-only token)"
docker cp "$REPO/scripts/preview.sh" $C:/tmp/preview.sh
url=$(docker exec -e IANITOR_URL=http://127.0.0.1:7878 -e IANITOR_PREVIEW_TOKEN="$FABRICA" $C sh /tmp/preview.sh open shop fix-42 http://127.0.0.1:23456 3600)
[ "$url" = "https://fix-42--shop.pv.smoke.test/" ] || fail "preview URL: $url"
ok "preview URL $url"
body=$(curl -sS --ssl-no-revoke --cacert "$WORK/root/domi-root.crt" --resolve fix-42--shop.pv.smoke.test:38443:127.0.0.1 https://fix-42--shop.pv.smoke.test:38443/ || true)
[ "$body" = "hello from fix-42" ] || fail "the preview through edge: $body"
ok "the preview answers through edge (Pingora under systemd), with a Domi certificate"
code=$(api "$FABRICA" -o /dev/null -w '%{http_code}' http://127.0.0.1:7878/api/v1/hosts)
[ "$code" = 403 ] || fail "preview token on hosts: $code"
ok "the preview token cannot read the hosts (403)"
step "closed on merge"
docker exec -e IANITOR_URL=http://127.0.0.1:7878 -e IANITOR_PREVIEW_TOKEN="$FABRICA" $C sh /tmp/preview.sh close shop fix-42 >/dev/null
for i in $(seq 45); do
code=$(curl -s -o /dev/null -w '%{http_code}' --ssl-no-revoke --cacert "$WORK/root/domi-root.crt" --resolve fix-42--shop.pv.smoke.test:38443:127.0.0.1 https://fix-42--shop.pv.smoke.test:38443/ || true)
[ "$code" != 200 ] && break
sleep 2
done
[ "$code" != 200 ] || fail "still served after close"
ok "gone after close ($code)"
echo "SMOKE PASSED"
+130
View File
@@ -0,0 +1,130 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
#
# Windows Caddy mode, end to end through the installer (T4). Everything happens in -Work, on
# non-standard ports, with a throw-away Domi root; no service is registered, no certificate is
# trusted, nothing is left running:
#
# 1. deploy\windows\install.ps1 -NoService (the release ianitor-control.exe, a given caddy.exe)
# 2. Caddy and control started in the console, as the services would start them
# 3. the intermediate signed offline with the throw-away root (docs/pki.md), control restarted
# so it adds the admin host
# 4. a previews-only token opens a branch preview with scripts\preview.ps1 (Fabrica's client)
# 5. the preview answers through Caddy with a Domi certificate; the admin host reaches control
# 6. the preview is closed and stops answering
#
# scripts\smoke-windows.ps1 -Control <ianitor-control.exe> -Caddy <caddy.exe> -Work <empty dir>
param(
[Parameter(Mandatory = $true)][string]$Control,
[Parameter(Mandatory = $true)][string]$Caddy,
[Parameter(Mandatory = $true)][string]$Work
)
$ErrorActionPreference = 'Stop'
$repo = Split-Path -Parent $PSScriptRoot
$Http = 18080; $Https = 18443; $Api = 17878; $Admin = 12019; $AppPort = 23456
$procs = @()
function Step($m) { Write-Host "== $m" }
function Check($ok, $m) { if (-not $ok) { throw "FAILED: $m" } ; Write-Host " ok: $m" }
try {
if (Test-Path $Work) { throw "$Work exists; give an empty, new folder" }
New-Item -ItemType Directory $Work | Out-Null
$pkg = Join-Path $Work 'pkg'; New-Item -ItemType Directory $pkg | Out-Null
Copy-Item $Control (Join-Path $pkg 'ianitor-control.exe')
Copy-Item (Join-Path $repo 'deploy\windows\install.ps1') $pkg
$ctl = Join-Path $Work 'bin\ianitor-control.exe'
$root = Join-Path $Work 'root'
$offline = Join-Path $Work 'offline-root'
$pass = Join-Path $Work 'offline-pass.txt'
[IO.File]::WriteAllText($pass, 'smoke-test-offline-passphrase')
Step 'a throw-away Domi root (offline step)'
& (Join-Path $pkg 'ianitor-control.exe') ca init --out $offline --passphrase-file $pass
Check ($LASTEXITCODE -eq 0) 'ca init'
Step 'install.ps1 -NoService'
& (Join-Path $pkg 'install.ps1') -NoService -AdminHost 'ianitor.smoke.test' -Tls domi `
-DomiRoot (Join-Path $offline 'domi-root.crt') -PreviewDomain 'pv.smoke.test' `
-PreviewUpstreams "127.0.0.1:20000-29999" -Root $root -Bin (Join-Path $Work 'bin') `
-HttpPort $Http -HttpsPort $Https -ApiPort $Api -CaddyAdminPort $Admin -Caddy $Caddy
$config = Join-Path $root 'control.toml'
Check (Test-Path $config) 'control.toml written'
function Start-Control {
$env:IANITOR_LOG_FILE = Join-Path $root 'logs\control.log'
$p = Start-Process -PassThru -WindowStyle Hidden -FilePath $ctl -ArgumentList '--config', "`"$config`""
Remove-Item Env:\IANITOR_LOG_FILE
for ($i = 0; $i -lt 60; $i++) {
try { $c = New-Object Net.Sockets.TcpClient('127.0.0.1', $Api); $c.Close(); return $p } catch { Start-Sleep -Milliseconds 500 }
}
throw 'control did not listen'
}
Step 'Caddy and control, as the services start them'
$env:APPDATA = Join-Path $Work 'caddy-appdata'
$procs += Start-Process -PassThru -WindowStyle Hidden -FilePath (Join-Path $Work 'bin\caddy.exe') `
-ArgumentList 'run', '--config', "`"$(Join-Path $root 'caddy\caddy.json')`"" `
-RedirectStandardError (Join-Path $root 'logs\caddy.log') -RedirectStandardOutput (Join-Path $root 'logs\caddy.out')
$p = Start-Control; $procs += $p
$adminTok = (& $ctl token create --name smoke-admin --config $config) | Select-Object -Last 1
$previewTok = (& $ctl token create --name fabrica-previews --scope previews --config $config) | Select-Object -Last 1
$auth = @{ Authorization = "Bearer $adminTok" }
$base = "http://127.0.0.1:$Api"
Step 'the intermediate, signed offline'
$r = Invoke-RestMethod -Method POST -Uri "$base/api/v1/certs/intermediate/renewal" -Headers $auth
$csr = Join-Path $Work 'intermediate.csr'
Invoke-WebRequest -UseBasicParsing -Uri "$base/api/v1/pki-requests/$($r.request_id)/csr" -Headers $auth -OutFile $csr
$crt = Join-Path $Work 'intermediate.crt'
& $ctl ca sign --root $offline --csr $csr --out $crt --yes --passphrase-file $pass
Check ($LASTEXITCODE -eq 0) 'ca sign'
& $ctl pki install $crt --config $config
Check ($LASTEXITCODE -eq 0) 'pki install'
Step 'control again (it adds the admin host now that it can issue its certificate)'
Stop-Process -Id $p.Id -Force; Start-Sleep 1
$procs = @($procs | Where-Object { $_.Id -ne $p.Id })
$p = Start-Control; $procs += $p
$deadline = (Get-Date).AddSeconds(120)
do {
Start-Sleep 2
$hosts = (Invoke-RestMethod -Uri "$base/api/v1/hosts" -Headers $auth).hosts.hostname
} until (($hosts -contains 'ianitor.smoke.test') -or (Get-Date) -gt $deadline)
Check ($hosts -contains 'ianitor.smoke.test') 'admin host in the routes'
Step 'a branch build on 127.0.0.1'
$site = Join-Path $Work 'app'; New-Item -ItemType Directory $site | Out-Null
[IO.File]::WriteAllText((Join-Path $site 'index.html'), 'hello from fix-42')
$procs += Start-Process -PassThru -WindowStyle Hidden -FilePath 'python' -ArgumentList '-m', 'http.server', $AppPort, '--bind', '127.0.0.1', '--directory', "`"$site`""
Start-Sleep 2
Step 'Fabrica opens the preview (scripts\preview.ps1, previews-only token)'
$env:IANITOR_URL = $base; $env:IANITOR_PREVIEW_TOKEN = $previewTok
$url = & (Join-Path $repo 'scripts\preview.ps1') open -Project 'shop' -Branch 'fix-42' -Upstream "http://127.0.0.1:$AppPort" -Ttl 3600
Check ($url -eq 'https://fix-42--shop.pv.smoke.test/') "preview URL $url"
$ca = Join-Path $offline 'domi-root.crt'
$body = & curl.exe -sS --ssl-no-revoke --cacert $ca --resolve "fix-42--shop.pv.smoke.test:${Https}:127.0.0.1" "https://fix-42--shop.pv.smoke.test:$Https/"
Check ($body -eq 'hello from fix-42') "the preview answers through Caddy with a Domi certificate ($body)"
$code = & curl.exe -s -o NUL -w '%{http_code}' --ssl-no-revoke --cacert $ca --resolve "ianitor.smoke.test:${Https}:127.0.0.1" "https://ianitor.smoke.test:$Https/api/v1/team"
Check ($code -eq '401') "the admin host reaches control and needs a sign-in ($code)"
$deny = & curl.exe -s -o NUL -w '%{http_code}' -H "Authorization: Bearer $previewTok" "$base/api/v1/hosts"
Check ($deny -eq '403') "the preview token cannot read the hosts ($deny)"
$list = & (Join-Path $repo 'scripts\preview.ps1') list
Check ($list -match 'fix-42--shop') 'listed'
Step 'closed on merge'
& (Join-Path $repo 'scripts\preview.ps1') close -Project 'shop' -Branch 'fix-42' | Out-Null
$deadline = (Get-Date).AddSeconds(90)
do {
Start-Sleep 2
$code = & curl.exe -s -o NUL -w '%{http_code}' --ssl-no-revoke --cacert $ca --resolve "fix-42--shop.pv.smoke.test:${Https}:127.0.0.1" "https://fix-42--shop.pv.smoke.test:$Https/"
} until (($code -ne '200') -or (Get-Date) -gt $deadline)
Check ($code -ne '200') "gone after close ($code)"
Write-Host 'SMOKE PASSED'
$global:LASTEXITCODE = 0
} finally {
foreach ($p in $procs) { try { Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue } catch {} }
Remove-Item Env:\IANITOR_PREVIEW_TOKEN -ErrorAction SilentlyContinue
}
+1
View File
@@ -15,6 +15,7 @@ tokio.workspace = true
serde_json.workspace = true
rustls.workspace = true
rcgen.workspace = true
toml.workspace = true
[dev-dependencies]
ianitor-control = { path = "../../crates/control" }
+83 -5
View File
@@ -7,9 +7,12 @@
//! to Caddy (the `caddy` binary running the generated JSON); status, selected headers and
//! body are compared. Everything listens on 127.0.0.1.
//!
//! It runs on Linux and on Windows. On Windows the paths in both configs are Windows paths
//! (`F:/…/certs/x.crt`, Caddy's `{file.F:/…/creds/api_key}`), which is what Windows Server's
//! Caddy mode serves from (T4); Pingora runs in-process there only as the reference.
//!
//! Test code: panics are failures.
#![cfg(unix)]
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::collections::BTreeMap;
@@ -50,6 +53,46 @@ fn host(name: &str, body: &str) -> (String, String) {
)
}
/// The preview domain of the fixtures, and two branch previews in it (T4): one with a plain
/// branch name, one with a hostile one (mapped to a hashed label).
pub const PREVIEW_DOMAIN: &str = "pv.test";
pub const PREVIEW_PLAIN: &str = "fix-42--shop.pv.test";
/// The host name of the hostile-branch preview.
pub fn preview_hostile() -> &'static str {
static H: std::sync::OnceLock<String> = std::sync::OnceLock::new();
H.get_or_init(|| {
ianitor_core::preview::hostname("github:acme/Web.App", "feature/Ünï ../x", PREVIEW_DOMAIN)
.expect("a preview host name")
})
}
/// A preview host file exactly as control writes it (`ianitor_control::previews::spec`).
fn preview_host(project: &str, branch: &str, upstream: &str) -> (String, String) {
let name = ianitor_core::preview::hostname(project, branch, PREVIEW_DOMAIN).unwrap();
let mut t = toml::Table::new();
t.insert("hostname".into(), name.clone().into());
t.insert(
"upstreams".into(),
toml::Value::Array(vec![upstream.into()]),
);
t.insert("tls".into(), "domi".into());
let mut rule = toml::Table::new();
rule.insert("action".into(), "set".into());
rule.insert("name".into(), "X-Robots-Tag".into());
rule.insert("value".into(), "noindex, nofollow".into());
t.insert(
"response_headers".into(),
toml::Value::Array(vec![toml::Value::Table(rule)]),
);
let mut p = toml::Table::new();
p.insert("project".into(), project.into());
p.insert("branch".into(), branch.into());
p.insert("expires_at".into(), toml::Value::Integer(4_000_000_000));
t.insert("preview".into(), toml::Value::Table(p));
(format!("hosts/{name}.toml"), toml::to_string(&t).unwrap())
}
impl Env {
pub async fn start() -> Env {
let app = Echo::start("app").await;
@@ -117,7 +160,15 @@ impl Env {
"device.test",
&format!("upstreams = [\"{}\"]\ndevice_certs = true\n", app.url()),
),
preview_host("shop", "fix-42", &app.url()),
preview_host("github:acme/Web.App", "feature/Ünï ../x", &ws.url()),
];
assert!(
hosts
.iter()
.any(|(f, _)| f == &format!("hosts/{PREVIEW_PLAIN}.toml")),
"the plain preview fixture is {PREVIEW_PLAIN}"
);
let sources: Vec<SourceFile> = hosts
.iter()
.map(|(n, c)| SourceFile {
@@ -171,13 +222,16 @@ impl Env {
}
pub fn options(&self, engine: &str) -> CompileOptions {
// On Windows these are drive paths (F:\\…), written with forward slashes as control
// writes them (`ianitor_core::compile::windows_path`).
let w = |p: String| compile::windows_path(&p);
CompileOptions {
http_listen: local(free_port()),
https_listen: local(free_port()),
cert_dir: self.dir.str("certs"),
state_dir: self.dir.str(&format!("state-{engine}")),
access_log: self.dir.str(&format!("logs/{engine}-access.log")),
caddy_credentials_dir: self.dir.str("creds"),
cert_dir: w(self.dir.str("certs")),
state_dir: w(self.dir.str(&format!("state-{engine}"))),
access_log: w(self.dir.str(&format!("logs/{engine}-access.log"))),
caddy_credentials_dir: w(self.dir.str("creds")),
caddy_admin: None,
caddy_admin_socket: None,
trusted_proxies: Vec::new(),
@@ -445,6 +499,30 @@ pub fn corpus() -> Vec<Case> {
Req::get(p, "https://evil.test/x"),
),
http("HTTP redirects to HTTPS", Req::get(p, "/a/b?c=d")),
https(
"preview: plain branch",
PREVIEW_PLAIN,
Req::get(PREVIEW_PLAIN, "/a?b=c"),
),
http(
"preview: HTTP redirects to HTTPS",
Req::get(PREVIEW_PLAIN, "/x"),
),
https(
"preview: unknown branch of the preview domain",
PREVIEW_PLAIN,
Req::get("main--shop.pv.test", "/"),
),
https(
"preview: hostile branch",
preview_hostile(),
Req::get(preview_hostile(), "/"),
),
ws(
"preview: websocket on a hostile branch",
preview_hostile(),
vec![],
),
http("HTTP unknown host", Req::get("unknown.test", "/")),
http(
"HTTP unknown ACME token",
+1
View File
@@ -126,6 +126,7 @@ mod unix {
pki: None,
ui: None,
engine: None,
previews: None,
};
// Start from the site file and every host except three; then a sequence of applies
+2 -11
View File
@@ -7,17 +7,8 @@
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
#[cfg(not(unix))]
#[test]
fn skipped_on_windows() {
eprintln!(
"SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md",
file!()
);
}
#[cfg(unix)]
mod unix {
// Runs on Linux and on Windows (with Windows paths; see the crate's docs).
mod both {
use ianitor_diff::{
Action, Env, break_caddy, break_edge, compile_pair, corpus, run_cases, run_corpus, settle,
start_caddy, start_edge,
+6 -1
View File
@@ -126,8 +126,13 @@ pub fn find_binary(name: &str) -> Option<PathBuf> {
return Some(PathBuf::from(p));
}
let path = std::env::var_os("PATH")?;
let file = if cfg!(windows) {
format!("{name}.exe")
} else {
name.to_owned()
};
std::env::split_paths(&path)
.map(|d| d.join(name))
.map(|d| d.join(&file))
.find(|p| p.is_file())
}