Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6ba3fa4b17 | |||
| 5df34bfae6 | |||
| 7322bbd856 | |||
| 0213021bb1 | |||
| c45dafa2a3 | |||
| 4d87537a76 | |||
| 09b8313a04 | |||
| 057abbc954 | |||
| 457aea86ca | |||
| 23a283ece9 | |||
| ba3a060b2e | |||
| 503916492d |
@@ -0,0 +1,2 @@
|
||||
# Local Fabrica runs: records, logs and artifacts (Fabrica core docs/FORMATS.md)
|
||||
runs/
|
||||
@@ -0,0 +1,11 @@
|
||||
# Ianitor Domi declares itself to Fabrica (Fabrica core docs/FORMATS.md, "Fabrica: the app"): a server part only,
|
||||
# the reverse proxy with its control plane and web UI, deployed by .fabrica/artifex/deploy.yaml through the server's
|
||||
# fabrica-deploy@ianitor. Fabrica's Apps screen shows one card for it: Deploy, then the Custos card. The colour is
|
||||
# the murex accent (packages/ui/src/tokens.css, --accent).
|
||||
name: Ianitor
|
||||
icon: globe
|
||||
color: "#e0a3dc"
|
||||
parts:
|
||||
server:
|
||||
pipeline: deploy
|
||||
input: ianitor
|
||||
@@ -0,0 +1,15 @@
|
||||
# Ianitor Domi onto the server (Fabrica docs/04_deploy.md): `fabrica deploy ianitor`, or Fabrica's Apps → Ianitor →
|
||||
# Deploy. The NixOS runner starts fabrica-deploy@ianitor: the server's clone is fast-forwarded, the flake input
|
||||
# `ianitor` updated (inputs.ianitor.nixosModules.ianitor, docs/deploy/configuration-server.patch), the system
|
||||
# switched, the health check asked, and the switch rolled back if it does not answer. After a deploy run
|
||||
# deploy/test-access.sh from a LAN machine (CLAUDE.md).
|
||||
name: deploy
|
||||
on:
|
||||
manual: true
|
||||
runner: nixos
|
||||
steps:
|
||||
- id: approve
|
||||
approve: "Deploy Ianitor ${{ commit }} to the server?"
|
||||
- id: switch
|
||||
needs: [approve]
|
||||
deploy: ianitor
|
||||
+16
-2
@@ -7,6 +7,8 @@
|
||||
import { onMount } from "svelte";
|
||||
import { Button, Dialog, Icon } from "@ianitor/ui";
|
||||
import type { IconName } from "@ianitor/ui";
|
||||
import EngineChip from "./components/EngineChip.svelte";
|
||||
import EnginePopover from "./components/EnginePopover.svelte";
|
||||
import TopBanners from "./components/TopBanners.svelte";
|
||||
import { app, navigate, refresh, startPolling } from "./lib/app.svelte";
|
||||
import { remembered } from "./lib/applies";
|
||||
@@ -72,7 +74,12 @@
|
||||
|
||||
function signIn() {
|
||||
const w = window.open("/signed-in", "ianitor-sign-in");
|
||||
if (!w) location.href = `/signed-in?back=${encodeURIComponent(app.path)}`;
|
||||
if (!w) {
|
||||
// The new tab was blocked: this tab goes to the sign-in, so an open form is saved first
|
||||
// (sessionStorage, this tab only) and comes back after it (§10).
|
||||
window.dispatchEvent(new Event("ianitor:save-draft"));
|
||||
location.href = `/signed-in?back=${encodeURIComponent(app.path)}`;
|
||||
}
|
||||
}
|
||||
|
||||
async function signedInAgain() {
|
||||
@@ -99,7 +106,7 @@
|
||||
{#if app.overview?.site?.auth_logout_url}<a class="domi-btn link" href={app.overview.site.auth_logout_url}>Sign out</a>{/if}
|
||||
</div>
|
||||
</nav>
|
||||
<header class="topbar"><span class="ia-wordmark">IANITOR DOMI</span></header>
|
||||
<header class="topbar"><span class="ia-wordmark">IANITOR DOMI</span>{#if app.phone}<EngineChip />{/if}</header>
|
||||
<main id="main" tabindex="-1">
|
||||
<TopBanners />
|
||||
{#if route.view === "hosts"}
|
||||
@@ -121,6 +128,13 @@
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{#if app.panel?.kind === "engine"}
|
||||
<EnginePopover onclose={() => {
|
||||
app.panel = null;
|
||||
document.querySelector<HTMLElement>("[data-engine-chip]")?.focus();
|
||||
}} />
|
||||
{/if}
|
||||
|
||||
<div class="ia-toasts" role="status" aria-live="polite">
|
||||
{#each app.toasts as t (t.id)}<div class="ia-toast"><Icon name="check" />{t.text}</div>{/each}
|
||||
</div>
|
||||
|
||||
@@ -4,10 +4,10 @@
|
||||
<script lang="ts">
|
||||
// Handoff §7.4 and §7.5: the last-change bar with Undo (1 click), and the reverted / not
|
||||
// applied banner that stands in for its first line.
|
||||
import { Banner, Button, Icon, Progress } from "@ianitor/ui";
|
||||
import { Banner, Button, Details, Icon, Progress } from "@ianitor/ui";
|
||||
import { ApiError, call, del, newKey, post, sentence } from "../lib/api";
|
||||
import { app, refresh, secondsLeft, toast } from "../lib/app.svelte";
|
||||
import { firstSentence, when } from "../lib/format";
|
||||
import { atTime, firstSentence, when } from "../lib/format";
|
||||
import type { ApplyView } from "../lib/types";
|
||||
|
||||
let { onshowsteps, onedit }: { onshowsteps: (id: string) => void; onedit: (a: ApplyView, field?: string) => void } = $props();
|
||||
@@ -21,7 +21,7 @@
|
||||
let pushing = $state(false);
|
||||
const dismissKey = $derived(last ? `apply:${last.id}` : "");
|
||||
|
||||
function runningHeading(summary: string, a: ApplyView | null): string {
|
||||
function runningHeading(summary: string, a: { kind: string; hosts: string[]; summary: string } | null): string {
|
||||
if (!a) return summary;
|
||||
const h = a.hosts[0] ?? "";
|
||||
switch (a.kind) {
|
||||
@@ -29,6 +29,8 @@
|
||||
case "remove": return `Removing ${h}`;
|
||||
case "edit": return `Changing ${h}`;
|
||||
case "share_links": return `Turning on share links for ${h}`;
|
||||
case "undo": return `Undoing: ${a.summary.replace(/^Undid: /, "")}`;
|
||||
case "restore": return a.summary.replace(/^Restored /, "Restoring ");
|
||||
default: return summary;
|
||||
}
|
||||
}
|
||||
@@ -85,7 +87,29 @@
|
||||
});
|
||||
const pushFailed = $derived(last?.state === "kept" && last.push?.state === "failed");
|
||||
const undoReason = $derived(undo?.blocked && undo.blocked.code !== "undo.nothing" ? undo.blocked.message : null);
|
||||
const watchLeft = $derived(last?.watch ? secondsLeft(last.watch.ends_at) : null);
|
||||
// Ticks every second on the local clock (§7.2), not only on the 5 s poll.
|
||||
const watchLeft = $derived(
|
||||
active?.watch_ends_at ? secondsLeft(active.watch_ends_at) : active?.seconds_left != null ? active.seconds_left : null,
|
||||
);
|
||||
// The outcome's offer, by code (§7.5).
|
||||
const offer = $derived.by(() => {
|
||||
const c = last?.reason?.code ?? "";
|
||||
if (/^apply\.reverted\.(not_found|redirect|sign_in)$/.test(c)) return { label: "Edit health check", field: "health_check.path" };
|
||||
if (/^apply\.(interrupted|reverted\.edge_lost|interrupted\.queued)$/.test(c)) return { label: "Try again", field: last?.reason?.field ?? undefined };
|
||||
if (/^apply\.failed\.(reload|build|edge_unreachable)$/.test(c)) return null;
|
||||
if (last?.attempted_host) return { label: "Edit and try again", field: last?.reason?.field ?? undefined };
|
||||
return null;
|
||||
});
|
||||
const pushLine = $derived.by(() => {
|
||||
const p = last?.push;
|
||||
const remote = "Gitea";
|
||||
switch (p?.error_code) {
|
||||
case "push.failed.rejected": return `Kept, but ${remote} has changes Ianitor does not have, so nothing was sent. Nothing is lost on this server.`;
|
||||
case "push.failed.auth": return `Kept, but ${remote} refused Ianitor's access key. Check the key in Custos.`;
|
||||
default: return `Kept, but not yet saved to ${remote}: ${remote} did not answer.${p?.next_try_at ? ` Ianitor tries again ${atTime(p.next_try_at, app.now)}.` : " Ianitor tries again by itself."}`;
|
||||
}
|
||||
});
|
||||
const canPushNow = $derived(pushFailed && last?.push?.error_code !== "push.failed.rejected");
|
||||
</script>
|
||||
|
||||
{#if last && (last.state === "reverted" || last.state === "failed") && !app.dismissed.includes(dismissKey)}
|
||||
@@ -93,8 +117,9 @@
|
||||
<Banner tone="notice" ondismiss={() => (app.dismissed = [...app.dismissed, dismissKey])}>
|
||||
{#snippet title()}<span class="ia-status" data-s="reverted"><Icon name="undo" /><span class="word">{last.state === "failed" ? "not applied" : "reverted"}</span></span> <strong>{parts[0]}</strong>{/snippet}
|
||||
{#if parts[1]}Reason: {parts[1]}{/if}
|
||||
{#if last.reason?.detail && last.reason.code.startsWith("apply.failed.")}<Details detail={last.reason.detail} />{/if}
|
||||
{#snippet actions()}
|
||||
{#if last.attempted_host}<Button variant="outline" onclick={() => onedit(last, last.reason?.field ?? undefined)}>Edit and try again</Button>{/if}
|
||||
{#if offer}<Button variant="outline" onclick={() => onedit(last, offer?.field)}>{offer.label}</Button>{/if}
|
||||
{/snippet}
|
||||
</Banner>
|
||||
{/if}
|
||||
@@ -104,8 +129,8 @@
|
||||
{#if active}
|
||||
<div class="grow">
|
||||
<div class="ia-status" data-s="running"><Icon name="clock" /><span class="word">{active.state === "queued" ? "waiting" : active.state === "watching" ? "watching" : "applying"}</span>
|
||||
<span>{runningHeading(active.summary, last && last.id === active.id ? last : null)}</span></div>
|
||||
<div class="ia-sub">{active.state === "queued" ? "Waiting for another change to finish" : `${watchLeft ?? active.seconds_left ?? 0} s left`}</div>
|
||||
<span>{runningHeading(active.summary, active.kind ? active : null)}</span></div>
|
||||
<div class="ia-sub">{active.state === "queued" ? "Waiting for another change to finish" : active.state === "watching" ? `${watchLeft ?? 0} s left` : "Checking and loading the change"}</div>
|
||||
{#if active.state === "watching" && watchLeft != null}
|
||||
{@const total = o?.site?.watch_seconds ?? 60}
|
||||
<Progress label="Health watch" max={total} now={total - watchLeft} text="{watchLeft} seconds left" />
|
||||
@@ -116,7 +141,7 @@
|
||||
<div class="grow">
|
||||
{#if last.state === "kept"}
|
||||
<div><span class="ia-status" data-s="kept"><Icon name="check" /><span class="word">kept</span></span> {last.summary}</div>
|
||||
<div class="ia-sub" class:warn={pushFailed}>{pushFailed ? "Kept, but not yet saved to Gitea. Ianitor tries again by itself." : keptLine}</div>
|
||||
<div class="ia-sub" class:warn={pushFailed}>{pushFailed ? pushLine : keptLine}</div>
|
||||
{:else if undo?.target}
|
||||
<div>Undo: {undo.target.summary}</div>
|
||||
{/if}
|
||||
@@ -125,7 +150,7 @@
|
||||
{#if undoReason}<div class="ia-sub" id="undo-reason">{undoReason}</div>{/if}
|
||||
{#if !undo?.target}<div class="ia-sub">Nothing to undo yet.</div>{/if}
|
||||
</div>
|
||||
{#if pushFailed}<Button onclick={pushNow} pending={pushing}>Try now</Button>{/if}
|
||||
{#if canPushNow}<Button onclick={pushNow} pending={pushing}>Try now</Button>{/if}
|
||||
{#if undo?.target}
|
||||
<Button icon="undo" onclick={doUndo} pending={undoing} disabled={!!undoReason || !undo.available}
|
||||
describedby={undoReason ? "undo-reason" : undefined}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<!-- This Source Code Form is subject to the terms of the Mozilla Public
|
||||
- License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
|
||||
<script lang="ts">
|
||||
// Handoff §2.4: the engine chip (click 1 of the switch). On the main screen's header on a
|
||||
// desktop, in the top bar on a phone (§2.16).
|
||||
import { Icon } from "@ianitor/ui";
|
||||
import { app } from "../lib/app.svelte";
|
||||
|
||||
const o = $derived(app.overview);
|
||||
const engineName = $derived(o?.engine.running === "caddy" ? "Caddy" : "Pingora");
|
||||
const engineLabel = $derived(
|
||||
o?.engine.state === "switching" ? "Engine: switching" : `Engine: ${engineName}${o?.engine.state === "stopped" ? ", not answering" : ""}. Change engine`,
|
||||
);
|
||||
</script>
|
||||
|
||||
{#if o}
|
||||
<button type="button" class="ia-engine" data-engine-chip aria-haspopup="dialog" aria-expanded={app.panel?.kind === "engine"} aria-label={engineLabel}
|
||||
onclick={() => (app.panel = app.panel?.kind === "engine" ? null : { kind: "engine" })}>
|
||||
{#if o.engine.state === "switching"}<Icon name="clock" /> Engine Switching…{:else}
|
||||
<span class="ia-status" data-s={o.engine.state === "stopped" ? "down" : "healthy"}><span class="ia-dot"></span></span>
|
||||
<small class="desktop">Engine</small> {engineName}{#if o.engine.running === "caddy"} <small>(fallback)</small>{/if}{/if}
|
||||
<Icon name="chevron" />
|
||||
</button>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
@media (max-width: 719.98px) { .desktop { display: none; } }
|
||||
</style>
|
||||
@@ -4,11 +4,11 @@
|
||||
<script lang="ts">
|
||||
// Handoff §9: the engine popover. Click 1 is the chip, click 2 "Switch to Caddy" (the popover
|
||||
// is the confirmation). The switch runs in control; this polls GET /engine until it ends.
|
||||
import { onDestroy } from "svelte";
|
||||
import { Banner, Button, Dialog, Icon, Progress } from "@ianitor/ui";
|
||||
import { onDestroy, onMount } from "svelte";
|
||||
import { Banner, Button, Details, Dialog, Icon, Progress } from "@ianitor/ui";
|
||||
import { call, get, newKey, sentence } from "../lib/api";
|
||||
import { app, refresh } from "../lib/app.svelte";
|
||||
import { when } from "../lib/format";
|
||||
import { whenInline } from "../lib/format";
|
||||
import type { EngineView } from "../lib/types";
|
||||
|
||||
let { onclose }: { onclose: () => void } = $props();
|
||||
@@ -23,7 +23,17 @@
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
onDestroy(() => clearTimeout(timer));
|
||||
|
||||
const activeLinks = $derived(app.overview?.hosts.filter((h) => h.share_links).length ?? 0);
|
||||
let activeLinks = $state(0);
|
||||
onMount(async () => {
|
||||
try {
|
||||
const l = await get<{ items: { state: string }[] }>("/share-links", { quiet: true });
|
||||
activeLinks = l.items.filter((x) => x.state === "active").length;
|
||||
} catch {
|
||||
/* the count is only a hint */
|
||||
}
|
||||
});
|
||||
const fr = $derived(e?.fallback_ready ?? null);
|
||||
const differs = $derived(fr ? fr.compared - fr.matched : 0);
|
||||
const notReady = $derived(running === "pingora" && !e?.fallback_ready?.built_at);
|
||||
const disabledReason = $derived(!e?.switchable ? "This server does not let Ianitor switch engines." : notReady ? "Caddy is not ready: its settings have not been built yet." : null);
|
||||
|
||||
@@ -62,17 +72,21 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<Dialog title="Serving with {name}" kind="popover" modal={false} {onclose}>
|
||||
<Dialog title={e?.state === "stopped" ? `${name} is not answering` : `Serving with ${name}`} kind="popover" modal={false} escape={!switching} toggle="[data-engine-chip]" {onclose}>
|
||||
<p class="ia-label">Engine</p>
|
||||
{#if e?.state === "stopped"}
|
||||
<p><strong>{name} is not answering.</strong> Visitors may not reach any host. Switching to {other} is the quickest way back.</p>
|
||||
<p>Visitors may not reach any host. Switching to {other} is the quickest way back.</p>
|
||||
{:else}
|
||||
<p class="ia-text2">
|
||||
{#if e?.since}Since {when(e.since, app.now)}. {/if}
|
||||
{#if e?.since}Since {whenInline(e.since, app.now)}. {/if}
|
||||
{#if running === "pingora"}
|
||||
{#if notReady}Caddy is not ready: its settings have not been built yet.{:else}Caddy is ready with the same routes: built {when(e?.fallback_ready?.built_at, app.now)}{e?.fallback_ready?.current ? "" : " (it is rebuilt from the current routes when you switch)"}.{/if}
|
||||
{#if notReady}Caddy is not ready: its settings have not been built yet.{:else if differs > 0}Caddy was built {whenInline(fr?.built_at, app.now)} with the same routes, but {differs} of {fr?.compared} {fr?.compared === 1 ? "host" : "hosts"} {differs === 1 ? "behaves" : "behave"} differently on it.{:else}Caddy is ready with the same routes: built {whenInline(fr?.built_at, app.now)}{fr?.compared ? (fr.compared === 1 ? ", and the host behaves the same" : `, and all ${fr.compared} hosts behave the same`) : ""}.{/if}
|
||||
{#if !notReady && !fr?.current} It is rebuilt from the current routes when you switch.{/if}
|
||||
{:else}Pingora is ready with the same routes.{/if}
|
||||
</p>
|
||||
{#if running === "pingora" && !notReady && fr?.differences.length}
|
||||
<Details detail={fr.differences.join("\n")} />
|
||||
{/if}
|
||||
{/if}
|
||||
<div class="ia-card">
|
||||
<p><strong>What happens</strong></p>
|
||||
@@ -81,10 +95,10 @@
|
||||
<li>Open connections close; videos and uploads in progress restart.</li>
|
||||
<li>Hosts and certificates stay the same.</li>
|
||||
{#if running === "pingora"}
|
||||
<li>Share links stop working while Caddy serves: visitors with a link get the normal sign-in. They work again when you switch back.{#if activeLinks} Hosts with share links: {activeLinks}.{/if}</li>
|
||||
<li>Changes wait while Caddy serves; switch back to make them.</li>
|
||||
<li>Share links stop working while Caddy serves: visitors with a link get the normal sign-in. They work again when you switch back.{#if activeLinks}{" "}{activeLinks === 1 ? "1 share link is" : `${activeLinks} share links are`} active.{/if}</li>
|
||||
<li>Changes keep working: Ianitor tries each one on Caddy and undoes it if a host stops answering.</li>
|
||||
{:else}
|
||||
<li>Share links work again, and changes can be made again.</li>
|
||||
<li>Share links work again.</li>
|
||||
{/if}
|
||||
<li>This page may lose contact for a few seconds.</li>
|
||||
</ul>
|
||||
|
||||
@@ -89,7 +89,7 @@
|
||||
}
|
||||
|
||||
const blocked = $derived(changesBlocked());
|
||||
const shareReason = $derived(!app.overview?.site?.share_links_available ? (underCaddy ? "Share links are paused while Caddy serves." : "Share links are not set up on this server.") : null);
|
||||
const shareReason = $derived(!app.overview?.site?.share_links_available ? (underCaddy ? "Share links are off while Caddy serves." : "Share links are not set up on this server.") : null);
|
||||
</script>
|
||||
|
||||
<div class="ia-list" role="table" aria-label="Hosts">
|
||||
@@ -111,7 +111,7 @@
|
||||
<span class="ia-sub phone">{w}{phoneDetail(h) ? ` · ${phoneDetail(h)}` : ""}</span>
|
||||
</span>
|
||||
<span role="cell" class="desktop">
|
||||
<span>{h.upstreams[0] ?? ""}</span>{#if h.upstreams.length > 1} <span class="ia-muted">+{h.upstreams.length - 1} more</span>{/if}
|
||||
<span>{h.upstreams[0] ?? ""}</span>{#if h.upstreams.length > 1}{" "}<span class="ia-muted">+{h.upstreams.length - 1} more</span>{/if}
|
||||
<span class="ia-sub" class:problem={s.problem} style="display:block">{running.includes(h.hostname) ? "Changing now · " : ""}{s.text}</span>
|
||||
{#if h.certificate.state === "pending"}<span class="ia-sub" style="display:block">Waiting for Let's Encrypt to issue the certificate.</span>{/if}
|
||||
{#if h.certificate.state === "failed"}
|
||||
|
||||
@@ -52,7 +52,9 @@
|
||||
|
||||
function pick(it: Item) {
|
||||
if (it.reason) return;
|
||||
close(false);
|
||||
// Focus back on More first: a dialog the item opens returns focus there when it closes
|
||||
// (§2.9), not to a menu item that no longer exists.
|
||||
close(true);
|
||||
it.run();
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
import { Banner, Button, Details, Dialog, Icon, Segmented } from "@ianitor/ui";
|
||||
import ApplyProgress from "./ApplyProgress.svelte";
|
||||
import { ApiError, call, del, get, newKey, sentence } from "../lib/api";
|
||||
import { app, changesBlocked, refresh, toast } from "../lib/app.svelte";
|
||||
import { app, changesBlocked, refresh, restoreLastKept, toast } from "../lib/app.svelte";
|
||||
import { FINAL, follow } from "../lib/applies";
|
||||
import { firstSentence } from "../lib/format";
|
||||
import type { ApplyView, ErrorBody, HeaderRule, HostSpec } from "../lib/types";
|
||||
@@ -62,6 +62,8 @@
|
||||
|
||||
// ---- the apply
|
||||
let apply = $state<ApplyView | null>(null);
|
||||
let restoring = $state(false);
|
||||
let restoreProblem = $state<string | null>(null);
|
||||
let phase = $state<"form" | "progress">("form");
|
||||
let stop: (() => void) | undefined;
|
||||
let closeTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
@@ -128,16 +130,43 @@
|
||||
rev = app.overview?.rev ?? null;
|
||||
if (!signinOk) host.auth = "none";
|
||||
}
|
||||
loading = false;
|
||||
if (focusField) {
|
||||
if (focusField.startsWith("health_check")) more = true;
|
||||
setTimeout(() => document.getElementById(fieldId(focusField))?.focus(), 0);
|
||||
// A form saved before this tab went to sign in comes back (App.svelte, signIn).
|
||||
try {
|
||||
const raw = sessionStorage.getItem(DRAFT);
|
||||
const d = raw ? (JSON.parse(raw) as { hostname: string; host: typeof host }) : null;
|
||||
if (d && d.hostname === (hostname ?? "") && !resume) {
|
||||
Object.assign(host, d.host);
|
||||
more = more || d.host.hc || d.host.req.length > 0 || d.host.resp.length > 0;
|
||||
}
|
||||
sessionStorage.removeItem(DRAFT);
|
||||
} catch {
|
||||
/* no storage: nothing to bring back */
|
||||
}
|
||||
loading = false;
|
||||
if (phase === "form") {
|
||||
// The Dialog focused its heading while this said "Loading…": now the first field
|
||||
// (Hostname; Send traffic to when editing), so typing right after opening works.
|
||||
const f = focusField ?? (hostname ? "upstreams[0]" : "hostname");
|
||||
if (f.startsWith("health_check")) more = true;
|
||||
setTimeout(() => document.getElementById(fieldId(f))?.focus(), 0);
|
||||
}
|
||||
window.addEventListener("ianitor:save-draft", saveDraft);
|
||||
});
|
||||
|
||||
const DRAFT = "ianitor-draft";
|
||||
function saveDraft() {
|
||||
if (phase !== "form") return;
|
||||
try {
|
||||
sessionStorage.setItem(DRAFT, JSON.stringify({ hostname: hostname ?? "", host: $state.snapshot(host) }));
|
||||
} catch {
|
||||
/* no storage */
|
||||
}
|
||||
}
|
||||
|
||||
onDestroy(() => {
|
||||
stop?.();
|
||||
clearTimeout(closeTimer);
|
||||
if (typeof window !== "undefined") window.removeEventListener("ianitor:save-draft", saveDraft);
|
||||
});
|
||||
|
||||
function fieldId(f: string): string {
|
||||
@@ -226,6 +255,7 @@
|
||||
function onApply(a: ApplyView) {
|
||||
apply = a;
|
||||
if (a.state === "kept") {
|
||||
if (a.kind !== "remove") app.focusHost = a.hosts[0] ?? null;
|
||||
closeTimer = setTimeout(() => onclose(), 1500);
|
||||
}
|
||||
}
|
||||
@@ -291,6 +321,10 @@
|
||||
return `Removing ${h}`;
|
||||
case "share_links":
|
||||
return `Turning on share links for ${h}`;
|
||||
case "undo":
|
||||
return `Undoing: ${apply.summary.replace(/^Undid: /, "")}`;
|
||||
case "restore":
|
||||
return apply.summary.replace(/^Restored /, "Restoring ");
|
||||
default:
|
||||
return `Changing ${h}`;
|
||||
}
|
||||
@@ -321,7 +355,7 @@
|
||||
{#if apply.state === "kept"}
|
||||
<Banner tone="kept">
|
||||
{#snippet title()}<span class="ia-status" data-s="kept"><span class="word">kept</span></span> <strong>{apply?.hosts[0] ?? name}</strong> {apply?.kind === "remove" ? "is removed." : "is live."}{/snippet}
|
||||
{apply.reason?.message ?? ""}{#if apply.commit_short} Saved as commit {apply.commit_short}{apply.push?.state === "pushed" ? " and pushed to Gitea" : ""}.{/if}
|
||||
{(apply.reason?.message ?? "").replace(/^\S+ is (live|removed)\.\s*/, "")}{#if apply.commit_short} Saved as commit {apply.commit_short}{apply.push?.state === "pushed" ? " and pushed to Gitea" : ""}.{/if}
|
||||
</Banner>
|
||||
{:else if apply.state === "reverted" || apply.state === "failed"}
|
||||
{@const parts = firstSentence(apply.reason?.message ?? "")}
|
||||
@@ -337,7 +371,12 @@
|
||||
{#if apply.reason?.detail}<Details detail={apply.reason.detail} />{/if}
|
||||
<p class="ia-hint">Your form is kept. History records the attempt as {apply.state === "failed" ? "not applied" : "reverted"}.</p>
|
||||
{:else if apply.state === "needs_attention"}
|
||||
<Banner tone="down" live="alert">{#snippet title()}<strong>Ianitor could not undo a failed change.</strong>{/snippet}{apply.reason?.message}</Banner>
|
||||
<Banner tone="down" live="alert">{#snippet title()}<strong>Ianitor could not undo a failed change.</strong>{/snippet}{apply.reason?.message}
|
||||
{#if restoreProblem}<p role="status">{restoreProblem}</p>{/if}
|
||||
{#snippet actions()}
|
||||
{#if app.overview?.undo?.target}<Button variant="primary" pending={restoring} onclick={async () => { restoring = true; restoreProblem = await restoreLastKept(); restoring = false; }}>Restore the last kept version</Button>{/if}
|
||||
{/snippet}
|
||||
</Banner>
|
||||
{/if}
|
||||
{:else}
|
||||
<form id="host-form" onsubmit={submit} novalidate>
|
||||
|
||||
@@ -46,8 +46,7 @@
|
||||
{@const r = i.renewal}
|
||||
<Banner tone="notice" label="Domi intermediate certificate">
|
||||
{#snippet title()}
|
||||
<span tabindex="-1">Sign the renewal on the offline computer. Check that it shows the same code:</span>
|
||||
<span class="code" aria-label="Match code {r.match_code}">{r.match_code}</span>
|
||||
<span tabindex="-1">Sign the renewal on the offline computer. The next page has the files, the command and a fingerprint to check.</span>
|
||||
{/snippet}
|
||||
The request stays open for {duration(secondsLeft(r.expires_at))}. {#if problem}{problem}{/if}
|
||||
{#snippet actions()}
|
||||
@@ -58,12 +57,9 @@
|
||||
{:else if i?.banner}
|
||||
<Banner tone={i.state === "due" ? "notice" : "down"} label="Domi intermediate certificate">
|
||||
{#snippet title()}<strong>{i.banner?.message}</strong>{/snippet}
|
||||
{i.state === "missing" ? "Setting it up makes a request that the Domi root signs on the offline computer." : "Renewing makes a request that the Domi root signs; check the match code on both screens."}
|
||||
{i.state === "missing" ? "Setting it up makes a request that the Domi root signs on the offline computer." : "Renewing makes a request that the Domi root signs on the offline computer."}
|
||||
{#if problem} {problem}{/if}
|
||||
{#snippet actions()}<Button variant="outline" onclick={renew} {pending}>{i.state === "missing" ? "Set up" : "Renew"}</Button>{/snippet}
|
||||
</Banner>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.code { font-family: var(--font-inscription); font-size: 1.4rem; letter-spacing: 0.16em; color: var(--accent-strong); margin-left: 8px; }
|
||||
</style>
|
||||
|
||||
@@ -17,8 +17,9 @@
|
||||
|
||||
let { hostname, onclose }: { hostname: string; onclose: () => void } = $props();
|
||||
|
||||
const row = $derived(app.overview?.hosts.find((h) => h.hostname === hostname));
|
||||
let on = $state(false);
|
||||
// Known before the Dialog mounts, so its focus lands on Copy link (§2.9), not the title.
|
||||
// svelte-ignore state_referenced_locally
|
||||
let on = $state(!!app.overview?.hosts.find((h) => h.hostname === hostname)?.share_links);
|
||||
let link = $state<MintedLink | null>(null);
|
||||
let minting = $state(false);
|
||||
let copied = $state(false);
|
||||
@@ -33,10 +34,9 @@
|
||||
let usingPassword = $state(false);
|
||||
let turning = $state<ApplyView | null>(null);
|
||||
let stopFollow: (() => void) | undefined;
|
||||
let secretBox: HTMLInputElement | undefined = $state();
|
||||
let secretBox: HTMLTextAreaElement | undefined = $state();
|
||||
|
||||
onMount(() => {
|
||||
on = !!row?.share_links;
|
||||
if (on) void mint();
|
||||
});
|
||||
onDestroy(() => stopFollow?.());
|
||||
@@ -122,7 +122,7 @@
|
||||
{#if link?.warning}<p class="ia-hint">{link.warning.message}</p>{/if}
|
||||
{#if problem}<Banner tone="notice" live="status">{#snippet title()}{problem}{/snippet}</Banner>{/if}
|
||||
{#if link}
|
||||
<input bind:this={secretBox} class="ia-secret" readonly value={link.url} aria-label="Share link" onfocus={(e) => (e.currentTarget as HTMLInputElement).select()} />
|
||||
<textarea bind:this={secretBox} class="ia-secret" readonly value={link.url} aria-label="Share link" onfocus={(e) => (e.currentTarget as HTMLTextAreaElement).select()}></textarea>
|
||||
{:else if minting}
|
||||
<p class="ia-muted">Making the link…</p>
|
||||
{/if}
|
||||
|
||||
@@ -5,31 +5,42 @@
|
||||
// Handoff §2.8 order: paused / needs attention, lost contact, health unavailable, the Caddy
|
||||
// notice, then (on Hosts) the intermediate banner. First on every screen.
|
||||
import { Banner, Button, Details } from "@ianitor/ui";
|
||||
import { post, sentence } from "../lib/api";
|
||||
import { app, refresh } from "../lib/app.svelte";
|
||||
import { when } from "../lib/format";
|
||||
import type { ApplyView } from "../lib/types";
|
||||
import { app, refresh, restorable as canRestore, restoreLastKept } from "../lib/app.svelte";
|
||||
import { atTime, whenInline } from "../lib/format";
|
||||
|
||||
const o = $derived(app.overview);
|
||||
let restoring = $state(false);
|
||||
let problem = $state<string | null>(null);
|
||||
|
||||
const restorable = $derived(
|
||||
!!o?.paused && ["apply.needs_attention", "control.files_unwritten"].includes(o.paused_reason ?? "") && !!o.undo?.target,
|
||||
const restorable = $derived(canRestore());
|
||||
|
||||
async function restore() {
|
||||
restoring = true;
|
||||
problem = await restoreLastKept();
|
||||
restoring = false;
|
||||
}
|
||||
|
||||
// §7.6: the bold line and line 2 by the pause's underlying code.
|
||||
const pause = $derived.by(() => {
|
||||
const code = o?.paused_reason ?? "";
|
||||
const message = o?.paused?.message ?? "";
|
||||
if (code === "apply.needs_attention")
|
||||
return { bold: "Ianitor could not undo a failed change.", line2: "Visitors are served the last good settings, but the routes repository still has the change. Restore the last kept version to make them match again.", extra: "" };
|
||||
if (code === "control.files_unwritten")
|
||||
return { bold: "The change is live, but Ianitor could not save the proxy settings to disk.", line2: "Changes are paused until Ianitor restarts and saves them. Restoring the last kept version also clears this.", extra: "On the server: sudo systemctl restart ianitor-control" };
|
||||
// control.paused wraps the reason: "Changes are paused: <reason>"; show the reason itself.
|
||||
const own = message.replace(/^Changes are paused: /, "");
|
||||
if (/^(repo|file|site)\./.test(code))
|
||||
return { bold: own, line2: `Fix the file in the ${o?.repo?.name ?? "routes"} repository; Ianitor picks it up by itself.`, extra: "" };
|
||||
return { bold: own, line2: "", extra: "" };
|
||||
});
|
||||
|
||||
// "Show details" for every pause (§7.6): the server's detail, the restart command, or the
|
||||
// full message when there is nothing more.
|
||||
const pauseDetail = $derived(
|
||||
[o?.paused_detail, pause.extra].filter(Boolean).join("\n") || (o?.paused ? (o.paused.message ?? "") : ""),
|
||||
);
|
||||
|
||||
async function restoreLastKept() {
|
||||
if (!o?.undo?.target) return;
|
||||
restoring = true;
|
||||
try {
|
||||
const a = await post<{ apply: ApplyView }>("/restore", { change_id: o.undo.target.change_id, base_rev: o.rev });
|
||||
app.panel = { kind: "host", resume: a.apply.id };
|
||||
} catch (e) {
|
||||
problem = sentence(e);
|
||||
} finally {
|
||||
restoring = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function retry() {
|
||||
await refresh();
|
||||
@@ -38,11 +49,13 @@
|
||||
|
||||
{#if o?.paused}
|
||||
<Banner tone="down" live="alert">
|
||||
{#snippet title()}<span class="ia-status" data-s="down"><span class="word">{restorable ? "needs attention" : "paused"}</span></span> <strong>{o.paused?.message}</strong>{/snippet}
|
||||
{#if restorable && o.undo?.target}Goes back to "{o.undo.target.summary}" from {when(o.undo.target.kept_at, app.now)}. It is checked like any change.{/if}
|
||||
{#if problem} {problem}{/if}
|
||||
{#snippet title()}<span class="ia-status" data-s="down"><span class="word">{o.paused_reason === "apply.needs_attention" ? "needs attention" : "paused"}</span></span> <strong>{pause.bold}</strong>{/snippet}
|
||||
{#if pause.line2}<span class="line2">{pause.line2}</span>{/if}
|
||||
{#if restorable && o.undo?.target}<p class="ia-hint">Goes back to "{o.undo.target.summary}" from {whenInline(o.undo.target.kept_at, app.now)}. It is checked like any change.</p>{/if}
|
||||
{#if problem}<p role="status">{problem}</p>{/if}
|
||||
{#if pauseDetail}<Details detail={pauseDetail} />{/if}
|
||||
{#snippet actions()}
|
||||
{#if restorable}<Button variant="primary" onclick={restoreLastKept} pending={restoring}>Restore the last kept version</Button>{/if}
|
||||
{#if restorable}<Button variant="primary" onclick={restore} pending={restoring}>Restore the last kept version</Button>{/if}
|
||||
{/snippet}
|
||||
</Banner>
|
||||
{/if}
|
||||
@@ -50,7 +63,7 @@
|
||||
{#if app.lostContact}
|
||||
<Banner tone="down" live="alert">
|
||||
{#snippet title()}<strong>{typeof navigator !== "undefined" && navigator.onLine === false ? "This device is offline. Ianitor keeps running." : "Ianitor's control service is not answering."}</strong>{/snippet}
|
||||
Traffic keeps flowing; changes wait until it is back.{#if app.lastUpdated} Last updated {when(new Date(app.lastUpdated).toISOString(), app.now)}.{/if}
|
||||
Traffic keeps flowing; changes wait until it is back.{#if app.lastUpdated} Last updated {atTime(new Date(app.lastUpdated).toISOString(), app.now)}.{/if}
|
||||
{#snippet actions()}<Button onclick={retry}>Try again now</Button>{/snippet}
|
||||
</Banner>
|
||||
{/if}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
// Shared UI state: the overview (polled, handoff §3), the route, contact and sign-in state,
|
||||
// the server clock offset and toasts. No business logic: everything shown comes from control.
|
||||
|
||||
import { call, setClientEvents } from "./api";
|
||||
import { call, newKey, sentence, setClientEvents } from "./api";
|
||||
import type { Overview } from "./types";
|
||||
|
||||
export interface Toast {
|
||||
@@ -31,6 +31,10 @@ export const app = $state({
|
||||
switchResult: null as null | { ok: boolean; title: string; text: string; detail?: string | null },
|
||||
/** A renewal just installed (handoff §13.5). */
|
||||
renewedUntil: null as null | string,
|
||||
/** After a kept add or edit: the row whose More button gets focus (§7.5). */
|
||||
focusHost: null as string | null,
|
||||
/** Narrower than 720 px (the phone layout, handoff §5.2). */
|
||||
phone: false,
|
||||
/** Panels the main screen opens (add/edit host, share, engine). */
|
||||
panel: null as null | { kind: "host"; hostname?: string; resume?: string } | { kind: "share"; hostname: string } | { kind: "engine" },
|
||||
});
|
||||
@@ -135,6 +139,12 @@ export function navigate(path: string): void {
|
||||
app.path = path;
|
||||
}
|
||||
|
||||
if (typeof window !== "undefined" && typeof window.matchMedia === "function") {
|
||||
const mq = window.matchMedia("(max-width: 719.98px)");
|
||||
app.phone = mq.matches;
|
||||
mq.addEventListener?.("change", (e) => (app.phone = e.matches));
|
||||
}
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
window.addEventListener("popstate", () => {
|
||||
app.path = location.pathname + location.search;
|
||||
@@ -148,3 +158,23 @@ export function changesBlocked(): string | null {
|
||||
if (o?.paused) return "Changes are paused.";
|
||||
return null;
|
||||
}
|
||||
|
||||
/** "Restore the last kept version" (handoff §7.6): start it and show its progress in a panel.
|
||||
* Returns the sentence to show when it could not start. */
|
||||
export async function restoreLastKept(): Promise<string | null> {
|
||||
const o = app.overview;
|
||||
if (!o?.undo?.target) return null;
|
||||
try {
|
||||
const a = await call<{ apply: { id: string } }>("POST", "/restore", { change_id: o.undo.target.change_id, base_rev: o.rev }, { idem: newKey() });
|
||||
if (a.data) app.panel = { kind: "host", resume: a.data.apply.id };
|
||||
return null;
|
||||
} catch (e) {
|
||||
return sentence(e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the pause can be cleared by restoring the last kept version. */
|
||||
export function restorable(): boolean {
|
||||
const o = app.overview;
|
||||
return !!o?.paused && ["apply.needs_attention", "control.files_unwritten"].includes(o.paused_reason ?? "") && !!o.undo?.target;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
// runs; quiet retries while edge reloads; the id kept in sessionStorage so a reload resumes it.
|
||||
|
||||
import { get } from "./api";
|
||||
import { refresh } from "./app.svelte";
|
||||
import { app, refresh } from "./app.svelte";
|
||||
import type { ApplyView } from "./types";
|
||||
|
||||
export const FINAL = ["kept", "reverted", "failed", "needs_attention"];
|
||||
@@ -36,6 +36,11 @@ export function follow(id: string, onupdate: (a: ApplyView) => void, every = 100
|
||||
remember(id);
|
||||
const tick = async () => {
|
||||
if (stopped) return;
|
||||
if (app.signedOut) {
|
||||
// No requests while signed out (the overview poll stops too); look again shortly.
|
||||
timer = setTimeout(tick, every);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const a = await get<ApplyView>(`/applies/${encodeURIComponent(id)}`);
|
||||
if (stopped) return;
|
||||
|
||||
@@ -25,6 +25,21 @@ export function when(iso: string | null | undefined, now = Date.now()): string {
|
||||
return `${d.getDate()} ${MONTHS[d.getMonth()]} ${hm}`;
|
||||
}
|
||||
|
||||
/** Inside a sentence: "today 14:02", "yesterday 21:14", "5 Nov 21:14". */
|
||||
export function whenInline(iso: string | null | undefined, now = Date.now()): string {
|
||||
return when(iso, now).replace(/^(Today|Yesterday)/, (s) => s.toLowerCase());
|
||||
}
|
||||
|
||||
/** After "at" / "on": "at 14:03", "yesterday at 21:14", "on 5 Nov at 21:14", "on 5 Nov 2025". */
|
||||
export function atTime(iso: string | null | undefined, now = Date.now()): string {
|
||||
const w = when(iso, now);
|
||||
if (!w) return "";
|
||||
if (w.startsWith("Today ")) return `at ${w.slice(6)}`;
|
||||
if (w.startsWith("Yesterday ")) return `yesterday at ${w.slice(10)}`;
|
||||
const m = /^(\d+ \w+) (\d\d:\d\d)$/.exec(w);
|
||||
return m ? `on ${m[1]} at ${m[2]}` : `on ${w}`;
|
||||
}
|
||||
|
||||
/** "14 November 2026 at 14:20". */
|
||||
export function longDate(iso: string | null | undefined, withTime = true): string {
|
||||
if (!iso) return "";
|
||||
@@ -57,12 +72,13 @@ export function ago(iso: string | null | undefined, now: number): string {
|
||||
return duration((now - Date.parse(iso)) / 1000) + " ago";
|
||||
}
|
||||
|
||||
/** "7 hosts · 5 healthy, 1 degraded, 1 down" (handoff §5.1). */
|
||||
export function countsSentence(c: { hosts: number; healthy: number; degraded: number; down: number; unknown: number }): string {
|
||||
/** "7 hosts · 5 healthy, 1 degraded, 1 down" (handoff §5.1); short (phone, §5.2): "5 healthy, 1 degraded, 1 down". */
|
||||
export function countsSentence(c: { hosts: number; healthy: number; degraded: number; down: number; unknown: number }, short = false): string {
|
||||
const parts = [`${c.healthy} healthy`];
|
||||
if (c.degraded) parts.push(`${c.degraded} degraded`);
|
||||
if (c.down) parts.push(`${c.down} down`);
|
||||
if (c.unknown) parts.push(`${c.unknown} not checked`);
|
||||
if (short) return parts.join(", ");
|
||||
return `${c.hosts} ${c.hosts === 1 ? "host" : "hosts"} · ${parts.join(", ")}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -113,6 +113,7 @@ export interface PkiRequest {
|
||||
device_id: string | null;
|
||||
name: string | null;
|
||||
csr_pem: string | null;
|
||||
csr_sha256?: string | null;
|
||||
not_after: string | null;
|
||||
message_code: string;
|
||||
message: string;
|
||||
@@ -136,7 +137,7 @@ export interface EngineView {
|
||||
since: string | null;
|
||||
target: string | null;
|
||||
switchable: boolean;
|
||||
fallback_ready: { built_at: string | null; current: boolean } | null;
|
||||
fallback_ready: { built_at: string | null; current: boolean; compared: number; matched: number; differences: string[] } | null;
|
||||
last_error: Reason | null;
|
||||
notes: Blocked[];
|
||||
}
|
||||
@@ -154,12 +155,13 @@ export interface Overview {
|
||||
engine: EngineView;
|
||||
last_apply: ApplyView | null;
|
||||
undo: UndoView;
|
||||
active_apply: { id: string; state: string; summary: string; seconds_left: number | null; queued: number } | null;
|
||||
active_apply: { id: string; state: string; summary: string; seconds_left: number | null; kind: string; hosts: string[]; watch_ends_at: string | null; queued: number } | null;
|
||||
repo: { name: string; last_push_at: string | null; unpushed: number; push_error_code: string | null } | null;
|
||||
intermediate: IntermediateView | null;
|
||||
site: { forward_auth_configured: boolean; acme_configured: boolean; secrets: string[]; watch_seconds: number; share_links_available: boolean; auth_logout_url?: string | null } | null;
|
||||
paused: Blocked | null;
|
||||
paused_reason: string | null;
|
||||
paused_detail?: string | null;
|
||||
health_error: Blocked | null;
|
||||
rev: string | null;
|
||||
viewer?: { name: string; via: string } | null;
|
||||
@@ -234,6 +236,7 @@ export interface CertsView {
|
||||
root: { offline: boolean; subject: string; not_after: string; sha256: string };
|
||||
devices: DeviceRow[];
|
||||
device_lifetime_days: number;
|
||||
device_valid_until: string | null;
|
||||
server_lifetime_days: number;
|
||||
approval: string;
|
||||
requests: PkiRequest[];
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
import IntermediateBanner from "../components/IntermediateBanner.svelte";
|
||||
import { ApiError, del, get, post, sentence } from "../lib/api";
|
||||
import { app, navigate, refresh, secondsLeft, toast } from "../lib/app.svelte";
|
||||
import { shortDate, when } from "../lib/format";
|
||||
import { atTime, shortDate } from "../lib/format";
|
||||
import type { Bundle, CertsView, DeviceRow, PkiRequest } from "../lib/types";
|
||||
|
||||
let { newDevice }: { newDevice: boolean } = $props();
|
||||
@@ -120,7 +120,11 @@
|
||||
}
|
||||
|
||||
const lifetime = $derived(certs?.device_lifetime_days ?? 365);
|
||||
const until = $derived(shortDate(new Date(Date.now() + lifetime * 86_400_000).toISOString()));
|
||||
// The server caps it at the intermediate's end (Q7); without one it cannot issue anyway.
|
||||
const until = $derived(shortDate(certs?.device_valid_until ?? new Date(Date.now() + lifetime * 86_400_000).toISOString()));
|
||||
const capped = $derived(
|
||||
!!certs?.device_valid_until && Date.parse(certs.device_valid_until) < Date.now() + (lifetime - 1) * 86_400_000,
|
||||
);
|
||||
const intState = $derived.by((): [import("@ianitor/ui").StatusKind, string] => {
|
||||
switch (certs?.intermediate?.state) {
|
||||
case "ok": return ["healthy", "valid"];
|
||||
@@ -187,18 +191,18 @@
|
||||
<p class="ia-hint" id="device-name-h">Shown in this list and inside the certificate.</p>
|
||||
</div>
|
||||
<Segmented legend="What is it" name="kind" bind:value={kind} options={[{ value: "phone", label: "Phone or tablet" }, { value: "computer", label: "Computer" }, { value: "app", label: "Domi app" }]} />
|
||||
<p class="ia-hint">Valid for {lifetime} days, until {until}. It lets this device into hosts that ask for a Domi device certificate.</p>
|
||||
<p class="ia-hint">{#if capped}Valid until {until}, when the Domi intermediate certificate ends (renew it to issue for a full year).{:else}Valid for {lifetime} days, until {until}.{/if} It lets this device into hosts that ask for a Domi device certificate.</p>
|
||||
</form>
|
||||
{:else if request.state === "waiting"}
|
||||
<p class="ia-status" data-s="running"><Icon name="clock" /><strong>Waiting for approval</strong></p>
|
||||
<p>Approve it on the server, and only if it shows the same code:</p>
|
||||
<p>Custos cannot approve device certificates yet, so approve it on the server, and only if it shows the same code:</p>
|
||||
<p class="ia-code" aria-label="Match code {request.match_code}">{request.match_code}</p>
|
||||
{#if request.approve_command}<p class="ia-hint">Run on the server:</p><pre class="ia-secret ia-cmd">{request.approve_command}</pre>{/if}
|
||||
<p class="ia-muted">The request stays open for {Math.floor(secondsLeft(request.expires_at) / 60)}:{String(secondsLeft(request.expires_at) % 60).padStart(2, "0")}. Nothing is issued until it is approved.</p>
|
||||
<p class="ia-muted">The request stays open for 10 minutes ({Math.floor(secondsLeft(request.expires_at) / 60)}:{String(secondsLeft(request.expires_at) % 60).padStart(2, "0")} left). Nothing is issued until it is approved.</p>
|
||||
<div><Button onclick={cancelRequest}>Cancel request</Button></div>
|
||||
<span class="sr-only" aria-live="polite">Waiting for approval. Code {request.match_code}.</span>
|
||||
{:else if issuedDevice}
|
||||
<Banner tone="kept" live="status">{#snippet title()}<strong>{issuedDevice.name} has a certificate.</strong> Approved at {when(request?.approved_at, app.now)}.{/snippet}</Banner>
|
||||
<Banner tone="kept" live="status">{#snippet title()}<strong>{issuedDevice.name} has a certificate.</strong> Approved {atTime(request?.approved_at, app.now)}.{/snippet}</Banner>
|
||||
<div class="buttons">
|
||||
<Button variant="outline" onclick={() => install(issuedDevice, "qr")}>Show QR code</Button>
|
||||
<Button onclick={() => install(issuedDevice, "p12")}>Download file (.p12)</Button>
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
import HostPanel from "../components/HostPanel.svelte";
|
||||
import { get, post, sentence } from "../lib/api";
|
||||
import { app, changesBlocked, navigate } from "../lib/app.svelte";
|
||||
import { FIELD_LABEL, fieldValue, longDate, when } from "../lib/format";
|
||||
import { FIELD_LABEL, fieldValue, when } from "../lib/format";
|
||||
import type { ApplyView, HistoryEntry, HostSpec, RestorePreview } from "../lib/types";
|
||||
|
||||
let { host, pick }: { host?: string; pick?: string } = $props();
|
||||
@@ -163,7 +163,6 @@
|
||||
{#if editFrom}
|
||||
<HostPanel prefill={editFrom} hostname={undefined} onclose={() => { editFrom = null; void load(); }} />
|
||||
{/if}
|
||||
<span class="sr-only">{longDate(entry?.at)}</span>
|
||||
|
||||
<style>
|
||||
.cols { display: flex; gap: 24px; flex-wrap: wrap; align-items: flex-start; }
|
||||
|
||||
@@ -3,16 +3,17 @@
|
||||
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
|
||||
<script lang="ts">
|
||||
// Handoff §5: the main screen.
|
||||
import { Banner, Button, Icon } from "@ianitor/ui";
|
||||
import { tick } from "svelte";
|
||||
import { Banner, Button } from "@ianitor/ui";
|
||||
import ChangeBar from "../components/ChangeBar.svelte";
|
||||
import EnginePopover from "../components/EnginePopover.svelte";
|
||||
import EngineChip from "../components/EngineChip.svelte";
|
||||
import HostList from "../components/HostList.svelte";
|
||||
import HostPanel from "../components/HostPanel.svelte";
|
||||
import IntermediateBanner from "../components/IntermediateBanner.svelte";
|
||||
import ShareDialog from "../components/ShareDialog.svelte";
|
||||
import { call, newKey, post, sentence } from "../lib/api";
|
||||
import { app, changesBlocked, navigate, refresh, toast } from "../lib/app.svelte";
|
||||
import { countsSentence, when } from "../lib/format";
|
||||
import { atTime, countsSentence } from "../lib/format";
|
||||
import type { ApplyView, HostSpec } from "../lib/types";
|
||||
|
||||
let { route }: { route: { newHost: boolean; edit?: string } } = $props();
|
||||
@@ -25,12 +26,18 @@
|
||||
const panelOpen = $derived(route.newHost || !!route.edit || app.panel?.kind === "host");
|
||||
const blocked = $derived(changesBlocked());
|
||||
|
||||
function closePanel() {
|
||||
async function closePanel() {
|
||||
prefill = null;
|
||||
focusField = undefined;
|
||||
if (app.panel?.kind === "host") app.panel = null;
|
||||
if (route.newHost || route.edit) navigate("/");
|
||||
void refresh();
|
||||
await refresh();
|
||||
const h = app.focusHost;
|
||||
app.focusHost = null;
|
||||
if (h) {
|
||||
await tick();
|
||||
document.querySelector<HTMLElement>(`[aria-label="More for ${h.replace(/["\\]/g, "")}"]`)?.focus();
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(h: string) {
|
||||
@@ -62,27 +69,15 @@
|
||||
}
|
||||
}
|
||||
|
||||
const engineName = $derived(o?.engine.running === "caddy" ? "Caddy" : "Pingora");
|
||||
const engineLabel = $derived(
|
||||
o?.engine.state === "switching" ? "Engine: switching" : `Engine: ${engineName}${o?.engine.state === "stopped" ? ", not answering" : ""}. Change engine`,
|
||||
);
|
||||
</script>
|
||||
|
||||
<div class="head">
|
||||
<div>
|
||||
<h1 class="ia-display">Hosts</h1>
|
||||
{#if o}<p class="ia-text2">{countsSentence(o.counts)}</p>{/if}
|
||||
{#if o}<p class={app.phone ? "ia-sub" : "ia-text2"}>{countsSentence(o.counts, app.phone)}</p>{/if}
|
||||
</div>
|
||||
<div class="actions">
|
||||
{#if o}
|
||||
<button type="button" class="ia-engine" aria-haspopup="dialog" aria-expanded={app.panel?.kind === "engine"} aria-label={engineLabel}
|
||||
onclick={() => (app.panel = app.panel?.kind === "engine" ? null : { kind: "engine" })}>
|
||||
{#if o.engine.state === "switching"}<Icon name="clock" /> Engine Switching…{:else}
|
||||
<span class="ia-status" data-s={o.engine.state === "stopped" ? "down" : "healthy"}><span class="ia-dot"></span></span>
|
||||
<small class="desktop">Engine</small> {engineName}{#if o.engine.running === "caddy"} <small>(fallback)</small>{/if}{/if}
|
||||
<Icon name="chevron" />
|
||||
</button>
|
||||
{/if}
|
||||
{#if !app.phone}<EngineChip />{/if}
|
||||
<Button variant="primary" icon="plus" label="Add a host" disabled={!!blocked} describedby={blocked ? "add-blocked" : undefined} onclick={() => navigate("/hosts/new")}>Host</Button>
|
||||
{#if blocked}<span class="sr-only" id="add-blocked">{blocked}</span>{/if}
|
||||
</div>
|
||||
@@ -115,7 +110,7 @@
|
||||
<hr class="ia-ornament" />
|
||||
<p class="ia-muted footer">
|
||||
Routes live in the {o.repo.name} repository, one file per host.
|
||||
{#if o.repo.last_push_at}Last pushed to Gitea at {when(o.repo.last_push_at, app.now)}.{/if}
|
||||
{#if o.repo.last_push_at}Last pushed to Gitea {atTime(o.repo.last_push_at, app.now)}.{/if}
|
||||
{#if o.repo.unpushed}{o.repo.unpushed} changes not yet pushed.{/if}
|
||||
<button type="button" class="domi-btn link" onclick={() => navigate("/history")}>See history</button>
|
||||
</p>
|
||||
@@ -129,13 +124,9 @@
|
||||
{#if app.panel?.kind === "share"}
|
||||
<ShareDialog hostname={app.panel.hostname} onclose={() => { app.panel = null; void refresh(); }} />
|
||||
{/if}
|
||||
{#if app.panel?.kind === "engine"}
|
||||
<EnginePopover onclose={() => (app.panel = null)} />
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.head { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: flex-end; gap: 16px; }
|
||||
.actions { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
|
||||
.footer { text-align: center; }
|
||||
@media (max-width: 719.98px) { .desktop { display: none; } }
|
||||
</style>
|
||||
|
||||
@@ -16,6 +16,20 @@
|
||||
let pending = $state(false);
|
||||
let starting = $state(false);
|
||||
const base = $derived(r?.file_base ?? `domi-intermediate-${new Date().toISOString().slice(0, 10)}`);
|
||||
const signCmd = $derived(r?.approve_command ?? `openssl x509 -req -in ${base}.csr -CA domi-root.crt -CAkey domi-root.key -days 365 -sha256 -extfile ${base}.ext -out ${base}.crt`);
|
||||
const checkCmd = $derived(`openssl req -in ${base}.csr -outform DER | openssl dgst -sha256`);
|
||||
let copied = $state(false);
|
||||
// Groups of 8, easier to compare by eye; openssl prints it without spaces.
|
||||
const group = (h: string) => h.match(/.{1,8}/g)?.join(" ") ?? h;
|
||||
async function copy(text: string) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
copied = true;
|
||||
setTimeout(() => (copied = false), 3000);
|
||||
} catch {
|
||||
err = "Your browser did not allow copying. Select the command and copy it.";
|
||||
}
|
||||
}
|
||||
|
||||
function save(text: string, name: string, type: string) {
|
||||
const url = URL.createObjectURL(new Blob([text], { type }));
|
||||
@@ -88,15 +102,19 @@
|
||||
<p class="ia-label">Step 1</p>
|
||||
<h2 class="ia-h3">Download the request</h2>
|
||||
<p class="ia-text2">This file asks the Domi root to sign a new intermediate certificate. It holds no secret.</p>
|
||||
<p>Check that the offline computer shows the same code: <span class="ia-code small" aria-label="Match code {r.match_code}">{r.match_code}</span></p>
|
||||
<div class="row"><Button icon="copy" onclick={download}>Download the request (.csr)</Button><Button icon="copy" onclick={downloadExt}>Download the signing settings (.ext)</Button></div>
|
||||
<div class="row"><Button icon="download" onclick={download}>Download the request (.csr)</Button><Button icon="download" onclick={downloadExt}>Download the signing settings (.ext)</Button></div>
|
||||
</section>
|
||||
<section class="step">
|
||||
<p class="ia-label">Step 2</p>
|
||||
<h2 class="ia-h3">Sign it on the offline computer</h2>
|
||||
<p class="ia-text2">Copy both files to the offline computer that holds the Domi root, then run:</p>
|
||||
<pre class="ia-secret ia-cmd">{r.approve_command ?? `openssl x509 -req -in ${base}.csr -CA domi-root.crt -CAkey domi-root.key -days 365 -sha256 -extfile ${base}.ext -out ${base}.crt`}</pre>
|
||||
<p class="ia-muted">Before signing, check that the request is the one this page shows: <code>openssl req -in {base}.csr -noout -subject</code>. (On a computer with Ianitor installed, <code>ianitor-control ca sign</code> does the same and shows the match code.)</p>
|
||||
<p class="ia-text2">Copy both files to the offline computer that holds the Domi root.</p>
|
||||
<p class="ia-text2">First check that the request is the one this server made. This prints its fingerprint:</p>
|
||||
<pre class="ia-secret ia-cmd">{checkCmd}</pre>
|
||||
{#if r.csr_sha256}<p>openssl must print the same fingerprint as this page: <span class="ia-cmd fp" aria-label="Fingerprint {r.csr_sha256}">{group(r.csr_sha256)}</span></p>{/if}
|
||||
<p class="ia-text2">Then sign it:</p>
|
||||
<pre class="ia-secret ia-cmd">{signCmd}</pre>
|
||||
<div class="row"><Button icon="copy" onclick={() => copy(signCmd)}>Copy command</Button>{#if copied}<span class="ia-status" data-s="kept" role="status"><Icon name="check" />Copied</span>{/if}</div>
|
||||
<p class="ia-muted">On a computer with Ianitor installed, <code>ianitor-control ca sign</code> signs it instead and shows the match code {r.match_code}.</p>
|
||||
</section>
|
||||
<section class="step">
|
||||
<p class="ia-label">Step 3</p>
|
||||
@@ -121,5 +139,5 @@
|
||||
<style>
|
||||
.row { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||
.step { border: 1px solid var(--hairline); border-radius: var(--radius-lg); padding: 20px; display: flex; flex-direction: column; gap: 10px; }
|
||||
.small { font-size: 1.4rem; }
|
||||
.fp { word-break: break-all; color: var(--accent-strong); }
|
||||
</style>
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
import { Banner, Button, Dialog, Segmented } from "@ianitor/ui";
|
||||
import { ApiError, call, del, get, newKey, patch, post, sentence } from "../lib/api";
|
||||
import { app, navigate, toast } from "../lib/app.svelte";
|
||||
import { shortDate, when } from "../lib/format";
|
||||
import { longDate, shortDate, whenInline } from "../lib/format";
|
||||
import type { CreatedToken, ShareLink, TokenRow } from "../lib/types";
|
||||
|
||||
let { tab }: { tab: string } = $props();
|
||||
@@ -164,7 +164,7 @@
|
||||
<div role="tabpanel" id="panel-{tab}" aria-labelledby="tab-{tab}" class="panel">
|
||||
{#if tab === "general"}
|
||||
<p class="ia-label">Routes repository</p>
|
||||
<p>{settings?.repo ? `${settings.repo.name} on Gitea · ${settings.repo.last_push_at ? "pushed " + when(settings.repo.last_push_at, app.now) : "not pushed yet"}` : "No place to push to is set up."}</p>
|
||||
<p>{settings?.repo ? `${settings.repo.name} on Gitea · ${settings.repo.last_push_at ? "pushed " + whenInline(settings.repo.last_push_at, app.now) : "not pushed yet"}` : "No place to push to is set up."}</p>
|
||||
<p class="ia-label">Health watch after apply</p>
|
||||
<p>{settings?.watch_seconds ?? app.overview?.site?.watch_seconds ?? 60} seconds</p>
|
||||
<p class="ia-label">Signed in</p>
|
||||
@@ -186,7 +186,7 @@
|
||||
<div class="grow">
|
||||
<span class="tname" class:struck={!!revoked[t.id] || !!t.revoked_at}>{t.name}</span>
|
||||
<span class="ia-sub" style="display:block">
|
||||
{#if revoked[t.id]}Revoked {when(revoked[t.id], app.now)}{:else}Made {shortDate(t.created_at)} · {t.last_used_at ? `last used ${when(t.last_used_at, app.now)}` : "never used"} · {t.expires_at ? `expires ${shortDate(t.expires_at)}` : "never expires"}{/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}
|
||||
</span>
|
||||
</div>
|
||||
{#if !revoked[t.id] && !t.revoked_at}
|
||||
@@ -221,7 +221,7 @@
|
||||
{#each active as l (l.id)}
|
||||
<li>
|
||||
<div class="grow"><strong>{l.hostname}</strong>{l.path_prefix !== "/" ? l.path_prefix : ""}
|
||||
<span class="ia-sub" style="display:block">Made {when(l.created_at, app.now)} · expires {when(l.expires_at, app.now)}{l.has_password ? " · password" : ""}</span></div>
|
||||
<span class="ia-sub" style="display:block">Made {whenInline(l.created_at, app.now)} · expires {whenInline(l.expires_at, app.now)}{l.has_password ? " · password" : ""}</span></div>
|
||||
<Button small onclick={() => stop(l)}>Stop this link</Button>
|
||||
</li>
|
||||
{/each}
|
||||
@@ -255,7 +255,7 @@
|
||||
<Button variant={tokenCopied ? "quiet" : "primary"} icon="copy" onclick={copyToken} data-autofocus>{tokenCopied ? "Copy again" : "Copy token"}</Button>
|
||||
</div>
|
||||
{#if tokenCopied}<p role="status">Copied. Paste it into Custos now. Ianitor cannot show it again.</p>{/if}
|
||||
<p class="ia-muted">{made.expires_at ? `Expires on ${shortDate(made.expires_at)}.` : "Never expires."}</p>
|
||||
<p class="ia-muted">{made.expires_at ? `Expires on ${longDate(made.expires_at, false)}.` : "Never expires."}</p>
|
||||
{#if askClose}
|
||||
<p role="alert">Close without copying? The token cannot be shown again.
|
||||
<Button small onclick={() => (askClose = false)}>Go back</Button> <Button small variant="danger" onclick={() => closeToken(true)}>Close anyway</Button></p>
|
||||
|
||||
@@ -146,7 +146,8 @@ describe("ROADMAP §4 flows, clicks counted", () => {
|
||||
start();
|
||||
await click(await screen.findByRole("button", { name: "Renew" }));
|
||||
await waitFor(() => expect(called("POST", "/certs/intermediate/renewal")).toBe(true));
|
||||
await screen.findByLabelText("Match code 47 19 83");
|
||||
// The renewal is waiting: the banner says where to sign it (no code to compare with openssl).
|
||||
await screen.findByRole("button", { name: "Sign it by hand" });
|
||||
expect(clicks).toBe(1);
|
||||
});
|
||||
|
||||
@@ -176,6 +177,39 @@ describe("focus", () => {
|
||||
await user.keyboard("recipes.home.test");
|
||||
expect((await screen.findByLabelText("Hostname") as HTMLInputElement).value).toBe("recipes.home.test");
|
||||
});
|
||||
|
||||
it("the share dialog opens on Copy link and gives focus back to the row's More button", async () => {
|
||||
start();
|
||||
const more = await screen.findByRole("button", { name: "More for wiki.home.test" });
|
||||
await click(more);
|
||||
await click(await screen.findByRole("menuitem", { name: /Share link/ }));
|
||||
const copy = await screen.findByRole("button", { name: "Copy link" });
|
||||
await waitFor(() => expect(document.activeElement).toBe(copy));
|
||||
// jsdom fires no cancel event on Esc for a modal dialog: close it with its button.
|
||||
await click(screen.getByRole("button", { name: "Close" }));
|
||||
await waitFor(() => expect(screen.queryByRole("button", { name: "Copy link" })).toBeNull());
|
||||
await waitFor(() => expect(document.activeElement).toBe(more));
|
||||
});
|
||||
|
||||
it("the engine popover closes with Esc and focus goes back to the chip", async () => {
|
||||
start();
|
||||
const chip = await screen.findByRole("button", { name: /^Engine: Pingora/ });
|
||||
await click(chip);
|
||||
await screen.findByRole("button", { name: "Switch to Caddy" });
|
||||
await user.keyboard("{Escape}");
|
||||
await waitFor(() => expect(screen.queryByRole("button", { name: "Switch to Caddy" })).toBeNull());
|
||||
expect(document.activeElement).toBe(screen.getByRole("button", { name: /^Engine: Pingora/ }));
|
||||
});
|
||||
|
||||
it("a click on the engine chip while its popover is open closes it", async () => {
|
||||
start();
|
||||
const chip = await screen.findByRole("button", { name: /^Engine: Pingora/ });
|
||||
await click(chip);
|
||||
await screen.findByRole("button", { name: "Switch to Caddy" });
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
await click(chip);
|
||||
await waitFor(() => expect(screen.queryByRole("button", { name: "Switch to Caddy" })).toBeNull());
|
||||
});
|
||||
});
|
||||
|
||||
describe("sign-in and contact", () => {
|
||||
|
||||
@@ -73,7 +73,7 @@ export function installMock(): Mock {
|
||||
since: now(),
|
||||
target: null,
|
||||
switchable: true,
|
||||
fallback_ready: { built_at: now(), current: true },
|
||||
fallback_ready: { built_at: now(), current: true, compared: 3, matched: 3, differences: ["Every host: Caddy adds its own Server and Via headers to answers, and a Content-Type when your service sends none."] },
|
||||
last_error: null,
|
||||
notes: [],
|
||||
},
|
||||
|
||||
@@ -281,6 +281,7 @@ pub async fn overview(
|
||||
intermediate: super::pki::intermediate_view(c),
|
||||
site,
|
||||
paused_reason: c.effective_pause().map(|p| p.code),
|
||||
paused_detail: c.effective_pause().and_then(|p| p.detail),
|
||||
paused: c.effective_pause().map(|p| Blocked {
|
||||
code: "control.paused".into(),
|
||||
message: message("control.paused", &messages::params([("reason", p.message)])),
|
||||
|
||||
@@ -544,6 +544,8 @@ pub struct Overview {
|
||||
/// Why changes are paused: the underlying code (`apply.needs_attention`, `control.files_unwritten`,
|
||||
/// `repo.unreadable`, …), so the UI can offer the right action.
|
||||
pub paused_reason: Option<String>,
|
||||
/// The technical detail behind the pause, for "Show details" (never a secret).
|
||||
pub paused_detail: Option<String>,
|
||||
/// Set when control cannot read health from edge (`health.unavailable`).
|
||||
pub health_error: Option<Blocked>,
|
||||
pub rev: Option<String>,
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
//! The deadline of a trial under Caddy (QC round 2, B2; the Phase 2 guarantee that an
|
||||
//! unconfirmed change never outlives control). Edge drops a trial by itself when control does
|
||||
//! not confirm it in time; Caddy has no such clock, so two things outside control's own process
|
||||
//! stand in for it:
|
||||
//!
|
||||
//! - `ianitor-control caddy-revert` (systemd `ExecStopPost=` of ianitor-control, so it runs
|
||||
//! after every stop, a crash included): with a trial out, Caddy goes back to caddy.json (the
|
||||
//! last good config) at once;
|
||||
//! - `ianitor-control caddy-guard` (its own unit next to caddy-fallback, so a hung control is
|
||||
//! covered too): once a second, it reverts a trial whose deadline has passed.
|
||||
//!
|
||||
//! Control *arms* the deadline (`caddy-trial.json` in its state dir) before it loads a trial,
|
||||
//! and *claims* it (an atomic rename) right after its journal says `confirmed`; the guard
|
||||
//! takes it with the same kind of rename (to `.reverting`, then `.expired` once Caddy is
|
||||
//! verified on caddy.json; given back if the load fails, so it is tried again). A crash between
|
||||
//! `confirmed` and the claim leaves both: the guard and caddy-revert see `confirmed` and leave
|
||||
//! the trial to recovery, which promotes it. Whoever renames first wins, so a trial is either confirmed by control or
|
||||
//! reverted by the guard, never both. caddy.json itself is only ever written with a confirmed
|
||||
//! config, so loading it is always safe.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::records::Journal;
|
||||
use crate::util::{read_json, write_json};
|
||||
|
||||
pub const DEADLINE_FILE: &str = "caddy-trial.json";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct TrialDeadline {
|
||||
pub apply_id: String,
|
||||
/// Unix seconds.
|
||||
pub deadline: u64,
|
||||
}
|
||||
|
||||
fn path(state_dir: &Path, suffix: &str) -> PathBuf {
|
||||
state_dir.join(format!("{DEADLINE_FILE}{suffix}"))
|
||||
}
|
||||
|
||||
/// Before a trial goes into Caddy.
|
||||
pub fn arm(state_dir: &Path, apply_id: &str, deadline: u64) -> Result<(), String> {
|
||||
write_json(
|
||||
&path(state_dir, ""),
|
||||
&TrialDeadline {
|
||||
apply_id: apply_id.to_owned(),
|
||||
deadline,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Control, before it confirms: `true` if it got the deadline first (the guard has not
|
||||
/// reverted the trial), `false` if the guard did.
|
||||
pub fn claim(state_dir: &Path) -> bool {
|
||||
let claimed = path(state_dir, ".claimed");
|
||||
if std::fs::rename(path(state_dir, ""), &claimed).is_err() {
|
||||
return false;
|
||||
}
|
||||
let _ = std::fs::remove_file(claimed);
|
||||
true
|
||||
}
|
||||
|
||||
/// After a trial is reverted (or at start): nothing is out any more.
|
||||
pub fn disarm(state_dir: &Path) {
|
||||
for s in ["", ".claimed", ".expired", ".reverting"] {
|
||||
let _ = std::fs::remove_file(path(state_dir, s));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn armed(state_dir: &Path) -> Option<TrialDeadline> {
|
||||
read_json(&path(state_dir, "")).ok().flatten()
|
||||
}
|
||||
|
||||
/// Whether control's journal says the change is confirmed (then it is being promoted and
|
||||
/// caddy.json will hold it; nothing to revert).
|
||||
fn confirmed(state_dir: &Path) -> bool {
|
||||
read_json::<Journal>(&state_dir.join("journal.json"))
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_some_and(|j| j.stage == "confirmed" || j.stage == "promoted")
|
||||
}
|
||||
|
||||
/// What to do now, for a deadline file as found (pure, for the tests).
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Verdict {
|
||||
Nothing,
|
||||
Revert,
|
||||
}
|
||||
|
||||
pub fn verdict(armed: Option<&TrialDeadline>, confirmed: bool, now: u64, at_stop: bool) -> Verdict {
|
||||
match armed {
|
||||
Some(d) if !confirmed && (at_stop || now > d.deadline) => Verdict::Revert,
|
||||
_ => Verdict::Nothing,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether Caddy is the engine that serves (the engine file; Pingora without `[engine]`).
|
||||
fn caddy_serves(cfg: &Config) -> bool {
|
||||
cfg.engine
|
||||
.as_ref()
|
||||
.is_some_and(|e| crate::switch::read_engine_file(&e.file) == "caddy")
|
||||
}
|
||||
|
||||
/// A revert that stopped half way (the guard died while loading) counts as armed again.
|
||||
fn resume_half_done(dir: &Path) {
|
||||
let reverting = path(dir, ".reverting");
|
||||
if reverting.exists() && !path(dir, "").exists() {
|
||||
let _ = std::fs::rename(reverting, path(dir, ""));
|
||||
}
|
||||
}
|
||||
|
||||
/// Take the deadline away from control (rename to `.reverting`), load the last good
|
||||
/// caddy.json and check that Caddy runs it; only then is the deadline marked expired. If the
|
||||
/// load fails, the deadline is given back, so the next try (or control's own claim, while
|
||||
/// Caddy still runs the trial) decides.
|
||||
async fn revert(cfg: &Config, why: &str) -> Result<bool, String> {
|
||||
let dir = &cfg.state_dir;
|
||||
let reverting = path(dir, ".reverting");
|
||||
if std::fs::rename(path(dir, ""), &reverting).is_err() {
|
||||
// Control claimed it a moment ago: it confirms; nothing to do.
|
||||
return Ok(false);
|
||||
}
|
||||
let loaded = async {
|
||||
let sock = cfg
|
||||
.caddy_compile()
|
||||
.caddy_admin_socket
|
||||
.clone()
|
||||
.ok_or("no caddy_admin_socket 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? {
|
||||
return Err("Caddy took caddy.json but does not run it".to_owned());
|
||||
}
|
||||
Ok::<_, String>(())
|
||||
}
|
||||
.await;
|
||||
match loaded {
|
||||
Ok(()) => {
|
||||
let _ = std::fs::rename(&reverting, path(dir, ".expired"));
|
||||
log::warn!(target: "ianitor::caddy-guard", "{why}: Caddy is back on the last good config");
|
||||
Ok(true)
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = std::fs::rename(&reverting, path(dir, ""));
|
||||
Err(format!("{why}, but Caddy could not be put back yet: {e}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `ianitor-control caddy-revert`: after control stops, a trial still out goes back at once
|
||||
/// (retried a few times, 1, 2, 4 and 8 s apart). With another engine serving there is no
|
||||
/// Caddy trial: a deadline left behind is cleared and nothing fails.
|
||||
pub async fn revert_after_stop(cfg: &Config) -> Result<bool, String> {
|
||||
let dir = &cfg.state_dir;
|
||||
if !caddy_serves(cfg) {
|
||||
disarm(dir);
|
||||
return Ok(false);
|
||||
}
|
||||
resume_half_done(dir);
|
||||
let mut wait = 1;
|
||||
loop {
|
||||
let r = match verdict(
|
||||
armed(dir).as_ref(),
|
||||
confirmed(dir),
|
||||
crate::util::now(),
|
||||
true,
|
||||
) {
|
||||
Verdict::Revert => revert(cfg, "control stopped with a trial loaded into Caddy").await,
|
||||
Verdict::Nothing => Ok(false),
|
||||
};
|
||||
match r {
|
||||
Err(e) if wait <= 8 => {
|
||||
log::error!(target: "ianitor::caddy-guard", "{e}; trying again in {wait} s");
|
||||
tokio::time::sleep(std::time::Duration::from_secs(wait)).await;
|
||||
wait *= 2;
|
||||
}
|
||||
other => return other,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One tick of `ianitor-control caddy-guard`.
|
||||
pub async fn tick(cfg: &Config) -> Result<bool, String> {
|
||||
let dir = &cfg.state_dir;
|
||||
if !caddy_serves(cfg) {
|
||||
return Ok(false);
|
||||
}
|
||||
resume_half_done(dir);
|
||||
match verdict(
|
||||
armed(dir).as_ref(),
|
||||
confirmed(dir),
|
||||
crate::util::now(),
|
||||
false,
|
||||
) {
|
||||
Verdict::Revert => revert(cfg, "a trial under Caddy passed its deadline unconfirmed").await,
|
||||
Verdict::Nothing => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// `ianitor-control caddy-guard`: forever, once a second; after a failed revert it tries
|
||||
/// again with a growing pause (2, 4, … 30 s).
|
||||
pub async fn run(cfg: Config) -> Result<(), String> {
|
||||
log::info!(target: "ianitor::caddy-guard", "watching {} for trials under Caddy", cfg.state_dir.display());
|
||||
let mut pause = 1u64;
|
||||
loop {
|
||||
match tick(&cfg).await {
|
||||
Ok(_) => pause = 1,
|
||||
Err(e) => {
|
||||
pause = (pause * 2).min(30);
|
||||
log::error!(target: "ianitor::caddy-guard", "{e}; trying again in {pause} s");
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_secs(pause)).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
|
||||
fn d(deadline: u64) -> TrialDeadline {
|
||||
TrialDeadline {
|
||||
apply_id: "ch_1".into(),
|
||||
deadline,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_guard_reverts_only_an_unconfirmed_trial_past_its_deadline() {
|
||||
assert_eq!(verdict(None, false, 100, false), Verdict::Nothing);
|
||||
assert_eq!(verdict(Some(&d(100)), false, 100, false), Verdict::Nothing);
|
||||
assert_eq!(verdict(Some(&d(100)), false, 101, false), Verdict::Revert);
|
||||
assert_eq!(verdict(Some(&d(100)), true, 500, false), Verdict::Nothing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_a_stop_an_unconfirmed_trial_goes_back_at_once() {
|
||||
assert_eq!(verdict(Some(&d(1000)), false, 1, true), Verdict::Revert);
|
||||
assert_eq!(verdict(Some(&d(1000)), true, 1, true), Verdict::Nothing);
|
||||
assert_eq!(verdict(None, false, 1, true), Verdict::Nothing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_and_the_guard_cannot_both_have_the_deadline() {
|
||||
let dir = std::env::temp_dir().join(format!("ianitor-guard-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
arm(&dir, "ch_1", 10).unwrap();
|
||||
assert_eq!(armed(&dir), Some(d(10)));
|
||||
// The guard took it (as `revert` does): control's claim fails.
|
||||
std::fs::rename(path(&dir, ""), path(&dir, ".expired")).unwrap();
|
||||
assert!(!claim(&dir));
|
||||
disarm(&dir);
|
||||
// Control claims first: nothing is left for the guard.
|
||||
arm(&dir, "ch_1", 10).unwrap();
|
||||
assert!(claim(&dir));
|
||||
assert!(armed(&dir).is_none());
|
||||
assert!(std::fs::rename(path(&dir, ""), path(&dir, ".expired")).is_err());
|
||||
disarm(&dir);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,9 @@
|
||||
|
||||
//! 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
|
||||
//! (`POST /load`, the whole JSON), and probing a host *through* Caddy for the health watch.
|
||||
//! (`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;
|
||||
@@ -13,20 +15,14 @@ use std::time::{Duration, Instant};
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// Load a full Caddy JSON config. Caddy swaps it in gracefully or refuses it (and keeps the
|
||||
/// old one).
|
||||
pub async fn load(socket: &Path, config: &[u8]) -> Result<(), String> {
|
||||
/// One request to Caddy's admin API (HTTP/1.0: the answer is never chunked).
|
||||
async fn admin(socket: &Path, request: &[u8]) -> Result<(u16, Vec<u8>), String> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let head = format!(
|
||||
"POST /load HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n",
|
||||
config.len()
|
||||
);
|
||||
let exchange = async {
|
||||
let mut s = tokio::net::UnixStream::connect(socket).await?;
|
||||
s.write_all(head.as_bytes()).await?;
|
||||
s.write_all(config).await?;
|
||||
s.write_all(request).await?;
|
||||
let mut buf = Vec::new();
|
||||
s.read_to_end(&mut buf).await?;
|
||||
Ok::<_, std::io::Error>(buf)
|
||||
@@ -35,29 +31,69 @@ pub async fn load(socket: &Path, config: &[u8]) -> Result<(), String> {
|
||||
.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 text = String::from_utf8_lossy(&buf);
|
||||
let status: u16 = text
|
||||
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")?;
|
||||
if (200..300).contains(&status) {
|
||||
Ok(())
|
||||
} else {
|
||||
let body = text.split("\r\n\r\n").nth(1).unwrap_or("").trim();
|
||||
Err(format!(
|
||||
"Caddy refused the config ({status}): {}",
|
||||
body.chars().take(400).collect::<String>()
|
||||
))
|
||||
}
|
||||
Ok((status, buf[split + 4..].to_vec()))
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = (socket, config);
|
||||
let _ = (socket, request);
|
||||
Err("Caddy's admin socket needs Unix".into())
|
||||
}
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
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",
|
||||
config.len()
|
||||
)
|
||||
.into_bytes();
|
||||
req.extend_from_slice(config);
|
||||
let (status, body) = admin(socket, &req).await?;
|
||||
if (200..300).contains(&status) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!(
|
||||
"Caddy refused the config ({status}): {}",
|
||||
String::from_utf8_lossy(&body)
|
||||
.trim()
|
||||
.chars()
|
||||
.take(400)
|
||||
.collect::<String>()
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// The config Caddy runs now.
|
||||
pub async fn running_config(socket: &Path) -> Result<serde_json::Value, String> {
|
||||
let (status, body) = admin(socket, b"GET /config/ HTTP/1.0\r\nHost: localhost\r\n\r\n").await?;
|
||||
if status != 200 {
|
||||
return Err(format!(
|
||||
"Caddy's admin API answered {status} to GET /config/"
|
||||
));
|
||||
}
|
||||
serde_json::from_slice(&body).map_err(|e| format!("Caddy's running config is not JSON: {e}"))
|
||||
}
|
||||
|
||||
/// Whether Caddy runs exactly this config (as JSON values, so formatting does not matter).
|
||||
pub async fn runs(socket: &Path, config: &[u8]) -> Result<bool, String> {
|
||||
let want: serde_json::Value =
|
||||
serde_json::from_slice(config).map_err(|e| format!("not JSON: {e}"))?;
|
||||
Ok(running_config(socket).await? == want)
|
||||
}
|
||||
|
||||
/// One probe through Caddy: `GET path` on the HTTPS listener with this SNI and Host.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Probe {
|
||||
@@ -156,3 +192,175 @@ pub async fn probe(addr: SocketAddr, host: &str, path: &str) -> Probe {
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// SHA-256 (hex) of the leaf certificate Caddy serves for this name: after a reload, whether
|
||||
/// Caddy really read the certificate files again (the backstop for B1).
|
||||
pub async fn served_cert_sha256(addr: SocketAddr, host: &str) -> Result<String, String> {
|
||||
let run = async {
|
||||
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||
let cfg = rustls::ClientConfig::builder_with_provider(provider)
|
||||
.with_safe_default_protocol_versions()
|
||||
.map_err(|e| e.to_string())?
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(Arc::new(AnyCert))
|
||||
.with_no_client_auth();
|
||||
let name =
|
||||
rustls_pki_types::ServerName::try_from(host.to_owned()).map_err(|e| e.to_string())?;
|
||||
let tcp = tokio::net::TcpStream::connect(addr)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
let tls = tokio_rustls::TlsConnector::from(Arc::new(cfg))
|
||||
.connect(name, tcp)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
let (_, conn) = tls.get_ref();
|
||||
let leaf = conn
|
||||
.peer_certificates()
|
||||
.and_then(|c| c.first())
|
||||
.ok_or("Caddy sent no certificate")?;
|
||||
Ok::<_, String>(crate::util::sha256_hex(leaf.as_ref()))
|
||||
};
|
||||
tokio::time::timeout(Duration::from_secs(5), run)
|
||||
.await
|
||||
.map_err(|_| "Caddy did not finish the handshake within 5 s".to_owned())?
|
||||
}
|
||||
|
||||
/// One health probe of an upstream, made by control while Caddy serves, with edge's rules
|
||||
/// (crates/edge/src/health.rs): a host with a health check gets `GET <path>` with the upstream
|
||||
/// address as Host and passes on 2xx; a host without one gets `GET /` with its own name as
|
||||
/// Host and passes on any answer below 500. 5 s timeout. `kind` uses edge's words.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UpstreamProbe {
|
||||
pub ok: bool,
|
||||
pub kind: Option<&'static str>,
|
||||
pub status: Option<u16>,
|
||||
pub latency_ms: Option<u64>,
|
||||
}
|
||||
|
||||
fn status_kind(status: u16) -> &'static str {
|
||||
match status {
|
||||
300..=399 => "redirect",
|
||||
401 | 403 => "sign_in",
|
||||
404 => "not_found",
|
||||
500..=599 => "server_error",
|
||||
_ => "bad_answer",
|
||||
}
|
||||
}
|
||||
|
||||
fn io_kind(e: &std::io::Error) -> &'static str {
|
||||
use std::io::ErrorKind as K;
|
||||
match e.kind() {
|
||||
K::ConnectionRefused | K::ConnectionReset | K::ConnectionAborted | K::BrokenPipe => {
|
||||
"refused"
|
||||
}
|
||||
K::TimedOut => "timeout",
|
||||
_ if e.to_string().contains("lookup") => "name",
|
||||
_ => "refused",
|
||||
}
|
||||
}
|
||||
|
||||
/// The roots an `https://` upstream is checked against: the system bundle (`SSL_CERT_FILE`,
|
||||
/// else the usual Debian/NixOS path), read once.
|
||||
fn system_roots() -> Arc<rustls::RootCertStore> {
|
||||
static ROOTS: std::sync::OnceLock<Arc<rustls::RootCertStore>> = std::sync::OnceLock::new();
|
||||
ROOTS
|
||||
.get_or_init(|| {
|
||||
let mut store = rustls::RootCertStore::empty();
|
||||
let path = std::env::var("SSL_CERT_FILE")
|
||||
.unwrap_or_else(|_| "/etc/ssl/certs/ca-certificates.crt".into());
|
||||
if let Ok(pem) = std::fs::read_to_string(path) {
|
||||
for der in ianitor_core::pki::chain_der(&pem).unwrap_or_default() {
|
||||
let _ = store.add(rustls_pki_types::CertificateDer::from(der));
|
||||
}
|
||||
}
|
||||
Arc::new(store)
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
pub async fn probe_upstream(
|
||||
u: &ianitor_core::Upstream,
|
||||
path: &str,
|
||||
host_header: &str,
|
||||
watch_only: bool,
|
||||
) -> UpstreamProbe {
|
||||
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
|
||||
let started = Instant::now();
|
||||
let fail = |kind: &'static str| UpstreamProbe {
|
||||
ok: false,
|
||||
kind: Some(kind),
|
||||
status: None,
|
||||
latency_ms: None,
|
||||
};
|
||||
async fn ask<S: AsyncRead + AsyncWrite + Unpin>(
|
||||
mut s: S,
|
||||
req: &[u8],
|
||||
) -> Result<Option<u16>, std::io::Error> {
|
||||
s.write_all(req).await?;
|
||||
let mut head = [0u8; 64];
|
||||
let mut n = 0;
|
||||
while n < 13 {
|
||||
let k = s.read(&mut head[n..]).await?;
|
||||
if k == 0 {
|
||||
break;
|
||||
}
|
||||
n += k;
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&head[..n])
|
||||
.split(' ')
|
||||
.nth(1)
|
||||
.and_then(|x| x.parse::<u16>().ok()))
|
||||
}
|
||||
let req = format!(
|
||||
"GET {path} HTTP/1.1\r\nHost: {host_header}\r\nUser-Agent: ianitor-health\r\nConnection: close\r\n\r\n"
|
||||
);
|
||||
let run = async {
|
||||
let tcp = match tokio::net::TcpStream::connect(u.authority()).await {
|
||||
Ok(t) => t,
|
||||
Err(e) => return Err(io_kind(&e)),
|
||||
};
|
||||
if u.scheme == ianitor_core::Scheme::Https {
|
||||
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||
let Ok(b) = rustls::ClientConfig::builder_with_provider(provider)
|
||||
.with_safe_default_protocol_versions()
|
||||
else {
|
||||
return Err("tls");
|
||||
};
|
||||
let cfg = b
|
||||
.with_root_certificates(system_roots())
|
||||
.with_no_client_auth();
|
||||
let Ok(name) = rustls_pki_types::ServerName::try_from(u.host_str()) else {
|
||||
return Err("name");
|
||||
};
|
||||
let tls = match tokio_rustls::TlsConnector::from(Arc::new(cfg))
|
||||
.connect(name, tcp)
|
||||
.await
|
||||
{
|
||||
Ok(t) => t,
|
||||
Err(_) => return Err("tls"),
|
||||
};
|
||||
ask(tls, req.as_bytes()).await.map_err(|e| io_kind(&e))
|
||||
} else {
|
||||
ask(tcp, req.as_bytes()).await.map_err(|e| io_kind(&e))
|
||||
}
|
||||
};
|
||||
match tokio::time::timeout(Duration::from_secs(5), run).await {
|
||||
Err(_) => fail("timeout"),
|
||||
Ok(Err(kind)) => fail(kind),
|
||||
Ok(Ok(None)) => fail("bad_answer"),
|
||||
Ok(Ok(Some(status))) => {
|
||||
let latency = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
|
||||
let ok = if watch_only {
|
||||
(100..500).contains(&status)
|
||||
} else {
|
||||
(200..300).contains(&status)
|
||||
};
|
||||
UpstreamProbe {
|
||||
ok,
|
||||
kind: (!ok).then(|| status_kind(status)),
|
||||
status: Some(status),
|
||||
latency_ms: Some(latency),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,6 +164,9 @@ pub struct Control {
|
||||
pub(crate) apply_lock: tokio::sync::Mutex<()>,
|
||||
/// Held while an engine is switched or told to reload its device or certificate files.
|
||||
pub(crate) engine_lock: tokio::sync::Mutex<()>,
|
||||
/// Serialises reading the device records and writing the device files (never held
|
||||
/// across an apply or a switch).
|
||||
pub(crate) devices_lock: tokio::sync::Mutex<()>,
|
||||
/// Why the device files are not (yet) in force, until a retry succeeds.
|
||||
pub devices_problem: Mutex<Option<String>>,
|
||||
}
|
||||
@@ -275,6 +278,7 @@ impl Control {
|
||||
pause_saved: std::sync::atomic::AtomicBool::new(true),
|
||||
apply_lock: tokio::sync::Mutex::new(()),
|
||||
engine_lock: tokio::sync::Mutex::new(()),
|
||||
devices_lock: tokio::sync::Mutex::new(()),
|
||||
devices_problem: Mutex::new(None),
|
||||
cfg,
|
||||
});
|
||||
@@ -1541,8 +1545,12 @@ impl Control {
|
||||
remove_if_exists(&p).map_err(|e| e.to_string())?;
|
||||
}
|
||||
if caddy {
|
||||
// Caddy must run caddy.json again, the last good config.
|
||||
// Caddy must run caddy.json again, the last good config (with the device files as
|
||||
// they are now); then no trial is out any more. Under the engine lock, so a device
|
||||
// change that saw the trial and left the reload to this point is not lost.
|
||||
let _engine = self.engine_lock.lock().await;
|
||||
self.caddy_reload().await?;
|
||||
crate::caddy_guard::disarm(&self.cfg.state_dir);
|
||||
return Ok(rev);
|
||||
}
|
||||
// Edge must now run edge.json, the last good config. If it confirmed the trial after
|
||||
@@ -1703,10 +1711,15 @@ impl Control {
|
||||
self.unpause();
|
||||
self.sync_files().await;
|
||||
}
|
||||
if self.engine_running() == "caddy"
|
||||
&& let Err(e) = self.caddy_reload().await
|
||||
{
|
||||
log::warn!(target: "ianitor::control", "Caddy did not load caddy.json at start: {e}");
|
||||
if self.engine_running() == "caddy" {
|
||||
match self.caddy_reload().await {
|
||||
Ok(()) => crate::caddy_guard::disarm(&self.cfg.state_dir),
|
||||
Err(e) => {
|
||||
log::warn!(target: "ianitor::control", "Caddy did not load caddy.json at start: {e}")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
crate::caddy_guard::disarm(&self.cfg.state_dir);
|
||||
}
|
||||
if let Err(e) = self.shares.ensure_revocation_file() {
|
||||
log::error!(target: "ianitor::share", "{e}");
|
||||
|
||||
@@ -3,13 +3,44 @@
|
||||
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
//! Applies while Caddy serves (Mark, 2026-11-08: changes keep working under Caddy). The same
|
||||
//! pipeline and journal as with edge; only the trial, the watch and the revert differ: the
|
||||
//! trial is loaded into Caddy through its admin socket, the touched hosts are probed through
|
||||
//! Caddy, and a revert loads caddy.json (the last good config) again.
|
||||
//! pipeline and journal as with edge; only the trial, the watch and the revert differ:
|
||||
//!
|
||||
//! - the trial is loaded into Caddy through its admin socket, after its deadline is armed
|
||||
//! (crate::caddy_guard: a crashed or hung control cannot leave it serving);
|
||||
//! - the watch judges health the way edge does (QC round 2, M1): control probes the upstreams
|
||||
//! itself with edge's rules, and the probe *through* Caddy only asks whether Caddy answers
|
||||
//! at all (any status counts, also its auth redirect, 401, 403 or 421);
|
||||
//! - every round checks that Caddy still runs the trial (M2: a reload by anyone else drops it);
|
||||
//! - a revert loads caddy.json (the last good config) again; a confirm claims the deadline,
|
||||
//! then promotes, loads caddy.json and checks that Caddy runs it.
|
||||
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use super::*;
|
||||
use crate::caddy_guard;
|
||||
use crate::caddy_link::{self, Probe};
|
||||
|
||||
/// Where control reaches Caddy's HTTPS listener (its own machine).
|
||||
fn local(addr: SocketAddr) -> SocketAddr {
|
||||
if addr.ip().is_unspecified() {
|
||||
let ip: std::net::IpAddr = if addr.is_ipv6() {
|
||||
std::net::Ipv6Addr::LOCALHOST.into()
|
||||
} else {
|
||||
std::net::Ipv4Addr::LOCALHOST.into()
|
||||
};
|
||||
SocketAddr::new(ip, addr.port())
|
||||
} else {
|
||||
addr
|
||||
}
|
||||
}
|
||||
|
||||
/// How one host is probed (edge's rules, crates/edge/src/health.rs).
|
||||
struct Rule {
|
||||
upstreams: Vec<ianitor_core::Upstream>,
|
||||
path: String,
|
||||
has_check: bool,
|
||||
}
|
||||
|
||||
impl Control {
|
||||
/// Caddy's admin socket, from `[compile_caddy]` (or `[compile]`).
|
||||
pub fn caddy_socket(&self) -> Option<std::path::PathBuf> {
|
||||
@@ -20,14 +51,87 @@ impl Control {
|
||||
.map(std::path::PathBuf::from)
|
||||
}
|
||||
|
||||
/// Load caddy.json (the last good config) into the running Caddy.
|
||||
/// Load caddy.json (the last good config) into the running Caddy, even when it is the
|
||||
/// config Caddy already runs (so it reads its files again), and check that it runs it.
|
||||
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")?;
|
||||
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
|
||||
caddy_link::load(&sock, &text).await?;
|
||||
if !caddy_link::runs(&sock, &text).await? {
|
||||
return Err("Caddy took the config but does not run it".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `caddy_reload`, then the backstop for certificate and device changes: Caddy must serve
|
||||
/// the certificate that is on disk now for a Domi host (it proves the files were read).
|
||||
pub async fn caddy_reload_checked(&self) -> Result<(), String> {
|
||||
self.caddy_reload().await?;
|
||||
let Ok((_, _, model)) = self.head_model() else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(h) = model
|
||||
.hosts()
|
||||
.iter()
|
||||
.find(|h| h.tls == ianitor_core::TlsMode::Domi)
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let file = std::path::Path::new(&self.cfg.caddy_compile().cert_dir)
|
||||
.join(format!("{}.crt", h.hostname));
|
||||
let want = std::fs::read_to_string(&file)
|
||||
.ok()
|
||||
.and_then(|pem| ianitor_core::pki::chain_der(&pem).ok())
|
||||
.and_then(|c| c.into_iter().next())
|
||||
.map(|der| crate::util::sha256_hex(&der))
|
||||
.ok_or_else(|| format!("cannot read {}", file.display()))?;
|
||||
let addr = local(self.cfg.caddy_compile().https_listen);
|
||||
let got = caddy_link::served_cert_sha256(addr, h.hostname.as_str()).await?;
|
||||
if got != want {
|
||||
return Err(format!(
|
||||
"Caddy still serves an older certificate for {} after the reload",
|
||||
h.hostname
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn caddy_rules(&self, plan: &Plan) -> BTreeMap<String, Rule> {
|
||||
plan.model
|
||||
.hosts()
|
||||
.iter()
|
||||
.map(|h| {
|
||||
(
|
||||
h.hostname.to_string(),
|
||||
Rule {
|
||||
upstreams: h.upstreams.clone(),
|
||||
path: h
|
||||
.health_check
|
||||
.as_ref()
|
||||
.map_or("/".to_owned(), |c| c.path.clone()),
|
||||
has_check: h.health_check.is_some(),
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// One round of edge-style upstream probes for one host; `(address, probe)` per upstream.
|
||||
async fn probe_host(hostname: &str, r: &Rule) -> Vec<(String, caddy_link::UpstreamProbe)> {
|
||||
let mut out = Vec::new();
|
||||
for u in &r.upstreams {
|
||||
let host_header = if r.has_check {
|
||||
u.authority()
|
||||
} else {
|
||||
hostname.to_owned()
|
||||
};
|
||||
let p = caddy_link::probe_upstream(u, &r.path, &host_header, !r.has_check).await;
|
||||
out.push((u.authority(), p));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub(super) async fn run_under_caddy(
|
||||
@@ -56,27 +160,10 @@ impl Control {
|
||||
.filter(|h| plan.target.host(h).is_some())
|
||||
.cloned()
|
||||
.collect();
|
||||
let addr = self.cfg.caddy_compile().https_listen;
|
||||
let path_of = |h: &str| -> (String, bool) {
|
||||
plan.model
|
||||
.hosts()
|
||||
.iter()
|
||||
.find(|x| x.hostname.as_str() == h)
|
||||
.and_then(|x| x.health_check.as_ref())
|
||||
.map(|hc| (hc.path.clone(), true))
|
||||
.unwrap_or_else(|| ("/".to_owned(), false))
|
||||
};
|
||||
let good = |p: &Probe, has_check: bool| match p {
|
||||
Probe::Status(s) => {
|
||||
if has_check {
|
||||
(200..300).contains(s)
|
||||
} else {
|
||||
*s < 500
|
||||
}
|
||||
}
|
||||
Probe::NoAnswer(_) => false,
|
||||
};
|
||||
// A host that already failed through Caddy before the change is no reason to revert.
|
||||
let addr = local(self.cfg.caddy_compile().https_listen);
|
||||
let rules = self.caddy_rules(plan);
|
||||
// A host whose upstreams already failed before the change is no reason to revert
|
||||
// (edge: `down_hosts`). Judged by the upstreams, as edge does.
|
||||
let existed: BTreeSet<String> = self
|
||||
.repo
|
||||
.tree(&j.base)
|
||||
@@ -90,16 +177,33 @@ impl Control {
|
||||
.unwrap_or_default();
|
||||
let mut was_down = BTreeSet::new();
|
||||
for h in &existed {
|
||||
let (path, check) = path_of(h);
|
||||
if !good(&caddy_link::probe(addr, h, &path).await, check) {
|
||||
if let Some(r) = rules.get(h)
|
||||
&& !Self::probe_host(h, r).await.iter().any(|(_, p)| p.ok)
|
||||
{
|
||||
was_down.insert(h.clone());
|
||||
}
|
||||
}
|
||||
|
||||
if let Err(e) = caddy_link::load(&sock, caddy_text.as_bytes()).await {
|
||||
return self
|
||||
.revert(id, &j, fail("apply.failed.reload", e), "failed")
|
||||
.await;
|
||||
let window = self.cfg.watch_secs;
|
||||
// The deadline goes out before the trial does (crate::caddy_guard).
|
||||
let deadline = now() + window + self.cfg.trial_margin_secs + 5;
|
||||
// Under the engine lock: a device change that looked a moment ago saw no trial and
|
||||
// reloads caddy.json; it must not land after the trial is in.
|
||||
let loaded = {
|
||||
let _engine = self.engine_lock.lock().await;
|
||||
match caddy_guard::arm(&self.cfg.state_dir, id, deadline) {
|
||||
Err(e) => {
|
||||
let mut r = reason("internal", Params::new());
|
||||
r.detail = Some(e);
|
||||
Err((r, "failed"))
|
||||
}
|
||||
Ok(()) => caddy_link::load(&sock, caddy_text.as_bytes())
|
||||
.await
|
||||
.map_err(|e| (fail("apply.failed.reload", e), "failed")),
|
||||
}
|
||||
};
|
||||
if let Err((r, state)) = loaded {
|
||||
return self.revert(id, &j, r, state).await;
|
||||
}
|
||||
j.stage = "trial_loaded".into();
|
||||
if let Err(e) = self.journal(&j) {
|
||||
@@ -115,7 +219,6 @@ impl Control {
|
||||
.filter(|h| !was_down.contains(*h))
|
||||
.cloned()
|
||||
.collect();
|
||||
let window = self.cfg.watch_secs;
|
||||
let mut kept_reason = if watch_hosts.is_empty() {
|
||||
reason(
|
||||
"apply.kept.removed",
|
||||
@@ -130,10 +233,10 @@ impl Control {
|
||||
]),
|
||||
)
|
||||
};
|
||||
let ends = now() + window;
|
||||
if judged.is_empty() {
|
||||
self.update(id, |r| r.step("watch", "skipped"));
|
||||
} else {
|
||||
let ends = now() + window;
|
||||
self.update(id, |r| {
|
||||
r.state = "watching".into();
|
||||
r.step("watch", "running");
|
||||
@@ -148,86 +251,19 @@ impl Control {
|
||||
.collect(),
|
||||
});
|
||||
});
|
||||
// hostname -> (passed, failed, failed in a row, last probe)
|
||||
let mut stats: BTreeMap<String, (u32, u32, u32, Option<Probe>)> = judged
|
||||
}
|
||||
if let Err(r) = self
|
||||
.caddy_watch(id, &sock, caddy_text, &judged, &rules, plan, addr, ends)
|
||||
.await
|
||||
{
|
||||
return self.revert(id, &j, r, "reverted").await;
|
||||
}
|
||||
if !judged.is_empty() {
|
||||
let no_check: Vec<String> = judged
|
||||
.iter()
|
||||
.map(|h| (h.clone(), (0, 0, 0, None)))
|
||||
.filter(|h| rules.get(*h).is_some_and(|r| !r.has_check))
|
||||
.cloned()
|
||||
.collect();
|
||||
let no_check: Vec<String> = judged.iter().filter(|h| !path_of(h).1).cloned().collect();
|
||||
loop {
|
||||
for h in &judged {
|
||||
let (path, check) = path_of(h);
|
||||
let p = caddy_link::probe(addr, h, &path).await;
|
||||
let ok = good(&p, check);
|
||||
if let Some(s) = stats.get_mut(h) {
|
||||
if ok {
|
||||
s.0 += 1;
|
||||
s.2 = 0;
|
||||
} else {
|
||||
s.1 += 1;
|
||||
s.2 += 1;
|
||||
}
|
||||
s.3 = Some(p);
|
||||
}
|
||||
}
|
||||
self.update(id, |r| {
|
||||
if let Some(w) = &mut r.watch {
|
||||
for wh in &mut w.hosts {
|
||||
if let Some(s) = stats.get(&wh.hostname) {
|
||||
wh.passed = s.0;
|
||||
wh.failed = s.1;
|
||||
wh.total = s.0 + s.1;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
let over = now() >= ends;
|
||||
let failing = stats
|
||||
.iter()
|
||||
.find(|(_, s)| s.2 >= 3 || (over && s.2 > 0))
|
||||
.map(|(h, s)| (h.clone(), s.clone()));
|
||||
if let Some((h, s)) = failing {
|
||||
let upstream = plan
|
||||
.model
|
||||
.hosts()
|
||||
.iter()
|
||||
.find(|x| x.hostname.as_str() == h)
|
||||
.and_then(|x| x.upstreams.first())
|
||||
.map(|u| u.to_string())
|
||||
.unwrap_or_default();
|
||||
let mut p = messages::params([
|
||||
("hostname", h.clone()),
|
||||
("verb", plan.verb.into()),
|
||||
("upstream", upstream.clone()),
|
||||
("count", s.1.to_string()),
|
||||
("of", (s.0 + s.1).to_string()),
|
||||
("seconds", window.to_string()),
|
||||
]);
|
||||
let (code, detail) = match &s.3 {
|
||||
Some(Probe::Status(st)) => {
|
||||
p.insert("status".into(), st.to_string());
|
||||
(
|
||||
"apply.reverted.server_error",
|
||||
format!("through Caddy: HTTP {st}"),
|
||||
)
|
||||
}
|
||||
Some(Probe::NoAnswer(e)) => {
|
||||
("apply.reverted.no_answer", format!("through Caddy: {e}"))
|
||||
}
|
||||
None => ("apply.reverted.no_answer", String::new()),
|
||||
};
|
||||
let mut r = reason(code, p);
|
||||
r.hostname = Some(h.clone());
|
||||
r.upstream = Some(upstream);
|
||||
r.field = Some("upstreams[0]".into());
|
||||
r.detail = Some(detail);
|
||||
return self.revert(id, &j, r, "reverted").await;
|
||||
}
|
||||
if over {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs(self.cfg.watch_every_secs)).await;
|
||||
}
|
||||
if !no_check.is_empty() && no_check.len() == judged.len() {
|
||||
kept_reason = reason(
|
||||
"apply.kept.no_watch",
|
||||
@@ -237,6 +273,10 @@ impl Control {
|
||||
self.update(id, |r| r.step("watch", "done"));
|
||||
}
|
||||
crash::point("watched");
|
||||
// Confirmed first, then the deadline is claimed (fix round 3): a crash in between
|
||||
// leaves the deadline armed *and* the journal confirmed, so the guard and caddy-revert
|
||||
// leave the trial alone and recovery promotes it. The other order would leave a window
|
||||
// with nothing armed and nothing confirmed, where nobody reverts Caddy.
|
||||
j.stage = "confirmed".into();
|
||||
if let Err(e) = self.journal(&j) {
|
||||
let mut r = reason("internal", Params::new());
|
||||
@@ -244,7 +284,22 @@ impl Control {
|
||||
return self.revert(id, &j, r, "failed").await;
|
||||
}
|
||||
crash::point("confirmed");
|
||||
// From the claim to Caddy running the promoted caddy.json, no device reload may load
|
||||
// the old caddy.json in between.
|
||||
let engine = self.engine_lock.lock().await;
|
||||
// The guard may have reverted a trial that ran past its deadline (a stalled control):
|
||||
// then this change is not kept.
|
||||
if !caddy_guard::claim(&self.cfg.state_dir) {
|
||||
drop(engine);
|
||||
let mut r = reason("apply.interrupted", Params::new());
|
||||
r.detail = Some(
|
||||
"the trial ran past its deadline, so Caddy went back to the last good config"
|
||||
.into(),
|
||||
);
|
||||
return self.revert(id, &j, r, "reverted").await;
|
||||
}
|
||||
if let Err(e) = self.promote() {
|
||||
drop(engine);
|
||||
log::error!(target: "ianitor::apply", "cannot write the config files: {e}");
|
||||
let mut p = reason("control.files_unwritten", Params::new());
|
||||
p.detail = Some(e.to_string());
|
||||
@@ -258,6 +313,12 @@ impl Control {
|
||||
return;
|
||||
}
|
||||
crash::point("promoted");
|
||||
// caddy.json now holds the change: Caddy loads what was written (with the device and
|
||||
// certificate files as they are now) and must run it.
|
||||
if let Err(e) = self.caddy_reload().await {
|
||||
log::error!(target: "ianitor::apply", "Caddy did not load the promoted caddy.json: {e}");
|
||||
}
|
||||
drop(engine);
|
||||
let push_step = self.push_step();
|
||||
self.update(id, |r| r.step("push", push_step));
|
||||
self.finish(id, "kept", Some(kept_reason), Vec::new());
|
||||
@@ -267,4 +328,139 @@ impl Control {
|
||||
}
|
||||
self.push_wake.notify_one();
|
||||
}
|
||||
|
||||
/// The watch under Caddy until `ends`: the reason to revert, if any.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn caddy_watch(
|
||||
&self,
|
||||
id: &str,
|
||||
sock: &std::path::Path,
|
||||
trial: &str,
|
||||
judged: &[String],
|
||||
rules: &BTreeMap<String, Rule>,
|
||||
plan: &Plan,
|
||||
addr: SocketAddr,
|
||||
ends: u64,
|
||||
) -> Result<(), Reason> {
|
||||
let mut seen: HashMap<(String, String), BTreeMap<u64, Check>> = HashMap::new();
|
||||
let mut seq = 0u64;
|
||||
let mut silent: BTreeMap<String, (u32, String)> = BTreeMap::new();
|
||||
let paths: HashMap<String, String> = rules
|
||||
.iter()
|
||||
.map(|(h, r)| (h.clone(), r.path.clone()))
|
||||
.collect();
|
||||
let mut first = true;
|
||||
loop {
|
||||
// Anyone else's reload (a device change, a restart of caddy-fallback) drops the
|
||||
// trial: then this is not a verdict on the change.
|
||||
match caddy_link::runs(sock, trial.as_bytes()).await {
|
||||
Ok(true) => {}
|
||||
Ok(false) => {
|
||||
let mut r = reason("apply.reverted.edge_lost", Params::new());
|
||||
r.detail = Some("Caddy no longer runs the trial config".into());
|
||||
return Err(r);
|
||||
}
|
||||
Err(e) => {
|
||||
let mut r = reason("apply.reverted.edge_lost", Params::new());
|
||||
r.detail = Some(e);
|
||||
return Err(r);
|
||||
}
|
||||
}
|
||||
if first {
|
||||
crash::point("watching");
|
||||
first = false;
|
||||
}
|
||||
let mut counts = Vec::new();
|
||||
for h in judged {
|
||||
let Some(rule) = rules.get(h) else { continue };
|
||||
// Does Caddy answer for this host at all? Any status does.
|
||||
match caddy_link::probe(addr, h, "/").await {
|
||||
Probe::Status(_) => {
|
||||
silent.remove(h);
|
||||
}
|
||||
Probe::NoAnswer(e) => {
|
||||
let s = silent.entry(h.clone()).or_insert((0, String::new()));
|
||||
s.0 += 1;
|
||||
s.1 = e;
|
||||
}
|
||||
}
|
||||
if let Some((n, e)) = silent.get(h)
|
||||
&& *n >= 3
|
||||
{
|
||||
let mut r = reason(
|
||||
"apply.reverted.no_answer",
|
||||
messages::params([
|
||||
("hostname", h.clone()),
|
||||
("verb", plan.verb.into()),
|
||||
("seconds", self.cfg.watch_secs.to_string()),
|
||||
]),
|
||||
);
|
||||
r.hostname = Some(h.clone());
|
||||
r.detail = Some(format!("Caddy does not answer for {h}: {e}"));
|
||||
return Err(r);
|
||||
}
|
||||
for (address, p) in Self::probe_host(h, rule).await {
|
||||
seq += 1;
|
||||
seen.entry((h.clone(), address)).or_default().insert(
|
||||
seq,
|
||||
Check {
|
||||
seq,
|
||||
at: now(),
|
||||
ok: p.ok,
|
||||
source: if rule.has_check {
|
||||
"health_check".into()
|
||||
} else {
|
||||
"watch".into()
|
||||
},
|
||||
kind: p.kind.map(str::to_owned),
|
||||
status: p.status,
|
||||
latency_ms: p.latency_ms,
|
||||
},
|
||||
);
|
||||
}
|
||||
let mut passed = 0u32;
|
||||
let mut failed = 0u32;
|
||||
let mut all_failing = !rule.upstreams.is_empty();
|
||||
for ((host, _), m) in &seen {
|
||||
if host != h {
|
||||
continue;
|
||||
}
|
||||
passed += m.values().filter(|c| c.ok).count() as u32;
|
||||
failed += m.values().filter(|c| !c.ok).count() as u32;
|
||||
if m.values().rev().take_while(|c| !c.ok).count() < 3 {
|
||||
all_failing = false;
|
||||
}
|
||||
}
|
||||
counts.push(WatchHost {
|
||||
hostname: h.clone(),
|
||||
passed,
|
||||
failed,
|
||||
total: passed + failed,
|
||||
});
|
||||
if all_failing {
|
||||
return Err(self.revert_reason(h, plan, &seen, &paths));
|
||||
}
|
||||
}
|
||||
self.update(id, |r| {
|
||||
if let Some(w) = &mut r.watch {
|
||||
w.hosts = counts;
|
||||
}
|
||||
});
|
||||
if now() >= ends {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs(self.cfg.watch_every_secs)).await;
|
||||
}
|
||||
// At the end, as with edge: every judged host needs an upstream whose last probe passed.
|
||||
for h in judged {
|
||||
let last_ok = seen
|
||||
.iter()
|
||||
.filter(|((host, _), _)| host == h)
|
||||
.any(|(_, m)| m.values().next_back().is_some_and(|c| c.ok));
|
||||
if !last_ok {
|
||||
return Err(self.revert_reason(h, plan, &seen, &paths));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
//! edge keeps serving the last good config.
|
||||
|
||||
pub mod api;
|
||||
pub mod caddy_guard;
|
||||
pub mod caddy_link;
|
||||
pub mod config;
|
||||
pub mod crash;
|
||||
|
||||
@@ -30,7 +30,8 @@ fn usage() -> ExitCode {
|
||||
eprintln!(
|
||||
"usage: ianitor-control --config <control.toml> | --dev [--edge-bin <path>] | \
|
||||
token create --name <name> [--expires-days <n> | --never] (--config <c> | --state-dir <d>) | \
|
||||
token list (...) | token revoke <id> (...) | openapi | check --config <c>"
|
||||
token list (...) | token revoke <id> (...) | openapi | check --config <c> | \
|
||||
caddy-revert --config <c> | caddy-guard --config <c>"
|
||||
);
|
||||
ExitCode::from(2)
|
||||
}
|
||||
@@ -395,6 +396,27 @@ fn main() -> ExitCode {
|
||||
Ok(())
|
||||
}
|
||||
Some("check") => state_dir(&args[1..]).map(|_| eprintln!("config is valid")),
|
||||
// Caddy trial deadline (ianitor_control::caddy_guard): after control stops, and the guard.
|
||||
Some(verb @ ("caddy-revert" | "caddy-guard")) => match args
|
||||
.iter()
|
||||
.position(|a| a == "--config")
|
||||
.and_then(|i| args.get(i + 1))
|
||||
{
|
||||
Some(p) => match Config::load(&PathBuf::from(p)) {
|
||||
Ok(cfg) if verb == "caddy-guard" => {
|
||||
rt.block_on(ianitor_control::caddy_guard::run(cfg))
|
||||
}
|
||||
Ok(cfg) => rt
|
||||
.block_on(ianitor_control::caddy_guard::revert_after_stop(&cfg))
|
||||
.map(|done| {
|
||||
if done {
|
||||
eprintln!("Caddy is back on the last good config.");
|
||||
}
|
||||
}),
|
||||
Err(e) => Err(e.to_string()),
|
||||
},
|
||||
None => return usage(),
|
||||
},
|
||||
Some("--dev") => rt.block_on(dev::run(&args[1..])),
|
||||
Some("--config") => match args.get(1) {
|
||||
Some(p) => match Config::load(&PathBuf::from(p)) {
|
||||
|
||||
@@ -218,9 +218,11 @@ fn bundle_password() -> Result<String, PkiFail> {
|
||||
|
||||
/// Private keys in `dir` that are not control's own: control refuses to run with one in its
|
||||
/// state directory (ROADMAP §1.2: the root is never on the server). Found by content (any
|
||||
/// `PRIVATE KEY` PEM block, plain or encrypted) and by name (`*root*key*`, `*root*.pem` with
|
||||
/// a key); the only keys allowed are `pki/intermediate.key`, `pki/pending-*.key` and
|
||||
/// `pki/devices/*.key`, which control writes encrypted itself.
|
||||
/// `PRIVATE KEY` PEM block, plain or encrypted) and by name (`*root*key*`); the only keys
|
||||
/// allowed are `pki/intermediate.key`, `pki/pending-*.key` and `pki/devices/*.key`, and those
|
||||
/// must hold exactly one key in control's own encrypted armour, nothing else. A symbolic link
|
||||
/// is never followed and never skipped: it is reported. Git's object store (`*.git/objects`,
|
||||
/// compressed history) is not read.
|
||||
pub fn root_key_files(dir: &Path) -> Vec<PathBuf> {
|
||||
let allowed = |p: &Path| -> bool {
|
||||
let Ok(rel) = p.strip_prefix(dir) else {
|
||||
@@ -242,6 +244,12 @@ pub fn root_key_files(dir: &Path) -> Vec<PathBuf> {
|
||||
_ => false,
|
||||
}
|
||||
};
|
||||
let own_armour = |b: &[u8]| -> bool {
|
||||
let t = String::from_utf8_lossy(b);
|
||||
let begins = t.matches("-----BEGIN ").count();
|
||||
let ours = t.matches(OWN_BEGIN).count();
|
||||
begins == 1 && ours == 1 && t.matches(KEY_MARK).count() == 2
|
||||
};
|
||||
let mut found = Vec::new();
|
||||
let mut stack = vec![(dir.to_path_buf(), 0)];
|
||||
while let Some((d, depth)) = stack.pop() {
|
||||
@@ -250,21 +258,41 @@ pub fn root_key_files(dir: &Path) -> Vec<PathBuf> {
|
||||
};
|
||||
for e in rd.flatten() {
|
||||
let p = e.path();
|
||||
let Ok(meta) = e.metadata() else { continue };
|
||||
// symlink_metadata: a link is looked at, not followed.
|
||||
let Ok(meta) = std::fs::symlink_metadata(&p) else {
|
||||
continue;
|
||||
};
|
||||
if meta.file_type().is_symlink() {
|
||||
found.push(p);
|
||||
continue;
|
||||
}
|
||||
if meta.is_dir() {
|
||||
if depth < 8 {
|
||||
let git_objects =
|
||||
e.file_name() == "objects" && d.extension().is_some_and(|x| x == "git");
|
||||
if depth < 8 && !git_objects {
|
||||
stack.push((p, depth + 1));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if !meta.is_file() || allowed(&p) {
|
||||
if !meta.is_file() {
|
||||
continue;
|
||||
}
|
||||
let read = || {
|
||||
(meta.len() <= 1 << 20)
|
||||
.then(|| std::fs::read(&p).ok())
|
||||
.flatten()
|
||||
};
|
||||
if allowed(&p) {
|
||||
// Control's own key files: one key, in control's encrypted armour.
|
||||
if !read().is_some_and(|b| own_armour(&b)) {
|
||||
found.push(p);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let name = e.file_name().to_string_lossy().to_ascii_lowercase();
|
||||
let by_name = name.contains("root") && name.contains("key");
|
||||
let by_content = meta.len() <= 1 << 20
|
||||
&& std::fs::read(&p)
|
||||
.is_ok_and(|b| b.windows(KEY_MARK.len()).any(|w| w == KEY_MARK.as_bytes()));
|
||||
let by_content =
|
||||
read().is_some_and(|b| b.windows(KEY_MARK.len()).any(|w| w == KEY_MARK.as_bytes()));
|
||||
if by_name || by_content {
|
||||
found.push(p);
|
||||
}
|
||||
@@ -275,6 +303,7 @@ pub fn root_key_files(dir: &Path) -> Vec<PathBuf> {
|
||||
|
||||
// Split so that this file does not match the pre-commit hook itself.
|
||||
const KEY_MARK: &str = concat!("PRIVATE ", "KEY-----");
|
||||
const OWN_BEGIN: &str = concat!("-----BEGIN IANITOR ENCRYPTED ", "PRIVATE KEY-----");
|
||||
|
||||
impl Pki {
|
||||
/// Open the CA state. The root certificate must be a CA and self-signed; the password
|
||||
@@ -1182,3 +1211,45 @@ pub fn cli_wait(state_dir: &Path, rid: &str, since: u64) -> Result<String, Strin
|
||||
std::thread::sleep(std::time::Duration::from_millis(250));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod root_key_tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn allowed_paths_hold_only_our_armour_links_are_reported_and_git_objects_are_not_read() {
|
||||
let dir = std::env::temp_dir().join(format!("ianitor-rk-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(dir.join("pki/devices")).unwrap();
|
||||
std::fs::create_dir_all(dir.join("routes.git/objects/ab")).unwrap();
|
||||
let key = pki::generate_key().unwrap();
|
||||
let sealed = pki::encrypt_key_with(&key, b"pw", 1000).unwrap();
|
||||
let plain = key.serialize_pem();
|
||||
std::fs::write(dir.join("pki/intermediate.key"), &sealed).unwrap();
|
||||
std::fs::write(dir.join("pki/devices/d1.key"), &sealed).unwrap();
|
||||
// Git's store is not read (a blob could hold anything, compressed or not).
|
||||
std::fs::write(dir.join("routes.git/objects/ab/cdef"), &plain).unwrap();
|
||||
assert!(
|
||||
root_key_files(&dir).is_empty(),
|
||||
"{:?}",
|
||||
root_key_files(&dir)
|
||||
);
|
||||
// A plain key, or a second block, in an allowed place is not ours.
|
||||
std::fs::write(dir.join("pki/pending-x.key"), &plain).unwrap();
|
||||
std::fs::write(dir.join("pki/devices/d2.key"), format!("{sealed}{plain}")).unwrap();
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink("/nonexistent/domi-root.key", dir.join("pki/devices/d3.key"))
|
||||
.unwrap();
|
||||
let found = root_key_files(&dir);
|
||||
assert!(found.contains(&dir.join("pki/pending-x.key")), "{found:?}");
|
||||
assert!(found.contains(&dir.join("pki/devices/d2.key")), "{found:?}");
|
||||
#[cfg(unix)]
|
||||
assert!(found.contains(&dir.join("pki/devices/d3.key")), "{found:?}");
|
||||
assert!(
|
||||
!found.contains(&dir.join("pki/intermediate.key")),
|
||||
"{found:?}"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,9 +164,16 @@ impl Control {
|
||||
}
|
||||
|
||||
/// The device files changed (issue or revoke): rewrite them and tell the engine at once.
|
||||
///
|
||||
/// It never waits for an apply (fix round 3): the files go to disk at once and edge is told
|
||||
/// at once, also during a watch (edge's trial reads the same files). Only when Caddy serves
|
||||
/// *and* a trial is out is the Caddy reload left to the end of that apply: a reload now
|
||||
/// would drop the trial, and the end of every Caddy trial loads caddy.json again (promote,
|
||||
/// revert, caddy-guard, caddy-revert), which reads the new files. During an engine switch
|
||||
/// (engine lock busy for more than a second) the engine being started reads them anyway.
|
||||
pub async fn devices_changed(&self) -> Result<(), String> {
|
||||
let Some(p) = &self.pki else { return Ok(()) };
|
||||
let _engine = self.engine_lock.lock().await;
|
||||
let _files = self.devices_lock.lock().await;
|
||||
let t = now();
|
||||
let mut result = Ok(());
|
||||
for dir in self.cert_dirs() {
|
||||
@@ -177,23 +184,34 @@ impl Control {
|
||||
));
|
||||
}
|
||||
}
|
||||
// Tell the serving engine every time, changed or not: a repeated Revoke nudges again.
|
||||
if result.is_ok() {
|
||||
result = if self.engine_running() == "caddy" {
|
||||
self.caddy_reload()
|
||||
.await
|
||||
.map_err(|e| format!("Caddy did not reload the device list: {e}"))
|
||||
} else if self.edge.attached() {
|
||||
self.edge
|
||||
.reload_devices()
|
||||
.await
|
||||
.map_err(|e| format!("edge did not re-read the device list: {e}"))
|
||||
} else {
|
||||
Ok(())
|
||||
// The engine lock is held for long only by a switch; an apply holds it for a moment
|
||||
// (loading a trial, or from the claim to the promoted reload), so then this waits.
|
||||
let engine =
|
||||
match tokio::time::timeout(Duration::from_secs(1), self.engine_lock.lock()).await {
|
||||
Ok(g) => Some(g),
|
||||
Err(_) if self.engine_state().state == "switching" => None,
|
||||
Err(_) => Some(self.engine_lock.lock().await),
|
||||
};
|
||||
// Tell the serving engine every time, changed or not: a repeated Revoke nudges again.
|
||||
// During a switch it is not told now, and never silently (QC round 4): the problem
|
||||
// stays set, so the retry tells whichever engine serves once the switch is over (the
|
||||
// switch itself also ends by telling it).
|
||||
let mut pending = None;
|
||||
if result.is_ok() {
|
||||
if engine.is_none() {
|
||||
pending = Some(
|
||||
"an engine switch is under way; the engine that serves after it is told then"
|
||||
.to_owned(),
|
||||
);
|
||||
} else {
|
||||
result = self.nudge_devices().await;
|
||||
}
|
||||
}
|
||||
if let Ok(mut pr) = self.devices_problem.lock() {
|
||||
*pr = result.as_ref().err().cloned();
|
||||
*pr = result.as_ref().err().cloned().or(pending.clone());
|
||||
}
|
||||
if let Some(p) = &pending {
|
||||
log::info!(target: "ianitor::pki", "{p}");
|
||||
}
|
||||
if let Err(e) = &result {
|
||||
log::error!(target: "ianitor::pki", "{e}; retrying");
|
||||
@@ -201,10 +219,32 @@ impl Control {
|
||||
result
|
||||
}
|
||||
|
||||
/// Tell the engine that serves to read the device files again. The caller holds the engine
|
||||
/// lock. Under Caddy with a trial out, the end of that apply does it (promote, revert, the
|
||||
/// guard and caddy-revert all load caddy.json, which reads the files).
|
||||
pub(crate) async fn nudge_devices(&self) -> Result<(), String> {
|
||||
let caddy = self.engine_running() == "caddy";
|
||||
if caddy && crate::caddy_guard::armed(&self.cfg.state_dir).is_some() {
|
||||
log::info!(target: "ianitor::pki", "a change is being tried on Caddy; Caddy reads the new device list when it ends");
|
||||
Ok(())
|
||||
} else if caddy {
|
||||
self.caddy_reload_checked()
|
||||
.await
|
||||
.map_err(|e| format!("Caddy did not reload the device list: {e}"))
|
||||
} else if self.edge.attached() {
|
||||
self.edge
|
||||
.reload_devices()
|
||||
.await
|
||||
.map_err(|e| format!("edge did not re-read the device list: {e}"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn reload_serving_engine(&self) {
|
||||
let _engine = self.engine_lock.lock().await;
|
||||
if self.engine_running() == "caddy" {
|
||||
if let Err(e) = self.caddy_reload().await {
|
||||
if let Err(e) = self.caddy_reload_checked().await {
|
||||
log::error!(target: "ianitor::pki", "Caddy did not reload the new certificates: {e}");
|
||||
}
|
||||
} else if self.edge.attached()
|
||||
|
||||
@@ -254,6 +254,17 @@ impl Control {
|
||||
});
|
||||
}
|
||||
}
|
||||
// Still under the engine lock: whichever engine serves now reads the device files again
|
||||
// (QC round 4). A device change during the switch only wrote them; a Caddy that was
|
||||
// already running, or started before they changed, would keep the old list.
|
||||
if self.pki.is_some()
|
||||
&& let Err(e) = self.nudge_devices().await
|
||||
{
|
||||
log::error!(target: "ianitor::engine", "after the switch: {e}; retrying");
|
||||
if let Ok(mut p) = self.devices_problem.lock() {
|
||||
*p = Some(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn units_and_cfg(&self) -> Result<(Arc<dyn Units>, EngineConfig), String> {
|
||||
|
||||
@@ -78,6 +78,12 @@ esac
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
let r = env.call("GET", "/api/v1/engine", None).await;
|
||||
// On a loaded machine a switch takes longer: stay under the API's 120 calls a
|
||||
// minute rather than fail on a 429.
|
||||
if r.status == 429 {
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
continue;
|
||||
}
|
||||
assert_eq!(r.status, 200, "{}", r.text);
|
||||
if r.json["state"] == "running" && r.json["running"] == running {
|
||||
return r.json;
|
||||
@@ -85,7 +91,7 @@ esac
|
||||
if Instant::now() > deadline {
|
||||
panic!("engine is {}\n{}", r.text, env.control_log());
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,11 +234,30 @@ mkdir -p "$dir"
|
||||
echo "$*" >> "{d}/fake/calls.log"
|
||||
case "$1:$2" in
|
||||
start:caddy-fallback.service)
|
||||
# Like systemd: starting a unit that is active does nothing.
|
||||
[ -e "$dir/$2" ] && exit 0
|
||||
XDG_DATA_HOME="{d}/caddy-state" XDG_CONFIG_HOME="{d}/caddy-state" HOME="{d}/caddy-state" \
|
||||
nohup "{c}" run --config "{d}/caddy/caddy.json" >> "{d}/logs/caddy.log" 2>&1 &
|
||||
echo $! > "{d}/fake/caddy.pid"; touch "$dir/$2" ;;
|
||||
echo $! > "{d}/fake/caddy.pid"
|
||||
# The NixOS module starts ianitor-caddy-guard with caddy-fallback (crate::caddy_guard).
|
||||
if [ ! -e "{d}/fake/no-guard" ]; then
|
||||
IANITOR_LOG=info nohup "{g}" caddy-guard --config "{d}/control.toml" >> "{d}/logs/caddy-guard.log" 2>&1 &
|
||||
echo $! > "{d}/fake/guard.pid"
|
||||
fi
|
||||
# fake/start-delay: Caddy serves at once, the unit reports active only later (a switch
|
||||
# that is still in wait_serving while Caddy has read its files).
|
||||
if [ -f "{d}/fake/start-delay" ]; then
|
||||
(sleep "$(cat "{d}/fake/start-delay")"; touch "$dir/$2") >/dev/null 2>&1 &
|
||||
else
|
||||
touch "$dir/$2"
|
||||
fi ;;
|
||||
stop:caddy-fallback.service)
|
||||
[ -f "{d}/fake/caddy.pid" ] && kill "$(cat "{d}/fake/caddy.pid")" 2>/dev/null; rm -f "$dir/$2" "{d}/fake/caddy.pid" ;;
|
||||
# fake/stop-delay and fake/fail-stop: a slow stop, and one that fails (Caddy keeps running).
|
||||
[ -f "{d}/fake/stop-delay" ] && sleep "$(cat "{d}/fake/stop-delay")"
|
||||
grep -qx "$2" "{d}/fake/fail-stop" 2>/dev/null && exit 1
|
||||
[ -f "{d}/fake/caddy.pid" ] && kill "$(cat "{d}/fake/caddy.pid")" 2>/dev/null
|
||||
[ -f "{d}/fake/guard.pid" ] && kill "$(cat "{d}/fake/guard.pid")" 2>/dev/null
|
||||
rm -f "$dir/$2" "{d}/fake/caddy.pid" "{d}/fake/guard.pid" ;;
|
||||
start:*) touch "$dir/$2" ;;
|
||||
stop:*) rm -f "$dir/$2" ;;
|
||||
is-active:*) [ "$2" = "--quiet" ] && shift; [ -e "$dir/$2" ] ;;
|
||||
@@ -240,7 +265,8 @@ case "$1:$2" in
|
||||
esac
|
||||
"#,
|
||||
d = dir.display(),
|
||||
c = caddy.display()
|
||||
c = caddy.display(),
|
||||
g = env!("CARGO_BIN_EXE_ianitor-control"),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -251,8 +277,10 @@ esac
|
||||
|
||||
impl Drop for CaddyEnv {
|
||||
fn drop(&mut self) {
|
||||
if let Ok(p) = std::fs::read_to_string(self.env.dir.join("fake/caddy.pid")) {
|
||||
let _ = std::process::Command::new("kill").arg(p.trim()).status();
|
||||
for f in ["fake/caddy.pid", "fake/guard.pid"] {
|
||||
if let Ok(p) = std::fs::read_to_string(self.env.dir.join(f)) {
|
||||
let _ = std::process::Command::new("kill").arg(p.trim()).status();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -392,4 +420,815 @@ esac
|
||||
&& !edge_json.contains("c.test")
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- QC round 2
|
||||
|
||||
async fn qc_env_with_caddy_site(site: String) -> Option<CaddyEnv> {
|
||||
let caddy = ianitor_testkit::proc::require_binary("caddy")?;
|
||||
let mut env = Env::new(EnvSpec {
|
||||
site,
|
||||
..Default::default()
|
||||
})
|
||||
.await;
|
||||
let fake = env.dir.join("fake/systemctl");
|
||||
std::fs::create_dir_all(env.dir.join("fake/units")).unwrap();
|
||||
std::fs::create_dir_all(env.dir.join("caddy-state")).unwrap();
|
||||
std::fs::write(&fake, fake_with_caddy(&env.dir.join("."), &caddy)).unwrap();
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
std::fs::write(env.dir.join("fake/units/ianitor-edge.service"), "").unwrap();
|
||||
let http = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port());
|
||||
let https = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port());
|
||||
let d = |p: &str| env.dir.join(p).display().to_string();
|
||||
let text = std::fs::read_to_string(env.config_path()).unwrap()
|
||||
+ &format!(
|
||||
"\n[engine]\nfile = \"{}\"\nsystemctl = \"{}\"\n\n[compile_caddy]\nhttp_listen = \"{http}\"\nhttps_listen = \"{https}\"\ncert_dir = \"{}\"\nstate_dir = \"{}\"\naccess_log = \"{}\"\ncaddy_credentials_dir = \"{}\"\ncaddy_admin_socket = \"{}\"\n",
|
||||
d("engine"),
|
||||
fake.display(),
|
||||
d("certs"),
|
||||
d("caddy-state"),
|
||||
d("logs/caddy-access.log"),
|
||||
d("creds"),
|
||||
d("caddy/admin.sock"),
|
||||
);
|
||||
std::fs::write(env.config_path(), text).unwrap();
|
||||
env.start_control(None);
|
||||
Some(CaddyEnv { env, https })
|
||||
}
|
||||
|
||||
/// QC r2: a forward-auth host with a health check is kept under edge (edge checks the
|
||||
/// upstream). Under Caddy the watch probes *through* Caddy without a session: Authelia's
|
||||
/// redirect is not 2xx, so the same change is reverted.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn qc_forward_auth_host_with_health_check_is_kept_under_caddy_as_under_edge() {
|
||||
let auth = ianitor_testkit::authelia::MockAuthelia::start().await;
|
||||
let site = format!("[forward_auth]\nurl = \"{}\"\n", auth.url());
|
||||
let Some(ce) = qc_env_with_caddy_site(site).await else {
|
||||
return;
|
||||
};
|
||||
let env = &ce.env;
|
||||
let echo = ianitor_testkit::upstream::Echo::start("app").await;
|
||||
let host = |h: &str| {
|
||||
json!({"host": {"hostname": h, "upstreams": [echo.url()], "tls": "domi",
|
||||
"auth": "forward-auth", "health_check": {"path": "/", "interval_secs": 1}}})
|
||||
};
|
||||
let rec = env
|
||||
.apply("POST", "/api/v1/hosts", Some(host("a.test")))
|
||||
.await;
|
||||
eprintln!("QC under edge: {}", rec["state"]);
|
||||
assert_eq!(rec["state"], "kept", "{rec}");
|
||||
let r = env
|
||||
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
|
||||
.await;
|
||||
assert_eq!(r.status, 202, "{}", r.text);
|
||||
wait_engine(env, "caddy").await;
|
||||
let rec = env
|
||||
.apply("POST", "/api/v1/hosts", Some(host("b.test")))
|
||||
.await;
|
||||
eprintln!(
|
||||
"QC under caddy: {} {}",
|
||||
rec["state"], rec["reason"]["detail"]
|
||||
);
|
||||
assert_eq!(rec["state"], "kept", "{rec}");
|
||||
}
|
||||
|
||||
/// QC r2: control nudges Caddy (device list, renewed certificates) by POST /load of the
|
||||
/// unchanged caddy.json. Caddy skips a load of an identical config, so the files it read at
|
||||
/// start are not read again.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn qc_reloading_the_same_caddy_json_rereads_the_certificate_files() {
|
||||
let Some(ce) = env_with_caddy().await else {
|
||||
return;
|
||||
};
|
||||
let env = &ce.env;
|
||||
let echo = ianitor_testkit::upstream::Echo::start("app").await;
|
||||
let rec = env
|
||||
.apply("POST", "/api/v1/hosts", Some(json!({"host": {"hostname": "a.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none"}})))
|
||||
.await;
|
||||
assert_eq!(rec["state"], "kept");
|
||||
let r = env
|
||||
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
|
||||
.await;
|
||||
assert_eq!(r.status, 202);
|
||||
wait_engine(env, "caddy").await;
|
||||
assert_eq!(visit(env, ce.https, "a.test").await, 200);
|
||||
// Replace a.test's certificate with one from a root the client does not trust.
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs() as i64;
|
||||
let (root, rk) = ianitor_core::pki::create_root(now).unwrap();
|
||||
let k = ianitor_core::pki::generate_key().unwrap();
|
||||
let csr =
|
||||
ianitor_core::pki::intermediate_csr(&k, ianitor_core::pki::INTERMEDIATE_CN).unwrap();
|
||||
let int = ianitor_core::pki::Intermediate::new(
|
||||
&ianitor_core::pki::sign_intermediate(&root, &rk, &csr, now).unwrap(),
|
||||
k,
|
||||
)
|
||||
.unwrap();
|
||||
let leaf = ianitor_core::pki::issue_server(&int, "a.test", now).unwrap();
|
||||
std::fs::write(env.dir.join("certs/a.test.key"), &leaf.key_pem).unwrap();
|
||||
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;
|
||||
assert!(r.is_ok(), "{r:?}");
|
||||
let after = visit(env, ce.https, "a.test").await;
|
||||
eprintln!(
|
||||
"QC after same-config load: visit = {after} (200 = old certificate still served)"
|
||||
);
|
||||
assert_ne!(
|
||||
after, 200,
|
||||
"Caddy still serves the certificate it read at start"
|
||||
);
|
||||
}
|
||||
|
||||
/// QC r2: a control crash with a trial loaded into Caddy. Edge reverts an unconfirmed trial
|
||||
/// by itself; Caddy has no deadline, so the unverified config keeps serving while control
|
||||
/// is down.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn qc_control_crash_mid_trial_under_caddy_leaves_the_last_good_config() {
|
||||
let Some(mut ce) = env_with_caddy().await else {
|
||||
return;
|
||||
};
|
||||
let echo = ianitor_testkit::upstream::Echo::start("app").await;
|
||||
let host = |h: &str| json!({"host": {"hostname": h, "upstreams": [echo.url()], "tls": "domi", "auth": "none"}});
|
||||
assert_eq!(
|
||||
ce.env
|
||||
.apply("POST", "/api/v1/hosts", Some(host("a.test")))
|
||||
.await["state"],
|
||||
"kept"
|
||||
);
|
||||
let r = ce
|
||||
.env
|
||||
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
|
||||
.await;
|
||||
assert_eq!(r.status, 202);
|
||||
wait_engine(&ce.env, "caddy").await;
|
||||
ce.env.kill_control();
|
||||
ce.env.start_control(Some("trial_loaded"));
|
||||
let r = ce
|
||||
.env
|
||||
.call("POST", "/api/v1/hosts", Some(host("b.test")))
|
||||
.await;
|
||||
assert_eq!(r.status, 202, "{}", r.text);
|
||||
let st = ce.env.wait_control_exit(Duration::from_secs(30));
|
||||
eprintln!("QC control exit: {st:?}");
|
||||
assert!(st.is_some());
|
||||
// Longer than edge's trial deadline would allow.
|
||||
tokio::time::sleep(Duration::from_secs(15)).await;
|
||||
let during = visit(&ce.env, ce.https, "b.test").await;
|
||||
eprintln!("QC b.test through Caddy 15 s after the crash, control down: {during}");
|
||||
ce.env.start_control(None);
|
||||
tokio::time::sleep(Duration::from_secs(3)).await;
|
||||
let after = visit(&ce.env, ce.https, "b.test").await;
|
||||
eprintln!("QC b.test after control restarted (recovery): {after}");
|
||||
assert_ne!(after, 200, "recovery must revert the trial");
|
||||
assert_ne!(
|
||||
during, 200,
|
||||
"Caddy served the unconfirmed trial while control was down"
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- fix round 2
|
||||
|
||||
/// Like `env_with_caddy`, with a chosen watch, and with or without the Caddy trial guard
|
||||
/// (the fake systemctl starts it next to Caddy unless `fake/no-guard` exists).
|
||||
async fn caddy_env(watch_secs: u64, guard: bool) -> Option<CaddyEnv> {
|
||||
let caddy = ianitor_testkit::proc::require_binary("caddy")?;
|
||||
let mut env = Env::new(EnvSpec {
|
||||
watch_secs,
|
||||
..Default::default()
|
||||
})
|
||||
.await;
|
||||
let fake = env.dir.join("fake/systemctl");
|
||||
std::fs::create_dir_all(env.dir.join("fake/units")).unwrap();
|
||||
std::fs::create_dir_all(env.dir.join("caddy-state")).unwrap();
|
||||
if !guard {
|
||||
std::fs::write(env.dir.join("fake/no-guard"), "").unwrap();
|
||||
}
|
||||
std::fs::write(&fake, fake_with_caddy(&env.dir.join("."), &caddy)).unwrap();
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
std::fs::write(env.dir.join("fake/units/ianitor-edge.service"), "").unwrap();
|
||||
let http = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port());
|
||||
let https = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port());
|
||||
let d = |p: &str| env.dir.join(p).display().to_string();
|
||||
let text = std::fs::read_to_string(env.config_path()).unwrap()
|
||||
+ &format!(
|
||||
"\n[engine]\nfile = \"{}\"\nsystemctl = \"{}\"\n\n[compile_caddy]\nhttp_listen = \"{http}\"\nhttps_listen = \"{https}\"\ncert_dir = \"{}\"\nstate_dir = \"{}\"\naccess_log = \"{}\"\ncaddy_credentials_dir = \"{}\"\ncaddy_admin_socket = \"{}\"\n",
|
||||
d("engine"),
|
||||
fake.display(),
|
||||
d("certs"),
|
||||
d("caddy-state"),
|
||||
d("logs/caddy-access.log"),
|
||||
d("creds"),
|
||||
d("caddy/admin.sock"),
|
||||
);
|
||||
std::fs::write(env.config_path(), text).unwrap();
|
||||
env.start_control(None);
|
||||
Some(CaddyEnv { env, https })
|
||||
}
|
||||
|
||||
async fn to_caddy_with(env: &Env, echo: &ianitor_testkit::upstream::Echo) {
|
||||
let rec = env
|
||||
.apply(
|
||||
"POST",
|
||||
"/api/v1/hosts",
|
||||
Some(json!({"host": {"hostname": "a.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none"}})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(rec["state"], "kept", "{rec}");
|
||||
let r = env
|
||||
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
|
||||
.await;
|
||||
assert_eq!(r.status, 202, "{}", r.text);
|
||||
wait_engine(env, "caddy").await;
|
||||
}
|
||||
|
||||
async fn wait_state(env: &Env, id: &str, state: &str) {
|
||||
let deadline = Instant::now() + Duration::from_secs(20);
|
||||
loop {
|
||||
let r = env
|
||||
.call("GET", &format!("/api/v1/applies/{id}"), None)
|
||||
.await;
|
||||
if r.json["state"] == state {
|
||||
return;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "never {state}: {}", r.text);
|
||||
tokio::time::sleep(Duration::from_millis(250)).await;
|
||||
}
|
||||
}
|
||||
|
||||
fn b_host(echo: &ianitor_testkit::upstream::Echo) -> Value {
|
||||
json!({"host": {"hostname": "b.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none"}})
|
||||
}
|
||||
|
||||
/// QC round 2, M2: something reloads Caddy during a trial's watch (a device change, a
|
||||
/// restart of caddy-fallback). The trial is gone from Caddy; the watch must notice and
|
||||
/// treat it as interrupted, not report it kept while Caddy serves the old config.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_reload_of_caddy_during_the_watch_is_noticed() {
|
||||
let Some(ce) = caddy_env(8, true).await else {
|
||||
return;
|
||||
};
|
||||
let env = &ce.env;
|
||||
let echo = ianitor_testkit::upstream::Echo::start("app").await;
|
||||
to_caddy_with(env, &echo).await;
|
||||
let r = env.call("POST", "/api/v1/hosts", Some(b_host(&echo))).await;
|
||||
assert_eq!(r.status, 202, "{}", r.text);
|
||||
let id = r.json["apply"]["id"].as_str().unwrap().to_owned();
|
||||
wait_state(env, &id, "watching").await;
|
||||
assert_eq!(
|
||||
visit(env, ce.https, "b.test").await,
|
||||
200,
|
||||
"the trial serves"
|
||||
);
|
||||
// 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();
|
||||
let rec = env.wait_apply(&id).await;
|
||||
assert_ne!(rec["state"], "kept", "{rec}");
|
||||
assert_eq!(rec["reason"]["code"], "apply.reverted.edge_lost", "{rec}");
|
||||
let now_good = std::fs::read_to_string(env.dir.join("caddy/caddy.json")).unwrap();
|
||||
assert!(!now_good.contains("b.test"), "{now_good}");
|
||||
assert_ne!(visit(env, ce.https, "b.test").await, 200);
|
||||
}
|
||||
|
||||
/// QC round 2, minor 3: the `watching` crash point under Caddy.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_crash_while_watching_under_caddy_is_reverted() {
|
||||
let Some(mut ce) = caddy_env(4, true).await else {
|
||||
return;
|
||||
};
|
||||
let echo = ianitor_testkit::upstream::Echo::start("app").await;
|
||||
to_caddy_with(&ce.env, &echo).await;
|
||||
ce.env.kill_control();
|
||||
ce.env.start_control(Some("watching"));
|
||||
let r = ce
|
||||
.env
|
||||
.call("POST", "/api/v1/hosts", Some(b_host(&echo)))
|
||||
.await;
|
||||
assert_eq!(r.status, 202, "{}", r.text);
|
||||
let id = r.json["apply"]["id"].as_str().unwrap().to_owned();
|
||||
assert!(ce.env.wait_control_exit(Duration::from_secs(30)).is_some());
|
||||
ce.env.start_control(None);
|
||||
let rec = ce.env.wait_apply(&id).await;
|
||||
assert_eq!(rec["state"], "reverted", "{rec}");
|
||||
assert_ne!(visit(&ce.env, ce.https, "b.test").await, 200);
|
||||
assert_eq!(visit(&ce.env, ce.https, "a.test").await, 200);
|
||||
}
|
||||
|
||||
/// QC round 2, B2 (a): what systemd runs after control stops (ExecStopPost): with an
|
||||
/// unconfirmed trial in the journal, Caddy goes back to the last good caddy.json at once,
|
||||
/// without waiting for the guard's deadline.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn caddy_revert_after_a_crash_loads_the_last_good_config() {
|
||||
let Some(mut ce) = caddy_env(3, false).await else {
|
||||
return;
|
||||
};
|
||||
let echo = ianitor_testkit::upstream::Echo::start("app").await;
|
||||
to_caddy_with(&ce.env, &echo).await;
|
||||
ce.env.kill_control();
|
||||
ce.env.start_control(Some("trial_loaded"));
|
||||
let r = ce
|
||||
.env
|
||||
.call("POST", "/api/v1/hosts", Some(b_host(&echo)))
|
||||
.await;
|
||||
assert_eq!(r.status, 202, "{}", r.text);
|
||||
assert!(ce.env.wait_control_exit(Duration::from_secs(30)).is_some());
|
||||
assert_eq!(
|
||||
visit(&ce.env, ce.https, "b.test").await,
|
||||
200,
|
||||
"the trial was loaded"
|
||||
);
|
||||
let config = ce.env.config_path();
|
||||
let revert = || {
|
||||
std::process::Command::new(env!("CARGO_BIN_EXE_ianitor-control"))
|
||||
.args(["caddy-revert", "--config"])
|
||||
.arg(&config)
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let out = revert();
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
assert_ne!(visit(&ce.env, ce.https, "b.test").await, 200);
|
||||
assert_eq!(visit(&ce.env, ce.https, "a.test").await, 200);
|
||||
// After recovery there is no trial: it changes nothing and succeeds.
|
||||
ce.env.start_control(None);
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
let out = revert();
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
assert_eq!(visit(&ce.env, ce.https, "a.test").await, 200);
|
||||
}
|
||||
|
||||
/// QC r3: a device revoked while Caddy serves. Control rewrites the allow list and loads
|
||||
/// caddy.json (must-revalidate); the revoked device must no longer get in, the newly
|
||||
/// allowed one must.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn qc_device_revoked_under_caddy_is_refused() {
|
||||
use ianitor_core::pki;
|
||||
use ianitor_testkit::client::{self, ClientCert, Req};
|
||||
let Some(ce) = env_with_caddy().await else {
|
||||
return;
|
||||
};
|
||||
let env = &ce.env;
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs() as i64;
|
||||
let (root, rk) = pki::create_root(now).unwrap();
|
||||
let k = pki::generate_key().unwrap();
|
||||
let csr = pki::intermediate_csr(&k, pki::INTERMEDIATE_CN).unwrap();
|
||||
let int =
|
||||
pki::Intermediate::new(&pki::sign_intermediate(&root, &rk, &csr, now).unwrap(), k)
|
||||
.unwrap();
|
||||
let phone = pki::issue_device(&int, "phone", now).unwrap();
|
||||
let laptop = pki::issue_device(&int, "laptop", now).unwrap();
|
||||
std::fs::write(env.dir.join("certs/domi-devices-ca.pem"), int.cert_pem()).unwrap();
|
||||
std::fs::write(env.dir.join("certs/domi-devices.pem"), &phone.cert_pem).unwrap();
|
||||
let cc = |d: &pki::Issued| ClientCert {
|
||||
chain_pem: d.chain_pem.clone(),
|
||||
key_pem: d.key_pem.clone(),
|
||||
tls12_only: false,
|
||||
};
|
||||
let echo = ianitor_testkit::upstream::Echo::start("app").await;
|
||||
let rec = env
|
||||
.apply("POST", "/api/v1/hosts", Some(json!({"host": {"hostname": "d.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none", "device_certs": true}})))
|
||||
.await;
|
||||
assert_eq!(rec["state"], "kept", "{rec}");
|
||||
let r = env
|
||||
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
|
||||
.await;
|
||||
assert_eq!(r.status, 202);
|
||||
wait_engine(env, "caddy").await;
|
||||
let visit_as = |d: &pki::Issued| {
|
||||
let c = cc(d);
|
||||
let roots = env.ca.roots();
|
||||
async move {
|
||||
match client::https_with_cert(
|
||||
ce.https,
|
||||
"d.test",
|
||||
roots,
|
||||
&c,
|
||||
&Req::get("d.test", "/"),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(r) => r.status,
|
||||
Err(_) => 0,
|
||||
}
|
||||
}
|
||||
};
|
||||
let before = visit_as(&phone).await;
|
||||
eprintln!("QC phone under Caddy before revocation: {before}");
|
||||
assert_eq!(before, 200);
|
||||
// Revoke the phone, allow the laptop; tell Caddy the way control does.
|
||||
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();
|
||||
assert!(
|
||||
ianitor_control::caddy_link::runs(&sock, &text)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
let phone_after = visit_as(&phone).await;
|
||||
let laptop_after = visit_as(&laptop).await;
|
||||
eprintln!("QC after revocation under Caddy: phone {phone_after}, laptop {laptop_after}");
|
||||
assert_ne!(phone_after, 200, "revoked phone still gets in under Caddy");
|
||||
assert_eq!(
|
||||
laptop_after, 200,
|
||||
"newly allowed laptop is not let in under Caddy"
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- fix round 3
|
||||
|
||||
/// A control with the Domi CA, an intermediate signed by a test root, one device issued
|
||||
/// and approved, and `d.test` asking for device certificates. With `caddy`, Caddy serves.
|
||||
struct PkiEnv {
|
||||
ce: CaddyEnv,
|
||||
roots: std::sync::Arc<rustls::RootCertStore>,
|
||||
device_id: String,
|
||||
device: ianitor_testkit::client::ClientCert,
|
||||
}
|
||||
|
||||
async fn pki_env(watch_secs: u64, caddy: bool) -> Option<PkiEnv> {
|
||||
use ianitor_core::pki;
|
||||
let ce = caddy_env(watch_secs, true).await?;
|
||||
let mut ce = ce;
|
||||
let env = &mut ce.env;
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs() as i64;
|
||||
let (root_pem, root_key) = pki::create_root(now).unwrap();
|
||||
std::fs::write(env.dir.join("offline-root.crt"), &root_pem).unwrap();
|
||||
std::fs::write(
|
||||
env.dir.join("creds/pki-password"),
|
||||
"round-three-password-123",
|
||||
)
|
||||
.unwrap();
|
||||
let text = std::fs::read_to_string(env.config_path()).unwrap()
|
||||
+ &format!(
|
||||
"\n[pki]\nroot_cert = \"{}\"\npassword_credential = \"pki-password\"\nkdf_iterations = 1000\n",
|
||||
env.dir.join("offline-root.crt").display()
|
||||
);
|
||||
std::fs::write(env.config_path(), text).unwrap();
|
||||
env.kill_control();
|
||||
env.start_control(None);
|
||||
let cli = |env: &Env, args: &[&str]| {
|
||||
env.command()
|
||||
.args(args)
|
||||
.arg("--config")
|
||||
.arg(env.config_path())
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
// The intermediate, signed offline.
|
||||
let r = env
|
||||
.call(
|
||||
"POST",
|
||||
"/api/v1/certs/intermediate/renewal",
|
||||
Some(json!({})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 202, "{}", r.text);
|
||||
let csr = r.json["csr_pem"].as_str().unwrap().to_owned();
|
||||
let signed = pki::sign_intermediate(&root_pem, &root_key, &csr, now).unwrap();
|
||||
std::fs::write(env.dir.join("int.crt"), signed).unwrap();
|
||||
let int_path = env.dir.join("int.crt").display().to_string();
|
||||
let out = cli(env, &["pki", "install", &int_path]);
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
// One device.
|
||||
let r = env
|
||||
.call(
|
||||
"POST",
|
||||
"/api/v1/certs/devices",
|
||||
Some(json!({"name": "phone", "kind": "phone"})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, 202, "{}", r.text);
|
||||
let code = r.json["match_code"].as_str().unwrap().to_owned();
|
||||
let out = cli(env, &["pki", "approve", &code]);
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
let devices: Value = serde_json::from_str(
|
||||
&std::fs::read_to_string(env.dir.join("state/pki/devices.json")).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let d = &devices[0];
|
||||
let device_id = d["id"].as_str().unwrap().to_owned();
|
||||
let sealed =
|
||||
std::fs::read_to_string(env.dir.join(&format!("state/pki/devices/{device_id}.key")))
|
||||
.unwrap();
|
||||
let key = pki::decrypt_key(&sealed, b"round-three-password-123").unwrap();
|
||||
let int_pem = std::fs::read_to_string(env.dir.join("state/pki/intermediate.crt")).unwrap();
|
||||
let device = ianitor_testkit::client::ClientCert {
|
||||
chain_pem: format!("{}{int_pem}", d["cert_pem"].as_str().unwrap()),
|
||||
key_pem: key.serialize_pem(),
|
||||
tls12_only: false,
|
||||
};
|
||||
let mut store = rustls::RootCertStore::empty();
|
||||
store
|
||||
.add(rustls_pki_types::CertificateDer::from(
|
||||
pki::chain_der(&root_pem).unwrap().remove(0),
|
||||
))
|
||||
.unwrap();
|
||||
let echo = ianitor_testkit::upstream::Echo::start("app").await;
|
||||
let rec = env
|
||||
.apply(
|
||||
"POST",
|
||||
"/api/v1/hosts",
|
||||
Some(json!({"host": {"hostname": "d.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none", "device_certs": true}})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(rec["state"], "kept", "{rec}");
|
||||
// The echo upstream must outlive this function: keep it running in the background.
|
||||
std::mem::forget(echo);
|
||||
if caddy {
|
||||
let r = env
|
||||
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
|
||||
.await;
|
||||
assert_eq!(r.status, 202, "{}", r.text);
|
||||
wait_engine(env, "caddy").await;
|
||||
}
|
||||
Some(PkiEnv {
|
||||
ce,
|
||||
roots: std::sync::Arc::new(store),
|
||||
device_id,
|
||||
device,
|
||||
})
|
||||
}
|
||||
|
||||
impl PkiEnv {
|
||||
async fn visit_as_device(&self, at: std::net::SocketAddr) -> u16 {
|
||||
match ianitor_testkit::client::https_with_cert(
|
||||
at,
|
||||
"d.test",
|
||||
self.roots.clone(),
|
||||
&self.device,
|
||||
&ianitor_testkit::client::Req::get("d.test", "/"),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(r) => r.status,
|
||||
Err(_) => 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn serving(&self, caddy: bool) -> std::net::SocketAddr {
|
||||
if caddy {
|
||||
self.ce.https
|
||||
} else {
|
||||
self.ce.env.edge.as_ref().unwrap().https
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fix round 3 (QC r3 Major): a revocation never waits for a running apply. The DELETE
|
||||
/// answers at once, the allow list is on disk at once, and the device is refused within
|
||||
/// edge's backstop window although an apply is still watching.
|
||||
async fn revoke_during_a_watch(caddy: bool) {
|
||||
let Some(p) = pki_env(6, caddy).await else {
|
||||
return;
|
||||
};
|
||||
let env = &p.ce.env;
|
||||
let at = p.serving(caddy);
|
||||
assert_eq!(p.visit_as_device(at).await, 200, "the device gets in");
|
||||
let echo = ianitor_testkit::upstream::Echo::start("app").await;
|
||||
let r = env.call("POST", "/api/v1/hosts", Some(b_host(&echo))).await;
|
||||
assert_eq!(r.status, 202, "{}", r.text);
|
||||
let id = r.json["apply"]["id"].as_str().unwrap().to_owned();
|
||||
wait_state(env, &id, "watching").await;
|
||||
let t = Instant::now();
|
||||
let d = env
|
||||
.call(
|
||||
"DELETE",
|
||||
&format!("/api/v1/certs/devices/{}", p.device_id),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
let took = t.elapsed();
|
||||
assert_eq!(d.status, 204, "{}", d.text);
|
||||
assert!(
|
||||
took < Duration::from_millis(1500),
|
||||
"the DELETE waited {took:?}"
|
||||
);
|
||||
let allow = std::fs::read_to_string(env.dir.join("certs/domi-devices.pem")).unwrap();
|
||||
let listed = p
|
||||
.device
|
||||
.chain_pem
|
||||
.split("-----END CERTIFICATE-----")
|
||||
.next()
|
||||
.unwrap();
|
||||
assert!(
|
||||
!allow.contains(listed.trim()),
|
||||
"the revoked device is still on the list"
|
||||
);
|
||||
if caddy {
|
||||
// Caddy keeps the trial until the apply ends; then the device is out at once.
|
||||
let rec = env.wait_apply(&id).await;
|
||||
assert_eq!(rec["state"], "kept", "{rec}");
|
||||
assert_ne!(
|
||||
p.visit_as_device(at).await,
|
||||
200,
|
||||
"revoked device still gets in under Caddy"
|
||||
);
|
||||
} else {
|
||||
let deadline = Instant::now() + Duration::from_secs(6);
|
||||
while p.visit_as_device(at).await == 200 {
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"revoked device still gets in under Pingora"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(250)).await;
|
||||
}
|
||||
let rec = env.wait_apply(&id).await;
|
||||
assert_eq!(rec["state"], "kept", "{rec}");
|
||||
}
|
||||
let c = env.call("GET", "/api/v1/certs", None).await;
|
||||
assert!(c.json["devices_problem"].is_null(), "{}", c.text);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_revocation_during_a_watch_is_in_force_at_once_under_pingora() {
|
||||
revoke_during_a_watch(false).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_revocation_during_a_watch_is_in_force_when_the_apply_ends_under_caddy() {
|
||||
revoke_during_a_watch(true).await;
|
||||
}
|
||||
|
||||
/// Fix round 3, minor 3: with Pingora serving, a deadline file left behind is cleared and
|
||||
/// caddy-revert succeeds (the unit must not show failed).
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn caddy_revert_with_pingora_serving_clears_a_stale_deadline() {
|
||||
let mut env = env().await;
|
||||
env.kill_control();
|
||||
std::fs::write(
|
||||
env.dir.join("state/caddy-trial.json"),
|
||||
r#"{"apply_id":"ch_x","deadline":1}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let out = env
|
||||
.command()
|
||||
.args(["caddy-revert", "--config"])
|
||||
.arg(env.config_path())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
assert!(!env.dir.join("state/caddy-trial.json").exists());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- fix round 4
|
||||
|
||||
async fn engine_view(env: &Env) -> Value {
|
||||
env.call("GET", "/api/v1/engine", None).await.json
|
||||
}
|
||||
|
||||
async fn wait_switching(env: &Env) {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while engine_view(env).await["state"] != "switching" {
|
||||
assert!(Instant::now() < deadline, "the switch never started");
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_switch_over(env: &Env) -> Value {
|
||||
let deadline = Instant::now() + Duration::from_secs(40);
|
||||
loop {
|
||||
let e = engine_view(env).await;
|
||||
if e["state"] == "running" {
|
||||
return e;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "the switch never ended: {e}");
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn revoke(env: &Env, id: &str) {
|
||||
let t = Instant::now();
|
||||
let d = env
|
||||
.call("DELETE", &format!("/api/v1/certs/devices/{id}"), None)
|
||||
.await;
|
||||
assert_eq!(d.status, 204, "{}", d.text);
|
||||
assert!(
|
||||
t.elapsed() < Duration::from_secs(3),
|
||||
"the DELETE waited {:?}",
|
||||
t.elapsed()
|
||||
);
|
||||
}
|
||||
|
||||
async fn refused_soon(p: &PkiEnv, at: std::net::SocketAddr, what: &str) {
|
||||
let deadline = Instant::now() + Duration::from_secs(4);
|
||||
while p.visit_as_device(at).await == 200 {
|
||||
assert!(Instant::now() < deadline, "{what}");
|
||||
tokio::time::sleep(Duration::from_millis(250)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// QC round 4, case A: a device is revoked while a switch to Caddy is still waiting for
|
||||
/// the unit, after Caddy has already read the allow list. The switch ends by telling
|
||||
/// Caddy again, so the device is refused once Caddy serves.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_revocation_during_a_switch_to_caddy_is_in_force_when_it_ends() {
|
||||
let Some(p) = pki_env(2, false).await else {
|
||||
return;
|
||||
};
|
||||
let env = &p.ce.env;
|
||||
std::fs::write(env.dir.join("fake/start-delay"), "5").unwrap();
|
||||
let r = env
|
||||
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
|
||||
.await;
|
||||
assert_eq!(r.status, 202, "{}", r.text);
|
||||
wait_switching(env).await;
|
||||
// Caddy is up and has read its files; the unit is not reported active yet.
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while p.visit_as_device(p.ce.https).await != 200 {
|
||||
assert!(Instant::now() < deadline, "Caddy did not come up");
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
}
|
||||
assert_eq!(engine_view(env).await["state"], "switching");
|
||||
revoke(env, &p.device_id).await;
|
||||
let e = wait_switch_over(env).await;
|
||||
assert_eq!(e["running"], "caddy", "{e}");
|
||||
refused_soon(
|
||||
&p,
|
||||
p.ce.https,
|
||||
"the revoked device still gets in under Caddy after the switch",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
/// QC round 4, case B: a switch away from Caddy fails before Caddy is stopped, and a
|
||||
/// device was revoked meanwhile. The Caddy that kept serving must refuse it.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_revocation_during_a_failed_switch_away_from_caddy_is_in_force() {
|
||||
let Some(p) = pki_env(2, true).await else {
|
||||
return;
|
||||
};
|
||||
let env = &p.ce.env;
|
||||
assert_eq!(
|
||||
p.visit_as_device(p.ce.https).await,
|
||||
200,
|
||||
"the device gets in"
|
||||
);
|
||||
std::fs::write(env.dir.join("fake/stop-delay"), "4").unwrap();
|
||||
std::fs::write(env.dir.join("fake/fail-stop"), "caddy-fallback.service\n").unwrap();
|
||||
let r = env
|
||||
.call("POST", "/api/v1/engine", Some(json!({"target": "pingora"})))
|
||||
.await;
|
||||
assert_eq!(r.status, 202, "{}", r.text);
|
||||
wait_switching(env).await;
|
||||
revoke(env, &p.device_id).await;
|
||||
let e = wait_switch_over(env).await;
|
||||
assert_eq!(e["running"], "caddy", "{e}");
|
||||
assert!(!e["last_error"].is_null(), "{e}");
|
||||
refused_soon(
|
||||
&p,
|
||||
p.ce.https,
|
||||
"the revoked device still gets in under the Caddy that kept serving",
|
||||
)
|
||||
.await;
|
||||
// Nothing is left pending.
|
||||
let deadline = Instant::now() + Duration::from_secs(6);
|
||||
loop {
|
||||
let c = env.call("GET", "/api/v1/certs", None).await;
|
||||
if c.json["devices_problem"].is_null() {
|
||||
break;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "{}", c.text);
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,12 +78,23 @@ pub fn hostname(host_header: &str) -> String {
|
||||
/// The client's address: the peer, or, when the peer is a trusted proxy, the rightmost
|
||||
/// `X-Forwarded-For` entry that is not itself trusted (the same right-to-left rule as Caddy's
|
||||
/// `trusted_proxies_strict`). Anything a client could forge to the left is ignored.
|
||||
/// An IPv4 address carried as IPv6 (`::ffff:127.0.0.1`) is the IPv4 address.
|
||||
fn canonical(ip: IpAddr) -> IpAddr {
|
||||
match ip {
|
||||
IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(ip, IpAddr::V4),
|
||||
v4 => v4,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn client_ip(session: &Session, trusted: &[IpAddr]) -> Option<IpAddr> {
|
||||
let peer = session
|
||||
.client_addr()
|
||||
.and_then(|a| a.as_inet())
|
||||
.map(|a| a.ip())?;
|
||||
if !trusted.contains(&peer) {
|
||||
let peer = canonical(
|
||||
session
|
||||
.client_addr()
|
||||
.and_then(|a| a.as_inet())
|
||||
.map(|a| a.ip())?,
|
||||
);
|
||||
let trusted_ip = |ip: &IpAddr| trusted.iter().any(|t| canonical(*t) == *ip);
|
||||
if !trusted_ip(&peer) {
|
||||
return Some(peer);
|
||||
}
|
||||
let mut last = peer;
|
||||
@@ -96,8 +107,8 @@ pub fn client_ip(session: &Session, trusted: &[IpAddr]) -> Option<IpAddr> {
|
||||
{
|
||||
let Ok(s) = v.to_str() else { return Some(last) };
|
||||
for part in s.rsplit(',') {
|
||||
match part.trim().parse::<IpAddr>() {
|
||||
Ok(ip) if trusted.contains(&ip) => last = ip,
|
||||
match part.trim().parse::<IpAddr>().map(canonical) {
|
||||
Ok(ip) if trusted_ip(&ip) => last = ip,
|
||||
Ok(ip) => return Some(ip),
|
||||
Err(_) => return Some(last),
|
||||
}
|
||||
@@ -506,6 +517,14 @@ pub fn contains(hay: &[u8], needle: &[u8]) -> bool {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_ipv4_mapped_address_is_the_ipv4_address() {
|
||||
let m = IpAddr::V6(std::net::Ipv4Addr::LOCALHOST.to_ipv6_mapped());
|
||||
assert_eq!(canonical(m), IpAddr::V4(std::net::Ipv4Addr::LOCALHOST));
|
||||
let v6 = IpAddr::V6(std::net::Ipv6Addr::LOCALHOST);
|
||||
assert_eq!(canonical(v6), v6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostname_strips_port_and_case() {
|
||||
assert_eq!(hostname("App.Test:8443"), "app.test");
|
||||
|
||||
@@ -264,4 +264,76 @@ mod unix {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// QC r2: end to end through Pingora (2 worker threads, pre-TLS hook): a handshake that
|
||||
/// fails after the resolver (bad ALPN) must not break the next TLS 1.2 device handshake.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn qc_tls12_device_after_bad_alpn_handshakes_end_to_end() {
|
||||
use std::sync::Arc;
|
||||
let echo = Echo::start("app").await;
|
||||
let p = pki();
|
||||
let (phone, phone_pem) = device(&p, "phone");
|
||||
let edge = setup(&echo, &p, &[&phone_pem]).await;
|
||||
let roots = edge.roots();
|
||||
let req = Req::get("locked.test", "/");
|
||||
let mut failures = Vec::new();
|
||||
let mut poisoned = 0;
|
||||
for i in 0..40 {
|
||||
let addr = edge.https;
|
||||
let r2 = roots.clone();
|
||||
let failed = tokio::task::spawn_blocking(move || {
|
||||
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||
let mut cfg = rustls::ClientConfig::builder_with_provider(provider)
|
||||
.with_safe_default_protocol_versions()
|
||||
.unwrap()
|
||||
.with_root_certificates(r2)
|
||||
.with_no_client_auth();
|
||||
cfg.alpn_protocols = vec![b"foo".to_vec()];
|
||||
let mut conn = rustls::ClientConnection::new(
|
||||
Arc::new(cfg),
|
||||
rustls_pki_types::ServerName::try_from("open.test".to_owned()).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut sock = std::net::TcpStream::connect(addr).unwrap();
|
||||
sock.set_read_timeout(Some(std::time::Duration::from_secs(5)))
|
||||
.unwrap();
|
||||
let mut r = Ok((0, 0));
|
||||
for _ in 0..5 {
|
||||
r = conn.complete_io(&mut sock);
|
||||
if r.is_err() || !conn.is_handshaking() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
r.is_err()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
if failed {
|
||||
poisoned += 1;
|
||||
}
|
||||
match client::https_with_cert(
|
||||
edge.https,
|
||||
"locked.test",
|
||||
roots.clone(),
|
||||
&tls12(&phone),
|
||||
&req,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(r) if r.status == 200 => {}
|
||||
other => failures.push(format!("{i}: {other:?}")),
|
||||
}
|
||||
}
|
||||
eprintln!(
|
||||
"QC poison handshakes that failed: {poisoned}/40; device failures: {}",
|
||||
failures.len()
|
||||
);
|
||||
assert_eq!(poisoned, 40, "the poison handshake must fail");
|
||||
assert!(
|
||||
failures.is_empty(),
|
||||
"{} of 40 TLS 1.2 device handshakes failed: {:?}",
|
||||
failures.len(),
|
||||
failures.first()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+30
-3
@@ -151,7 +151,7 @@ in
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
example = [ "127.0.0.1" ];
|
||||
description = "Proxies in front of edge whose X-Forwarded-For names the client (beside Caddy: 127.0.0.1), for the share-link throttle and the access log. Off by default.";
|
||||
description = "Proxies in front of edge whose X-Forwarded-For names the client (beside Caddy: 127.0.0.1), for the share-link throttle and the access log. Off by default: on a loopback listener any local process could then claim any address (docs/deploy/beside-caddy.md).";
|
||||
};
|
||||
};
|
||||
|
||||
@@ -252,7 +252,9 @@ in
|
||||
}) userCreds;
|
||||
|
||||
users.groups.ianitor = { };
|
||||
users.users.ianitor-control = { isSystemUser = true; group = "ianitor"; home = "${stateRoot}/control"; };
|
||||
# Only control (and Caddy itself) may reach Caddy's admin socket; edge is not in it.
|
||||
users.groups.ianitor-caddy-admin = { };
|
||||
users.users.ianitor-control = { isSystemUser = true; group = "ianitor"; extraGroups = [ "ianitor-caddy-admin" ]; home = "${stateRoot}/control"; };
|
||||
users.users.ianitor-edge = { isSystemUser = true; group = "ianitor"; };
|
||||
users.users.caddy-fallback = { isSystemUser = true; group = "ianitor"; };
|
||||
|
||||
@@ -300,6 +302,10 @@ in
|
||||
User = "ianitor-control";
|
||||
Group = "ianitor";
|
||||
ExecStart = "${pkg}/bin/ianitor-control --config ${controlToml}";
|
||||
# After every stop, a crash included: a trial still loaded into Caddy goes back to the
|
||||
# last good caddy.json at once (ianitor_control::caddy_guard). It runs after a crash
|
||||
# too, so no separate OnFailure= unit is needed.
|
||||
ExecStopPost = "${pkg}/bin/ianitor-control caddy-revert --config ${controlToml}";
|
||||
LoadCredential = loadCreds controlCreds ++ [ "ui-proof:${runProof}/ui-proof" ];
|
||||
ReadWritePaths = [ stateRoot ];
|
||||
Restart = "on-failure";
|
||||
@@ -352,7 +358,10 @@ in
|
||||
};
|
||||
serviceConfig = hardening // {
|
||||
User = "caddy-fallback";
|
||||
Group = "ianitor";
|
||||
# The admin socket (and its runtime directory) belong to this group; "ianitor" for the
|
||||
# certificates and logs.
|
||||
Group = "ianitor-caddy-admin";
|
||||
SupplementaryGroups = [ "ianitor" ];
|
||||
ExecStart = "${cfg.caddyPackage}/bin/caddy run --config ${stateRoot}/caddy/caddy.json";
|
||||
LoadCredential = loadCreds cfg.credentials ++ [ "ui-proof:${runProof}/ui-proof" ];
|
||||
RuntimeDirectory = "caddy-fallback";
|
||||
@@ -367,6 +376,24 @@ in
|
||||
};
|
||||
};
|
||||
|
||||
# The deadline of a trial under Caddy, outside control (a hung control included): once a
|
||||
# second it reverts a trial past its deadline to the last good caddy.json. Runs with Caddy.
|
||||
systemd.services.ianitor-caddy-guard = {
|
||||
description = "Ianitor: deadline for changes tried on Caddy";
|
||||
partOf = [ "caddy-fallback.service" ];
|
||||
after = [ "caddy-fallback.service" ];
|
||||
wantedBy = [ "caddy-fallback.service" ];
|
||||
environment.IANITOR_LOG = "info";
|
||||
serviceConfig = hardening // {
|
||||
User = "ianitor-control";
|
||||
Group = "ianitor";
|
||||
ExecStart = "${pkg}/bin/ianitor-control caddy-guard --config ${controlToml}";
|
||||
ReadWritePaths = [ "${stateRoot}/control" ];
|
||||
Restart = "always";
|
||||
RestartSec = 1;
|
||||
};
|
||||
};
|
||||
|
||||
# At boot: start the engine the UI chose last (ROADMAP §3).
|
||||
systemd.services.ianitor-engine-select = {
|
||||
description = "Ianitor: start the chosen engine";
|
||||
|
||||
@@ -157,6 +157,27 @@ in
|
||||
assert wait_apply(server, t, r["apply"]["id"])["state"] == "kept"
|
||||
server.succeed("curl -s -o /dev/null -w '%{http_code}' --cacert ${testRoot}/domi-root.crt --resolve two.test:443:127.0.0.1 https://two.test/ | grep -q 200")
|
||||
|
||||
# The trial's deadline under Caddy does not depend on control (fix round 2, B2): the guard
|
||||
# runs with Caddy, only control may use Caddy's admin socket, and a control killed during
|
||||
# the watch leaves Caddy on the last good config (ExecStopPost=caddy-revert).
|
||||
server.succeed("systemctl is-active ianitor-caddy-guard.service")
|
||||
server.fail("runuser -u ianitor-edge -- test -w /run/caddy-fallback/admin.sock")
|
||||
server.succeed("runuser -u ianitor-control -- test -w /run/caddy-fallback/admin.sock")
|
||||
r = api(server, t, "POST", "/hosts", {"host": {
|
||||
"hostname": "three.test", "upstreams": ["http://127.0.0.1:8000"], "tls": "domi", "auth": "none"}})
|
||||
three = r["apply"]["id"]
|
||||
for _ in range(60):
|
||||
if api(server, t, "GET", f"/applies/{three}").get("state") == "watching":
|
||||
break
|
||||
time.sleep(0.5)
|
||||
assert visit(server, "three.test") == "200", "the trial serves"
|
||||
server.succeed("systemctl kill --signal=KILL ianitor-control.service")
|
||||
server.wait_until_fails("curl -s -o /dev/null -w '%{http_code}' --cacert ${testRoot}/domi-root.crt --resolve three.test:443:127.0.0.1 https://three.test/ | grep -q 200", timeout=10)
|
||||
server.wait_for_unit("ianitor-control.service")
|
||||
server.wait_until_succeeds(f"curl -sf -H 'Authorization: Bearer {t}' http://127.0.0.1:7878/api/v1/overview")
|
||||
assert wait_apply(server, t, three)["state"] == "reverted"
|
||||
assert visit(server, "two.test") == "200"
|
||||
|
||||
api(server, t, "POST", "/engine", {"target": "pingora"})
|
||||
server.wait_until_succeeds(
|
||||
f"curl -s -H 'Authorization: Bearer {t}' http://127.0.0.1:7878/api/v1/engine | jq -e '.running == \"pingora\" and .state == \"running\"'"
|
||||
|
||||
+42
-2
@@ -144,13 +144,53 @@ Identity gate, tunnel, Domi templates, ACME server, HTTP/3, migrating public sit
|
||||
|:--|:--|:--|
|
||||
| 1 Core and engine | Done | Merged to main 2026-11-07. Tests run in WSL2; ACME checked only against Pebble. The Let's Encrypt staging check moved to phase 3 (Mark, 2026-11-07). |
|
||||
| 2 Control plane | Done | Merged to main 2026-11-07 (PR 3): routes repo, journaled apply with trial/watch/revert, undo, restore, share links, API tokens, REST API + OpenAPI, `--dev`. Four QC rounds; every finding fixed or listed in Handover. Real Gitea, systemd credentials and Authelia not exercised. |
|
||||
| 3 Web UI, PKI, NixOS | Not started | UI design drafted: claude.ai/artifact/GEiCCPcGC1hiCkA2NrrH9u ("murex" palette on the Domi system, approved). Carries the Let's Encrypt staging check, on the first low-risk host beside Caddy. |
|
||||
| 3 Web UI, PKI, NixOS | Built and merged; Done criteria pending Mark | Merged to main 2026-11-08 (PR 5): web UI (murex palette), Domi CA and device mTLS, UI sign-in behind Authelia, runtime engine switch with changes under Caddy, NixOS flake, module and VM tests. Click smoke test green. Not yet done: VM tests run on a KVM host, Mark's nixos-rebuild on the staging mirror, deploy/test-access.sh there, the LE staging check. |
|
||||
| 4 Hardening and release | Not started | Known gaps carried here: see Handover. |
|
||||
|
||||
## 10. Handover
|
||||
(Rewritten at the end of every session: what changed, what was not verified, which build is deployed, the next step.)
|
||||
|
||||
**2026-11-07: Phase 2, control plane.**
|
||||
**2026-11-08: Ianitor declared to Fabrica.**
|
||||
- **Changed:** `.fabrica/app.yaml` (a server part, flake input `ianitor`) and `.fabrica/artifex/deploy.yaml` (approve,
|
||||
then `deploy: ianitor`), so Fabrica's Apps screen shows an Ianitor card with Deploy. `fabrica artifex check`: 0 problems.
|
||||
- **Deployed:** nothing; no deploy was started.
|
||||
- **For Mark, before the card's Deploy can work:** the server flake needs the `ianitor` input (the patch in
|
||||
docs/deploy/configuration-server.patch; with `rev=` pinned, `nix flake update ianitor` cannot move it, so drop the
|
||||
`rev=` once the first lock is reviewed), and `ianitor` in `services.fabrica-artifex.deploy.inputs` (Fabrica
|
||||
docs/04_deploy.md) with its health URL.
|
||||
|
||||
**2026-11-08: Phase 3, web UI, PKI, NixOS.**
|
||||
- **Changed:**
|
||||
- apps/web and packages/ui: Svelte 5 UI from the designer's hand-off (docs/ui-handoff.md, decisions in docs/ui-decisions.md), murex palette, self-hosted fonts, no outside requests (CSP). vitest click smoke test for every §4 flow, with the accepted 4th clicks.
|
||||
- Domi CA in core and control (docs/pki.md): ECDSA P-256; root made offline by `ianitor-control ca init`; intermediate key encrypted at rest; server certificates 90 days, device certificates 1 year and never past the intermediate; control refuses to start with a private key it does not expect in its state dir. Device mTLS in edge and Caddy (`device_certs` hosts, allow list, 421 on SNI/Host mismatch).
|
||||
- §8.6 answered: Custos has no CSR signing; ticket written (docs/custos-ticket.md, not filed); interim manual openssl signing and `pki approve` on the server.
|
||||
- UI sign-in (G14): a per-boot `ui-proof` secret that only the admin host behind Authelia sends; control trusts Remote-User only with it.
|
||||
- Engine switch at runtime through polkit (start/stop of exactly two units). Changes keep working under Caddy: trials loaded through its admin socket, watched by probing upstreams with edge's rules, reverted by control, a deadline guard unit, or ExecStopPost after a crash. Share links are off under Caddy.
|
||||
- Test hooks moved behind the default `test-hooks` feature; the Nix release build is checked to contain none.
|
||||
- flake.nix (`.#ianitor`, `.#ianitor-web`, `nixosModules.ianitor`), deploy/nixos with four VM tests, deploy/test-access.sh; docs/deploy/configuration-server.patch and beside-caddy.md (flowers.stage and esp32.stage on the staging mirror, the LE staging check).
|
||||
- Tests: core 103, edge 57, control 75, diff 4, testkit 1 (240); vitest 15; svelte-check clean; hook self-test 55. Four QC rounds and two design reviews; every finding fixed or listed below.
|
||||
- **Deployed:** nothing. The server is unchanged. The prepared change is docs/deploy/configuration-server.patch; Mark runs it (beside-caddy.md).
|
||||
- **Not verified:**
|
||||
- The four NixOS VM tests: written and their drivers build, but never run (no /dev/kvm in WSL2).
|
||||
- Real systemd, polkit, LoadCredential, Authelia, Gitea push and Caddy under systemd; the module against hyperv-infra's nixpkgs 24.11.
|
||||
- The caddy guard retrying a failed load (code reading only).
|
||||
- PKCS#12 (AES-256) install on older iOS and macOS; a screen reader; a real clipboard copy in Chrome, Firefox and iOS Safari.
|
||||
- https upstreams: Caddy-path probes use the system CA bundle; not compared with Pingora's roots.
|
||||
- **Known gaps for later phases:**
|
||||
- Edge beside Caddy listens on loopback TCP, so any local process could forge X-Forwarded-For; `trustedProxies` stays off there. A Unix-socket listener is the fix. (phase 4)
|
||||
- Control on a Unix socket only edge can reach (G14 option b). (phase 4)
|
||||
- Share links under Caddy need a validator Caddy calls via forward_auth. (before v1.1)
|
||||
- "All hosts answered" after a switch is not claimed: control does not check every host.
|
||||
- A revocation during an engine switch reaches the engine at the end of the switch (or by the 2 s retry), not at once.
|
||||
- The open `apply_sequence` flake from phase 2 has not recurred, but its cause is still unknown.
|
||||
- **Decided by Mark (2026-11-07/08):** the share link on a host with links off keeps 4 clicks; UI sign-in by a secret header from edge; the switch to Caddy is allowed with differences shown; share links off under Caddy for v1; device approval falls back to `pki approve`; manual intermediate signing is a §4 exception; device certificates last 1 year; confirmations on Stop all and Revoke; hidden tabs stop polling after 15 minutes; token lifetime choice; "Open to anyone" chip; production runs Authelia outside Configuration_Server; trial hosts flowers.stage and esp32.stage; changes keep working under Caddy.
|
||||
- **Still open:**
|
||||
- Mark: add hyperv-infra/ianitor/domi-root.crt (made offline), apply the patch with the merged commit hash, deploy to the staging mirror, run deploy/test-access.sh, then the LE staging check (it needs a new public name on production).
|
||||
- Run the VM tests on a machine with KVM (`nix flake check`).
|
||||
- (e) Delete F:\pwt and the merged remote branches.
|
||||
- **Next step:** Mark's staging deploy and the VM tests close Phase 3; then Phase 4.
|
||||
|
||||
**2026-11-07: Phase 2, control plane** (kept for its open items).
|
||||
- **Changed:**
|
||||
- Phase 2 on branch control/phase-2: crates/control (routes repo through the `git` binary, journaled apply with edge trial reloads, 60 s watch and revert, undo/redo, restore, push with retry, share links, API tokens, REST API with OpenAPI, `--dev`), edge in-process reload over an admin Unix socket, share-link checks and visitor pages in edge, share tokens and the exact `hosts/<hostname>.toml` loader in core.
|
||||
- docs/api.md (curl examples, run end to end against `--dev`) and docs/ui-api.md (the designer's contract for phase 3, with the deviations listed at its end).
|
||||
|
||||
+26
-7
@@ -309,22 +309,41 @@ allows exactly `ianitor-edge.service` and `caddy-fallback.service`, verbs start
|
||||
waits until it serves; if it does not within 20 s, it starts the old one again and reports
|
||||
`engine.switch_failed`. The switch waits for a running apply (same lock, first come first
|
||||
served: a queued switch runs right after the apply in progress, before any apply queued after
|
||||
it). Back on Pingora, edge is reloaded so it serves what was applied while Caddy served.
|
||||
it). Back on Pingora, edge is reloaded so it serves what was applied while Caddy served. Every
|
||||
switch, kept or gone back, ends by telling the engine that serves to read the device files again;
|
||||
a device change during a switch only writes them and shows `devices_problem` ("an engine switch is
|
||||
under way") until then, and the 2 s retry tells the serving engine too.
|
||||
Refusals: `engine.unmanaged` (no `[engine]` in control.toml), `engine.same`, `engine.switching`,
|
||||
`engine.not_ready` (Caddy's settings cannot be built from the current routes).
|
||||
|
||||
While Caddy serves (decisions Q3, Q4; Mark 2026-11-08):
|
||||
- **changes keep working**: applies, Undo and Restore go through the same pipeline. Both outputs
|
||||
are compiled; the trial is loaded into Caddy through its admin API (`POST /load` on the Unix
|
||||
socket `[compile_caddy] caddy_admin_socket`, `/run/caddy-fallback/admin.sock` under NixOS), the
|
||||
touched hosts are probed *through Caddy* for the watch window, and a revert loads the previous
|
||||
`caddy.json` again. Without `caddy_admin_socket` an apply under Caddy fails with
|
||||
`apply.failed.reload` and nothing changes;
|
||||
socket `[compile_caddy] caddy_admin_socket`, `/run/caddy-fallback/admin.sock` under NixOS,
|
||||
group `ianitor-caddy-admin`: control and Caddy, not edge), and a revert loads the previous
|
||||
`caddy.json` again. Every load sends `Cache-Control: must-revalidate`, so Caddy reads its
|
||||
certificate and device files again even when the config is unchanged. The watch judges health
|
||||
as edge does: control probes the upstreams itself with edge's rules (health check: `GET <path>`,
|
||||
Host = the upstream, 2xx; none: `GET /`, Host = the hostname, below 500), and a probe *through*
|
||||
Caddy only asks that Caddy answers at all (any status, its sign-in redirect included). Each
|
||||
round also checks that Caddy still runs the trial (`GET /config/`); if anything else reloaded it,
|
||||
the change is undone as `apply.reverted.edge_lost`. Without `caddy_admin_socket` an apply under
|
||||
Caddy fails with `apply.failed.reload` and nothing changes;
|
||||
- **an unconfirmed trial never outlives control**, as with edge: control arms a deadline
|
||||
(`caddy-trial.json` in its state directory: watch + margin) before loading the trial and claims
|
||||
it right after the journal says `confirmed` (a crash in between leaves both, and recovery
|
||||
promotes). A guard revert counts only once Caddy is verified on caddy.json; a failed load is
|
||||
retried with a growing pause. With Pingora serving, caddy-revert only clears a stale deadline. `ianitor-caddy-guard` (a unit that runs with caddy-fallback,
|
||||
`ianitor-control caddy-guard`) reverts a trial past its deadline, which covers a hung control;
|
||||
ianitor-control's `ExecStopPost=ianitor-control caddy-revert` reverts at once after any stop or
|
||||
crash. Whoever renames the deadline file first wins, so a trial is either kept or reverted;
|
||||
- device issues and revocations never wait for an apply: the files are written and edge is told
|
||||
at once. Under Caddy, Caddy is reloaded at once and checked to serve the certificate on disk
|
||||
for a Domi host (else `devices_problem`, retried), except while a trial is out: then the end
|
||||
of that apply (promote or revert, both load caddy.json) brings the new files in;
|
||||
- **share links are off**: minting is `409 share.engine_caddy`, and a visitor with a link gets the
|
||||
normal sign-in (fails closed). Caddy cannot check a share token and control never serves
|
||||
visitors; a validator Caddy calls through `forward_auth` is planned before v1.1;
|
||||
- device issues and revocations reload Caddy through the same socket (Caddy reads the allow list
|
||||
when a config is loaded).
|
||||
|
||||
A revocation is in force only once the serving engine has the new list. If the list cannot be
|
||||
written or the engine does not take it, `DELETE /certs/devices/{id}` answers `503
|
||||
|
||||
@@ -32,6 +32,14 @@ visitor ── Caddy :443 (as today) ── https://127.0.0.1:18443 Ianitor edg
|
||||
- Caddy keeps the public side for the two names and hands them to Ianitor over TLS; Ianitor
|
||||
serves them with Domi certificates, which Caddy checks against the Domi root (a public file).
|
||||
- Every other host is untouched. Rollback: revert the patch and switch (below).
|
||||
- Visitor addresses: Ianitor sees every visit coming from 127.0.0.1 (Caddy), so the share-link
|
||||
throttle counts all visitors together and the visit log shows 127.0.0.0. The option
|
||||
`services.ianitor.edge.trustedProxies = [ "127.0.0.1" ]` would make edge believe Caddy's
|
||||
`X-Forwarded-For` instead, but edge listens on a TCP port on loopback that **any local user or
|
||||
process can reach**, and any of them could then claim any address. It stays **off** for the
|
||||
trial (the two hosts have no share links and no visit log); turn it on only on a machine where
|
||||
every local account is trusted. (A Unix-socket listener for edge, which Caddy alone could reach,
|
||||
is the proper fix; not built yet.)
|
||||
|
||||
## The patch
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@ new file mode 100644
|
||||
index 0000000..cd23016
|
||||
--- /dev/null
|
||||
+++ b/hyperv-infra/modules/ianitor.nix
|
||||
@@ -0,0 +1,51 @@
|
||||
@@ -0,0 +1,49 @@
|
||||
+{ config, lib, inputs, ... }:
|
||||
+
|
||||
+# Ianitor beside Caddy (Ianitor ROADMAP §1.12, Phase 3): two low-risk hosts, flowers and esp32,
|
||||
@@ -100,8 +100,6 @@ index 0000000..cd23016
|
||||
+ httpListen = "127.0.0.1:18080";
|
||||
+ httpsListen = "127.0.0.1:18443";
|
||||
+ openFirewall = false;
|
||||
+ # Caddy in front, on loopback: its X-Forwarded-For names the visitor (throttle, logs).
|
||||
+ trustedProxies = [ "127.0.0.1" ];
|
||||
+ };
|
||||
+ control.listen = "127.0.0.1:7878";
|
||||
+ shareLinkKeyFile = config.sops.secrets."ianitor/share-link-key".path;
|
||||
|
||||
+2
-1
@@ -545,4 +545,5 @@ Recorded by the Phase 3 implementation (branch `phase-3`); docs/api.md has the c
|
||||
10 minutes.
|
||||
- New host field `device_certs` (bool): only Domi device certificates on the allow list get in.
|
||||
- `overview.paused_reason` gives the underlying code (`apply.needs_attention`,
|
||||
`control.files_unwritten`, `repo.*`) next to `paused {code: "control.paused"}`.
|
||||
`control.files_unwritten`, `repo.*`) next to `paused {code: "control.paused"}`, and
|
||||
`overview.paused_detail` the technical detail behind it (for "Show details").
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
onclose,
|
||||
escape = true,
|
||||
closable = true,
|
||||
toggle,
|
||||
children,
|
||||
footer,
|
||||
}: {
|
||||
@@ -26,6 +27,8 @@
|
||||
onclose: () => void;
|
||||
escape?: boolean;
|
||||
closable?: boolean;
|
||||
/** A popover's opener (a CSS selector): a click there is the opener's, which toggles it. */
|
||||
toggle?: string;
|
||||
children?: Snippet;
|
||||
footer?: Snippet;
|
||||
} = $props();
|
||||
@@ -39,12 +42,32 @@
|
||||
if (modal && typeof el.showModal === "function") el.showModal();
|
||||
else if (typeof el.show === "function") el.show();
|
||||
else el.setAttribute("open", "");
|
||||
const first = el.querySelector<HTMLElement>(
|
||||
"[data-autofocus], input:not([type=hidden]):not([readonly]):not([type=radio]), textarea, select",
|
||||
);
|
||||
const first =
|
||||
el.querySelector<HTMLElement>("[data-autofocus]") ??
|
||||
el.querySelector<HTMLElement>("input:not([type=hidden]):not([readonly]):not([type=radio]), textarea:not([readonly]), select");
|
||||
(first ?? el.querySelector<HTMLElement>(".ia-dialog-title"))?.focus();
|
||||
}
|
||||
// A dialog opened with show() (the popover) gets no cancel event: Esc and a click outside
|
||||
// close it here, like the modal ones.
|
||||
const key = (e: KeyboardEvent) => {
|
||||
if (!modal && e.key === "Escape" && escape) {
|
||||
e.preventDefault();
|
||||
onclose();
|
||||
}
|
||||
};
|
||||
const down = (e: PointerEvent) => {
|
||||
if (!modal && escape && el && e.target instanceof Node && !el.contains(e.target)) {
|
||||
if (toggle && e.target instanceof Element && e.target.closest(toggle)) return;
|
||||
onclose();
|
||||
}
|
||||
};
|
||||
document.addEventListener("keydown", key);
|
||||
// On the next turn, so the click that opened the popover does not close it.
|
||||
const t = setTimeout(() => document.addEventListener("pointerdown", down), 0);
|
||||
return () => {
|
||||
clearTimeout(t);
|
||||
document.removeEventListener("keydown", key);
|
||||
document.removeEventListener("pointerdown", down);
|
||||
if (opener instanceof HTMLElement && document.contains(opener)) opener.focus();
|
||||
};
|
||||
});
|
||||
|
||||
@@ -12,6 +12,15 @@
|
||||
@import "@fontsource/manrope/latin-400.css";
|
||||
@import "@fontsource/manrope/latin-600.css";
|
||||
@import "@fontsource/manrope/latin-700.css";
|
||||
/* latin-ext: Czech names and places (č, ř, ů) in host names, device names and messages. */
|
||||
@import "@fontsource/cinzel/latin-ext-500.css";
|
||||
@import "@fontsource/cormorant-garamond/latin-ext-500.css";
|
||||
@import "@fontsource/cormorant-garamond/latin-ext-600.css";
|
||||
@import "@fontsource/manrope/latin-ext-400.css";
|
||||
@import "@fontsource/manrope/latin-ext-600.css";
|
||||
@import "@fontsource/manrope/latin-ext-700.css";
|
||||
|
||||
html, body { margin: 0; }
|
||||
|
||||
.ia .sr-only {
|
||||
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden;
|
||||
@@ -98,7 +107,10 @@
|
||||
.ia .ia-engine small { color: var(--muted); font-weight: 400; font-size: 0.86rem; }
|
||||
|
||||
/* ── Lists and rows (§2.5) ──────────────────────────────────────────────── */
|
||||
.ia .ia-list { border: 1px solid var(--hairline); border-radius: var(--radius-lg); overflow: hidden; }
|
||||
.ia .ia-list { border: 1px solid var(--hairline); border-radius: var(--radius-lg); }
|
||||
/* No overflow clipping on the list: a row's menu must reach past it. The end rows carry the corners. */
|
||||
.ia .ia-list > :first-child { border-top-left-radius: calc(var(--radius-lg) - 1px); border-top-right-radius: calc(var(--radius-lg) - 1px); }
|
||||
.ia .ia-list > :last-child { border-bottom-left-radius: calc(var(--radius-lg) - 1px); border-bottom-right-radius: calc(var(--radius-lg) - 1px); }
|
||||
.ia .ia-row { display: grid; grid-template-columns: 128px minmax(0, 1.4fr) minmax(0, 1.6fr) 44px; gap: 16px; padding: 12px 10px 12px 18px; align-items: start; border-top: 1px solid var(--hairline); }
|
||||
.ia .ia-row:first-child { border-top: 0; }
|
||||
.ia .ia-row.head { background: var(--colonnade); padding-top: 10px; padding-bottom: 10px; align-items: center; }
|
||||
@@ -121,6 +133,7 @@
|
||||
background: none; color: var(--text-2); font-weight: 600; font-size: 0.92rem; text-align: left; cursor: pointer;
|
||||
}
|
||||
.ia .ia-menu [role="menuitem"]:hover, .ia .ia-menu [role="menuitem"]:focus { background: var(--surface-2); color: var(--text); outline: none; }
|
||||
.ia .ia-menu [role="menuitem"]:focus-visible { outline: var(--focus-ring); outline-offset: -2px; }
|
||||
.ia .ia-menu [role="menuitem"].danger { color: var(--danger); }
|
||||
.ia .ia-menu [role="menuitem"][aria-disabled="true"] { color: var(--disabled); cursor: not-allowed; flex-wrap: wrap; padding-top: 6px; padding-bottom: 6px; }
|
||||
.ia .ia-menu .reason { flex-basis: 100%; padding-left: 28px; font-weight: 400; font-size: var(--fs-sub); color: var(--muted); }
|
||||
@@ -185,7 +198,7 @@
|
||||
@media (max-width: 719.98px) { .ia .ia-toasts { right: 16px; left: 16px; bottom: calc(80px + env(safe-area-inset-bottom)); } }
|
||||
.ia .ia-progress { height: 6px; border-radius: 3px; background: var(--surface-2); overflow: hidden; }
|
||||
.ia .ia-progress > span { display: block; height: 100%; background: var(--accent); transition: width var(--dur-tick) linear; }
|
||||
.ia .ia-secret { display: block; width: 100%; background: var(--surface); border: 1px solid var(--control-edge); border-radius: var(--radius-sm); box-shadow: var(--carved); padding: 12px 14px; font-weight: 600; letter-spacing: 0.02em; word-break: break-all; color: var(--text); font: inherit; }
|
||||
.ia .ia-secret { display: block; width: 100%; background: var(--surface); border: 1px solid var(--control-edge); border-radius: var(--radius-sm); box-shadow: var(--carved); padding: 12px 14px; font: inherit; font-weight: 600; letter-spacing: 0.02em; word-break: break-all; overflow-wrap: anywhere; white-space: pre-wrap; color: var(--text); resize: none; }
|
||||
.ia .ia-details pre { background: var(--surface); border-radius: var(--radius-sm); color: var(--muted); font-size: var(--fs-sub); white-space: pre-wrap; padding: 10px 12px; margin: 6px 0; }
|
||||
.ia .ia-frame { border: 1px solid var(--hairline); border-radius: var(--radius-lg); padding: 32px; text-align: center; }
|
||||
.ia .ia-card { background: var(--surface); border: 1px solid var(--hairline); border-radius: var(--radius); padding: 12px 14px; }
|
||||
|
||||
@@ -17,6 +17,7 @@ export const ICONS = {
|
||||
building: "M4 21V5l8-3 8 3v16M9 21v-5h6v5M8 8h2M14 8h2M8 12h2M14 12h2",
|
||||
swap: "M7 7h13l-4-4M17 17H4l4 4",
|
||||
copy: "M9 9h11v11H9zM5 15H4V4h11v1",
|
||||
download: "M12 4v11M7 10l5 5 5-5M5 20h14",
|
||||
chevron: "M6 9l6 6 6-6",
|
||||
dots: "M5 12h.01M12 12h.01M19 12h.01",
|
||||
close: "M6 6l12 12M18 6 6 18",
|
||||
|
||||
Reference in New Issue
Block a user