From 83270e07466d6019418329958c486bd5d8327080 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 17 Nov 2026 13:29:35 +0100 Subject: [PATCH 01/15] [core] Previews: branch and project names to one safe host label, and the [preview] table of a host file (tests first) --- crates/core/src/error.rs | 7 +- crates/core/src/lib.rs | 3 +- crates/core/src/model.rs | 14 ++ crates/core/src/preview.rs | 145 +++++++++++++++++++ crates/core/src/validate.rs | 43 +++++- crates/core/tests/preview.rs | 265 +++++++++++++++++++++++++++++++++++ 6 files changed, 474 insertions(+), 3 deletions(-) create mode 100644 crates/core/src/preview.rs create mode 100644 crates/core/tests/preview.rs diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs index e4dbc84..bc3f8e0 100644 --- a/crates/core/src/error.rs +++ b/crates/core/src/error.rs @@ -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) -> 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, } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 83e19de..75ca94d 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -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}; diff --git a/crates/core/src/model.rs b/crates/core/src/model.rs index b4822af..e4ad367 100644 --- a/crates/core/src/model.rs +++ b/crates/core/src/model.rs @@ -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, +} + +/// 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`). diff --git a/crates/core/src/preview.rs b/crates/core/src/preview.rs new file mode 100644 index 0000000..81db26d --- /dev/null +++ b/crates/core/src/preview.rs @@ -0,0 +1,145 @@ +// 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 and project names come from a git host and +//! are hostile input; this module turns them into one safe DNS label. +//! +//! The label is `--`, 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 { + 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 { + 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) +} diff --git a/crates/core/src/validate.rs b/crates/core/src/validate.rs index d9fb9ac..2ff3b39 100644 --- a/crates/core/src/validate.rs +++ b/crates/core/src/validate.rs @@ -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, #[serde(default)] response_headers: Vec, + preview: Option, +} + +#[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 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 RawAccessLog::Off => AccessLog::Off, RawAccessLog::Truncated => AccessLog::Truncated, }, + preview, }) } diff --git a/crates/core/tests/preview.rs b/crates/core/tests/preview.rs new file mode 100644 index 0000000..4de5dfa --- /dev/null +++ b/crates/core/tests/preview.rs @@ -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/. + +//! Preview host names (T4, written before the code): `--.`. +//! 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& + +{#if problem} (problem = null)}>{#snippet title()}{problem}{/snippet}{/if} +{#if team?.authelia} +

Authelia signs people in on this server. Team links work too.

+{/if} +

People

+
    + {#each team?.members ?? [] as m (m.id)} +
  • +
    {m.name}{team?.me?.id === m.id ? " (you)" : ""} + {m.role} · since {shortDate(m.added_at)}{m.match_code ? ` · Domi identity ${m.match_code}` : ""}
    + {#if admin && team?.me?.id !== m.id} + {#if confirmRemove === m.id} + Remove {m.name}? They are signed out everywhere. + + + {:else} + + {/if} + {/if} +
  • + {/each} +
+ +{#if admin} +
+
+ + +
+ + +
+

Members change hosts and previews. Admins also manage people, API tokens, the engine and certificates.

+ {#if link} +
+ (e.currentTarget as HTMLInputElement).select()} /> + +
+ {/if} +{/if} + +{#if team?.me} +

Your Domi identity

+
+
+ + +
+ +
+

Your teammates see its match code next to your name, the same digits Custos shows.

+{/if} + + diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index 5eedc8f..59b4ad0 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -139,7 +139,7 @@ export async function call( 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); diff --git a/apps/web/src/lib/app.svelte.ts b/apps/web/src/lib/app.svelte.ts index be2af13..3f73ec6 100644 --- a/apps/web/src/lib/app.svelte.ts +++ b/apps/web/src/lib/app.svelte.ts @@ -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, diff --git a/apps/web/src/lib/types.ts b/apps/web/src/lib/types.ts index 73bffda..63bf738 100644 --- a/apps/web/src/lib/types.ts +++ b/apps/web/src/lib/types.ts @@ -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; +} diff --git a/apps/web/src/views/Previews.svelte b/apps/web/src/views/Previews.svelte new file mode 100644 index 0000000..554f0d7 --- /dev/null +++ b/apps/web/src/views/Previews.svelte @@ -0,0 +1,103 @@ + + + +

Previews

+{#if problem} (problem = null)}>{#snippet title()}{problem}{/snippet}{/if} + +{#if list && !list.domain} +
+

Previews are off

+

Set a preview domain in control.toml ([previews] domain) and point a wildcard DNS record at this server. Then every branch Fabrica builds gets its own address here.

+
+{:else if list && list.items.length === 0} +
+

No previews open

+

When Fabrica builds a branch, its preview appears here as <branch>--<project>.{list.domain}. It closes on merge or when its time runs out.

+
+{:else if list} +

Under {list.domain}. Fabrica opens them with a token that can only manage previews.

+
    + {#each list.items as p (p.hostname)} + {@const [kind, label] = badge(p)} +
  • + +
    + {p.hostname} + {p.branch} · {p.project} · to {p.upstream} · closes {whenInline(p.expires_at, app.now)} + {#if p.problem}{p.problem}{/if} +
    + {#if confirm === p.hostname} + Close the preview of {p.branch}? Its address stops working. + + + {:else} + + {/if} +
  • + {/each} +
+{/if} + + diff --git a/apps/web/src/views/Settings.svelte b/apps/web/src/views/Settings.svelte index 2cd2f0f..30a0c38 100644 --- a/apps/web/src/views/Settings.svelte +++ b/apps/web/src/views/Settings.svelte @@ -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([]); let problem = $state(null); let expiry = $state<"year" | "never">("year"); + let scope = $state<"full" | "previews">("full"); let made = $state(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("/tokens", body); tokenName = made.name; tokenCopied = false; @@ -164,18 +167,22 @@
{#if tab === "general"}

Routes repository

-

{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."}

+

{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."}

Health watch after apply

{settings?.watch_seconds ?? app.overview?.site?.watch_seconds ?? 60} seconds

Signed in

-

{viewer ? (viewer.via === "authelia" ? `${viewer.name} through Authelia` : `API token "${viewer.name}"`) : "Through Authelia"}

+

{viewer ? (viewer.via === "authelia" ? `${viewer.name} through Authelia` : viewer.via === "session" ? viewer.name : `API token "${viewer.name}"`) : "Not signed in"}

{#if app.overview?.site?.auth_logout_url}

Sign out

{/if} + {:else if tab === "team"} + {:else if tab === "api"}

API tokens

+
+

Fabrica needs a previews-only token: it can open and close branch previews and touch nothing else. Keep it in the Custos team vault.

The API listens on 127.0.0.1 only. Ianitor keeps a hash of each token, never the token.

{#if tokens.length === 0}

No API tokens

Scripts and other Domi apps use a token to talk to Ianitor.

@@ -184,7 +191,7 @@ {#each tokens as t (t.id)}
  • - {t.name} + {t.name}{#if t.scope === "previews"} previews only{/if} {#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} @@ -233,7 +240,7 @@ {/if} {/if} {:else} -

    Ianitor Domi 0.1.0

    +

    Ianitor Domi 0.2.0

    MPL-2.0

    Built, tested and signed by Fabrica Domi

    Source on Gitea

    diff --git a/apps/web/tests/flows.test.ts b/apps/web/tests/flows.test.ts index 8a21e87..6ff7534 100644 --- a/apps/web/tests/flows.test.ts +++ b/apps/web/tests/flows.test.ts @@ -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(); diff --git a/apps/web/tests/mockApi.ts b/apps/web/tests/mockApi.ts index d849ccc..8e86dbe 100644 --- a/apps/web/tests/mockApi.ts +++ b/apps/web/tests/mockApi.ts @@ -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; @@ -65,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 }, }; } @@ -170,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" }]], ]; } -- 2.53.0 From 09f6b12676ed559877d8934352c48fb12340ec62 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 17 Nov 2026 20:42:01 +0100 Subject: [PATCH 08/15] [tests] Linux-only tests follow the Caddy admin address type and the [previews] config field --- crates/control/tests/engine_switch.rs | 33 +++++++++++++++++++-------- tests/diff/tests/apply_sequence.rs | 1 + 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/crates/control/tests/engine_switch.rs b/crates/control/tests/engine_switch.rs index 42ddf4a..c16d9dc 100644 --- a/crates/control/tests/engine_switch.rs +++ b/crates/control/tests/engine_switch.rs @@ -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; diff --git a/tests/diff/tests/apply_sequence.rs b/tests/diff/tests/apply_sequence.rs index 37c3f93..1c928e2 100644 --- a/tests/diff/tests/apply_sequence.rs +++ b/tests/diff/tests/apply_sequence.rs @@ -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.53.0 From 49c05e25239a6966401c04ed5cbe8b98c521e37e Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 17 Nov 2026 20:42:04 +0100 Subject: [PATCH 09/15] [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 --- .dockerignore | 9 ++ deploy/docker/Dockerfile | 110 ++++++++++++++ deploy/docker/compose.yaml | 57 ++++++++ deploy/docker/entrypoint.sh | 39 +++++ deploy/linux/ianitor-control.service | 34 +++++ deploy/linux/ianitor-edge.service | 39 +++++ deploy/linux/install.sh | 81 +++++++++++ deploy/linux/setup.sh | 144 +++++++++++++++++++ deploy/windows/install.ps1 | 208 +++++++++++++++++++++++++++ scripts/preview.ps1 | 60 ++++++++ scripts/preview.sh | 78 ++++++++++ scripts/smoke-windows.ps1 | 129 +++++++++++++++++ 12 files changed, 988 insertions(+) create mode 100644 .dockerignore create mode 100644 deploy/docker/Dockerfile create mode 100644 deploy/docker/compose.yaml create mode 100644 deploy/docker/entrypoint.sh create mode 100644 deploy/linux/ianitor-control.service create mode 100644 deploy/linux/ianitor-edge.service create mode 100644 deploy/linux/install.sh create mode 100644 deploy/linux/setup.sh create mode 100644 deploy/windows/install.ps1 create mode 100644 scripts/preview.ps1 create mode 100644 scripts/preview.sh create mode 100644 scripts/smoke-windows.ps1 diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..4e10f48 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,9 @@ +target +**/node_modules +**/dist +.git +.fabrica +bench +*.log +result +result-* diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfile new file mode 100644 index 0000000..2097535 --- /dev/null +++ b/deploy/docker/Dockerfile @@ -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.10.3 + +# ------------------------------------------------------------------ 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 +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"] diff --git a/deploy/docker/compose.yaml b/deploy/docker/compose.yaml new file mode 100644 index 0000000..b9f7eec --- /dev/null +++ b/deploy/docker/compose.yaml @@ -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: diff --git a/deploy/docker/entrypoint.sh b/deploy/docker/entrypoint.sh new file mode 100644 index 0000000..00f220e --- /dev/null +++ b/deploy/docker/entrypoint.sh @@ -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 +# 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 diff --git a/deploy/linux/ianitor-control.service b/deploy/linux/ianitor-control.service new file mode 100644 index 0000000..f85848a --- /dev/null +++ b/deploy/linux/ianitor-control.service @@ -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 diff --git a/deploy/linux/ianitor-edge.service b/deploy/linux/ianitor-edge.service new file mode 100644 index 0000000..09cb308 --- /dev/null +++ b/deploy/linux/ianitor-edge.service @@ -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=:/var/lib/ianitor/credentials/ 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 diff --git a/deploy/linux/install.sh b/deploy/linux/install.sh new file mode 100644 index 0000000..5bbe005 --- /dev/null +++ b/deploy/linux/install.sh @@ -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= 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)" diff --git a/deploy/linux/setup.sh b/deploy/linux/setup.sh new file mode 100644 index 0000000..f02b3da --- /dev/null +++ b/deploy/linux/setup.sh @@ -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" <&2 diff --git a/deploy/windows/install.ps1 b/deploy/windows/install.ps1 new file mode 100644 index 0000000..aeee8ba --- /dev/null +++ b/deploy/windows/install.ps1 @@ -0,0 +1,208 @@ +# 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 ] +# [-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" } +} +# 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'; Plain $DomiRoot 'DomiRoot' +$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. +icacls $Root /inheritance:r /grant:r '*S-1-5-32-544:(OI)(CI)F' '*S-1-5-18:(OI)(CI)F' '*S-1-5-19:(OI)(CI)M' | Out-Null + +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 diff --git a/scripts/preview.ps1 b/scripts/preview.ps1 new file mode 100644 index 0000000..b631209 --- /dev/null +++ b/scripts/preview.ps1 @@ -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)" } + } +} diff --git a/scripts/preview.sh b/scripts/preview.sh new file mode 100644 index 0000000..39f6b27 --- /dev/null +++ b/scripts/preview.sh @@ -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 [ttl-seconds] prints the preview's URL +# scripts/preview.sh close +# 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 [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 " >&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 diff --git a/scripts/smoke-windows.ps1 b/scripts/smoke-windows.ps1 new file mode 100644 index 0000000..c01abc6 --- /dev/null +++ b/scripts/smoke-windows.ps1 @@ -0,0 +1,129 @@ +# 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 -Caddy -Work +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 --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}' --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}' --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' +} finally { + foreach ($p in $procs) { try { Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue } catch {} } + Remove-Item Env:\IANITOR_PREVIEW_TOKEN -ErrorAction SilentlyContinue +} -- 2.53.0 From d5d522fe4b31a25c060ea74d453972dd3bcd3b22 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 17 Nov 2026 20:55:41 +0100 Subject: [PATCH 10/15] [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) --- crates/control/src/previews.rs | 7 +++---- deploy/docker/Dockerfile | 2 +- deploy/windows/install.ps1 | 12 ++++++++++-- scripts/smoke-windows.ps1 | 7 ++++--- 4 files changed, 18 insertions(+), 10 deletions(-) diff --git a/crates/control/src/previews.rs b/crates/control/src/previews.rs index 24e2d5f..ca952a0 100644 --- a/crates/control/src/previews.rs +++ b/crates/control/src/previews.rs @@ -335,10 +335,9 @@ impl Control { share_links: false, device_certs: false, access_log: "off".into(), - health_check: Some(crate::hostspec::HealthCheckSpec { - path: "/api/v1/health".into(), - interval_secs: 10, - }), + // 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 { diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfile index 2097535..945bc49 100644 --- a/deploy/docker/Dockerfile +++ b/deploy/docker/Dockerfile @@ -12,7 +12,7 @@ ARG RUST=1.99-bookworm ARG CADDY=2.11.7 -ARG PEBBLE=v2.10.3 +ARG PEBBLE=v2.6.0 # ------------------------------------------------------------------ Rust toolchain + native deps FROM rust:${RUST} AS rust diff --git a/deploy/windows/install.ps1 b/deploy/windows/install.ps1 index aeee8ba..be654c7 100644 --- a/deploy/windows/install.ps1 +++ b/deploy/windows/install.ps1 @@ -47,6 +47,10 @@ 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 '\\', '/') } @@ -55,7 +59,7 @@ if (-not $NoService) { 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'; Plain $DomiRoot 'DomiRoot' +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 @@ -88,7 +92,11 @@ foreach ($d in 'control', 'edge', 'caddy', 'certs', 'caddy-state', 'logs', 'cred New-Item -ItemType Directory -Force (Join-Path $Root $d) | Out-Null } # Only Administrators, SYSTEM and the services' account (LocalService) see the state. -icacls $Root /inheritance:r /grant:r '*S-1-5-32-544:(OI)(CI)F' '*S-1-5-18:(OI)(CI)F' '*S-1-5-19:(OI)(CI)M' | Out-Null +$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" diff --git a/scripts/smoke-windows.ps1 b/scripts/smoke-windows.ps1 index c01abc6..7bd8f8d 100644 --- a/scripts/smoke-windows.ps1 +++ b/scripts/smoke-windows.ps1 @@ -105,9 +105,9 @@ try { $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 --cacert $ca --resolve "fix-42--shop.pv.smoke.test:${Https}:127.0.0.1" "https://fix-42--shop.pv.smoke.test:$Https/" + $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}' --cacert $ca --resolve "ianitor.smoke.test:${Https}:127.0.0.1" "https://ianitor.smoke.test:$Https/api/v1/team" + $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)" @@ -119,10 +119,11 @@ try { $deadline = (Get-Date).AddSeconds(90) do { Start-Sleep 2 - $code = & curl.exe -s -o NUL -w '%{http_code}' --cacert $ca --resolve "fix-42--shop.pv.smoke.test:${Https}:127.0.0.1" "https://fix-42--shop.pv.smoke.test:$Https/" + $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 -- 2.53.0 From defd722cc2e7fa4b0e16064cfe84aa1ebcdfcf00 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 17 Nov 2026 20:59:42 +0100 Subject: [PATCH 11/15] [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 --- .fabrica/artifex/release.yaml | 38 ++++++++++-- .fabrica/notes/0.2.0.md | 17 ++++++ Cargo.lock | 10 ++-- Cargo.toml | 2 +- apps/web/package.json | 2 +- deploy/docker/Dockerfile | 2 +- deploy/nixos/module.nix | 40 +++++++++++++ docs/api.md | 18 ++++++ docs/custos-ticket.md | 18 ++++++ docs/deploy/anywhere.md | 80 +++++++++++++++++++++++++ docs/previews.md | 107 ++++++++++++++++++++++++++++++++++ packages/ui/package.json | 2 +- scripts/package-windows.mjs | 39 +++++++++++++ scripts/smoke-docker.sh | 89 ++++++++++++++++++++++++++++ scripts/smoke-linux.sh | 100 +++++++++++++++++++++++++++++++ 15 files changed, 549 insertions(+), 15 deletions(-) create mode 100644 .fabrica/notes/0.2.0.md create mode 100644 docs/deploy/anywhere.md create mode 100644 docs/previews.md create mode 100644 scripts/package-windows.mjs create mode 100644 scripts/smoke-docker.sh create mode 100644 scripts/smoke-linux.sh diff --git a/.fabrica/artifex/release.yaml b/.fabrica/artifex/release.yaml index e05263b..8489dd9 100644 --- a/.fabrica/artifex/release.yaml +++ b/.fabrica/artifex/release.yaml @@ -1,7 +1,9 @@ -# Ianitor Domi: the Gitea release of a v* tag (docs/release.md). Ianitor ships no binary (the server builds it with -# Nix and the deploy pipeline switches it in), so a release is its notes and screenshots of the web UI, published 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). # `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 @@ -22,6 +24,27 @@ steps: - id: test needs: [install] run: pnpm --filter web test + # 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: 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"] @@ -30,13 +53,16 @@ steps: run: node apps/web/scripts/shots.mjs artifacts: ["target/aula/aula-*.png", "target/aula/aula.json"] - id: approve - needs: [version, notes, shots] - approve: "Publish Ianitor ${{ tag }}: its 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-*-linux-x86_64.tar.gz" + - "**/install.sh" + - "**/ianitor-*-windows-x86_64.zip" - "**/release-notes.md" - "**/release-notes.json" - "**/aula-*.png" diff --git a/.fabrica/notes/0.2.0.md b/.fabrica/notes/0.2.0.md new file mode 100644 index 0000000..38c84c6 --- /dev/null +++ b/.fabrica/notes/0.2.0.md @@ -0,0 +1,17 @@ +Ianitor Domi now runs for any small team, not only on a NixOS server, and gives Fabrica a preview address for +every branch. + +- **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 `--.` 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. diff --git a/Cargo.lock b/Cargo.lock index 4bc91fe..ce19c31 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1304,7 +1304,7 @@ dependencies = [ [[package]] name = "ianitor-control" -version = "0.1.0" +version = "0.2.0" dependencies = [ "axum", "base64 0.22.1", @@ -1333,7 +1333,7 @@ dependencies = [ [[package]] name = "ianitor-core" -version = "0.1.0" +version = "0.2.0" dependencies = [ "base64 0.22.1", "domi-pki", @@ -1350,7 +1350,7 @@ dependencies = [ [[package]] name = "ianitor-diff" -version = "0.1.0" +version = "0.2.0" dependencies = [ "ianitor-control", "ianitor-core", @@ -1365,7 +1365,7 @@ dependencies = [ [[package]] name = "ianitor-edge" -version = "0.1.0" +version = "0.2.0" dependencies = [ "arc-swap", "async-trait", @@ -1393,7 +1393,7 @@ dependencies = [ [[package]] name = "ianitor-testkit" -version = "0.1.0" +version = "0.2.0" dependencies = [ "bytes", "futures-util", diff --git a/Cargo.toml b/Cargo.toml index 87ef073..def1a2b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/core", "crates/edge", "crates/control", "tests/diff", "tests/support"] [workspace.package] -version = "0.1.0" +version = "0.2.0" edition = "2024" rust-version = "1.89" license = "MPL-2.0" diff --git a/apps/web/package.json b/apps/web/package.json index c5adebc..ae1073c 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,6 +1,6 @@ { "name": "web", - "version": "0.1.0", + "version": "0.2.0", "private": true, "license": "MPL-2.0", "description": "Ianitor Domi web UI (Svelte 5, runes, TypeScript strict). A pure client of the control API.", diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfile index 945bc49..5b3240a 100644 --- a/deploy/docker/Dockerfile +++ b/deploy/docker/Dockerfile @@ -59,7 +59,7 @@ RUN cargo build --release --locked -p ianitor-edge \ && strip target/release/ianitor-edge target/release/ianitor-control FROM node:22-bookworm-slim AS web -RUN corepack enable +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 diff --git a/deploy/nixos/module.nix b/deploy/nixos/module.nix index 34699d1..19a2f1f 100644 --- a/deploy/nixos/module.nix +++ b/deploy/nixos/module.nix @@ -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 (`--.`); 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; diff --git a/docs/api.md b/docs/api.md index 8674ae6..192e79c 100644 --- a/docs/api.md +++ b/docs/api.md @@ -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 ` prints the first admin's link, `https:///#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: diff --git a/docs/custos-ticket.md b/docs/custos-ticket.md index 0afeb54..6f7f675 100644 --- a/docs/custos-ticket.md +++ b/docs/custos-ticket.md @@ -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). diff --git a/docs/deploy/anywhere.md b/docs/deploy/anywhere.md new file mode 100644 index 0000000..f307d10 --- /dev/null +++ b/docs/deploy/anywhere.md @@ -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 --config `), 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. diff --git a/docs/previews.md b/docs/previews.md new file mode 100644 index 0000000..e054399 --- /dev/null +++ b/docs/previews.md @@ -0,0 +1,107 @@ +# Branch previews (T4) + +Every branch Fabrica builds can get its own address: `--.`, 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 `, 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 `; 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/.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 `--` (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). diff --git a/packages/ui/package.json b/packages/ui/package.json index 71f8664..1fbc695 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -1,6 +1,6 @@ { "name": "@ianitor/ui", - "version": "0.1.0", + "version": "0.2.0", "private": true, "license": "MPL-2.0", "description": "The shared dark Domi theme (murex palette) and its Svelte components.", diff --git a/scripts/package-windows.mjs b/scripts/package-windows.mjs new file mode 100644 index 0000000..a77d707 --- /dev/null +++ b/scripts/package-windows.mjs @@ -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--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); diff --git a/scripts/smoke-docker.sh b/scripts/smoke-docker.sh new file mode 100644 index 0000000..66fcf2e --- /dev/null +++ b/scripts/smoke-docker.sh @@ -0,0 +1,89 @@ +#!/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 +set -euo pipefail + +IMAGE=$1 CTL=$2 WORK=$3 +REPO=$(cd "$(dirname "$0")/.." && 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; exit 1; } +cleanup() { + "${DC[@]}" down -v --remove-orphans >/dev/null 2>&1 || true + docker rm -f $P-app >/dev/null 2>&1 || true +} +trap cleanup EXIT +[ ! -e "$WORK" ] || fail "$WORK exists; give a new folder" +mkdir -p "$WORK" +# 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 >/dev/null 2>&1 || 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 --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}' --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}' --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" diff --git a/scripts/smoke-linux.sh b/scripts/smoke-linux.sh new file mode 100644 index 0000000..79ebd37 --- /dev/null +++ b/scripts/smoke-linux.sh @@ -0,0 +1,100 @@ +#!/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 +set -euo pipefail + +DIST=$1 CTL=$2 WORK=$3 +REPO=$(cd "$(dirname "$0")/.." && 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" +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 --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}' --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" -- 2.53.0 From 695ed178a5c4e14242750ee21b367479a2e834b3 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 17 Nov 2026 21:18:19 +0100 Subject: [PATCH 12/15] [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 --- CLAUDE.md | 3 +++ crates/control/src/engine.rs | 3 ++- crates/control/src/previews.rs | 8 +++++++- crates/control/tests/previews.rs | 4 ++-- scripts/smoke-docker.sh | 4 ++++ 5 files changed, 18 insertions(+), 4 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 98fb469..e296d14 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -14,10 +14,13 @@ 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 node apps/web/scripts/shots.mjs # the release's screenshots (demo data, headless Edge) -> target/aula (docs/release.md) diff --git a/crates/control/src/engine.rs b/crates/control/src/engine.rs index 44f4ef3..f777c6a 100644 --- a/crates/control/src/engine.rs +++ b/crates/control/src/engine.rs @@ -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 }, diff --git a/crates/control/src/previews.rs b/crates/control/src/previews.rs index ca952a0..64b2efb 100644 --- a/crates/control/src/previews.rs +++ b/crates/control/src/previews.rs @@ -9,6 +9,9 @@ //! (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; @@ -95,7 +98,10 @@ fn parse_entry(e: &str) -> Option { ports, }); } - plain(&name).then(|| Allowed { + if !plain(&name) { + return None; + } + Some(Allowed { target: Target::Name(name), ports, }) diff --git a/crates/control/tests/previews.rs b/crates/control/tests/previews.rs index f140f94..0a87a32 100644 --- a/crates/control/tests/previews.rs +++ b/crates/control/tests/previews.rs @@ -22,7 +22,7 @@ use serde_json::{Value, json}; const DOMAIN: &str = "pv.example.test"; struct Ctl { - dir: TempDir, + _dir: TempDir, api: SocketAddr, admin: String, preview: String, @@ -112,7 +112,7 @@ sweep_secs = 1 "control did not listen" ); Ctl { - dir, + _dir: dir, api, admin, preview, diff --git a/scripts/smoke-docker.sh b/scripts/smoke-docker.sh index 66fcf2e..01a276d 100644 --- a/scripts/smoke-docker.sh +++ b/scripts/smoke-docker.sh @@ -10,6 +10,9 @@ # # scripts/smoke-docker.sh 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) @@ -24,6 +27,7 @@ fail() { echo "FAILED: $*" >&2; 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" -- 2.53.0 From 2aa8d661270cbeea946a0e5cfd774922e647a4e9 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 17 Nov 2026 21:35:34 +0100 Subject: [PATCH 13/15] [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 --- crates/control/src/api/mod.rs | 11 ++++++++--- scripts/smoke-docker.sh | 14 ++++++++------ scripts/smoke-linux.sh | 11 ++++++++--- 3 files changed, 24 insertions(+), 12 deletions(-) diff --git a/crates/control/src/api/mod.rs b/crates/control/src/api/mod.rs index b532bc6..1ca33bb 100644 --- a/crates/control/src/api/mod.rs +++ b/crates/control/src/api/mod.rs @@ -357,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)) diff --git a/scripts/smoke-docker.sh b/scripts/smoke-docker.sh index 01a276d..35649f1 100644 --- a/scripts/smoke-docker.sh +++ b/scripts/smoke-docker.sh @@ -15,7 +15,7 @@ set -euo pipefail export MSYS_NO_PATHCONV=1 MSYS2_ENV_CONV_EXCL='*' IMAGE=$1 CTL=$2 WORK=$3 -REPO=$(cd "$(dirname "$0")/.." && pwd) +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 @@ -23,7 +23,7 @@ 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; exit 1; } +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 @@ -32,6 +32,8 @@ cleanup() { 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"; } @@ -43,7 +45,7 @@ docker run --rm -i -v ${P}_state:/v alpine:3.20 sh -c 'cat > /v/domi-root.crt && ok "root in the state volume" step "docker compose up" -"${DC[@]}" up -d >/dev/null 2>&1 || fail "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) @@ -71,10 +73,10 @@ 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 --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=$(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}' --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=$(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") @@ -84,7 +86,7 @@ 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}' --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=$(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 diff --git a/scripts/smoke-linux.sh b/scripts/smoke-linux.sh index 79ebd37..5757bdd 100644 --- a/scripts/smoke-linux.sh +++ b/scripts/smoke-linux.sh @@ -12,9 +12,11 @@ # # scripts/smoke-linux.sh 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) +REPO=$(cd "$(dirname "$0")/.." && (pwd -W 2>/dev/null || pwd)) C=ianitor-smoke-linux step() { echo "== $*"; } ok() { echo " ok: $*"; } @@ -23,6 +25,9 @@ cleanup() { docker rm -f $C >/dev/null 2>&1 || true; docker rmi -f $C:latest >/d 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/') @@ -81,7 +86,7 @@ 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 --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=$(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) @@ -91,7 +96,7 @@ 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}' --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=$(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 -- 2.53.0 From 6956f23cb298c0fb32afa45fb49b8bc6695c428b Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 17 Nov 2026 21:42:52 +0100 Subject: [PATCH 14/15] [tests] Caddy mode: a minute for Caddy to start on a busy machine --- crates/control/tests/caddy_mode.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/control/tests/caddy_mode.rs b/crates/control/tests/caddy_mode.rs index f137c47..87c55fb 100644 --- a/crates/control/tests/caddy_mode.rs +++ b/crates/control/tests/caddy_mode.rs @@ -113,7 +113,7 @@ async fn a_branch_preview_answers_through_caddy_without_an_edge() { .unwrap(), ); assert!( - wait_for_port(admin, Duration::from_secs(20)), + 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(); -- 2.53.0 From 67888aa7913748af567433d716e89a0af5da1714 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 17 Nov 2026 22:16:50 +0100 Subject: [PATCH 15/15] [docs] Roadmap: T4 status and handover --- docs/ROADMAP.md | 51 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index c6abe94..1d614f5 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -146,10 +146,61 @@ Identity gate, tunnel, Domi templates, ACME server, HTTP/3, migrating public sit | 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 | 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-17: T4, Ianitor anywhere, previews for Fabrica, team sign-in (Fabrica docs/32_coherence.md).** +- **Changed:** + - core: `preview` (branch and project → one safe label, `--.`, 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."; 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) v1.0.0 (git tag in Cargo.toml): the same public API, the same error messages and the same encrypted-key format -- 2.53.0