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/.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/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/Cargo.lock b/Cargo.lock index 361846a..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", @@ -1326,12 +1326,14 @@ dependencies = [ "tokio", "tokio-rustls", "toml", + "url", "utoipa", + "windows-service", ] [[package]] name = "ianitor-core" -version = "0.1.0" +version = "0.2.0" dependencies = [ "base64 0.22.1", "domi-pki", @@ -1348,7 +1350,7 @@ dependencies = [ [[package]] name = "ianitor-diff" -version = "0.1.0" +version = "0.2.0" dependencies = [ "ianitor-control", "ianitor-core", @@ -1358,11 +1360,12 @@ dependencies = [ "rustls", "serde_json", "tokio", + "toml", ] [[package]] name = "ianitor-edge" -version = "0.1.0" +version = "0.2.0" dependencies = [ "arc-swap", "async-trait", @@ -1390,7 +1393,7 @@ dependencies = [ [[package]] name = "ianitor-testkit" -version = "0.1.0" +version = "0.2.0" dependencies = [ "bytes", "futures-util", @@ -3552,6 +3555,12 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "widestring" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471" + [[package]] name = "winapi-util" version = "0.1.11" @@ -3567,6 +3576,17 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-service" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "857224b3b211c6f3616921f081ee54721ee3ad2ace2fac6a6337e032f7b4dcf2" +dependencies = [ + "bitflags", + "widestring", + "windows-sys 0.61.2", +] + [[package]] name = "windows-sys" version = "0.52.0" 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/apps/web/src/App.svelte b/apps/web/src/App.svelte index f073ddc..22b687a 100644 --- a/apps/web/src/App.svelte +++ b/apps/web/src/App.svelte @@ -15,6 +15,7 @@ import Certificates from "./views/Certificates.svelte"; import History from "./views/History.svelte"; import Hosts from "./views/Hosts.svelte"; + import Previews from "./views/Previews.svelte"; import RenewByHand from "./views/RenewByHand.svelte"; import Settings from "./views/Settings.svelte"; import SignedIn from "./views/SignedIn.svelte"; @@ -24,6 +25,7 @@ const p = u.pathname.replace(/\/+$/, "") || "/"; const seg = p.split("/").filter(Boolean).map(decodeURIComponent); if (p === "/signed-in") return { view: "signed-in" as const }; + if (seg[0] === "previews") return { view: "previews" as const }; if (seg[0] === "history") return { view: "history" as const, host: u.searchParams.get("host") ?? undefined, pick: seg[1] }; if (seg[0] === "certificates") return { view: seg[1] === "renew-by-hand" ? ("renew" as const) : ("certs" as const), newDevice: seg[1] === "new" }; if (seg[0] === "settings") return { view: "settings" as const, tab: seg[1] ?? "general" }; @@ -32,18 +34,51 @@ const NAV: { href: string; label: string; icon: IconName; views: string[] }[] = [ { href: "/", label: "Hosts", icon: "building", views: ["hosts"] }, + { href: "/previews", label: "Previews", icon: "link", views: ["previews"] }, { href: "/history", label: "History", icon: "history", views: ["history"] }, { href: "/certificates", label: "Certificates", icon: "shield", views: ["certs", "renew"] }, { href: "/settings/general", label: "Settings", icon: "gear", views: ["settings"] }, ]; - const TITLES: Record = { hosts: "Hosts", history: "History", certs: "Certificates", renew: "Certificates", settings: "Settings", "signed-in": "Signed in" }; + const TITLES: Record = { hosts: "Hosts", history: "History", previews: "Previews", certs: "Certificates", renew: "Certificates", settings: "Settings", "signed-in": "Signed in" }; $effect(() => { document.title = `${TITLES[route.view] ?? "Hosts"} — Ianitor Domi`; }); + // A setup or invite link (`#signin=`, crate::team): one click on the link signs in. + async function signInFromLink(): Promise { + const m = /^#signin=([A-Za-z0-9_-]{8,100})$/.exec(location.hash); + if (!m) return; + history.replaceState(null, "", location.pathname + location.search); + try { + const r = await fetch("/api/v1/session", { + method: "POST", + headers: { "Content-Type": "application/json", "X-Ianitor-UI": "1" }, + body: JSON.stringify({ code: m[1], device: navigator.platform || "Browser" }), + credentials: "same-origin", + }); + if (!r.ok) { + const j = await r.json().catch(() => null); + app.linkProblem = j?.error?.message ?? "This sign-in link does not work."; + } + } catch { + app.linkProblem = "Ianitor did not answer the sign-in."; + } + } + + async function signOutSession() { + try { + await fetch("/api/v1/session/end", { method: "POST", headers: { "X-Ianitor-UI": "1" }, credentials: "same-origin" }); + } finally { + location.href = "/"; + } + } + onMount(() => { if (route.view === "signed-in") return; + if (location.hash.startsWith("#signin=")) { + void signInFromLink().then(() => refresh()); + } const stop = startPolling(); // Resume an apply this tab was watching before a reload or a sign-in (§3). const id = remembered(); @@ -101,7 +136,8 @@ go(e, n.href)}>{n.label} {/each}
-

{viewer?.via === "authelia" ? `Signed in as ${viewer.name} through Authelia` : viewer ? `Using the API token "${viewer.name}"` : "Signed in through Authelia"}

+

{viewer?.via === "authelia" ? `Signed in as ${viewer.name} through Authelia` : viewer?.via === "session" ? `Signed in as ${viewer.name}` : viewer ? `Using the API token "${viewer.name}"` : "Not signed in"}

+ {#if viewer?.via === "session"}{/if}

Control on 127.0.0.1 only

{#if app.overview?.site?.auth_logout_url}Sign out{/if}
@@ -109,8 +145,11 @@
IANITOR DOMI{#if app.phone}{/if}
+ {#if app.linkProblem}{/if} {#if route.view === "hosts"} + {:else if route.view === "previews"} + {:else if route.view === "history"} {#key route.host}{/key} {:else if route.view === "certs"} @@ -141,7 +180,7 @@ {#if app.signedOut} {}}> -

Sign in again; this page keeps what you typed.

+

Sign in again; this page keeps what you typed. Without Authelia, open your sign-in link again or ask an admin of your team for a new one.

{#snippet footer()} @@ -167,7 +206,7 @@ .topbar { display: flex; align-items: center; justify-content: space-between; background: var(--colonnade); border-bottom: 1px solid var(--hairline); padding: 10px 16px; } .topbar .ia-wordmark { font-size: 12px; letter-spacing: 0.26em; } main { padding: 18px 16px calc(90px + env(safe-area-inset-bottom)); gap: 14px; } - .bottombar { display: grid; grid-template-columns: repeat(4, 1fr); position: fixed; left: 0; right: 0; bottom: 0; background: var(--colonnade); border-top: 1px solid var(--hairline); padding: 6px 8px calc(10px + env(safe-area-inset-bottom)); z-index: 40; } + .bottombar { display: grid; grid-template-columns: repeat(5, 1fr); position: fixed; left: 0; right: 0; bottom: 0; background: var(--colonnade); border-top: 1px solid var(--hairline); padding: 6px 8px calc(10px + env(safe-area-inset-bottom)); z-index: 40; } .bottombar a { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; min-height: var(--phone-bar-h); border-radius: var(--radius-sm); color: var(--text-2); font-weight: 600; font-size: var(--fs-tab-phone); text-decoration: none; } .bottombar a[aria-current="page"] { background: var(--surface-2); color: var(--text); } .bottombar a[aria-current="page"] :global(svg) { color: var(--accent); } diff --git a/apps/web/src/components/TeamTab.svelte b/apps/web/src/components/TeamTab.svelte new file mode 100644 index 0000000..44582d2 --- /dev/null +++ b/apps/web/src/components/TeamTab.svelte @@ -0,0 +1,137 @@ + + + +{#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" }]], ]; } diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index bd32f97..0faee82 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -23,6 +23,7 @@ test-hooks = [] [dependencies] ianitor-core.workspace = true +url.workspace = true rustls.workspace = true rustls-pki-types.workspace = true tokio-rustls.workspace = true @@ -44,6 +45,10 @@ qrcode = { version = "0.14", default-features = false, features = ["svg"] } # The offline root CLI asks for its passphrase without echo. rpassword = "7" +# Windows Server, Caddy mode: the service control manager starts control and the guard. +[target.'cfg(windows)'.dependencies] +windows-service = "0.8" + [dev-dependencies] ianitor-testkit.workspace = true p12-keystore = "0.4" diff --git a/crates/control/src/api/handlers.rs b/crates/control/src/api/handlers.rs index 1ab3760..e8b410b 100644 --- a/crates/control/src/api/handlers.rs +++ b/crates/control/src/api/handlers.rs @@ -300,6 +300,8 @@ pub async fn overview( viewer: Some(Viewer { via: if actor.token_id.starts_with("user:") { "authelia".into() + } else if actor.member.is_some() { + "session".into() } else { "token".into() }, @@ -935,6 +937,9 @@ pub struct TokenCreate { pub expires_in_days: Option, #[serde(default)] pub never_expires: bool, + /// `full` (default) or `previews`: a token for Fabrica that may only use `/api/v1/previews`. + #[serde(default)] + pub scope: Option, } /// Make a token. Its value is in this response only. @@ -966,7 +971,19 @@ pub async fn create_token( let name = b .name .unwrap_or_else(|| format!("Token {}", ianitor_core::time::long_date(now()))); - let (rec, value) = st.ctl.tokens.create(&name, expires).map_err(|e| { + let scope = match b.scope.as_deref() { + None => crate::tokens::Scope::Full, + Some(s) => crate::tokens::Scope::parse(s).ok_or_else(|| { + let mut e = ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "token.scope_value", + Params::new(), + ); + e.body.field = Some("scope".into()); + e + })?, + }; + let (rec, value) = st.ctl.tokens.create(&name, expires, scope).map_err(|e| { if e == "token.name" { let mut err = ApiError::new( StatusCode::UNPROCESSABLE_ENTITY, @@ -1384,7 +1401,11 @@ impl Modify for Bearer { mint_share_link, list_share_links, stop_share_link, stop_all_share_links, health, openapi, super::pki::get_certs, super::pki::request_device, super::pki::get_request, super::pki::cancel_request, super::pki::get_csr, super::pki::get_ext, super::pki::put_certificate, super::pki::renew, super::pki::revoke_device, - super::pki::make_bundle, super::pki::download_bundle, super::pki::get_engine, super::pki::switch_engine + super::pki::make_bundle, super::pki::download_bundle, super::pki::get_engine, super::pki::switch_engine, + super::previews::list_previews, super::previews::open_preview, super::previews::get_preview, + super::previews::kill_preview, super::previews::close_preview, + super::team::sign_out, super::team::get_team, super::team::invite, super::team::cancel_invite, + super::team::remove_member, super::team::set_root ), components(schemas( HostSpec, HealthCheckSpec, HeaderRuleSpec, HostWrite, HostPatch, UndoBody, RestoreBody, TokenCreate, @@ -1394,13 +1415,17 @@ impl Modify for Bearer { HealthReport, Done, super::pki::CertsView, super::pki::PkiRequestView, super::pki::IntermediateView, super::pki::RootView, super::pki::DeviceView, super::pki::DeviceRequestBody, super::pki::CertificateBody, super::pki::BundleBody, super::pki::BundleView, super::pki::EngineSwitchView, super::pki::EngineBody, - FallbackReady + FallbackReady, crate::hostspec::PreviewSpec, super::previews::PreviewOpen, super::previews::PreviewClose, + super::previews::PreviewView, super::previews::PreviewOpened, super::previews::PreviewOne, + super::previews::PreviewList, super::previews::PreviewClosed, + super::team::SignIn, super::team::SignedIn, super::team::MemberView, super::team::TeamView, + super::team::InviteBody, super::team::InviteMade, super::team::InviteView, super::team::RootBody )), modifiers(&Bearer), tags( (name = "overview"), (name = "hosts"), (name = "applies"), (name = "history"), (name = "repo"), (name = "settings"), (name = "tokens"), (name = "share-links"), - (name = "certs"), (name = "engine") + (name = "certs"), (name = "engine"), (name = "previews"), (name = "team") ) )] pub struct ApiDoc; diff --git a/crates/control/src/api/mod.rs b/crates/control/src/api/mod.rs index c63c84f..1ca33bb 100644 --- a/crates/control/src/api/mod.rs +++ b/crates/control/src/api/mod.rs @@ -17,6 +17,8 @@ pub mod handlers; pub mod pki; +pub mod previews; +pub mod team; pub mod ui; pub mod views; @@ -45,11 +47,36 @@ use views::{ErrorBody, ErrorEnvelope}; pub const MAX_BODY: usize = 64 * 1024; const RATE_PER_MINUTE: u32 = 120; -/// Who is calling: the API token's id and name. +/// Who is calling: the API token's id and name, and what the token may do. #[derive(Debug, Clone)] pub struct Actor { pub token_id: String, pub name: String, + pub scope: crate::tokens::Scope, + /// A team member signed in with a session (`crate::team`): their id, session and role. + /// `None` for API tokens and Authelia sign-ins, which may do everything. + pub member: Option, + pub session: Option, + pub role: Option, +} + +/// What only an admin may do (a `member` session gets 403 `team.admin_only`): API tokens, +/// the team, the engine and the CA. +fn admin_only(method: &str, path: &str) -> bool { + let write = !matches!(method, "GET" | "HEAD" | "OPTIONS"); + path.starts_with("/api/v1/tokens") + || (path.starts_with("/api/v1/team/") && !path.starts_with("/api/v1/team/me/")) + || (write && path == "/api/v1/engine") + || (write && path.starts_with("/api/v1/certs/intermediate")) + || path.starts_with("/api/v1/pki-requests") +} + +/// The only routes a `previews` token may call (T4: it can never touch another host). +fn in_preview_scope(path: &str) -> bool { + path == "/api/v1/previews" + || path + .strip_prefix("/api/v1/previews/") + .is_some_and(|rest| !rest.is_empty() && !rest.contains('/')) } pub enum Stored { @@ -330,11 +357,16 @@ pub(crate) fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool { format!("127.0.0.1:{port}"), format!("[::1]:{port}"), ]; - // The admin host edge forwards the UI on, with or without edge's HTTPS port. + // The admin host the engine forwards the UI on, with any port: behind Docker's or a + // router's port mapping the visitor's port is not the engine's (T4). The name is what + // keeps a rebound DNS name out. let ui = ctl.cfg.ui.as_ref().and_then(|u| u.hostname.as_deref()); let ui_ok = ui.is_some_and(|u| { - let edge_port = ctl.cfg.compile.https_listen.port(); - host.eq_ignore_ascii_case(u) || host.eq_ignore_ascii_case(&format!("{u}:{edge_port}")) + let name = match host.rsplit_once(':') { + Some((n, p)) if !p.is_empty() && p.bytes().all(|c| c.is_ascii_digit()) => n, + _ => host, + }; + name.eq_ignore_ascii_case(u) }); ui_ok || ok.iter().any(|o| o.eq_ignore_ascii_case(host)) @@ -461,10 +493,65 @@ async fn guard(State(st): State>, mut req: Request, next: Next) -> req.extensions_mut().insert(Actor { token_id: format!("user:{user}"), name: display, + scope: crate::tokens::Scope::Full, + member: None, + session: None, + role: None, }); return Ok(next.run(req).await); } } + // A team session (crate::team): the cookie, when no API token is given. + if !req.headers().contains_key(header::AUTHORIZATION) + && let Some(value) = team::session_cookie(req.headers()) + { + let ctl = st.ctl.clone(); + let found = tokio::task::spawn_blocking(move || ctl.team.check(&value)) + .await + .ok() + .flatten(); + let Some((member, session)) = found else { + return Err(ApiError::new( + StatusCode::UNAUTHORIZED, + "session.unknown", + Params::new(), + )); + }; + let same_site = req + .headers() + .get("sec-fetch-site") + .is_none_or(|v| matches!(v.as_bytes(), b"same-origin" | b"none")); + if write && (!ui || !same_site) { + return Err(ApiError::new( + StatusCode::FORBIDDEN, + "request.csrf", + Params::new(), + )); + } + if member.role != crate::team::Role::Admin + && admin_only(method.as_str(), req.uri().path()) + { + return Err(ApiError::new( + StatusCode::FORBIDDEN, + "team.admin_only", + Params::new(), + )); + } + st.limit(&format!("member:{}", member.id), RATE_PER_MINUTE, 60) + .map_err(|s| { + ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()) + .retry(s) + })?; + req.extensions_mut().insert(Actor { + token_id: format!("member:{}", member.id), + name: member.name.clone(), + scope: crate::tokens::Scope::Full, + member: Some(member.id), + session: Some(session.id), + role: Some(member.role), + }); + return Ok(next.run(req).await); + } let auth = req .headers() .get(header::AUTHORIZATION) @@ -490,6 +577,13 @@ async fn guard(State(st): State>, mut req: Request, next: Next) -> }; ApiError::new(StatusCode::UNAUTHORIZED, code, params) })?; + if tok.scope == crate::tokens::Scope::Previews && !in_preview_scope(req.uri().path()) { + return Err(ApiError::new( + StatusCode::FORBIDDEN, + "token.scope", + Params::new(), + )); + } st.limit(&format!("token:{}", tok.id), RATE_PER_MINUTE, 60) .map_err(|s| { ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s) @@ -497,6 +591,10 @@ async fn guard(State(st): State>, mut req: Request, next: Next) -> req.extensions_mut().insert(Actor { token_id: tok.id, name: tok.name, + scope: tok.scope, + member: None, + session: None, + role: None, }); Ok(next.run(req).await) } @@ -620,6 +718,21 @@ pub fn router(st: Arc) -> Router { "/api/v1/engine", get(pki::get_engine).post(pki::switch_engine), ) + .route( + "/api/v1/previews", + get(previews::list_previews).post(previews::open_preview), + ) + .route("/api/v1/previews/close", post(previews::close_preview)) + .route( + "/api/v1/previews/{hostname}", + get(previews::get_preview).delete(previews::kill_preview), + ) + .route("/api/v1/team", get(team::get_team)) + .route("/api/v1/team/invites", post(team::invite)) + .route("/api/v1/team/invites/{id}", delete(team::cancel_invite)) + .route("/api/v1/team/members/{id}", delete(team::remove_member)) + .route("/api/v1/team/me/root", axum::routing::put(team::set_root)) + .route("/api/v1/session/end", post(team::sign_out)) .route("/api/v1/health", get(h::health)) .route("/api/v1/openapi.json", get(h::openapi)) .method_not_allowed_fallback(method_not_allowed) diff --git a/crates/control/src/api/previews.rs b/crates/control/src/api/previews.rs new file mode 100644 index 0000000..48dcfd3 --- /dev/null +++ b/crates/control/src/api/previews.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/. + +//! `/api/v1/previews`: Fabrica's branch previews (T4). The only routes a `previews` token may +//! call (the guard in `api` refuses every other route for it). + +// An error answer is built once per failed request; boxing it buys nothing. +#![allow(clippy::result_large_err)] + +use std::sync::Arc; + +use axum::Extension; +use axum::extract::{Path, State}; +use axum::http::StatusCode; +use axum::response::{IntoResponse, Response}; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; + +use super::views::{ApplyView, apply_view}; +use super::{Actor, ApiError, AppState, Body}; +use crate::messages::Params; +use crate::util::rfc3339; + +type Shared = State>; + +fn json(status: StatusCode, v: &T) -> Response { + (status, axum::Json(v)).into_response() +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct PreviewOpen { + /// Fabrica's project, e.g. `mnovak/Arca` or `github:acme/web`. + pub project: String, + /// The git branch, as the git host names it. + pub branch: String, + /// Where the branch's build runs, e.g. `http://10.0.0.5:8080` (must be in `[previews] upstreams`). + pub upstream: String, + /// Seconds until the preview closes by itself (default from `[previews]`). + pub ttl: Option, +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct PreviewClose { + pub project: String, + pub branch: String, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct PreviewView { + pub hostname: String, + /// `https:///` + pub url: String, + pub project: String, + pub branch: String, + pub upstream: String, + pub expires_at: String, + /// `applying`, `live` or `failed`. + pub state: String, + /// Why it failed, in plain English. + #[serde(skip_serializing_if = "Option::is_none")] + pub problem: Option, +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct PreviewOpened { + pub preview: PreviewView, + pub apply: ApplyView, +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct PreviewOne { + pub preview: PreviewView, +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct PreviewList { + pub items: Vec, + /// The domain previews live under; absent when previews are off. + pub domain: Option, +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct PreviewClosed { + pub apply: ApplyView, +} + +fn view(st: &AppState, p: &crate::previews::Listed) -> PreviewView { + let (state, problem) = st + .ctl + .preview_state(&p.hostname) + .unwrap_or(("live".into(), None)); + PreviewView { + url: format!("https://{}/", p.hostname), + hostname: p.hostname.clone(), + project: p.project.clone(), + branch: p.branch.clone(), + upstream: p.upstream.clone(), + expires_at: rfc3339(p.expires_at), + state, + problem, + } +} + +/// Every open preview. +#[utoipa::path(get, path = "/api/v1/previews", tag = "previews", + responses((status = 200, body = PreviewList)), security(("bearer" = [])))] +pub async fn list_previews(State(st): Shared) -> Result { + let domain = st.ctl.cfg.previews.as_ref().map(|p| p.domain.clone()); + let items = if domain.is_some() { + st.ctl.previews()?.iter().map(|p| view(&st, p)).collect() + } else { + Vec::new() + }; + Ok(json(StatusCode::OK, &PreviewList { items, domain })) +} + +/// Open a branch's preview, or move it to a new upstream and lifetime. The host is +/// `--.`; it is live when its apply is kept. +#[utoipa::path(post, path = "/api/v1/previews", tag = "previews", request_body = PreviewOpen, + responses((status = 202, body = PreviewOpened), (status = 403, body = super::views::ErrorEnvelope), + (status = 409, body = super::views::ErrorEnvelope), (status = 422, body = super::views::ErrorEnvelope)), + security(("bearer" = [])))] +pub async fn open_preview( + State(st): Shared, + Extension(actor): Extension, + body: Body, +) -> Result { + let b = body.value; + let (hostname, expires_at, rec) = + st.ctl + .open_preview(&b.project, &b.branch, &b.upstream, b.ttl, &actor.name)?; + let preview = PreviewView { + url: format!("https://{hostname}/"), + hostname, + project: b.project, + branch: b.branch, + upstream: b.upstream, + expires_at: rfc3339(expires_at), + state: "applying".into(), + problem: None, + }; + Ok(json( + StatusCode::ACCEPTED, + &PreviewOpened { + preview, + apply: apply_view(&st.ctl, &rec), + }, + )) +} + +/// One preview and where it stands (Fabrica polls this after opening one). +#[utoipa::path(get, path = "/api/v1/previews/{hostname}", tag = "previews", + params(("hostname" = String, Path)), + responses((status = 200, body = PreviewOne), (status = 404, body = super::views::ErrorEnvelope)), + security(("bearer" = [])))] +pub async fn get_preview( + State(st): Shared, + Path(hostname): Path, +) -> Result { + st.ctl.previews_cfg()?; + let not_found = || ApiError::new(StatusCode::NOT_FOUND, "preview.not_found", Params::new()); + if let Some(p) = st + .ctl + .previews()? + .into_iter() + .find(|p| p.hostname == hostname) + { + return Ok(json( + StatusCode::OK, + &PreviewOne { + preview: view(&st, &p), + }, + )); + } + // Not at the head: a preview whose apply is still running or failed. + let (state, problem) = st.ctl.preview_state(&hostname).ok_or_else(not_found)?; + let rec = st + .ctl + .records() + .into_iter() + .rev() + .find(|r| r.hosts.contains(&hostname)) + .ok_or_else(not_found)?; + let pv = rec + .attempted_host + .as_ref() + .and_then(|h| h.preview.clone()) + .ok_or_else(not_found)?; + Ok(json( + StatusCode::OK, + &PreviewOne { + preview: PreviewView { + url: format!("https://{hostname}/"), + hostname, + project: pv.project, + branch: pv.branch, + upstream: rec + .attempted_host + .as_ref() + .and_then(|h| h.upstreams.first().cloned()) + .unwrap_or_default(), + expires_at: rfc3339(u64::try_from(pv.expires_at).unwrap_or(0)), + state, + problem, + }, + }, + )) +} + +/// Close a preview now (the previews screen's Close, or Fabrica after a merge). +#[utoipa::path(delete, path = "/api/v1/previews/{hostname}", tag = "previews", + params(("hostname" = String, Path)), + responses((status = 202, body = PreviewClosed), (status = 404, body = super::views::ErrorEnvelope)), + security(("bearer" = [])))] +pub async fn kill_preview( + State(st): Shared, + Extension(actor): Extension, + Path(hostname): Path, +) -> Result { + let rec = st.ctl.close_preview(&hostname, &actor.name, "Closed the")?; + Ok(json( + StatusCode::ACCEPTED, + &PreviewClosed { + apply: apply_view(&st.ctl, &rec), + }, + )) +} + +/// Close a branch's preview by project and branch (Fabrica, when the branch is merged or +/// deleted). +#[utoipa::path(post, path = "/api/v1/previews/close", tag = "previews", request_body = PreviewClose, + responses((status = 202, body = PreviewClosed), (status = 404, body = super::views::ErrorEnvelope)), + security(("bearer" = [])))] +pub async fn close_preview( + State(st): Shared, + Extension(actor): Extension, + body: Body, +) -> Result { + let b = body.value; + let p = st.ctl.previews_cfg()?; + let hostname = ianitor_core::preview::hostname(&b.project, &b.branch, &p.domain) + .map_err(crate::previews::name_fail)?; + let mine = st + .ctl + .previews()? + .into_iter() + .any(|x| x.hostname == hostname && x.project == b.project && x.branch == b.branch); + if !mine { + return Err(ApiError::new( + StatusCode::NOT_FOUND, + "preview.not_found", + Params::new(), + )); + } + let rec = st.ctl.close_preview(&hostname, &actor.name, "Closed the")?; + Ok(json( + StatusCode::ACCEPTED, + &PreviewClosed { + apply: apply_view(&st.ctl, &rec), + }, + )) +} diff --git a/crates/control/src/api/team.rs b/crates/control/src/api/team.rs new file mode 100644 index 0000000..9cf45c6 --- /dev/null +++ b/crates/control/src/api/team.rs @@ -0,0 +1,351 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Team sign-in and the team list (`crate::team`). `POST /api/v1/session` is the one call +//! without a token or session: it redeems a setup or invite link. Everything else here goes +//! through the guard; inviting and removing people needs the admin role. + +// An error answer is built once per failed request; boxing it buys nothing. +#![allow(clippy::result_large_err)] + +use std::sync::Arc; + +use axum::Extension; +use axum::extract::{Path, Request, State}; +use axum::http::{HeaderMap, HeaderValue, StatusCode, header}; +use axum::response::{IntoResponse, Response}; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; + +use super::{Actor, ApiError, AppState, Body}; +use crate::messages::Params; +use crate::team::{COOKIE, Member, Role, SESSION_SECS, match_code}; +use crate::util::rfc3339; + +type Shared = State>; + +fn json(status: StatusCode, v: &T) -> Response { + (status, axum::Json(v)).into_response() +} + +fn refused(code: &'static str) -> ApiError { + let status = match code { + "internal" => StatusCode::INTERNAL_SERVER_ERROR, + "session.code" => StatusCode::UNAUTHORIZED, + "team.not_found" => StatusCode::NOT_FOUND, + "team.last_admin" | "team.full" => StatusCode::CONFLICT, + _ => StatusCode::UNPROCESSABLE_ENTITY, + }; + ApiError::new(status, code, Params::new()) +} + +/// The session cookie's value from a request, if any. +pub fn session_cookie(headers: &HeaderMap) -> Option { + headers + .get_all(header::COOKIE) + .iter() + .filter_map(|v| v.to_str().ok()) + .flat_map(|v| v.split(';')) + .filter_map(|kv| kv.trim().split_once('=')) + .find(|(k, _)| *k == COOKIE) + .map(|(_, v)| v.to_owned()) +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct SignIn { + /// The code from a setup or invite link (`#signin=`). + pub code: String, + /// Your name (setup links only; an invite already names you). + pub name: Option, + /// What to call this browser in the sessions list. + pub device: Option, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct MemberView { + pub id: String, + pub name: String, + /// `admin` or `member`. + pub role: String, + pub added_at: String, + /// The member's Tessera root and its match code, when they recorded it. + pub tessera_root: Option, + pub match_code: Option, +} + +impl From<&Member> for MemberView { + fn from(m: &Member) -> Self { + MemberView { + id: m.id.clone(), + name: m.name.clone(), + role: m.role.as_str().into(), + added_at: rfc3339(m.added_at), + tessera_root: m.tessera_root.clone(), + match_code: m.tessera_root.as_deref().and_then(match_code), + } + } +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct SignedIn { + pub member: MemberView, +} + +/// Redeem a setup or invite link: sets the session cookie. No token needed (this is the +/// door). At most 20 tries a minute for the whole server. +pub async fn sign_in(st: Arc, req: Request) -> Response { + async { + if st.limit("signin", 20, 60).is_err() { + return Err(ApiError::new( + StatusCode::TOO_MANY_REQUESTS, + "rate.limited", + Params::new(), + ) + .retry(60)); + } + // Only the UI's own page signs in (the custom header needs a CORS preflight that + // control never answers), and never a cross-site page. + let h = req.headers(); + let ui = h.get("x-ianitor-ui").is_some_and(|v| v.as_bytes() == b"1"); + let site_ok = h + .get("sec-fetch-site") + .is_none_or(|v| matches!(v.as_bytes(), b"same-origin" | b"none")); + if !ui || !site_ok { + return Err(ApiError::new( + StatusCode::FORBIDDEN, + "request.csrf", + Params::new(), + )); + } + let body = as axum::extract::FromRequest<()>>::from_request(req, &()).await?; + let b = body.value; + let team = st.ctl.team.clone(); + let device = b.device.unwrap_or_else(|| "Browser".into()); + let (member, value) = + tokio::task::spawn_blocking(move || team.redeem(&b.code, b.name.as_deref(), &device)) + .await + .map_err(|_| ApiError::internal("sign-in"))? + .map_err(|r| refused(r.0))?; + log::info!(target: "ianitor::team", "{} ({}) signed in", member.name, member.role.as_str()); + let mut resp = json( + StatusCode::OK, + &SignedIn { + member: MemberView::from(&member), + }, + ); + let cookie = format!( + "{COOKIE}={value}; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age={SESSION_SECS}" + ); + if let Ok(v) = HeaderValue::from_str(&cookie) { + resp.headers_mut().insert(header::SET_COOKIE, v); + } + resp.headers_mut() + .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + Ok(resp) + } + .await + .unwrap_or_else(IntoResponse::into_response) +} + +/// Sign this browser out. +#[utoipa::path(post, path = "/api/v1/session/end", tag = "team", + responses((status = 200, body = super::views::Done)), security(("bearer" = [])))] +pub async fn sign_out( + State(st): Shared, + Extension(actor): Extension, +) -> Result { + if let Some(id) = &actor.session { + st.ctl.team.end_session(id).map_err(ApiError::internal)?; + } + let mut resp = json( + StatusCode::OK, + &super::views::Done { + message: "Done.".into(), + }, + ); + if let Ok(v) = HeaderValue::from_str(&format!( + "{COOKIE}=; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=0" + )) { + resp.headers_mut().insert(header::SET_COOKIE, v); + } + Ok(resp) +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct InviteView { + pub id: String, + pub name: Option, + pub role: String, + pub expires_at: String, +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct TeamView { + /// Who is asking; absent for an API token. + pub me: Option, + pub members: Vec, + pub invites: Vec, + /// Whether Authelia signs people in on this server instead. + pub authelia: bool, +} + +/// The team: members, open invites, and who you are. +#[utoipa::path(get, path = "/api/v1/team", tag = "team", + responses((status = 200, body = TeamView)), security(("bearer" = [])))] +pub async fn get_team( + State(st): Shared, + Extension(actor): Extension, +) -> Result { + let members = st.ctl.team.members().map_err(ApiError::internal)?; + let invites = st + .ctl + .team + .codes() + .map_err(ApiError::internal)? + .into_iter() + .filter(|c| c.kind == "invite") + .map(|c| InviteView { + id: c.id, + name: c.name, + role: c.role.as_str().into(), + expires_at: rfc3339(c.expires_at), + }) + .collect(); + let me = actor + .member + .as_ref() + .and_then(|id| members.iter().find(|m| &m.id == id)) + .map(MemberView::from); + Ok(json( + StatusCode::OK, + &TeamView { + me, + members: members.iter().map(MemberView::from).collect(), + invites, + authelia: st.ctl.ui_proof.is_some(), + }, + )) +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct InviteBody { + pub name: String, + /// `admin` or `member` (default). + pub role: Option, +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct InviteMade { + pub invite: InviteView, + /// Send this to the person: `/#signin=`. Shown once. + pub link_fragment: String, +} + +/// Invite someone (admin). The link is shown once. +#[utoipa::path(post, path = "/api/v1/team/invites", tag = "team", request_body = InviteBody, + responses((status = 201, body = InviteMade), (status = 403, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn invite( + State(st): Shared, + Extension(actor): Extension, + body: Body, +) -> Result { + let role = match body.value.role.as_deref() { + None => Role::Member, + Some(r) => Role::parse(r).ok_or_else(|| refused("team.role"))?, + }; + let (code, value) = st + .ctl + .team + .invite(&body.value.name, role, &actor.name) + .map_err(|r| refused(r.0))?; + log::info!(target: "ianitor::team", "{} invited {} as {}", actor.name, code.name.clone().unwrap_or_default(), role.as_str()); + Ok(json( + StatusCode::CREATED, + &InviteMade { + invite: InviteView { + id: code.id, + name: code.name, + role: role.as_str().into(), + expires_at: rfc3339(code.expires_at), + }, + link_fragment: format!("#signin={value}"), + }, + )) +} + +/// Cancel an invite that was not used (admin). +#[utoipa::path(delete, path = "/api/v1/team/invites/{id}", tag = "team", params(("id" = String, Path)), + responses((status = 200, body = super::views::Done)), security(("bearer" = [])))] +pub async fn cancel_invite( + State(st): Shared, + Path(id): Path, +) -> Result { + if !st.ctl.team.cancel_invite(&id).map_err(ApiError::internal)? { + return Err(refused("team.not_found")); + } + Ok(json( + StatusCode::OK, + &super::views::Done { + message: "Done.".into(), + }, + )) +} + +/// Remove a member and sign them out everywhere (admin). The last admin stays. +#[utoipa::path(delete, path = "/api/v1/team/members/{id}", tag = "team", params(("id" = String, Path)), + responses((status = 200, body = super::views::Done), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn remove_member( + State(st): Shared, + Extension(actor): Extension, + Path(id): Path, +) -> Result { + match st.ctl.team.remove(&id).map_err(|r| refused(r.0))? { + Some(m) => { + log::info!(target: "ianitor::team", "{} removed {}", actor.name, m.name); + Ok(json( + StatusCode::OK, + &super::views::Done { + message: "Done.".into(), + }, + )) + } + None => Err(refused("team.not_found")), + } +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct RootBody { + /// Your Tessera root (base64url, as Custos shows it under Domi identity), or null. + pub tessera_root: Option, +} + +/// Record your own Tessera root, so the team list shows its match code. +#[utoipa::path(put, path = "/api/v1/team/me/root", tag = "team", request_body = RootBody, + responses((status = 200, body = super::views::Done)), security(("bearer" = [])))] +pub async fn set_root( + State(st): Shared, + Extension(actor): Extension, + body: Body, +) -> Result { + let Some(me) = &actor.member else { + return Err(ApiError::new( + StatusCode::FORBIDDEN, + "team.session_only", + Params::new(), + )); + }; + st.ctl + .team + .set_root(me, body.value.tessera_root.as_deref()) + .map_err(|r| refused(r.0))?; + Ok(json( + StatusCode::OK, + &super::views::Done { + message: "Done.".into(), + }, + )) +} diff --git a/crates/control/src/api/ui.rs b/crates/control/src/api/ui.rs index 8b878c8..5608695 100644 --- a/crates/control/src/api/ui.rs +++ b/crates/control/src/api/ui.rs @@ -43,6 +43,22 @@ pub async fn front(State(st): State>, req: Request, next: Next) -> .into_response(), }; } + // The door: redeeming a setup or invite link needs no token (crate::team). + if path == "/api/v1/session" { + if !host_allowed(&st.ctl, req.headers()) { + return ApiError::new(StatusCode::FORBIDDEN, "request.host", Params::new()) + .into_response(); + } + if req.method() != "POST" { + return ApiError::new( + StatusCode::METHOD_NOT_ALLOWED, + "request.method", + Params::new(), + ) + .into_response(); + } + return super::team::sign_in(st, req).await; + } if path.starts_with("/api/") || path == "/api" { return next.run(req).await; } diff --git a/crates/control/src/api/views.rs b/crates/control/src/api/views.rs index 323efd1..e4d6fec 100644 --- a/crates/control/src/api/views.rs +++ b/crates/control/src/api/views.rs @@ -746,6 +746,8 @@ pub struct TokenView { pub last_used_at: Option, pub expires_at: Option, pub revoked_at: Option, + /// `full` or `previews`. + pub scope: String, } impl From<&crate::tokens::TokenRecord> for TokenView { @@ -757,6 +759,7 @@ impl From<&crate::tokens::TokenRecord> for TokenView { last_used_at: t(r.last_used_at), expires_at: t(r.expires_at), revoked_at: t(r.revoked_at), + scope: r.scope.as_str().into(), } } } diff --git a/crates/control/src/caddy_guard.rs b/crates/control/src/caddy_guard.rs index e931672..10b1039 100644 --- a/crates/control/src/caddy_guard.rs +++ b/crates/control/src/caddy_guard.rs @@ -127,15 +127,12 @@ async fn revert(cfg: &Config, why: &str) -> Result { return Ok(false); } let loaded = async { - let sock = cfg - .caddy_compile() - .caddy_admin_socket - .clone() - .ok_or("no caddy_admin_socket is configured")?; + let sock = crate::caddy_link::Admin::from_compile(cfg.caddy_compile()) + .ok_or("no caddy_admin_socket (or loopback caddy_admin) is configured")?; let text = std::fs::read(&cfg.caddy.config) .map_err(|e| format!("cannot read {}: {e}", cfg.caddy.config.display()))?; - crate::caddy_link::load(Path::new(&sock), &text).await?; - if !crate::caddy_link::runs(Path::new(&sock), &text).await? { + crate::caddy_link::load(&sock, &text).await?; + if !crate::caddy_link::runs(&sock, &text).await? { return Err("Caddy took caddy.json but does not run it".to_owned()); } Ok::<_, String>(()) diff --git a/crates/control/src/caddy_link.rs b/crates/control/src/caddy_link.rs index 4dcc777..89fc5cb 100644 --- a/crates/control/src/caddy_link.rs +++ b/crates/control/src/caddy_link.rs @@ -3,60 +3,116 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! Control's side of the Caddy fallback while it serves (Mark, 2026-11-08: changes keep -//! working under Caddy): loading a config through Caddy's admin API on its Unix socket +//! working under Caddy): loading a config through Caddy's admin API on its Unix socket, or on +//! loopback TCP where there are no Unix sockets (Windows Caddy mode, T4) //! (`POST /load`, the whole JSON) and reading back what runs (`GET /config/`), probing a host //! *through* Caddy ("does Caddy answer at all") and its upstreams directly (the health watch, //! judged like edge's), and the certificate Caddy serves. use std::net::SocketAddr; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::{Duration, Instant}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + const TIMEOUT: Duration = Duration::from_secs(10); -/// One request to Caddy's admin API (HTTP/1.0: the answer is never chunked). -async fn admin(socket: &Path, request: &[u8]) -> Result<(u16, Vec), String> { - #[cfg(unix)] - { - use tokio::io::{AsyncReadExt, AsyncWriteExt}; - let exchange = async { - let mut s = tokio::net::UnixStream::connect(socket).await?; +/// Where Caddy's admin API listens: a Unix socket (Linux, mode 0660), or loopback TCP +/// (Windows, where control and Caddy are the only services and the port is on 127.0.0.1). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Admin { + Unix(PathBuf), + Tcp(SocketAddr), +} + +impl Admin { + /// From the compile facts: the socket when there is one, else a loopback TCP address. + pub fn from_compile(c: &crate::config::Compile) -> Option { + match (&c.caddy_admin_socket, c.caddy_admin) { + (Some(s), _) => Some(Admin::Unix(PathBuf::from(s))), + (None, Some(a)) if a.ip().is_loopback() => Some(Admin::Tcp(a)), + _ => None, + } + } + + /// The `Host` header Caddy's admin API accepts (its origin check). + fn host(&self) -> String { + match self { + Admin::Unix(_) => "localhost".into(), + Admin::Tcp(a) => a.to_string(), + } + } +} + +impl From<&Path> for Admin { + fn from(p: &Path) -> Admin { + Admin::Unix(p.to_owned()) + } +} + +async fn exchange(admin: &Admin, request: &[u8]) -> std::io::Result> { + let mut buf = Vec::new(); + match admin { + #[cfg(unix)] + Admin::Unix(p) => { + let mut s = tokio::net::UnixStream::connect(p).await?; s.write_all(request).await?; - let mut buf = Vec::new(); s.read_to_end(&mut buf).await?; - Ok::<_, std::io::Error>(buf) - }; - let buf = tokio::time::timeout(TIMEOUT, exchange) - .await - .map_err(|_| "Caddy's admin API did not answer within 10 s".to_owned())? - .map_err(|e| format!("Caddy's admin API cannot be reached: {e}"))?; - let split = buf + } + #[cfg(not(unix))] + Admin::Unix(_) => { + return Err(std::io::Error::other( + "Caddy's admin socket needs Unix; set caddy_admin = \"127.0.0.1:2019\" instead", + )); + } + Admin::Tcp(a) => { + let mut s = tokio::net::TcpStream::connect(a).await?; + s.write_all(request).await?; + s.read_to_end(&mut buf).await?; + } + } + Ok(buf) +} + +/// One request to Caddy's admin API (HTTP/1.0: the answer is never chunked). `request` has +/// `{host}` where the Host header value goes. +async fn admin(admin: &Admin, request: &[u8]) -> Result<(u16, Vec), String> { + let host = admin.host(); + let request = { + let split = request .windows(4) .position(|w| w == b"\r\n\r\n") - .ok_or("no answer from Caddy's admin API")?; - let head = String::from_utf8_lossy(&buf[..split]); - let status: u16 = head - .split(' ') - .nth(1) - .and_then(|s| s.parse().ok()) - .ok_or("no answer from Caddy's admin API")?; - Ok((status, buf[split + 4..].to_vec())) - } - #[cfg(not(unix))] - { - let _ = (socket, request); - Err("Caddy's admin socket needs Unix".into()) - } + .unwrap_or(request.len()); + let head = String::from_utf8_lossy(&request[..split]).replace("{host}", &host); + let mut r = head.into_bytes(); + r.extend_from_slice(&request[split..]); + r + }; + let buf = tokio::time::timeout(TIMEOUT, exchange(admin, &request)) + .await + .map_err(|_| "Caddy's admin API did not answer within 10 s".to_owned())? + .map_err(|e| format!("Caddy's admin API cannot be reached: {e}"))?; + let split = buf + .windows(4) + .position(|w| w == b"\r\n\r\n") + .ok_or("no answer from Caddy's admin API")?; + let head = String::from_utf8_lossy(&buf[..split]); + let status: u16 = head + .split(' ') + .nth(1) + .and_then(|s| s.parse().ok()) + .ok_or("no answer from Caddy's admin API")?; + Ok((status, buf[split + 4..].to_vec())) } /// Load a full Caddy JSON config. Caddy swaps it in gracefully or refuses it (and keeps the /// old one). `Cache-Control: must-revalidate` makes Caddy load it even when it is the same as /// the running one, so certificate and device files are read again (without it an identical /// config is a no-op: QC round 2, B1; `qc_reloading_the_same_caddy_json_rereads_the_certificate_files`). -pub async fn load(socket: &Path, config: &[u8]) -> Result<(), String> { +pub async fn load(socket: &Admin, config: &[u8]) -> Result<(), String> { let mut req = format!( - "POST /load HTTP/1.0\r\nHost: localhost\r\nContent-Type: application/json\r\nCache-Control: must-revalidate\r\nContent-Length: {}\r\n\r\n", + "POST /load HTTP/1.0\r\nHost: {{host}}\r\nContent-Type: application/json\r\nCache-Control: must-revalidate\r\nContent-Length: {}\r\n\r\n", config.len() ) .into_bytes(); @@ -77,8 +133,8 @@ pub async fn load(socket: &Path, config: &[u8]) -> Result<(), String> { } /// The config Caddy runs now. -pub async fn running_config(socket: &Path) -> Result { - let (status, body) = admin(socket, b"GET /config/ HTTP/1.0\r\nHost: localhost\r\n\r\n").await?; +pub async fn running_config(socket: &Admin) -> Result { + let (status, body) = admin(socket, b"GET /config/ HTTP/1.0\r\nHost: {host}\r\n\r\n").await?; if status != 200 { return Err(format!( "Caddy's admin API answered {status} to GET /config/" @@ -88,7 +144,7 @@ pub async fn running_config(socket: &Path) -> Result } /// Whether Caddy runs exactly this config (as JSON values, so formatting does not matter). -pub async fn runs(socket: &Path, config: &[u8]) -> Result { +pub async fn runs(socket: &Admin, config: &[u8]) -> Result { let want: serde_json::Value = serde_json::from_slice(config).map_err(|e| format!("not JSON: {e}"))?; Ok(running_config(socket).await? == want) diff --git a/crates/control/src/config.rs b/crates/control/src/config.rs index ac2736e..f8dd774 100644 --- a/crates/control/src/config.rs +++ b/crates/control/src/config.rs @@ -58,6 +58,61 @@ pub struct Config { /// Switching between Pingora and the Caddy fallback at runtime. #[serde(default)] pub engine: Option, + /// Branch previews for Fabrica (`POST /api/v1/previews`); off without it. + #[serde(default)] + pub previews: Option, +} + +/// `[previews]`: where branch previews live and what they may point at. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PreviewsConfig { + /// Previews are `--.`; a wildcard DNS record points here. + pub domain: String, + /// `domi` (the Domi CA, internal) or `letsencrypt` (public; one certificate per preview). + #[serde(default = "default_preview_tls")] + pub tls: String, + /// `none` (anyone with the address) or `forward-auth` (behind the site's sign-in). + #[serde(default = "default_preview_auth")] + pub auth: String, + /// Where previews may send traffic: `10.0.0.0/8`, `127.0.0.1:20000-29999`, `app.internal`, + /// `*.svc.internal:8080`. Nothing else is accepted; control's own port and Caddy's admin + /// port never are. Empty: every preview is refused. + #[serde(default)] + pub upstreams: Vec, + #[serde(default = "default_preview_ttl")] + pub default_ttl_secs: u64, + #[serde(default = "default_preview_min_ttl")] + pub min_ttl_secs: u64, + #[serde(default = "default_preview_max_ttl")] + pub max_ttl_secs: u64, + #[serde(default = "default_preview_max")] + pub max_previews: usize, + /// How often expired previews are looked for. + #[serde(default = "default_preview_sweep")] + pub sweep_secs: u64, +} + +fn default_preview_tls() -> String { + "domi".into() +} +fn default_preview_auth() -> String { + "none".into() +} +fn default_preview_ttl() -> u64 { + 72 * 3600 +} +fn default_preview_min_ttl() -> u64 { + 300 +} +fn default_preview_max_ttl() -> u64 { + 30 * 86_400 +} +fn default_preview_max() -> usize { + 100 +} +fn default_preview_sweep() -> u64 { + 30 } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -120,13 +175,14 @@ pub struct Compile { impl Compile { pub fn options(&self) -> CompileOptions { + use ianitor_core::compile::windows_path as w; CompileOptions { http_listen: self.http_listen, https_listen: self.https_listen, - cert_dir: self.cert_dir.clone(), - state_dir: self.state_dir.clone(), - access_log: self.access_log.clone(), - caddy_credentials_dir: self.caddy_credentials_dir.clone(), + cert_dir: w(&self.cert_dir), + state_dir: w(&self.state_dir), + access_log: w(&self.access_log), + caddy_credentials_dir: w(&self.caddy_credentials_dir), caddy_admin: self.caddy_admin, caddy_admin_socket: self.caddy_admin_socket.clone(), trusted_proxies: self.trusted_proxies.clone(), @@ -240,6 +296,9 @@ impl Config { "pki.kdf_iterations must be at least {MIN_KDF_ITERATIONS}" ))); } + if let Some(p) = &self.previews { + crate::previews::check_config(p, self).map_err(ConfigError::Invalid)?; + } if let Some(m) = empty_model() { for c in std::iter::once(&self.compile).chain(self.compile_caddy.as_ref()) { ianitor_core::compile::edge(&m, &c.options()) @@ -344,6 +403,12 @@ pub struct UiConfig { /// Authelia's logout address (e.g. `https://auth.example/logout`), shown as "Sign out". #[serde(default)] pub logout_url: Option, + /// Without Authelia (T4): control keeps the admin host in the routes repository itself, + /// as a plain host to this API with this certificate (`letsencrypt` or `domi`); people + /// sign in with team links (crate::team). Unset: the admin host is managed by hand + /// (the NixOS module's Authelia setup). + #[serde(default)] + pub admin_tls: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/crates/control/src/dev.rs b/crates/control/src/dev.rs index 2b59ad6..4eddf0e 100644 --- a/crates/control/src/dev.rs +++ b/crates/control/src/dev.rs @@ -168,13 +168,26 @@ pub async fn run(args: &[String]) -> Result<(), String> { proof_credential: None, static_dir: Some(PathBuf::from(d)), logout_url: None, + admin_tls: None, }), engine: None, + // Branch previews on a name nobody can own (RFC 2606), from loopback test upstreams. + previews: Some(ianitor_control::config::PreviewsConfig { + domain: "preview.dev.test".into(), + tls: "domi".into(), + auth: "none".into(), + upstreams: vec!["127.0.0.1:20000-29999".into(), "10.0.0.0/8".into()], + default_ttl_secs: 72 * 3600, + min_ttl_secs: 60, + max_ttl_secs: 30 * 86_400, + max_previews: 100, + sweep_secs: 10, + }), }; cfg.check().map_err(|e| e.to_string())?; Repo::open_seeded(&cfg.git, &cfg.routes.repo, &cfg.state_dir, "main", SITE) .map_err(|e| e.to_string())?; - let (_, token) = Tokens::new(&cfg.state_dir).create("dev", None)?; + let (_, token) = Tokens::new(&cfg.state_dir).create("dev", None, Default::default())?; // Control writes edge.json first; then edge can start from it. let ctl_cfg = cfg.clone(); diff --git a/crates/control/src/engine.rs b/crates/control/src/engine.rs index e49bf61..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 }, @@ -53,6 +54,8 @@ struct Job { id: String, change: Change, base_rev: Option, + /// Replaces the plan's summary (and so the commit message), e.g. for previews. + summary: Option, } /// A refusal, before or during an apply. @@ -141,6 +144,8 @@ pub struct Control { pub repo: Repo, pub edge: EdgeLink, pub tokens: Tokens, + /// Team members and their sessions (sign-in without Authelia). + pub team: Arc, pub shares: Shares, pub share_key: Option, /// The Domi CA, when `[pki]` is configured. @@ -245,6 +250,7 @@ impl Control { let paused: Option = read_json(&cfg.state_dir.join("paused.json"))?; let c = Arc::new(Control { tokens: Tokens::new(&cfg.state_dir), + team: Arc::new(crate::team::Team::new(&cfg.state_dir)), shares: Shares::new(&cfg.state_dir, &cfg.edge.share_revocations), repo, edge, @@ -740,6 +746,18 @@ impl Control { change: Change, base_rev: Option, actor: &str, + ) -> Result { + self.submit_as(change, base_rev, actor, None) + } + + /// [`Control::submit`] with a summary of the caller's own (the history line and commit + /// message), e.g. "Opened the preview of fix-42 (shop)". + pub fn submit_as( + &self, + change: Change, + base_rev: Option, + actor: &str, + summary: Option, ) -> Result { if let Some(p) = self.paused_for(&change, false) { return Err(Fail::new( @@ -749,7 +767,10 @@ impl Control { )); } let (head, tree) = self.head_and_tree()?; - let plan = self.plan(&change, &head, &tree, base_rev.as_deref())?; + let mut plan = self.plan(&change, &head, &tree, base_rev.as_deref())?; + if let Some(s) = &summary { + plan.summary = s.clone(); + } self.compile(&plan.model)?; let id = format!( "ch_{}", @@ -792,6 +813,7 @@ impl Control { id, change, base_rev, + summary, }); } self.wake.notify_one(); @@ -930,7 +952,14 @@ impl Control { Ok(x) => x, Err(f) => return self.finish(&id, "failed", Some(f.reason), f.errors), }; - let plan = match self.plan(&job.change, &head, &tree, job.base_rev.as_deref()) { + let plan = match self + .plan(&job.change, &head, &tree, job.base_rev.as_deref()) + .map(|mut p| { + if let Some(s) = &job.summary { + p.summary = s.clone(); + } + p + }) { Ok(p) => p, Err(f) => return self.finish(&id, "failed", Some(f.reason), f.errors), }; @@ -1000,7 +1029,7 @@ impl Control { } crash::point("committed"); - if !self.edge.attached() { + if !self.edge.attached() && self.engine_running() != "caddy" { // Development without an edge: write the files directly, nothing to watch. let r = write_atomic(&self.cfg.edge.config, edge_text.as_bytes(), 0o644) .and_then(|_| write_atomic(&self.cfg.caddy.config, caddy_text.as_bytes(), 0o644)); diff --git a/crates/control/src/engine/caddy_apply.rs b/crates/control/src/engine/caddy_apply.rs index 9b61bee..36bb810 100644 --- a/crates/control/src/engine/caddy_apply.rs +++ b/crates/control/src/engine/caddy_apply.rs @@ -42,13 +42,10 @@ struct Rule { } impl Control { - /// Caddy's admin socket, from `[compile_caddy]` (or `[compile]`). - pub fn caddy_socket(&self) -> Option { - self.cfg - .caddy_compile() - .caddy_admin_socket - .as_ref() - .map(std::path::PathBuf::from) + /// Caddy's admin API, from `[compile_caddy]` (or `[compile]`): its Unix socket, or its + /// loopback TCP address on Windows. + pub fn caddy_socket(&self) -> Option { + caddy_link::Admin::from_compile(self.cfg.caddy_compile()) } /// Load caddy.json (the last good config) into the running Caddy, even when it is the @@ -56,7 +53,7 @@ impl Control { pub async fn caddy_reload(&self) -> Result<(), String> { let sock = self .caddy_socket() - .ok_or("no caddy_admin_socket is configured, so Caddy cannot be told")?; + .ok_or("no caddy_admin_socket (or loopback caddy_admin) is configured, so Caddy cannot be told")?; let text = std::fs::read(&self.cfg.caddy.config) .map_err(|e| format!("cannot read {}: {e}", self.cfg.caddy.config.display()))?; caddy_link::load(&sock, &text).await?; @@ -334,7 +331,7 @@ impl Control { async fn caddy_watch( &self, id: &str, - sock: &std::path::Path, + sock: &caddy_link::Admin, trial: &str, judged: &[String], rules: &BTreeMap, diff --git a/crates/control/src/hostspec.rs b/crates/control/src/hostspec.rs index 2b7e8ec..de55734 100644 --- a/crates/control/src/hostspec.rs +++ b/crates/control/src/hostspec.rs @@ -38,6 +38,18 @@ pub struct HostSpec { pub request_headers: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub response_headers: Vec, + /// Set on a branch preview (Fabrica); written by `/api/v1/previews`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub preview: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct PreviewSpec { + pub project: String, + pub branch: String, + /// Unix seconds. + pub expires_at: i64, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)] @@ -178,6 +190,7 @@ mod tests { secret: None, }], response_headers: vec![], + preview: None, }; let text = h.to_toml().unwrap(); assert_eq!(HostSpec::from_toml(&text).unwrap(), h); diff --git a/crates/control/src/lib.rs b/crates/control/src/lib.rs index 65d3279..3435f2e 100644 --- a/crates/control/src/lib.rs +++ b/crates/control/src/lib.rs @@ -18,10 +18,12 @@ pub mod logger; pub mod messages; pub mod pki; pub mod pki_ctl; +pub mod previews; pub mod records; pub mod repo; pub mod shares; pub mod switch; +pub mod team; pub mod tokens; pub mod util; @@ -42,6 +44,11 @@ pub async fn serve( tokio::spawn(ctl.clone().health_poller()); tokio::spawn(ctl.clone().pusher()); tokio::spawn(ctl.clone().pki_poller()); + tokio::spawn(ctl.clone().preview_sweeper()); + ctl.ensure_admin_host(); + if ctl.cfg.ui.is_some() && !ctl.team.has_members() && ctl.ui_proof.is_none() { + log::warn!(target: "ianitor::team", "nobody is in the team yet: run `ianitor-control team setup-link --config ` and open the link it prints"); + } let app = api::router(api::AppState::new(ctl.clone())); if !listen.ip().is_loopback() { return Err("ianitor-control only listens on loopback".into()); diff --git a/crates/control/src/logger.rs b/crates/control/src/logger.rs index 89e01ea..6efb682 100644 --- a/crates/control/src/logger.rs +++ b/crates/control/src/logger.rs @@ -12,6 +12,8 @@ use log::{Level, LevelFilter, Log, Metadata, Record}; struct Stderr { own: LevelFilter, + /// `$IANITOR_LOG_FILE` or `--log-file`: append here instead of stderr (Windows services). + file: Option>, } impl Log for Stderr { @@ -33,12 +35,27 @@ impl Log for Stderr { Level::Debug => "DEBUG", Level::Trace => "TRACE", }; - let _ = writeln!( - std::io::stderr().lock(), - "{lvl} {}: {}", - r.target(), - r.args() - ); + match &self.file { + Some(f) => { + if let Ok(mut f) = f.lock() { + let _ = writeln!( + f, + "{} {lvl} {}: {}", + crate::util::rfc3339(crate::util::now()), + r.target(), + r.args() + ); + } + } + None => { + let _ = writeln!( + std::io::stderr().lock(), + "{lvl} {}: {}", + r.target(), + r.args() + ); + } + } } } @@ -48,6 +65,22 @@ impl Log for Stderr { } pub fn init(level: Option<&str>) { + init_to( + level, + std::env::var_os("IANITOR_LOG_FILE").map(std::path::PathBuf::from), + ); +} + +/// Like [`init`], appending to `file` when given. +pub fn init_to(level: Option<&str>, file: Option) { + let file = file.and_then(|p| { + std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(p) + .ok() + .map(std::sync::Mutex::new) + }); let own = match level.map(str::to_ascii_lowercase).as_deref() { Some("error") => LevelFilter::Error, Some("warn") => LevelFilter::Warn, @@ -55,7 +88,7 @@ pub fn init(level: Option<&str>) { Some("trace") => LevelFilter::Trace, _ => LevelFilter::Info, }; - if log::set_boxed_logger(Box::new(Stderr { own })).is_ok() { + if log::set_boxed_logger(Box::new(Stderr { own, file })).is_ok() { log::set_max_level(own); } } diff --git a/crates/control/src/main.rs b/crates/control/src/main.rs index a5fc768..c94eab4 100644 --- a/crates/control/src/main.rs +++ b/crates/control/src/main.rs @@ -5,7 +5,7 @@ //! ```text //! ianitor-control --config run the control plane //! ianitor-control --dev [--edge-bin ] temporary everything on 127.0.0.1 -//! ianitor-control token create --name [--expires-days | --never] (--config | --state-dir ) +//! ianitor-control token create --name [--scope full|previews] [--expires-days | --never] (--config | --state-dir ) //! ianitor-control token list (--config | --state-dir ) //! ianitor-control token revoke (--config | --state-dir ) //! ianitor-control openapi print the OpenAPI document @@ -15,6 +15,8 @@ //! ianitor-control ca init --out [--passphrase-file ] the offline root (never on the server) //! ianitor-control ca sign --root --csr --out [--yes] sign an intermediate offline //! ianitor-control check --config check the config and exit +//! ianitor-control team setup-link|list --config the first admin's sign-in link +//! ianitor-control service control|caddy-guard --config [--log-file ] Windows service //! ``` //! The log level comes from `$IANITOR_LOG`. As `GIT_ASKPASS` (with `$IANITOR_ASKPASS=1`), //! the binary answers git's prompt from the push credential file. @@ -25,6 +27,8 @@ use std::process::ExitCode; use ianitor_control::{Config, logger, tokens::Tokens}; mod dev; +#[cfg(windows)] +mod winsvc; fn usage() -> ExitCode { eprintln!( @@ -139,12 +143,19 @@ fn token(args: &[String]) -> Result<(), String> { match args.first().map(String::as_str) { Some("create") => { let mut name = None; + let mut scope = ianitor_control::tokens::Scope::Full; let mut expires = Some(ianitor_control::util::now() + 365 * 86_400); let mut it = args.iter().skip(1); while let Some(a) = it.next() { match a.as_str() { "--name" => name = it.next().cloned(), "--never" => expires = None, + "--scope" => { + scope = it + .next() + .and_then(|s| ianitor_control::tokens::Scope::parse(s)) + .ok_or("--scope must be full or previews")?; + } "--expires-days" => { let d: u64 = it .next() @@ -157,7 +168,7 @@ fn token(args: &[String]) -> Result<(), String> { } } let name = name.ok_or("--name is required")?; - let (rec, value) = tokens.create(&name, expires).map_err(|e| { + let (rec, value) = tokens.create(&name, expires, scope).map_err(|e| { if e == "token.name" { "the name must be 1 to 64 letters, digits, spaces, dots, dashes or underscores" .to_owned() @@ -166,8 +177,10 @@ fn token(args: &[String]) -> Result<(), String> { } })?; eprintln!( - "Token {} ({}) created. It is shown once; save it in Custos now:", - rec.id, rec.name + "Token {} ({}, scope {}) created. It is shown once; save it in Custos now:", + rec.id, + rec.name, + rec.scope.as_str() ); println!("{value}"); Ok(()) @@ -186,6 +199,9 @@ fn token(args: &[String]) -> Result<(), String> { .map(|e| format!(" REVOKED {}", ianitor_control::util::rfc3339(e))) .unwrap_or_default() ); + if t.scope != ianitor_control::tokens::Scope::Full { + println!(" scope {}", t.scope.as_str()); + } } Ok(()) } @@ -371,12 +387,66 @@ fn pki_cli(args: &[String]) -> Result<(), String> { } } +/// `team setup-link | list` on the server, as the user control runs as. +fn team_cli(args: &[String]) -> Result<(), String> { + let path = arg_after(args, "--config").ok_or("team setup-link|list --config ")?; + let cfg = Config::load(&PathBuf::from(path)).map_err(|e| e.to_string())?; + same_owner(&cfg.state_dir)?; + let team = ianitor_control::team::Team::new(&cfg.state_dir); + match args.first().map(String::as_str) { + Some("setup-link") => { + let (code, until) = team.setup_code()?; + let base = match cfg.ui.as_ref().and_then(|u| u.hostname.as_ref()) { + Some(h) => format!("https://{h}/"), + None => format!("http://{}/", cfg.listen), + }; + eprintln!( + "Open this link to sign in as the team's first admin. It works once, until {}:", + ianitor_control::util::rfc3339(until) + ); + println!("{base}#signin={code}"); + Ok(()) + } + Some("list") => { + for m in team.members()? { + println!("{} {} {}", m.id, m.role.as_str(), m.name); + } + Ok(()) + } + _ => Err("team setup-link|list --config ".into()), + } +} + fn main() -> ExitCode { if std::env::var("IANITOR_ASKPASS").as_deref() == Ok("1") { return askpass(); } - logger::init(std::env::var("IANITOR_LOG").ok().as_deref()); let args: Vec = std::env::args().skip(1).collect(); + let log_file = args + .iter() + .position(|a| a == "--log-file") + .and_then(|i| args.get(i + 1)) + .map(PathBuf::from); + match log_file { + Some(f) => logger::init_to(std::env::var("IANITOR_LOG").ok().as_deref(), Some(f)), + None => logger::init(std::env::var("IANITOR_LOG").ok().as_deref()), + } + // Windows Server, Caddy mode: started by the service control manager. + if args.first().map(String::as_str) == Some("service") { + #[cfg(windows)] + return match winsvc::run(&args[1..]) { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("ianitor-control: {e}"); + ExitCode::FAILURE + } + }; + #[cfg(not(windows))] + { + eprintln!("ianitor-control: `service` is for Windows; use the systemd units on Linux"); + return ExitCode::FAILURE; + } + } let rt = match tokio::runtime::Builder::new_multi_thread() .enable_all() .build() @@ -390,6 +460,7 @@ fn main() -> ExitCode { let result = match args.first().map(String::as_str) { Some("token") => token(&args[1..]), Some("pki") => pki_cli(&args[1..]), + Some("team") => team_cli(&args[1..]), Some("ca") => ca(&args[1..]), Some("openapi") => { println!("{}", ianitor_control::api::openapi_json()); diff --git a/crates/control/src/messages.rs b/crates/control/src/messages.rs index fe01126..99b7627 100644 --- a/crates/control/src/messages.rs +++ b/crates/control/src/messages.rs @@ -205,6 +205,43 @@ fn template(code: &str) -> &'static str { "token.not_found" => "There is no API token with that id.", "token.name" => "Use 1 to 64 letters, digits, spaces, dots, dashes or underscores.", "token.expiry" => "Choose between 1 and 3650 days, or never.", + "token.scope" => { + "This API token may only open and close branch previews (/api/v1/previews)." + } + "token.scope_value" => "A token's scope is full or previews.", + "session.code" => { + "This sign-in link does not work: it was used, it expired, or it was mistyped. Ask an admin for a new one." + } + "session.unknown" => { + "You are signed out. Open your sign-in link again, or ask an admin for one." + } + "team.admin_only" => "Only an admin of this team can do that.", + "team.last_admin" => "The team needs at least one admin. Make someone else an admin first.", + "team.full" => "The team is full (64 people, 100 open invites).", + "team.name" => "Enter a name of 1 to 64 characters.", + "team.role" => "A role is admin or member.", + "team.root" => "That is not a Tessera root. Copy it from Custos, Domi identity.", + "team.not_found" => "There is no such member or invite.", + "team.session_only" => "Only a signed-in person can do that, not an API token.", + "preview.off" => { + "Previews are off on this server: set a preview domain under [previews] in control.toml." + } + "preview.taken" => { + "{hostname} is already used by another host or branch, so this branch's preview cannot have it." + } + "preview.not_found" => "There is no preview at that address.", + "preview.branch" => "The branch name {problem}.", + "preview.project" => "The project name {problem}.", + "preview.domain" => "The preview address is not usable: {problem}.", + "preview.ttl" => "Choose a lifetime between {min} and {max} seconds.", + "preview.upstream" => { + "Write the preview's address as http://host:port or https://host:port, without a path, user or password." + } + "preview.upstream_not_allowed" => { + "{upstream} is not an address previews may use. Allowed: {allowed}." + } + "preview.too_many" => "There are already {max} previews. Close some first.", + "preview.expired" => "Preview of {branch} expired", "rate.limited" => "Too many requests in a short time. Try again in {seconds} s.", "control.files_unwritten" => { "The change is live, but Ianitor could not save the proxy settings to disk. Changes are paused until Ianitor restarts and saves them." diff --git a/crates/control/src/previews.rs b/crates/control/src/previews.rs new file mode 100644 index 0000000..64b2efb --- /dev/null +++ b/crates/control/src/previews.rs @@ -0,0 +1,598 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Branch previews for Fabrica (Fabrica docs/32_coherence.md, T4). A preview is an ordinary +//! host file in the routes repository with a `[preview]` table, so it goes through the same +//! validation, compilers, differential tests and commit-confirmed apply as any host. This +//! module holds what is preview-only: the host body control writes, the upstream allow list +//! (a preview token is hostile: it must not be able to publish this machine's admin ports), +//! and the sweeper that closes expired previews. + +// A refusal is built once per failed request; boxing it buys nothing (as in `engine`). +#![allow(clippy::result_large_err)] + +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; +use std::sync::Arc; +use std::time::Duration; + +use crate::config::{Config, PreviewsConfig}; +use crate::engine::{Change, Control, Fail}; +use crate::hostspec::{HeaderRuleSpec, HostSpec, PreviewSpec}; +use crate::messages::{self, Params}; +use crate::util::now; + +/// The actor name the sweeper's removals carry in the history. +pub const EXPIRY_ACTOR: &str = "Preview expiry"; + +/// One entry of `[previews] upstreams`. +#[derive(Debug, Clone, PartialEq, Eq)] +enum Target { + Net(IpAddr, u8), + Name(String), + /// `*.suffix`: any name ending in `.suffix`. + Suffix(String), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct Allowed { + target: Target, + ports: Option<(u16, u16)>, +} + +fn parse_ports(p: &str) -> Option<(u16, u16)> { + let (lo, hi) = match p.split_once('-') { + Some((a, b)) => (a.parse().ok()?, b.parse().ok()?), + None => { + let x: u16 = p.parse().ok()?; + (x, x) + } + }; + (lo >= 1 && lo <= hi).then_some((lo, hi)) +} + +fn parse_entry(e: &str) -> Option { + let e = e.trim(); + // IPv6 networks carry no port (`fd00::/8`); everything else may end in `:port[-port]`. + if e.matches(':').count() > 1 { + let (ip, bits) = e.split_once('/').unwrap_or((e, "128")); + let ip: Ipv6Addr = ip.parse().ok()?; + let bits: u8 = bits.parse().ok().filter(|b| *b <= 128)?; + return Some(Allowed { + target: Target::Net(IpAddr::V6(ip), bits), + ports: None, + }); + } + let (host, ports) = match e.rsplit_once(':') { + Some((h, p)) => (h, Some(parse_ports(p)?)), + None => (e, None), + }; + if let Some((ip, bits)) = host.split_once('/') { + let ip: Ipv4Addr = ip.parse().ok()?; + let bits: u8 = bits.parse().ok().filter(|b| *b <= 32)?; + return Some(Allowed { + target: Target::Net(IpAddr::V4(ip), bits), + ports, + }); + } + if let Ok(ip) = host.parse::() { + return Some(Allowed { + target: Target::Net(IpAddr::V4(ip), 32), + ports, + }); + } + let name = host.to_ascii_lowercase(); + let plain = |n: &str| { + !n.is_empty() + && n.len() <= 253 + && n.split('.').all(|l| { + !l.is_empty() + && l.len() <= 63 + && l.bytes() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-') + }) + }; + if let Some(suffix) = name.strip_prefix("*.") { + return plain(suffix).then(|| Allowed { + target: Target::Suffix(suffix.to_owned()), + ports, + }); + } + if !plain(&name) { + return None; + } + Some(Allowed { + target: Target::Name(name), + ports, + }) +} + +fn in_net(ip: IpAddr, net: IpAddr, bits: u8) -> bool { + match (ip, net) { + (IpAddr::V4(a), IpAddr::V4(n)) => { + let mask = if bits == 0 { + 0 + } else { + u32::MAX << (32 - u32::from(bits)) + }; + u32::from(a) & mask == u32::from(n) & mask + } + (IpAddr::V6(a), IpAddr::V6(n)) => { + let mask = if bits == 0 { + 0 + } else { + u128::MAX << (128 - u32::from(bits)) + }; + u128::from(a) & mask == u128::from(n) & mask + } + _ => false, + } +} + +/// Addresses no preview may ever use, whatever the allow list says. +fn never(ip: IpAddr) -> bool { + match ip { + IpAddr::V4(v) => { + v.is_unspecified() || v.is_link_local() || v.is_multicast() || v.is_broadcast() + } + IpAddr::V6(v) => { + v.is_unspecified() + || v.is_multicast() + || (v.segments()[0] & 0xffc0) == 0xfe80 + || v.to_ipv4_mapped().is_some() + } + } +} + +/// Check the `[previews]` section at start. +pub fn check_config(p: &PreviewsConfig, cfg: &Config) -> Result<(), String> { + ianitor_core::preview::hostname("p", "main", &p.domain) + .map_err(|e| format!("previews.domain: {e}"))?; + if !["domi", "letsencrypt"].contains(&p.tls.as_str()) { + return Err("previews.tls must be domi or letsencrypt".into()); + } + if !["none", "forward-auth"].contains(&p.auth.as_str()) { + return Err("previews.auth must be none or forward-auth".into()); + } + for u in &p.upstreams { + if parse_entry(u).is_none() { + return Err(format!( + "previews.upstreams: {u:?} is not a network (10.0.0.0/8), an address with ports (127.0.0.1:20000-29999) or a name (app.internal, *.svc.internal)" + )); + } + } + if p.min_ttl_secs == 0 + || p.min_ttl_secs > p.max_ttl_secs + || !(p.min_ttl_secs..=p.max_ttl_secs).contains(&p.default_ttl_secs) + { + return Err( + "previews: min_ttl_secs ≤ default_ttl_secs ≤ max_ttl_secs, and min_ttl_secs > 0".into(), + ); + } + if !(1..=3600).contains(&p.sweep_secs) || !(1..=10_000).contains(&p.max_previews) { + return Err("previews: sweep_secs 1 to 3600, max_previews 1 to 10000".into()); + } + let _ = cfg; + Ok(()) +} + +fn fail(status: u16, code: &str, params: Params) -> Fail { + Fail::new(status, code, params) +} + +/// Whether a preview may send traffic to `upstream`; the parsed URL's host and port. +pub fn check_upstream(cfg: &Config, p: &PreviewsConfig, upstream: &str) -> Result<(), Fail> { + let bad = || fail(422, "preview.upstream", Params::new()); + if upstream.is_empty() + || upstream.len() > 512 + || !upstream.bytes().all(|c| c.is_ascii_graphic()) + { + return Err(bad()); + } + let u = url::Url::parse(upstream).map_err(|_| bad())?; + if !["http", "https"].contains(&u.scheme()) + || !u.username().is_empty() + || u.password().is_some() + || u.query().is_some() + || u.fragment().is_some() + || !(u.path().is_empty() || u.path() == "/") + { + return Err(bad()); + } + let port = u.port_or_known_default().ok_or_else(bad)?; + let host = u.host().ok_or_else(bad)?; + let shown = || { + messages::params([ + ("upstream", upstream.to_owned()), + ("allowed", { + if p.upstreams.is_empty() { + "nothing yet (set [previews] upstreams)".to_owned() + } else { + p.upstreams.join(", ") + } + }), + ]) + }; + let not_allowed = || fail(403, "preview.upstream_not_allowed", shown()); + let ip = match &host { + url::Host::Ipv4(v) => Some(IpAddr::V4(*v)), + url::Host::Ipv6(v) => Some(IpAddr::V6(*v)), + url::Host::Domain(_) => None, + }; + if let Some(ip) = ip { + if never(ip) { + return Err(not_allowed()); + } + // This machine's own control API and Caddy admin API, whatever the list says. + if ip.is_loopback() { + let admin_ports = std::iter::once(cfg.listen.port()).chain( + [cfg.compile.caddy_admin, cfg.caddy_compile().caddy_admin] + .into_iter() + .flatten() + .map(|a| a.port()), + ); + if admin_ports.into_iter().any(|a| a == port) || port == 2019 { + return Err(not_allowed()); + } + } + } + let name = match &host { + url::Host::Domain(d) => Some(d.to_ascii_lowercase()), + _ => None, + }; + let ok = p.upstreams.iter().filter_map(|e| parse_entry(e)).any(|a| { + let port_ok = a.ports.is_none_or(|(lo, hi)| (lo..=hi).contains(&port)); + let host_ok = match (&a.target, ip, &name) { + (Target::Net(net, bits), Some(ip), _) => in_net(ip, *net, *bits), + (Target::Name(n), _, Some(h)) => n == h, + (Target::Suffix(s), _, Some(h)) => h.ends_with(&format!(".{s}")), + _ => false, + }; + port_ok && host_ok + }); + if ok { Ok(()) } else { Err(not_allowed()) } +} + +/// The host body of a branch's preview. +pub fn spec( + p: &PreviewsConfig, + hostname: &str, + project: &str, + branch: &str, + upstream: &str, + expires_at: u64, +) -> HostSpec { + HostSpec { + hostname: hostname.to_owned(), + upstreams: vec![upstream.trim_end_matches('/').to_owned()], + tls: p.tls.clone(), + auth: p.auth.clone(), + websockets: true, + share_links: false, + device_certs: false, + access_log: "off".into(), + health_check: None, + request_headers: Vec::new(), + // A preview is not for search engines. + response_headers: vec![HeaderRuleSpec { + action: "set".into(), + name: "X-Robots-Tag".into(), + value: Some("noindex, nofollow".into()), + secret: None, + }], + preview: Some(PreviewSpec { + project: project.to_owned(), + branch: branch.to_owned(), + expires_at: i64::try_from(expires_at).unwrap_or(i64::MAX), + }), + } +} + +/// A preview's field problem as an API refusal. +pub fn name_fail(e: ianitor_core::preview::PreviewError) -> Fail { + use ianitor_core::preview::PreviewError as P; + let (code, problem) = match &e { + P::Branch(r) => ("preview.branch", (*r).to_owned()), + P::Project(r) => ("preview.project", (*r).to_owned()), + P::Domain(r) => ("preview.domain", r.clone()), + }; + let mut f = fail(422, code, messages::params([("problem", problem)])); + f.reason.field = Some( + match e { + P::Branch(_) => "branch", + P::Project(_) => "project", + P::Domain(_) => "domain", + } + .into(), + ); + f +} + +/// What the previews screen and Fabrica see. +#[derive(Debug, Clone)] +pub struct Listed { + pub hostname: String, + pub project: String, + pub branch: String, + pub upstream: String, + pub expires_at: u64, +} + +impl Control { + /// With `[ui] hostname` and `admin_tls`: make sure the admin host (the web UI and this + /// API, through the engine) is in the routes repository; queue it at start if not. + pub fn ensure_admin_host(&self) { + let Some(ui) = &self.cfg.ui else { return }; + let (Some(host), Some(tls)) = (&ui.hostname, &ui.admin_tls) else { + return; + }; + let Ok((_, tree, _)) = self.head_model() else { + return; + }; + if tree.host(host).is_some() { + return; + } + let spec = HostSpec { + hostname: host.clone(), + upstreams: vec![format!("http://{}", self.cfg.listen)], + tls: tls.clone(), + auth: "none".into(), + websockets: false, + share_links: false, + device_certs: false, + access_log: "off".into(), + // No health path: every API path needs a sign-in, so a probe would see 401 and + // the apply would be reverted. Any answer from control counts as up. + health_check: None, + request_headers: Vec::new(), + response_headers: vec![ + HeaderRuleSpec { + action: "set".into(), + name: "X-Robots-Tag".into(), + value: Some("noindex, nofollow".into()), + secret: None, + }, + HeaderRuleSpec { + action: "set".into(), + name: "Strict-Transport-Security".into(), + value: Some("max-age=31536000".into()), + secret: None, + }, + ], + preview: None, + }; + match self.submit_as( + Change::Put { spec, create: true }, + None, + "Setup", + Some(format!("Added the admin host {host} (the web UI)")), + ) { + Ok(_) => log::info!(target: "ianitor::control", "adding the admin host {host}"), + Err(f) => { + log::error!(target: "ianitor::control", "cannot add the admin host {host}: {}", f.reason.message) + } + } + } + + pub fn previews_cfg(&self) -> Result<&PreviewsConfig, Fail> { + self.cfg + .previews + .as_ref() + .ok_or_else(|| fail(409, "preview.off", Params::new())) + } + + /// Every preview at the branch head, by host name. + pub fn previews(&self) -> Result, Fail> { + let (_, _, model) = self.head_model()?; + Ok(model + .hosts() + .iter() + .filter_map(|h| { + let p = h.preview.as_ref()?; + Some(Listed { + hostname: h.hostname.to_string(), + project: p.project.clone(), + branch: p.branch.clone(), + upstream: h + .upstreams + .first() + .map(ToString::to_string) + .unwrap_or_default(), + expires_at: p.expires_at, + }) + }) + .collect()) + } + + /// Open (or move) a branch's preview. + pub fn open_preview( + &self, + project: &str, + branch: &str, + upstream: &str, + ttl: Option, + actor: &str, + ) -> Result<(String, u64, crate::records::ApplyRecord), Fail> { + let p = self.previews_cfg()?; + let hostname = + ianitor_core::preview::hostname(project, branch, &p.domain).map_err(name_fail)?; + let ttl = ttl.unwrap_or(p.default_ttl_secs); + if !(p.min_ttl_secs..=p.max_ttl_secs).contains(&ttl) { + let mut f = fail( + 422, + "preview.ttl", + messages::params([ + ("min", p.min_ttl_secs.to_string()), + ("max", p.max_ttl_secs.to_string()), + ]), + ); + f.reason.field = Some("ttl".into()); + return Err(f); + } + check_upstream(&self.cfg, p, upstream)?; + let previews = self.previews()?; + let (_, tree, model) = self.head_model()?; + let existing = model + .hosts() + .iter() + .find(|h| h.hostname.as_str() == hostname); + let create = match existing { + None => { + if previews.len() >= p.max_previews { + return Err(fail( + 409, + "preview.too_many", + messages::params([("max", p.max_previews.to_string())]), + )); + } + true + } + Some(h) => match &h.preview { + Some(pv) if pv.project == project && pv.branch == branch => false, + _ => { + return Err(fail( + 409, + "preview.taken", + messages::params([("hostname", hostname.clone())]), + )); + } + }, + }; + drop(tree); + let expires_at = now().saturating_add(ttl); + let spec = spec(p, &hostname, project, branch, upstream, expires_at); + let summary = format!( + "{} the preview of {branch} ({project})", + if create { "Opened" } else { "Moved" } + ); + let rec = self.submit_as(Change::Put { spec, create }, None, actor, Some(summary))?; + Ok((hostname, expires_at, rec)) + } + + /// Close a preview by its host name. Only preview hosts. + pub fn close_preview( + &self, + hostname: &str, + actor: &str, + why: &str, + ) -> Result { + self.previews_cfg()?; + let pv = self + .previews()? + .into_iter() + .find(|p| p.hostname == hostname) + .ok_or_else(|| fail(404, "preview.not_found", Params::new()))?; + let summary = format!("{why} preview of {} ({})", pv.branch, pv.project); + self.submit_as( + Change::Delete { + hostname: hostname.to_owned(), + }, + None, + actor, + Some(summary), + ) + } + + /// Where a preview stands: `applying`, `live`, `failed` (with why), or not a preview. + pub fn preview_state(&self, hostname: &str) -> Option<(String, Option)> { + let live = self.previews().ok()?.iter().any(|p| p.hostname == hostname); + let last = self + .records() + .into_iter() + .rev() + .find(|r| r.hosts.iter().any(|h| h == hostname)); + let pending = last + .as_ref() + .is_some_and(|r| !["kept", "reverted", "failed"].contains(&r.state.as_str())); + if pending { + return Some(("applying".into(), None)); + } + if live { + return Some(("live".into(), None)); + } + let r = last?; + // A preview that never went live because its apply failed. + (r.summary.contains("the preview of") && r.state != "kept").then(|| { + ( + "failed".into(), + r.reason.as_ref().map(|x| x.message.clone()), + ) + }) + } + + /// Close expired previews, every `sweep_secs`. + pub async fn preview_sweeper(self: Arc) { + let Some(p) = self.cfg.previews.clone() else { + return; + }; + loop { + tokio::time::sleep(Duration::from_secs(p.sweep_secs)).await; + let Ok(list) = self.previews() else { + continue; + }; + let t = now(); + let busy: Vec = self + .records() + .into_iter() + .filter(|r| !["kept", "reverted", "failed"].contains(&r.state.as_str())) + .flat_map(|r| r.hosts) + .collect(); + for pv in list.iter().filter(|p| p.expires_at <= t) { + if busy.contains(&pv.hostname) { + continue; + } + match self.close_preview(&pv.hostname, EXPIRY_ACTOR, "Closed the expired") { + Ok(_) => { + log::info!(target: "ianitor::previews", "the preview {} expired; closing it", pv.hostname) + } + Err(f) => { + log::warn!(target: "ianitor::previews", "cannot close the expired preview {}: {}", pv.hostname, f.reason.message) + } + } + } + } + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + + #[test] + fn allow_list_entries_parse() { + for ok in [ + "10.0.0.0/8", + "127.0.0.1:20000-29999", + "192.168.1.5:8080", + "app.internal", + "app.internal:3000", + "*.svc.internal", + "fd00::/8", + ] { + assert!(parse_entry(ok).is_some(), "{ok}"); + } + for bad in [ + "", + "10.0.0.0/33", + "a b", + "x:0", + "x:9-1", + "*.", + "http://x", + "1.2.3.4/8:70000", + ] { + assert!(parse_entry(bad).is_none(), "{bad}"); + } + } + + #[test] + fn networks_match() { + let n = |s: &str| s.parse::().unwrap(); + assert!(in_net(n("10.1.2.3"), n("10.0.0.0"), 8)); + assert!(!in_net(n("11.1.2.3"), n("10.0.0.0"), 8)); + assert!(in_net(n("fd12::1"), n("fd00::"), 8)); + assert!(in_net(n("1.2.3.4"), n("0.0.0.0"), 0)); + assert!(never(n("0.0.0.0")) && never(n("169.254.169.254")) && never(n("::ffff:127.0.0.1"))); + } +} diff --git a/crates/control/src/team.rs b/crates/control/src/team.rs new file mode 100644 index 0000000..96cbb75 --- /dev/null +++ b/crates/control/src/team.rs @@ -0,0 +1,470 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Team sign-in without Authelia (T4: Ianitor on any server, for a small team). Authelia stays +//! an option (`[ui] proof_credential`, docs/api.md "Sign-in"); this is the default elsewhere. +//! +//! - **The founding admin** signs in with a one-time **setup link** (`#signin=isc_…`): made at +//! the first start of a server with no member, printed by the installer +//! (`ianitor-control team setup-link`), valid 7 days, one use. +//! - **Teammates** get an **invite link** from an admin (Settings → Team → Invite), for a role: +//! `admin` (everything) or `member` (hosts, previews, history; not tokens, the team, the +//! engine or the CA). One use, 7 days. +//! - Redeeming a link makes a **session**: `ise_` + 32 random bytes in an `HttpOnly`, +//! `Secure`, `SameSite=Strict`, `__Host-` cookie, 30 days, no sliding. Control stores only +//! SHA-256 of codes and sessions (in `team.json`, 0600), so a copy of the state directory +//! signs no one in. Signing out ends the session; removing a member ends all of theirs. +//! - A member may record their **Tessera root** (the Domi identity's public key, as Custos +//! shows it) so the team list shows its match code. Signing in *with* the Tessera key (a +//! browser Domi key) and Custos approval of admin changes need operations Custos does not +//! have yet (docs/custos-ticket.md, T4 part); until then admin changes need the admin role. + +use std::path::{Path, PathBuf}; + +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use serde::{Deserialize, Serialize}; + +use crate::util::{ct_eq, hex, now, random, read_json, sha256_hex, write_json}; + +pub const COOKIE: &str = "__Host-ianitor"; +pub const SESSION_SECS: u64 = 30 * 86_400; +pub const CODE_SECS: u64 = 7 * 86_400; +const MAX_MEMBERS: usize = 64; +const MAX_SESSIONS: usize = 400; +const MAX_CODES: usize = 100; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Role { + Admin, + Member, +} + +impl Role { + pub fn as_str(self) -> &'static str { + match self { + Role::Admin => "admin", + Role::Member => "member", + } + } + pub fn parse(s: &str) -> Option { + match s { + "admin" => Some(Role::Admin), + "member" => Some(Role::Member), + _ => None, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Member { + pub id: String, + pub name: String, + pub role: Role, + /// The member's Tessera root public key (base64url, 32 bytes), when they gave it. + #[serde(default)] + pub tessera_root: Option, + pub added_at: u64, + pub added_by: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Session { + pub id: String, + pub sha256: String, + pub member: String, + /// What the browser was called at sign-in (`Laptop`, `Phone`). + pub device: String, + pub created_at: u64, + pub expires_at: u64, + pub last_used_at: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Code { + pub id: String, + pub sha256: String, + /// `setup` (the founding admin) or `invite`. + pub kind: String, + pub role: Role, + /// The invitee's name, as the admin typed it. + pub name: Option, + pub expires_at: u64, + pub created_by: String, +} + +#[derive(Debug, Default, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct TeamFile { + members: Vec, + sessions: Vec, + codes: Vec, +} + +/// Why a sign-in or a team change was refused (an API error code). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Refused(pub &'static str); + +pub struct Team { + path: PathBuf, + lock: std::sync::Mutex<()>, +} + +struct Guard<'a> { + _m: std::sync::MutexGuard<'a, ()>, + _f: std::fs::File, +} + +pub fn valid_name(n: &str) -> bool { + let n = n.trim(); + !n.is_empty() && n.chars().count() <= 64 && !n.chars().any(char::is_control) +} + +/// A Tessera root as Custos shows it: base64url of 32 bytes. +pub fn valid_root(r: &str) -> bool { + URL_SAFE_NO_PAD + .decode(r.trim()) + .is_ok_and(|b| b.len() == 32) +} + +/// The 6-digit match code of a Tessera key, exactly as Fundamentum's `tessera::match_code` +/// (docs/TESSERA.md §5): SHA-256 of `"tessera match v1"` and the key, first 4 bytes +/// big-endian, mod 10^6; shown as `474 719`. +pub fn match_code(root: &str) -> Option { + let b = URL_SAFE_NO_PAD.decode(root.trim()).ok()?; + let mut ctx = ring::digest::Context::new(&ring::digest::SHA256); + ctx.update(b"tessera match v1"); + ctx.update(&b); + let d = ctx.finish(); + let n = u32::from_be_bytes([d.as_ref()[0], d.as_ref()[1], d.as_ref()[2], d.as_ref()[3]]); + let c = n % 1_000_000; + Some(format!("{:03} {:03}", c / 1000, c % 1000)) +} + +fn secret(prefix: &str) -> Result { + Ok(format!( + "{prefix}_{}", + URL_SAFE_NO_PAD.encode(random::<32>().map_err(|e| e.to_string())?) + )) +} + +fn new_id() -> Result { + Ok(hex(&random::<8>().map_err(|e| e.to_string())?)) +} + +impl Team { + pub fn new(state_dir: &Path) -> Team { + Team { + path: state_dir.join("team.json"), + lock: std::sync::Mutex::new(()), + } + } + + fn guard(&self) -> Result, String> { + let m = self + .lock + .lock() + .map_err(|_| "team store unavailable".to_owned())?; + let path = self.path.with_file_name("team.lock"); + if let Some(d) = path.parent() { + std::fs::create_dir_all(d) + .map_err(|e| format!("cannot create {}: {e}", d.display()))?; + } + let f = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(&path) + .map_err(|e| format!("cannot open {}: {e}", path.display()))?; + f.lock() + .map_err(|e| format!("cannot lock {}: {e}", path.display()))?; + Ok(Guard { _m: m, _f: f }) + } + + fn load(&self) -> Result { + let mut f: TeamFile = read_json(&self.path)?.unwrap_or_default(); + let t = now(); + f.sessions.retain(|s| s.expires_at > t); + f.codes.retain(|c| c.expires_at > t); + Ok(f) + } + + fn save(&self, f: &TeamFile) -> Result<(), String> { + write_json(&self.path, f) + } + + pub fn members(&self) -> Result, String> { + let _g = self.guard()?; + Ok(self.load()?.members) + } + + /// Open invites (never their values). + pub fn codes(&self) -> Result, String> { + let _g = self.guard()?; + Ok(self.load()?.codes) + } + + pub fn has_members(&self) -> bool { + self.members().is_ok_and(|m| !m.is_empty()) + } + + /// A new setup code for the founding admin, while the team has no member. Older setup + /// codes stop working. + pub fn setup_code(&self) -> Result<(String, u64), String> { + let _g = self.guard()?; + let mut f = self.load()?; + if !f.members.is_empty() { + return Err( + "the team already has members; an admin invites people from Settings → Team".into(), + ); + } + f.codes.retain(|c| c.kind != "setup"); + let value = secret("isc")?; + let expires_at = now() + CODE_SECS; + f.codes.push(Code { + id: new_id()?, + sha256: sha256_hex(value.as_bytes()), + kind: "setup".into(), + role: Role::Admin, + name: None, + expires_at, + created_by: "setup".into(), + }); + self.save(&f)?; + Ok((value, expires_at)) + } + + /// An invite for one person (admin only, checked by the caller). + pub fn invite(&self, name: &str, role: Role, by: &str) -> Result<(Code, String), Refused> { + let _g = self.guard().map_err(|_| Refused("internal"))?; + let mut f = self.load().map_err(|_| Refused("internal"))?; + if !valid_name(name) { + return Err(Refused("team.name")); + } + if f.codes.len() >= MAX_CODES || f.members.len() >= MAX_MEMBERS { + return Err(Refused("team.full")); + } + let value = secret("iin").map_err(|_| Refused("internal"))?; + let code = Code { + id: new_id().map_err(|_| Refused("internal"))?, + sha256: sha256_hex(value.as_bytes()), + kind: "invite".into(), + role, + name: Some(name.trim().to_owned()), + expires_at: now() + CODE_SECS, + created_by: by.to_owned(), + }; + f.codes.push(code.clone()); + self.save(&f).map_err(|_| Refused("internal"))?; + Ok((code, value)) + } + + pub fn cancel_invite(&self, id: &str) -> Result { + let _g = self.guard()?; + let mut f = self.load()?; + let before = f.codes.len(); + f.codes.retain(|c| !(c.id == id && c.kind == "invite")); + let gone = f.codes.len() != before; + self.save(&f)?; + Ok(gone) + } + + /// Redeem a setup or invite code: the member (made now) and a new session's value. + pub fn redeem( + &self, + code: &str, + name: Option<&str>, + device: &str, + ) -> Result<(Member, String), Refused> { + let _g = self.guard().map_err(|_| Refused("internal"))?; + let mut f = self.load().map_err(|_| Refused("internal"))?; + let presented = sha256_hex(code.trim().as_bytes()); + let Some(pos) = f + .codes + .iter() + .position(|c| ct_eq(c.sha256.as_bytes(), presented.as_bytes())) + else { + return Err(Refused("session.code")); + }; + let c = f.codes.remove(pos); + if c.kind == "setup" && !f.members.is_empty() { + return Err(Refused("session.code")); + } + let name = match (c.name.as_deref(), name) { + (Some(n), _) => n.to_owned(), + (None, Some(n)) if valid_name(n) => n.trim().to_owned(), + (None, _) => "Admin".to_owned(), + }; + if f.members.len() >= MAX_MEMBERS { + return Err(Refused("team.full")); + } + let member = Member { + id: new_id().map_err(|_| Refused("internal"))?, + name, + role: c.role, + tessera_root: None, + added_at: now(), + added_by: c.created_by.clone(), + }; + f.members.push(member.clone()); + let value = self.push_session(&mut f, &member.id, device)?; + self.save(&f).map_err(|_| Refused("internal"))?; + Ok((member, value)) + } + + fn push_session( + &self, + f: &mut TeamFile, + member: &str, + device: &str, + ) -> Result { + let value = secret("ise").map_err(|_| Refused("internal"))?; + let t = now(); + if f.sessions.len() >= MAX_SESSIONS { + // The oldest one goes. + f.sessions.sort_by_key(|s| s.created_at); + f.sessions.remove(0); + } + let device = if valid_name(device) { + device.trim().to_owned() + } else { + "Browser".to_owned() + }; + f.sessions.push(Session { + id: new_id().map_err(|_| Refused("internal"))?, + sha256: sha256_hex(value.as_bytes()), + member: member.to_owned(), + device, + created_at: t, + expires_at: t + SESSION_SECS, + last_used_at: Some(t), + }); + Ok(value) + } + + /// The member and session behind a cookie value. + pub fn check(&self, value: &str) -> Option<(Member, Session)> { + if !value.starts_with("ise_") || value.len() > 100 { + return None; + } + let _g = self.guard().ok()?; + let mut f = self.load().ok()?; + let presented = sha256_hex(value.as_bytes()); + let s = f + .sessions + .iter_mut() + .find(|s| ct_eq(s.sha256.as_bytes(), presented.as_bytes()))?; + let t = now(); + let touch = s.last_used_at.is_none_or(|l| t.saturating_sub(l) >= 60); + if touch { + s.last_used_at = Some(t); + } + let s = s.clone(); + let m = f.members.iter().find(|m| m.id == s.member)?.clone(); + if touch { + let _ = self.save(&f); + } + Some((m, s)) + } + + pub fn end_session(&self, id: &str) -> Result<(), String> { + let _g = self.guard()?; + let mut f = self.load()?; + f.sessions.retain(|s| s.id != id); + self.save(&f) + } + + /// Remove a member and every session of theirs. The last admin stays. + pub fn remove(&self, id: &str) -> Result, Refused> { + let _g = self.guard().map_err(|_| Refused("internal"))?; + let mut f = self.load().map_err(|_| Refused("internal"))?; + let Some(m) = f.members.iter().find(|m| m.id == id).cloned() else { + return Ok(None); + }; + let admins = f.members.iter().filter(|m| m.role == Role::Admin).count(); + if m.role == Role::Admin && admins <= 1 { + return Err(Refused("team.last_admin")); + } + f.members.retain(|x| x.id != id); + f.sessions.retain(|s| s.member != id); + self.save(&f).map_err(|_| Refused("internal"))?; + Ok(Some(m)) + } + + /// Record (or clear) a member's own Tessera root. + pub fn set_root(&self, member: &str, root: Option<&str>) -> Result<(), Refused> { + if root.is_some_and(|r| !valid_root(r)) { + return Err(Refused("team.root")); + } + let _g = self.guard().map_err(|_| Refused("internal"))?; + let mut f = self.load().map_err(|_| Refused("internal"))?; + let m = f + .members + .iter_mut() + .find(|m| m.id == member) + .ok_or(Refused("team.not_found"))?; + m.tessera_root = root.map(|r| r.trim().to_owned()); + self.save(&f).map_err(|_| Refused("internal")) + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + + fn dir(n: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("ianitor-team-{n}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + d + } + + #[test] + fn setup_then_invite_then_sessions() { + let d = dir("flow"); + let t = Team::new(&d); + let (setup, _) = t.setup_code().unwrap(); + assert!(t.redeem("isc_wrong", Some("Mark"), "Laptop").is_err()); + let (mark, s1) = t.redeem(&setup, Some("Mark"), "Laptop").unwrap(); + assert_eq!(mark.role, Role::Admin); + // One use only, and no second setup once there is a member. + assert_eq!( + t.redeem(&setup, Some("Eve"), "x").unwrap_err(), + Refused("session.code") + ); + assert!(t.setup_code().is_err()); + let (who, _) = t.check(&s1).unwrap(); + assert_eq!(who.name, "Mark"); + // Only hashes on disk. + let stored = std::fs::read_to_string(d.join("team.json")).unwrap(); + assert!(!stored.contains(&s1) && !stored.contains(&setup)); + let (_, inv) = t.invite("Petra", Role::Member, &mark.id).unwrap(); + let (petra, s2) = t.redeem(&inv, Some("Someone else"), "Phone").unwrap(); + assert_eq!((petra.name.as_str(), petra.role), ("Petra", Role::Member)); + // The last admin cannot go; a member can, with their sessions. + assert_eq!(t.remove(&mark.id).unwrap_err(), Refused("team.last_admin")); + t.remove(&petra.id).unwrap(); + assert!(t.check(&s2).is_none()); + let (_, s) = t.check(&s1).unwrap(); + t.end_session(&s.id).unwrap(); + assert!(t.check(&s1).is_none()); + let _ = std::fs::remove_dir_all(&d); + } + + #[test] + fn tessera_roots_are_checked() { + assert!(valid_root(&URL_SAFE_NO_PAD.encode([7u8; 32]))); + assert!(!valid_root("not base64!")); + assert!(!valid_root(&URL_SAFE_NO_PAD.encode([7u8; 31]))); + // Fundamentum's vector (crates/tessera/tests/mandatory.rs, MATCH_SEVENS = "016810"). + assert_eq!( + match_code(&URL_SAFE_NO_PAD.encode([7u8; 32])).unwrap(), + "016 810" + ); + } +} diff --git a/crates/control/src/tokens.rs b/crates/control/src/tokens.rs index 1bde3ea..7fa9501 100644 --- a/crates/control/src/tokens.rs +++ b/crates/control/src/tokens.rs @@ -23,6 +23,34 @@ use serde::{Deserialize, Serialize}; use crate::util::{ct_eq, hex, now, random, read_json, sha256_hex, write_json}; +/// What a token may do. `full` (the default, and every token made before T4) may do +/// everything the API offers; `previews` may only use `/api/v1/previews` (Fabrica's branch +/// previews), so a leaked preview token can never touch another host. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Scope { + #[default] + Full, + Previews, +} + +impl Scope { + pub fn as_str(self) -> &'static str { + match self { + Scope::Full => "full", + Scope::Previews => "previews", + } + } + + pub fn parse(s: &str) -> Option { + match s { + "full" => Some(Scope::Full), + "previews" => Some(Scope::Previews), + _ => None, + } + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct TokenRecord { @@ -33,6 +61,8 @@ pub struct TokenRecord { pub expires_at: Option, pub last_used_at: Option, pub revoked_at: Option, + #[serde(default)] + pub scope: Scope, } #[derive(Debug, Default, Serialize, Deserialize)] @@ -117,6 +147,7 @@ impl Tokens { &self, name: &str, expires_at: Option, + scope: Scope, ) -> Result<(TokenRecord, String), String> { let _g = self.guard()?; if !valid_name(name) { @@ -137,6 +168,7 @@ impl Tokens { expires_at, last_used_at: None, revoked_at: None, + scope, }; f.tokens.push(rec.clone()); self.save(&f)?; @@ -231,7 +263,7 @@ mod tests { fn create_check_revoke() { let d = std::env::temp_dir().join(format!("ianitor-tokens-{}", std::process::id())); let t = Tokens::new(&d); - let (rec, value) = t.create("laptop", None).unwrap(); + let (rec, value) = t.create("laptop", None, Scope::Full).unwrap(); assert!(value.starts_with("ian_")); let stored = std::fs::read_to_string(d.join("tokens.json")).unwrap(); assert!(!stored.contains(&value[21..]), "only the hash is stored"); @@ -253,7 +285,7 @@ mod tests { t.check(Some(&format!("Bearer {value}"))).unwrap_err(), Refusal::Revoked(_) )); - let (_, v2) = t.create("old", Some(1)).unwrap(); + let (_, v2) = t.create("old", Some(1), Scope::Full).unwrap(); assert_eq!( t.check(Some(&format!("Bearer {v2}"))).unwrap_err(), Refusal::Expired(1) diff --git a/crates/control/src/winsvc.rs b/crates/control/src/winsvc.rs new file mode 100644 index 0000000..7e42c3a --- /dev/null +++ b/crates/control/src/winsvc.rs @@ -0,0 +1,109 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Windows Server, Caddy mode (Fabrica docs/32_coherence.md §2.5, T4): what the service +//! control manager starts. `ianitor-control service control --config ` is the control +//! plane, `ianitor-control service caddy-guard --config ` the Caddy trial deadline guard +//! (its own service, so a hung or crashed control cannot leave Caddy on an unconfirmed +//! trial). Both stop cleanly on the SCM's Stop. `deploy/windows/install.ps1` registers them. +//! Logs go to the file given with `--log-file` (stderr goes nowhere under the SCM). + +use std::ffi::OsString; +use std::sync::OnceLock; +use std::time::Duration; + +use windows_service::service::{ + ServiceControl, ServiceControlAccept, ServiceExitCode, ServiceState, ServiceStatus, ServiceType, +}; +use windows_service::service_control_handler::{self, ServiceControlHandlerResult}; +use windows_service::{define_windows_service, service_dispatcher}; + +static ARGS: OnceLock> = OnceLock::new(); + +define_windows_service!(ffi_service_main, service_main); + +/// Hand this process to the service control manager (blocks until the service stops). +pub fn run(args: &[String]) -> Result<(), String> { + let _ = ARGS.set(args.to_vec()); + // The name is ignored for a service in its own process. + service_dispatcher::start("IanitorControl", ffi_service_main) + .map_err(|e| format!("not started by the service control manager ({e}); run it as a service, or use --config to run it in a console")) +} + +fn status(state: ServiceState, code: u32) -> ServiceStatus { + ServiceStatus { + service_type: ServiceType::OWN_PROCESS, + current_state: state, + controls_accepted: if state == ServiceState::Running { + ServiceControlAccept::STOP | ServiceControlAccept::SHUTDOWN + } else { + ServiceControlAccept::empty() + }, + exit_code: ServiceExitCode::Win32(code), + checkpoint: 0, + wait_hint: Duration::from_secs(10), + process_id: None, + } +} + +fn service_main(_: Vec) { + let args = ARGS.get().cloned().unwrap_or_default(); + let (tx, rx) = tokio::sync::oneshot::channel::<()>(); + let tx = std::sync::Mutex::new(Some(tx)); + let handler = move |c| match c { + ServiceControl::Stop | ServiceControl::Shutdown => { + if let Ok(mut t) = tx.lock() + && let Some(t) = t.take() + { + let _ = t.send(()); + } + ServiceControlHandlerResult::NoError + } + ServiceControl::Interrogate => ServiceControlHandlerResult::NoError, + _ => ServiceControlHandlerResult::NotImplemented, + }; + let Ok(h) = service_control_handler::register("IanitorControl", handler) else { + return; + }; + let _ = h.set_service_status(status(ServiceState::Running, 0)); + let result = serve(&args, rx); + if let Err(e) = &result { + log::error!(target: "ianitor::service", "{e}"); + } + let _ = h.set_service_status(status(ServiceState::Stopped, u32::from(result.is_err()))); +} + +fn serve(args: &[String], stop: tokio::sync::oneshot::Receiver<()>) -> Result<(), String> { + let what = args.first().map(String::as_str).unwrap_or("control"); + let config = args + .iter() + .position(|a| a == "--config") + .and_then(|i| args.get(i + 1)) + .ok_or("service: --config is required")?; + let cfg = + ianitor_control::Config::load(std::path::Path::new(config)).map_err(|e| e.to_string())?; + let rt = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .map_err(|e| e.to_string())?; + rt.block_on(async move { + match what { + "control" => { + ianitor_control::serve(cfg, async { + let _ = stop.await; + }) + .await + } + "caddy-guard" => { + tokio::select! { + r = ianitor_control::caddy_guard::run(cfg) => r, + _ = stop => Ok(()), + } + } + other => Err(format!( + "service: unknown part {other:?} (control or caddy-guard)" + )), + } + }) +} diff --git a/crates/control/tests/caddy_mode.rs b/crates/control/tests/caddy_mode.rs new file mode 100644 index 0000000..87c55fb --- /dev/null +++ b/crates/control/tests/caddy_mode.rs @@ -0,0 +1,280 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Caddy mode end to end (T4: Windows Server runs control with Caddy as the data plane, no +//! edge). Control runs with `engine = caddy`, Caddy's admin API on loopback TCP (as on +//! Windows), and the Domi CA. A previews-only token opens a branch preview; the apply goes +//! through Caddy (trial, watch, confirm); the preview's address then answers through Caddy +//! with a Domi certificate; closing it takes it away again. Runs on Windows and on Linux. +//! Needs `caddy` on PATH or `$IANITOR_CADDY_BIN` (else it fails, unless IANITOR_ALLOW_SKIP=1). + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::net::SocketAddr; +use std::process::{Command, Stdio}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use ianitor_control::Config; +use ianitor_control::tokens::{Scope, Tokens}; +use ianitor_testkit::client::{self, Req}; +use ianitor_testkit::more::{JsonResp, tcp_json}; +use ianitor_testkit::proc::{ChildGuard, TempDir, free_port, local, require_binary, wait_for_port}; +use ianitor_testkit::upstream::Echo; +use serde_json::{Value, json}; + +fn s(p: &std::path::Path) -> String { + p.to_string_lossy().replace('\\', "/") +} + +async fn call( + api: SocketAddr, + token: &str, + method: &str, + path: &str, + body: Option, +) -> JsonResp { + let auth = format!("Bearer {token}"); + tcp_json( + api, + method, + path, + &[("Authorization", &auth)], + body.as_ref(), + ) + .await + .unwrap() +} + +async fn settle(api: SocketAddr, token: &str, apply: &Value) -> Value { + let id = apply["id"].as_str().unwrap().to_owned(); + let t = Instant::now(); + loop { + let r = call(api, token, "GET", &format!("/api/v1/applies/{id}"), None).await; + if ["kept", "reverted", "failed"].contains(&r.json["state"].as_str().unwrap_or("")) { + return r.json; + } + assert!( + t.elapsed() < Duration::from_secs(90), + "apply stuck: {}", + r.text + ); + tokio::time::sleep(Duration::from_millis(700)).await; + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_branch_preview_answers_through_caddy_without_an_edge() { + let Some(caddy) = require_binary("caddy") else { + return; + }; + let dir = TempDir::new("caddy-mode"); + for d in [ + "state", + "edge", + "caddy", + "certs", + "creds", + "caddy-state", + "root", + "xdg", + ] { + std::fs::create_dir_all(dir.join(d)).unwrap(); + } + // The offline root (a test one) and the intermediate's password. + let now = ianitor_control::util::now(); + let (root_pem, root_key) = ianitor_core::pki::create_root(now as i64).unwrap(); + std::fs::write(dir.join("root/domi-root.crt"), &root_pem).unwrap(); + std::fs::write( + dir.join("creds/pki-password"), + "caddy-mode-test-password-0123456789", + ) + .unwrap(); + + let api = local(free_port()); + let admin = local(free_port()); + let (http, https) = (free_port(), free_port()); + // Caddy starts with only its admin API, as the installer starts it; control loads the rest. + let boot = json!({"admin": {"listen": admin.to_string()}}).to_string(); + std::fs::write(dir.join("caddy/boot.json"), &boot).unwrap(); + let log = std::fs::File::create(dir.join("caddy.log")).unwrap(); + let _caddy = ChildGuard( + Command::new(&caddy) + .args(["run", "--config"]) + .arg(dir.join("caddy/boot.json")) + .env("HOME", dir.join("xdg")) + .env("XDG_CONFIG_HOME", dir.join("xdg")) + .env("XDG_DATA_HOME", dir.join("xdg")) + .env("APPDATA", dir.join("xdg")) + .stdout(Stdio::from(log.try_clone().unwrap())) + .stderr(Stdio::from(log)) + .spawn() + .unwrap(), + ); + assert!( + wait_for_port(admin, Duration::from_secs(60)), + "Caddy's admin API did not start" + ); + std::fs::write(dir.join("state/engine"), "caddy\n").unwrap(); + + let text = format!( + r#"listen = "{api}" +state_dir = "{state}" +credentials_dir = "{creds}" +watch_secs = 2 +watch_every_secs = 1 +trial_margin_secs = 5 + +[routes] +repo = "{repo}" + +[edge] +config = "{edge}/edge.json" +share_revocations = "{edge}/share-revocations.json" + +[caddy] +config = "{caddy_dir}/caddy.json" + +[compile] +http_listen = "127.0.0.1:{http}" +https_listen = "127.0.0.1:{https}" +cert_dir = "{certs}" +state_dir = "{caddy_state}" +access_log = "{caddy_state}/access.log" +caddy_credentials_dir = "{creds}" +caddy_admin = "{admin}" + +[pki] +root_cert = "{root}/domi-root.crt" +kdf_iterations = 10000 + +[engine] +file = "{state}/engine" +units = "none" + +[previews] +domain = "pv.test" +tls = "domi" +upstreams = ["127.0.0.1:1024-65535"] +min_ttl_secs = 60 +"#, + state = s(&dir.join("state")), + creds = s(&dir.join("creds")), + repo = s(&dir.join("routes.git")), + edge = s(&dir.join("edge")), + caddy_dir = s(&dir.join("caddy")), + certs = s(&dir.join("certs")), + caddy_state = s(&dir.join("caddy-state")), + root = s(&dir.join("root")), + ); + std::fs::write(dir.join("control.toml"), text).unwrap(); + let cfg = Config::load(&dir.join("control.toml")).unwrap(); + + // The intermediate, signed by the test root (the offline step of docs/pki.md). + { + let c = ianitor_control::Control::open(cfg.clone()).await.unwrap(); + let p = c.pki.as_ref().unwrap(); + let r = p.request_renewal(now, "test").unwrap(); + let signed = ianitor_core::pki::sign_intermediate( + &root_pem, + &root_key, + r.csr_pem.as_deref().unwrap(), + now as i64, + ) + .unwrap(); + p.install_intermediate(&r.id, &signed, now).unwrap(); + } + let tokens = Tokens::new(&dir.join("state")); + let (_, admin_tok) = tokens.create("admin", None, Scope::Full).unwrap(); + let (_, fabrica) = tokens.create("fabrica", None, Scope::Previews).unwrap(); + let (tx, rx) = tokio::sync::oneshot::channel::<()>(); + tokio::spawn(ianitor_control::serve(cfg, async { + let _ = rx.await; + })); + assert!(wait_for_port(api, Duration::from_secs(20))); + + let r = call(api, &admin_tok, "GET", "/api/v1/overview", None).await; + assert_eq!(r.json["engine"]["running"], "caddy", "{}", r.text); + assert_eq!(r.json["engine"]["switchable"], false, "{}", r.text); + + // Fabrica opens the branch's preview. + let app = Echo::start("preview-app").await; + let r = call( + api, + &fabrica, + "POST", + "/api/v1/previews", + Some(json!({"project": "shop", "branch": "fix-42", "upstream": app.url(), "ttl": 3600})), + ) + .await; + assert_eq!(r.status, 202, "{}", r.text); + let host = r.json["preview"]["hostname"].as_str().unwrap().to_owned(); + assert_eq!(host, "fix-42--shop.pv.test"); + let done = settle(api, &admin_tok, &r.json["apply"]).await; + assert_eq!(done["state"], "kept", "{done}"); + let steps: Vec = done["steps"] + .as_array() + .unwrap() + .iter() + .map(|s| { + format!( + "{}={}", + s["key"].as_str().unwrap(), + s["state"].as_str().unwrap() + ) + }) + .collect(); + assert!( + steps.contains(&"watch=done".to_owned()), + "watched through Caddy: {steps:?}" + ); + + // The preview answers through Caddy, with a certificate from the Domi CA. + let mut roots = rustls::RootCertStore::empty(); + for der in ianitor_core::pki::chain_der(&root_pem).unwrap() { + roots + .add(rustls_pki_types::CertificateDer::from(der)) + .unwrap(); + } + let roots = Arc::new(roots); + let https_addr = local(https); + let resp = client::https(https_addr, &host, roots.clone(), &Req::get(&host, "/hello")) + .await + .unwrap(); + assert_eq!(resp.status, 200); + assert_eq!(resp.header("x-robots-tag"), Some("noindex, nofollow")); + assert!(String::from_utf8_lossy(&resp.body).contains("preview-app")); + let r = call( + api, + &fabrica, + "GET", + &format!("/api/v1/previews/{host}"), + None, + ) + .await; + assert_eq!(r.json["preview"]["state"], "live", "{}", r.text); + + // Closed on merge: Caddy stops serving it. + let r = call( + api, + &fabrica, + "POST", + "/api/v1/previews/close", + Some(json!({"project": "shop", "branch": "fix-42"})), + ) + .await; + assert_eq!(r.status, 202, "{}", r.text); + assert_eq!( + settle(api, &admin_tok, &r.json["apply"]).await["state"], + "kept" + ); + let gone = client::https(https_addr, &host, roots, &Req::get(&host, "/hello")).await; + assert!( + gone.as_ref() + .map_or(true, |r| r.status == 404 || r.status == 421), + "{:?}", + gone.map(|r| r.status) + ); + let _ = tx.send(()); +} 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/crates/control/tests/previews.rs b/crates/control/tests/previews.rs new file mode 100644 index 0000000..0a87a32 --- /dev/null +++ b/crates/control/tests/previews.rs @@ -0,0 +1,539 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Branch previews for Fabrica (T4, tests first). `POST /api/v1/previews {project, branch, +//! upstream, ttl}` gives the branch the host `--.`; a token +//! scoped to previews may do that and nothing else. These tests run control in this process +//! without an edge (applies are kept at once), so they run on Windows too; the end-to-end +//! runs through Pingora and Caddy are in tests/diff and scripts/preview-smoke.*. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::net::SocketAddr; +use std::time::{Duration, Instant}; + +use ianitor_control::Config; +use ianitor_control::tokens::{Scope, Tokens}; +use ianitor_testkit::more::{JsonResp, tcp_json}; +use ianitor_testkit::proc::{TempDir, free_port, local, wait_for_port}; +use serde_json::{Value, json}; + +const DOMAIN: &str = "pv.example.test"; + +struct Ctl { + _dir: TempDir, + api: SocketAddr, + admin: String, + preview: String, + stop: Option>, +} + +impl Drop for Ctl { + fn drop(&mut self) { + if let Some(s) = self.stop.take() { + let _ = s.send(()); + } + } +} + +fn s(p: &std::path::Path) -> String { + p.to_string_lossy().replace('\\', "/") +} + +impl Ctl { + async fn start(extra: &str) -> Ctl { + let dir = TempDir::new("pv"); + for d in ["state", "edge", "caddy", "certs", "creds", "edge-state"] { + std::fs::create_dir_all(dir.join(d)).unwrap(); + } + let api = local(free_port()); + let text = format!( + r#"listen = "{api}" +state_dir = "{state}" +credentials_dir = "{creds}" + +[routes] +repo = "{repo}" + +[edge] +config = "{edge}/edge.json" +share_revocations = "{edge}/share-revocations.json" + +[caddy] +config = "{caddy}/caddy.json" + +[compile] +http_listen = "127.0.0.1:{http}" +https_listen = "127.0.0.1:{https}" +cert_dir = "{certs}" +state_dir = "{edge_state}" +access_log = "{edge_state}/access.log" +caddy_credentials_dir = "{creds}" + +[previews] +domain = "{DOMAIN}" +tls = "letsencrypt" +upstreams = ["10.0.0.0/8", "127.0.0.1:20000-29999", "app.internal"] +min_ttl_secs = 1 +sweep_secs = 1 +{extra} +"#, + state = s(&dir.join("state")), + creds = s(&dir.join("creds")), + repo = s(&dir.join("routes.git")), + edge = s(&dir.join("edge")), + caddy = s(&dir.join("caddy")), + certs = s(&dir.join("certs")), + edge_state = s(&dir.join("edge-state")), + http = free_port(), + https = free_port(), + ); + let path = dir.join("control.toml"); + std::fs::write(&path, text).unwrap(); + let cfg = Config::load(&path).unwrap(); + let tokens = Tokens::new(&dir.join("state")); + let (_, admin) = tokens.create("admin", None, Scope::Full).unwrap(); + let (_, preview) = tokens + .create("fabrica previews", None, Scope::Previews) + .unwrap(); + let (tx, rx) = tokio::sync::oneshot::channel::<()>(); + tokio::spawn(async move { + if let Err(e) = ianitor_control::serve(cfg, async { + let _ = rx.await; + }) + .await + { + panic!("control stopped: {e}"); + } + }); + assert!( + wait_for_port(api, Duration::from_secs(20)), + "control did not listen" + ); + Ctl { + _dir: dir, + api, + admin, + preview, + stop: Some(tx), + } + } + + async fn call(&self, token: &str, method: &str, path: &str, body: Option) -> JsonResp { + let auth = format!("Bearer {token}"); + tcp_json( + self.api, + method, + path, + &[("Authorization", &auth)], + body.as_ref(), + ) + .await + .unwrap() + } + + async fn admin(&self, method: &str, path: &str, body: Option) -> JsonResp { + self.call(&self.admin, method, path, body).await + } + + async fn fabrica(&self, method: &str, path: &str, body: Option) -> JsonResp { + self.call(&self.preview, method, path, body).await + } + + /// Wait for an apply to end; returns its final state. + async fn settle(&self, apply: &Value) -> String { + let id = apply["id"].as_str().expect("an apply id").to_owned(); + let t = Instant::now(); + loop { + let r = self + .admin("GET", &format!("/api/v1/applies/{id}"), None) + .await; + let state = r.json["state"].as_str().unwrap_or("").to_owned(); + if ["kept", "reverted", "failed"].contains(&state.as_str()) { + return state; + } + assert!( + t.elapsed() < Duration::from_secs(30), + "apply {id} stuck: {}", + r.text + ); + tokio::time::sleep(Duration::from_millis(700)).await; + } + } + + async fn host_names(&self) -> Vec { + let r = self.admin("GET", "/api/v1/hosts", None).await; + assert_eq!(r.status, 200, "{}", r.text); + r.json["hosts"] + .as_array() + .unwrap() + .iter() + .map(|h| h["hostname"].as_str().unwrap().to_owned()) + .collect() + } + + async fn add_plain_host(&self, hostname: &str) { + let r = self + .admin( + "POST", + "/api/v1/hosts", + Some(json!({"host": {"hostname": hostname, "upstreams": ["http://10.0.0.9:80"]}})), + ) + .await; + assert_eq!(r.status, 202, "{}", r.text); + assert_eq!(self.settle(&r.json["apply"]).await, "kept"); + } + + async fn open_preview(&self, project: &str, branch: &str, upstream: &str) -> JsonResp { + self.fabrica( + "POST", + "/api/v1/previews", + Some(json!({"project": project, "branch": branch, "upstream": upstream, "ttl": 3600})), + ) + .await + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_preview_token_cannot_touch_non_preview_hosts() { + let c = Ctl::start("").await; + c.add_plain_host("www.example.test").await; + let www = + json!({"host": {"hostname": "www.example.test", "upstreams": ["http://10.6.6.6:80"]}}); + + // Everything outside /api/v1/previews is refused, reads included. + let refused: Vec<(&str, &str, Option)> = vec![ + ("GET", "/api/v1/overview", None), + ("GET", "/api/v1/hosts", None), + ("GET", "/api/v1/hosts/www.example.test", None), + ( + "POST", + "/api/v1/hosts", + Some( + json!({"host": {"hostname": "evil.example.test", "upstreams": ["http://10.6.6.6:80"]}}), + ), + ), + ("PUT", "/api/v1/hosts/www.example.test", Some(www.clone())), + ( + "PATCH", + "/api/v1/hosts/www.example.test", + Some(json!({"share_links": true})), + ), + ("DELETE", "/api/v1/hosts/www.example.test", None), + ("POST", "/api/v1/hosts/validate", Some(www["host"].clone())), + ("POST", "/api/v1/undo", Some(json!({}))), + ("POST", "/api/v1/restore", Some(json!({"change_id": "x"}))), + ("GET", "/api/v1/history", None), + ("GET", "/api/v1/applies", None), + ("GET", "/api/v1/tokens", None), + ("POST", "/api/v1/tokens", Some(json!({"name": "escalate"}))), + ( + "POST", + "/api/v1/hosts/www.example.test/share-links", + Some(json!({})), + ), + ("POST", "/api/v1/share-links/stop-all", None), + ("GET", "/api/v1/certs", None), + ("POST", "/api/v1/engine", Some(json!({"target": "caddy"}))), + ("POST", "/api/v1/repo/push", None), + ("GET", "/api/v1/settings", None), + ("GET", "/api/v1/team", None), + ]; + for (m, p, b) in refused { + let r = c.fabrica(m, p, b).await; + assert_eq!(r.status, 403, "{m} {p}: {}", r.text); + assert_eq!( + r.json["error"]["code"], "token.scope", + "{m} {p}: {}", + r.text + ); + } + + // The previews API refuses a host that is not a preview. + let r = c + .fabrica("DELETE", "/api/v1/previews/www.example.test", None) + .await; + assert_eq!(r.status, 404, "{}", r.text); + assert_eq!(r.json["error"]["code"], "preview.not_found"); + let r = c + .fabrica("GET", "/api/v1/previews/www.example.test", None) + .await; + assert_eq!(r.status, 404, "{}", r.text); + + // A non-preview host at exactly the name a preview would get is not taken over. + let taken = format!("main--shop.{DOMAIN}"); + c.add_plain_host(&taken).await; + let r = c.open_preview("shop", "main", "http://10.0.0.5:8080").await; + assert_eq!(r.status, 409, "{}", r.text); + assert_eq!(r.json["error"]["code"], "preview.taken"); + let r = c + .admin("GET", &format!("/api/v1/hosts/{taken}"), None) + .await; + assert_eq!( + r.json["host"]["upstreams"][0], "http://10.0.0.9:80", + "{}", + r.text + ); + let r = c + .fabrica( + "POST", + "/api/v1/previews/close", + Some(json!({"project": "shop", "branch": "main"})), + ) + .await; + assert_eq!(r.status, 404, "{}", r.text); + + // A preview the token made touches only its own file, and the list holds only previews. + let r = c + .open_preview("shop", "fix-1", "http://10.0.0.5:8080") + .await; + assert_eq!(r.status, 202, "{}", r.text); + assert_eq!(c.settle(&r.json["apply"]).await, "kept"); + let hosts = r.json["apply"]["hosts"].as_array().unwrap().clone(); + assert_eq!(hosts, vec![json!(format!("fix-1--shop.{DOMAIN}"))]); + let r = c.fabrica("GET", "/api/v1/previews", None).await; + assert_eq!(r.status, 200, "{}", r.text); + let listed: Vec<&str> = r.json["items"] + .as_array() + .unwrap() + .iter() + .map(|p| p["hostname"].as_str().unwrap()) + .collect(); + assert_eq!(listed, vec![format!("fix-1--shop.{DOMAIN}").as_str()]); + let mut names = c.host_names().await; + names.sort(); + assert_eq!( + names, + vec![ + format!("fix-1--shop.{DOMAIN}"), + taken.clone(), + "www.example.test".into() + ] + ); + + // An admin can still kill a preview; the scoped token was never needed for that. + let r = c + .admin( + "DELETE", + &format!("/api/v1/previews/fix-1--shop.{DOMAIN}"), + None, + ) + .await; + assert_eq!(r.status, 202, "{}", r.text); + assert_eq!(c.settle(&r.json["apply"]).await, "kept"); + assert!( + !c.host_names() + .await + .iter() + .any(|h| h.starts_with("fix-1--")) + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_preview_token_cannot_point_a_preview_at_this_machine_s_admin_ports() { + let c = Ctl::start("").await; + let control_port = c.api.port(); + for upstream in [ + // control itself, Caddy's admin API, anything on loopback outside the allowed range + format!("http://127.0.0.1:{control_port}"), + "http://127.0.0.1:2019".to_owned(), + "http://localhost:20001".to_owned(), + "http://[::1]:20001".to_owned(), + "http://0.0.0.0:20001".to_owned(), + "http://169.254.169.254:80".to_owned(), + // not in the allow list + "http://192.168.1.10:8080".to_owned(), + "http://other.internal:8080".to_owned(), + // not an upstream at all + "http://user:pw@10.0.0.5:8080".to_owned(), + "http://10.0.0.5:8080/path".to_owned(), + "file:///etc/passwd".to_owned(), + "".to_owned(), + ] { + let r = c.open_preview("shop", "main", &upstream).await; + assert!( + r.status == 422 || r.status == 403, + "{upstream}: {} {}", + r.status, + r.text + ); + assert!( + r.json["error"]["code"].as_str().is_some_and( + |c| c.starts_with("preview.upstream") || c.starts_with("host.upstream") + ), + "{upstream}: {}", + r.text + ); + } + assert!(c.host_names().await.is_empty()); + // Allowed: the private range, the loopback port range, the listed name. + for (b, u) in [ + ("a", "http://10.1.2.3:8080"), + ("b", "http://127.0.0.1:20001"), + ("c", "http://app.internal:3000"), + ] { + let r = c.open_preview("shop", b, u).await; + assert_eq!(r.status, 202, "{u}: {}", r.text); + assert_eq!(c.settle(&r.json["apply"]).await, "kept"); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_preview_lives_until_closed_or_expired() { + let c = Ctl::start("").await; + // Open, with a hostile branch name: the host is safe and the API says where it is. + let r = c + .open_preview( + "github:acme/Web.App", + "feature/Ünï ../../etc", + "http://10.0.0.5:8080", + ) + .await; + assert_eq!(r.status, 202, "{}", r.text); + let host = r.json["preview"]["hostname"].as_str().unwrap().to_owned(); + assert!(host.ends_with(&format!(".{DOMAIN}")), "{host}"); + assert!(host.split('.').next().unwrap().contains("--")); + assert_eq!(r.json["preview"]["url"], format!("https://{host}/")); + assert_eq!(c.settle(&r.json["apply"]).await, "kept"); + let r = c + .fabrica("GET", &format!("/api/v1/previews/{host}"), None) + .await; + assert_eq!(r.status, 200, "{}", r.text); + assert_eq!(r.json["preview"]["branch"], "feature/Ünï ../../etc"); + assert_eq!(r.json["preview"]["state"], "live", "{}", r.text); + + // A new deploy of the same branch moves the same host, it does not add one. + let r = c + .open_preview( + "github:acme/Web.App", + "feature/Ünï ../../etc", + "http://10.0.0.6:8080", + ) + .await; + assert_eq!(r.status, 202, "{}", r.text); + assert_eq!(r.json["preview"]["hostname"], host.as_str()); + assert_eq!(c.settle(&r.json["apply"]).await, "kept"); + let r = c.admin("GET", &format!("/api/v1/hosts/{host}"), None).await; + assert_eq!(r.json["host"]["upstreams"][0], "http://10.0.0.6:8080"); + assert_eq!(c.host_names().await.len(), 1); + + // Closed on merge, by project and branch. + let r = c + .fabrica( + "POST", + "/api/v1/previews/close", + Some(json!({"project": "github:acme/Web.App", "branch": "feature/Ünï ../../etc"})), + ) + .await; + assert_eq!(r.status, 202, "{}", r.text); + assert_eq!(c.settle(&r.json["apply"]).await, "kept"); + assert!(c.host_names().await.is_empty()); + + // Expired: removed by control by itself. + let r = c + .fabrica( + "POST", + "/api/v1/previews", + Some(json!({"project": "shop", "branch": "short", "upstream": "http://10.0.0.5:80", "ttl": 2})), + ) + .await; + assert_eq!(r.status, 202, "{}", r.text); + assert_eq!(c.settle(&r.json["apply"]).await, "kept"); + let t = Instant::now(); + while !c.host_names().await.is_empty() { + assert!( + t.elapsed() < Duration::from_secs(30), + "the expired preview stayed" + ); + tokio::time::sleep(Duration::from_millis(700)).await; + } + let r = c.admin("GET", "/api/v1/history", None).await; + assert!(r.text.contains("expired"), "{}", r.text); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn bad_preview_requests_are_refused_with_a_reason() { + let c = Ctl::start( + "max_ttl_secs = 86400 +default_ttl_secs = 3600", + ) + .await; + for (body, code) in [ + ( + json!({"project": "shop", "branch": "a\nb", "upstream": "http://10.0.0.5:80"}), + "preview.branch", + ), + ( + json!({"project": "shop", "branch": "", "upstream": "http://10.0.0.5:80"}), + "preview.branch", + ), + ( + json!({"project": "sh op", "branch": "main", "upstream": "http://10.0.0.5:80"}), + "preview.project", + ), + ( + json!({"project": "shop", "branch": "main", "upstream": "http://10.0.0.5:80", "ttl": 0}), + "preview.ttl", + ), + ( + json!({"project": "shop", "branch": "main", "upstream": "http://10.0.0.5:80", "ttl": 864000}), + "preview.ttl", + ), + ( + json!({"project": "shop", "branch": "main", "upstream": "http://10.0.0.5:80", "auth": "none"}), + "request.body_unknown_field", + ), + ] { + let r = c + .fabrica("POST", "/api/v1/previews", Some(body.clone())) + .await; + assert_eq!(r.json["error"]["code"], code, "{body}: {}", r.text); + assert!(r.status == 422 || r.status == 400, "{body}: {}", r.text); + } + assert!(c.host_names().await.is_empty()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn without_a_preview_domain_the_api_says_previews_are_off() { + let c = Ctl::start("").await; + // Replace the config with one that has no [previews] section, then restart. + drop(c); + let c2 = { + let dir = TempDir::new("pv-off"); + std::fs::create_dir_all(dir.join("state")).unwrap(); + let api = local(free_port()); + let text = format!( + "listen = \"{api}\"\nstate_dir = \"{st}\"\n\n[routes]\nrepo = \"{repo}\"\n\n[edge]\nconfig = \"{d}/edge.json\"\nshare_revocations = \"{d}/rev.json\"\n\n[caddy]\nconfig = \"{d}/caddy.json\"\n\n[compile]\nhttp_listen = \"127.0.0.1:{h}\"\nhttps_listen = \"127.0.0.1:{hs}\"\ncert_dir = \"{d}\"\nstate_dir = \"{d}\"\naccess_log = \"{d}/a.log\"\ncaddy_credentials_dir = \"{d}\"\n", + st = s(&dir.join("state")), + repo = s(&dir.join("routes.git")), + d = s(dir.path()), + h = free_port(), + hs = free_port(), + ); + std::fs::write(dir.join("control.toml"), text).unwrap(); + let cfg = Config::load(&dir.join("control.toml")).unwrap(); + let (_, tok) = Tokens::new(&dir.join("state")) + .create("fabrica", None, Scope::Previews) + .unwrap(); + let (tx, rx) = tokio::sync::oneshot::channel::<()>(); + tokio::spawn(ianitor_control::serve(cfg, async { + let _ = rx.await; + })); + assert!(wait_for_port(api, Duration::from_secs(20))); + (dir, api, tok, tx) + }; + let auth = format!("Bearer {}", c2.2); + let r = tcp_json( + c2.1, + "POST", + "/api/v1/previews", + &[("Authorization", &auth)], + Some(&json!({"project": "shop", "branch": "main", "upstream": "http://10.0.0.5:80"})), + ) + .await + .unwrap(); + assert_eq!(r.status, 409, "{}", r.text); + assert_eq!(r.json["error"]["code"], "preview.off"); + let _ = c2.3.send(()); +} diff --git a/crates/control/tests/stores.rs b/crates/control/tests/stores.rs index 716880b..d79dca2 100644 --- a/crates/control/tests/stores.rs +++ b/crates/control/tests/stores.rs @@ -27,7 +27,11 @@ fn a_cli_revoke_is_not_lost_while_the_server_records_token_use() { let d = TempDir::new("tok-race"); let server = Tokens::new(d.path()); let values: Vec<_> = (0..150) - .map(|i| server.create(&format!("t{i}"), None).unwrap()) + .map(|i| { + server + .create(&format!("t{i}"), None, Default::default()) + .unwrap() + }) .collect(); let victim = values[75].0.id.clone(); let mut cli = std::process::Command::new(bin) @@ -77,7 +81,9 @@ fn concurrent_creates_from_the_cli_and_the_server_all_survive() { }) .collect(); for i in 0..40 { - server.create(&format!("srv{i}"), None).unwrap(); + server + .create(&format!("srv{i}"), None, Default::default()) + .unwrap(); } for c in &mut clis { assert!(c.wait().unwrap().success()); diff --git a/crates/control/tests/team.rs b/crates/control/tests/team.rs new file mode 100644 index 0000000..a81e2ec --- /dev/null +++ b/crates/control/tests/team.rs @@ -0,0 +1,257 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Team sign-in without Authelia (T4): the setup link makes the founding admin, invites make +//! members, a session cookie identifies them, members cannot do admin things, and browser +//! writes need the UI header. Runs on Windows and Linux (control in this process, no edge). + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::net::SocketAddr; +use std::time::Duration; + +use ianitor_control::Config; +use ianitor_control::team::Team; +use ianitor_testkit::more::{JsonResp, tcp_json}; +use ianitor_testkit::proc::{TempDir, free_port, local, wait_for_port}; +use serde_json::{Value, json}; + +fn s(p: &std::path::Path) -> String { + p.to_string_lossy().replace('\\', "/") +} + +async fn start() -> (TempDir, SocketAddr, tokio::sync::oneshot::Sender<()>) { + let dir = TempDir::new("team"); + std::fs::create_dir_all(dir.join("state")).unwrap(); + let api = local(free_port()); + let text = format!( + "listen = \"{api}\"\nstate_dir = \"{st}\"\n\n[routes]\nrepo = \"{repo}\"\n\n[edge]\nconfig = \"{d}/edge.json\"\nshare_revocations = \"{d}/rev.json\"\n\n[caddy]\nconfig = \"{d}/caddy.json\"\n\n[compile]\nhttp_listen = \"127.0.0.1:{h}\"\nhttps_listen = \"127.0.0.1:{hs}\"\ncert_dir = \"{d}\"\nstate_dir = \"{d}\"\naccess_log = \"{d}/a.log\"\ncaddy_credentials_dir = \"{d}\"\n", + st = s(&dir.join("state")), + repo = s(&dir.join("routes.git")), + d = s(dir.path()), + h = free_port(), + hs = free_port(), + ); + std::fs::write(dir.join("control.toml"), text).unwrap(); + let cfg = Config::load(&dir.join("control.toml")).unwrap(); + let (tx, rx) = tokio::sync::oneshot::channel::<()>(); + tokio::spawn(ianitor_control::serve(cfg, async { + let _ = rx.await; + })); + assert!(wait_for_port(api, Duration::from_secs(20))); + (dir, api, tx) +} + +async fn req(api: SocketAddr, m: &str, p: &str, h: &[(&str, &str)], b: Option) -> JsonResp { + tcp_json(api, m, p, h, b.as_ref()).await.unwrap() +} + +fn cookie_of(r: &JsonResp) -> String { + let set = r + .headers + .iter() + .find(|(n, _)| n == "set-cookie") + .map(|(_, v)| v.clone()) + .expect("a Set-Cookie"); + for part in ["HttpOnly", "Secure", "SameSite=Strict", "Path=/"] { + assert!(set.contains(part), "{set}"); + } + assert!(set.starts_with("__Host-ianitor=ise_"), "{set}"); + set.split(';').next().unwrap().to_owned() +} + +async fn sign_in(api: SocketAddr, code: &str, name: &str) -> (JsonResp, String) { + let r = req( + api, + "POST", + "/api/v1/session", + &[("X-Ianitor-UI", "1"), ("Sec-Fetch-Site", "same-origin")], + Some(json!({"code": code, "name": name, "device": "Laptop"})), + ) + .await; + assert_eq!(r.status, 200, "{}", r.text); + let c = cookie_of(&r); + (r, c) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_setup_link_then_invites_sign_a_team_in() { + let (dir, api, _stop) = start().await; + let (setup, _) = Team::new(&dir.join("state")).setup_code().unwrap(); + + // The door refuses bad codes, other sites and pages that are not the UI. + for (headers, code) in [ + (vec![("X-Ianitor-UI", "1")], "isc_wrong"), + (vec![], setup.as_str()), + ( + vec![("X-Ianitor-UI", "1"), ("Sec-Fetch-Site", "cross-site")], + setup.as_str(), + ), + ] { + let r = req( + api, + "POST", + "/api/v1/session", + &headers, + Some(json!({"code": code})), + ) + .await; + assert!( + r.status == 401 || r.status == 403, + "{headers:?}: {}", + r.text + ); + assert!(!r.headers.iter().any(|(n, _)| n == "set-cookie")); + } + + let (r, mark) = sign_in(api, &setup, "Mark").await; + assert_eq!(r.json["member"]["role"], "admin"); + let ov = req(api, "GET", "/api/v1/overview", &[("Cookie", &mark)], None).await; + assert_eq!(ov.status, 200, "{}", ov.text); + assert_eq!(ov.json["viewer"]["via"], "session"); + assert_eq!(ov.json["viewer"]["name"], "Mark"); + // The setup link worked once. + let r = req( + api, + "POST", + "/api/v1/session", + &[("X-Ianitor-UI", "1")], + Some(json!({"code": setup})), + ) + .await; + assert_eq!(r.status, 401, "{}", r.text); + + // A browser write without the UI header is refused (CSRF), with it it works. + let r = req( + api, + "POST", + "/api/v1/team/invites", + &[("Cookie", &mark)], + Some(json!({"name": "Petra"})), + ) + .await; + assert_eq!(r.status, 403, "{}", r.text); + assert_eq!(r.json["error"]["code"], "request.csrf"); + let r = req( + api, + "POST", + "/api/v1/team/invites", + &[("Cookie", &mark), ("X-Ianitor-UI", "1")], + Some(json!({"name": "Petra", "role": "member"})), + ) + .await; + assert_eq!(r.status, 201, "{}", r.text); + let code = r.json["link_fragment"] + .as_str() + .unwrap() + .strip_prefix("#signin=") + .unwrap() + .to_owned(); + + // Petra is a member: hosts yes, tokens, the team and the engine no. + let (_, petra) = sign_in(api, &code, "Not Petra").await; + let team = req(api, "GET", "/api/v1/team", &[("Cookie", &petra)], None).await; + assert_eq!(team.json["me"]["name"], "Petra", "{}", team.text); + for (m, p, b) in [ + ("GET", "/api/v1/tokens", None), + ("POST", "/api/v1/tokens", Some(json!({"name": "x"}))), + ( + "POST", + "/api/v1/team/invites", + Some(json!({"name": "Eve", "role": "admin"})), + ), + ("POST", "/api/v1/engine", Some(json!({"target": "caddy"}))), + ] { + let r = req(api, m, p, &[("Cookie", &petra), ("X-Ianitor-UI", "1")], b).await; + assert_eq!(r.status, 403, "{m} {p}: {}", r.text); + assert_eq!(r.json["error"]["code"], "team.admin_only", "{m} {p}"); + } + let r = req( + api, + "POST", + "/api/v1/hosts", + &[("Cookie", &petra), ("X-Ianitor-UI", "1")], + Some( + json!({"host": {"hostname": "wiki.example.test", "upstreams": ["http://10.0.0.2:80"]}}), + ), + ) + .await; + assert_eq!(r.status, 202, "{}", r.text); + + // A member records their Tessera root; the list shows its match code. + let root = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc"; + let r = req( + api, + "PUT", + "/api/v1/team/me/root", + &[("Cookie", &petra), ("X-Ianitor-UI", "1")], + Some(json!({"tessera_root": root})), + ) + .await; + assert_eq!(r.status, 200, "{}", r.text); + let team = req(api, "GET", "/api/v1/team", &[("Cookie", &mark)], None).await; + let p = team.json["members"] + .as_array() + .unwrap() + .iter() + .find(|m| m["name"] == "Petra") + .unwrap() + .clone(); + assert_eq!(p["match_code"], "016 810"); + + // Removing Petra signs her out; a forged cookie gets nothing; the last admin stays. + let id = p["id"].as_str().unwrap(); + let r = req( + api, + "DELETE", + &format!("/api/v1/team/members/{id}"), + &[("Cookie", &mark), ("X-Ianitor-UI", "1")], + None, + ) + .await; + assert_eq!(r.status, 200, "{}", r.text); + let r = req(api, "GET", "/api/v1/overview", &[("Cookie", &petra)], None).await; + assert_eq!(r.status, 401, "{}", r.text); + let r = req( + api, + "GET", + "/api/v1/overview", + &[("Cookie", "__Host-ianitor=ise_forged")], + None, + ) + .await; + assert_eq!(r.status, 401); + let me = team.json["members"] + .as_array() + .unwrap() + .iter() + .find(|m| m["name"] == "Mark") + .unwrap()["id"] + .as_str() + .unwrap() + .to_owned(); + let r = req( + api, + "DELETE", + &format!("/api/v1/team/members/{me}"), + &[("Cookie", &mark), ("X-Ianitor-UI", "1")], + None, + ) + .await; + assert_eq!(r.status, 409, "{}", r.text); + assert_eq!(r.json["error"]["code"], "team.last_admin"); + + // Signing out ends this browser's session. + let r = req( + api, + "POST", + "/api/v1/session/end", + &[("Cookie", &mark), ("X-Ianitor-UI", "1")], + None, + ) + .await; + assert_eq!(r.status, 200, "{}", r.text); + let r = req(api, "GET", "/api/v1/overview", &[("Cookie", &mark)], None).await; + assert_eq!(r.status, 401); +} diff --git a/crates/core/src/compile/mod.rs b/crates/core/src/compile/mod.rs index c03b71c..190a074 100644 --- a/crates/core/src/compile/mod.rs +++ b/crates/core/src/compile/mod.rs @@ -109,9 +109,13 @@ fn check_options(o: &CompileOptions) -> Result<(), CompileError> { Ok(()) } -/// Paths end up inside JSON strings and Caddy `{file.*}` placeholders. +/// Paths end up inside JSON strings and Caddy `{file.*}` placeholders. Absolute: `/…` on +/// Linux, or a drive path with forward slashes on Windows (`C:/ProgramData/Ianitor/…`, which +/// Caddy and Go read as is; control writes backslashes as `/`, see [`windows_path`]). fn check_path(p: &str) -> Result<(), &'static str> { - if !p.starts_with('/') { + let drive = + p.len() >= 3 && p.as_bytes()[0].is_ascii_alphabetic() && &p.as_bytes()[1..3] == b":/"; + if !p.starts_with('/') && !drive { return Err("it must be an absolute path"); } if p.len() > 1024 { @@ -126,6 +130,19 @@ fn check_path(p: &str) -> Result<(), &'static str> { Ok(()) } +/// A Windows path as the compilers take it: `C:\ProgramData\Ianitor` → `C:/ProgramData/Ianitor`. +/// Anything that is not a drive path is returned unchanged (and a Linux path with a backslash +/// is still refused by the option check). +pub fn windows_path(p: &str) -> String { + let b = p.as_bytes(); + if b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b[2] == b'\\' || b[2] == b'/') + { + p.replace('\\', "/") + } else { + p.to_owned() + } +} + /// Identity headers never accepted from clients on forward-auth hosts: Authelia's four, then /// any other configured copy header (case-insensitive, no duplicates). fn strip_headers(fa: &crate::ForwardAuth) -> Vec { 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/pki.rs b/crates/core/src/pki.rs index 39383e8..68774a9 100644 --- a/crates/core/src/pki.rs +++ b/crates/core/src/pki.rs @@ -32,8 +32,8 @@ use ring::rand::{SecureRandom, SystemRandom}; pub use domi_pki::{ CertInfo, DEVICE_DAYS, EkuInfo, INTERMEDIATE_DAYS, INTERMEDIATE_OPENSSL_EXT, KeyPair, - KeyUsageInfo, ORG, ROOT_CN, ROOT_DAYS, SERVER_DAYS, SERVER_RENEW_DAYS, der_to_pem, - match_code, openssl_sign_command, sha256_hex, + KeyUsageInfo, ORG, ROOT_CN, ROOT_DAYS, SERVER_DAYS, SERVER_RENEW_DAYS, der_to_pem, match_code, + openssl_sign_command, sha256_hex, }; /// Subject CN of the intermediate. Signers refuse a CSR whose CN does not start with this. diff --git a/crates/core/src/preview.rs b/crates/core/src/preview.rs new file mode 100644 index 0000000..68d68bb --- /dev/null +++ b/crates/core/src/preview.rs @@ -0,0 +1,149 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Branch previews (Fabrica docs/32_coherence.md, T4): every branch of a project gets the host +//! `--.`. Branch 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..b2d90aa --- /dev/null +++ b/crates/core/tests/preview.rs @@ -0,0 +1,301 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Preview host names (T4, written before the code): `--.`. +//! Branch 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&