Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/holger

holger-recipe/src/estate_ron.rs

//! **The estate's server declaration** — the `holger.ron` every Holger estate box
//! boots (lane W2, 2026-10-19).
//!
//! This is the ONE generator of the shipped config. `cargo xtask estate-media`
//! writes [`medium`] and passes it to the forge as `holger_ron=@…` for the main
//! and twin media (`holger`, `holger-keep`); the private kit holds no copy.
//!
//! What it turns on, all of it from the estate's first boot:
//!
//! * **the intake chain** — `incoming → quarantine → approved → production`, the
//!   promotion ladder over exactly those four, `promotion.intake` naming them;
//! * **the scan** at SCANNED — [`SCAN_REQUIRED`] (`vulnerability`, `sbom`);
//! * **two-person approval** — `approvals: 2` ([`APPROVALS`]);
//! * **intel** — `intel: (db_dir: <data>/intel, offline: false)` on the data disk: a
//!   sold estate is online, so the box's `intel.refresh` job fetches OSV, NVD and
//!   KEV once at boot and daily (lane W4). The airgap form ([`EstateRon::airgapped`])
//!   keeps `offline: true` and takes intel only as a signed bundle. Both forms name
//!   `intel.trust_policy` on the release ([`INTEL_TRUST_STAGED`] under [`RELEASE_ROOT`]):
//!   the medium carries the SLOT, the estate's operator fills it with the policy that pins
//!   the estate's own intel signers (`cargo xtask estate-media --intel-trust <policy.ron>`,
//!   the medium parameter `intel_trust_policy`). A medium composed without one boots, and
//!   `POST /-/intel/import` is then refused by name (`holger-import-4`, no trust policy):
//!   fail-closed, never an unverified advisory database (lane P5);
//! * **the provenance scanner** (`scan.provenance`, `default: prefer`): every package's
//!   attestations (cosign keyless, DSSE, SLSA, PEP 740, npm) are verified offline and recorded
//!   (lane HOL-MVP-FORMATS: the Security page said "Provenance: off");
//! * **the audit chain** with a checkpoint every [`CHECKPOINT_EVERY`] records;
//! * **duties** — the console principal imports, administers and audits
//!   ([`CONSOLE_DUTIES`]); people get theirs through their groups
//!   ([`group_duties`]), and [`APPROVER_GROUP`] is the group an invite gives a second
//!   approver (docs/estate-approvers.md);
//! * **plugin trust** — `ron_plugin_trust_roots` names the korp root the medium
//!   carries on its release ([`KORP_ROOT_STAGED`] under [`RELEASE_ROOT`]);
//! * **npm through the chain** — the repository [`NPM_REPOSITORY`] (`ron_repo_type: "npm"`, no
//!   archive) is `promotion.intake.npm`: `npm publish` there is INGESTED into `incoming`, and its
//!   packument and tarballs are the AVAILABLE set, linked under `repo.<estate>` (lane P5);
//! * **cargo through the chain** — the repository [`CARGO_REPOSITORY`] (`ron_repo_type: "rust"`,
//!   no storage) is `promotion.intake.cargo`: `cargo publish` there is INGESTED into
//!   `incoming`, its sparse index and downloads are the AVAILABLE set, and `cargo yank` is
//!   recorded for AVAILABLE versions (lane HOL-CARGO-PUBLISH-DOOR);
//! * **an OCI registry** — the repository [`OCI_REPOSITORY`] (`ron_repo_type: "oci"`, the
//!   writable Distribution v2 registry under the store): Docker/OCI is an MVP format, and an MVP
//!   box never pulls from the internet, so images (and Helm charts as OCI artifacts) are pushed
//!   to it and pulled from it (lane HOL-MVP-FORMATS);
//! * **apt, dnf, Helm, Maven and Go as views of the chain** — [`CHAIN_VIEWS`]: archive-less
//!   repositories that serve production's AVAILABLE set under their name (lane HOL-MVP-FORMATS).
//!
//! **The estate's name is never a constant.** One medium serves every estate, so
//! the medium form carries [`ESTATE_PLACEHOLDER`] in `ron_base_url`, and the box
//! fills it from the name the ONE box's installer feeds it (the join reply's
//! `estate`, holger `server_lib::Holger::resolve_estate`). [`for_estate`] renders the
//! same file with the name filled in, as the box ends up reading it.
//!
//! Pure: no file system, no parser, wasm32-safe like the rest of the recipe.

use crate::packaging::BOX_HOLGER_DATA;

/// Where the box keeps the Sigstore trust root the medium seeds (lane HOL-OCI-EVIDENCE,
/// server-lib `sigstore_trust::DIR`), under the data root.
pub const TRUST_DIR: &str = "holger-trust";

/// The placeholder for the estate's own name in the medium form.
pub const ESTATE_PLACEHOLDER: &str = "{estate}";
/// The repository host of an estate: `repo.<estate>`. The front routes it to the
/// primary (edda `estate-front::route`, `repo_hosts`); the estate name itself is the
/// console's host, which the front never routes to the repository.
pub const REPO_HOST_PREFIX: &str = "repo.";
/// The appliance's durable root on a box (`HOLGER_APPLIANCE_DATA`).
pub const BOX_APPLIANCE_ROOT: &str = "/data";
/// **Where the RELEASE's files are on a box** (lane B1): korp-start lays the medium's release
/// declaration — this file, the korp root — there on every start, verified with the app
/// (`korp_installer::release::RUN_DIR`; server-lib `declaration::RELEASE_DIR`; xtask holds
/// the three equal).
pub const RELEASE_ROOT: &str = "/run/korp/release";
/// The console principal: the static token each box derives from the front's offered
/// console key and its own (A7 row 14, server-cli `paired::install_console_token`, written
/// to `<appliance>/holger-console-token`); no shop feeds it.
pub const CONSOLE_PRINCIPAL: &str = "console";
/// The console bearer's file under the appliance root (server-cli `paired::CONSOLE_TOKEN_FILE`).
pub const CONSOLE_TOKEN_FILE: &str = "holger-console-token";
/// The duties of the console principal. It is the machine importer (uploads it
/// carries are imported by it, so it never approves them), the repository admin
/// (seals onward) and an auditor. It holds no `SecurityApprover`: approval is a
/// person's act.
pub const CONSOLE_DUTIES: [&str; 3] = ["Importer", "RepositoryAdmin", "Auditor"];
/// The scanner kinds every artifact needs at SCANNED.
pub const SCAN_REQUIRED: [&str; 2] = ["vulnerability", "sbom"];
/// Distinct approvers for APPROVED (never the importer).
pub const APPROVALS: u32 = 2;
/// Records between two audit checkpoints.
pub const CHECKPOINT_EVERY: u64 = 256;
/// The four intake repositories, in chain order.
pub const INTAKE_REPOS: [&str; 4] = ["incoming", "quarantine", "approved", "production"];
/// **The primary's sealed slot** (lane F9): the raw repository the estate front keeps its
/// installer material in (holger-estate-front `sealed::SEALED_REPOSITORY`), Admin only — the
/// console's bearer. The kit's install declared it; the media's own declaration did not, so a
/// shop-paired front could never keep its material (test3-holger-rs, r6). The twin follows it
/// like every other repository.
pub const SEALED_REPOSITORY: &str = "monetize-backup";
/// **The chain's npm door** (lane P5): one npm registry URL, `https://repo.<estate>/npm/`, for
/// `npm publish` (INGESTED into `incoming`) and `npm install` (the AVAILABLE set).
pub const NPM_REPOSITORY: &str = "npm";
/// **The chain's cargo door** (lane HOL-CARGO-PUBLISH-DOOR): one sparse registry,
/// `sparse+https://repo.<estate>/crates/index/`, for `cargo publish` (INGESTED into
/// `incoming`), `cargo install` (the AVAILABLE set) and `cargo yank`.
pub const CARGO_REPOSITORY: &str = "crates";
/// **The estate's OCI registry** (lane HOL-MVP-FORMATS, owner 2026-10-30): `https://repo.<estate>/v2/oci/…`,
/// `docker push`/`docker pull` and `helm push`/`helm pull oci://` (server-lib `fmt-docker`).
pub const OCI_REPOSITORY: &str = "oci";
/// **The estate's chain views** (lane HOL-MVP-FORMATS, owner 2026-10-30: deb and rpm "must work
/// too"): `(name, ron_repo_type)`, each an archive-less repository that server-lib makes a
/// read-only view of the intake chain's AVAILABLE set under `<name>/` (`chain_view`): apt
/// (`https://repo.<estate>/deb stable main`), dnf (`baseurl=https://repo.<estate>/rpm`), Helm
/// (`/helm/index.yaml`), Maven (`/maven/`) and the GOPROXY (`/go/`). A package reaches one
/// only through the chain: uploaded into `incoming` at `<name>/<path>` and walked to AVAILABLE.
pub const CHAIN_VIEWS: [(&str, &str); 5] = [
    ("deb", "deb"),
    ("rpm", "rpm"),
    ("helm", "helm"),
    ("maven", "maven3"),
    ("go", "go"),
];
/// **Every repository the declaration names**, in its order (NIGHT-PUBREPO): the names an
/// estate's public list may take ([`public_repositories_refusal`]).
pub const REPOSITORIES: [&str; 14] = [
    "bundles",
    SEALED_REPOSITORY,
    "incoming",
    "quarantine",
    "approved",
    "production",
    CARGO_REPOSITORY,
    NPM_REPOSITORY,
    OCI_REPOSITORY,
    CHAIN_VIEWS[0].0,
    CHAIN_VIEWS[1].0,
    CHAIN_VIEWS[2].0,
    CHAIN_VIEWS[3].0,
    CHAIN_VIEWS[4].0,
];
/// **The feed key naming the estate's public repositories** (NIGHT-PUBREPO, owner 2026-10-28):
/// the ONE box feeds an estate's main and twin `public_repositories = "crates,npm"` from its
/// declaration (`[estates.<label>] public_repositories`), and the box makes exactly those
/// `visibility: Public` (server-lib `Holger::resolve_public_repositories`). Unfed: none.
pub const PUBLIC_REPOSITORIES_FEED: &str = "public_repositories";
/// A public list naming a repository the declaration does not have, refused by name.
pub const PUBLIC_REPOSITORY_UNKNOWN: &str = "[public-repository-unknown]";
/// The group an invite puts a second approver in (`POST /-/auth/passkey/invites`
/// with `{"groups": ["holger-security-approvers"]}`). It sorts after
/// `holger-readers`, so an invite by the `reader` role never lands here by accident
/// (`passkey::group_for_role` takes the first group by name).
pub const APPROVER_GROUP: &str = "holger-security-approvers";
/// The group of auditors.
pub const AUDITOR_GROUP: &str = "holger-security-auditors";
/// The korp root the medium stages, PEM (a staged parameter is text), under the
/// appliance root. holger-server writes its DER beside the plugin floor at boot.
/// The scan sandbox's directory under the data root (`holger_sandbox::media::Layout`,
/// lane HOLGER-MEDIA): crun, the worker's and ClamAV's rootfs, clamd's socket, the jobs.
/// Every scan on the box runs in it (`rules: (sandbox: required)`), and ClamAV is required.
pub const SANDBOX_DIR: &str = "sandbox";
pub const KORP_ROOT_STAGED: &str = "korp-root-ca.pem";
/// The estate's intel trust policy (an update-bundle `TrustPolicy`, RON) as the medium
/// stages it on the release: `intel.trust_policy` names it, carried `holger.intel/v1`
/// bundles verify against it. Per estate: the operator supplies it (lane P5).
pub const INTEL_TRUST_STAGED: &str = "intel-trust.ron";
/// **The CVE data the medium ships** (row HOL-INTEL-ON-MEDIA): a `holger.intel/v1` bundle built
/// when the medium is composed, signed by Holger's release signer, staged on the release as text
/// (the medium parameter `intel_bundle`, `cargo xtask estate-media --intel-release-cert`).
/// `intel.bundled` names it; the box imports it at first boot.
pub const INTEL_BUNDLE_STAGED: &str = "intel-bundle.b64";
/// The policy pinning Holger's release signer for `holger.intel/v1` (the medium parameter
/// `intel_release_trust`): `intel.release_trust_policy` names it.
pub const INTEL_RELEASE_TRUST_STAGED: &str = "intel-release-trust.ron";
/// **The bundles door's trust policy on the release** (lane HOL-BUNDLES-DOOR): the medium
/// parameter `bundles_trust_policy` stages it, and `promotion.intake.bundles_trust_policy`
/// names it. A medium composed without one boots, and every PUT into `bundles` is refused by
/// name (`holger-bundles-1`), never stored unverified.
pub const BUNDLES_TRUST_STAGED: &str = "bundles-trust.ron";
/// The published korp root (dwarves `trust/korp-root-ca.der`, sha256 6b19bf47…, the
/// ONE box's `[plugin_root]` pin), as PEM.
pub const KORP_ROOT_PEM: &str = include_str!("../trust/korp-root-ca.pem");

/// Where the paths of the declaration point.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EstateRon {
    /// The estate's name (`test3.holger.rs`). `None` = the medium form, with
    /// [`ESTATE_PLACEHOLDER`] in its place.
    pub estate: Option<String>,
    /// holger's own data root ([`BOX_HOLGER_DATA`] on a box).
    pub data: String,
    /// The appliance root ([`BOX_APPLIANCE_ROOT`] on a box).
    pub appliance: String,
    /// Where the release's files are ([`RELEASE_ROOT`] on a box): the korp root rides the
    /// release with this declaration.
    pub release: String,
    /// The gRPC and HTTP binds.
    pub grpc_bind: String,
    pub http_bind: String,
    /// `true` (a sold estate, online): `intel.offline: false`, the box refreshes
    /// its own advisories. `false` (the airgap tier): `intel.offline: true`.
    pub online_intel: bool,
    /// **The repositories this estate makes public** (NIGHT-PUBREPO): rendered
    /// `visibility: Public`, read with no sign-in on the gated estate. Empty (the medium, every
    /// sold Holger): none.
    pub public_repositories: Vec<String>,
}

impl EstateRon {
    /// The box's own paths and binds.
    #[must_use]
    pub fn on_a_box(estate: Option<&str>) -> Self {
        Self {
            estate: estate.map(str::to_string),
            data: BOX_HOLGER_DATA.to_string(),
            appliance: BOX_APPLIANCE_ROOT.to_string(),
            release: RELEASE_ROOT.to_string(),
            grpc_bind: "0.0.0.0:50051".to_string(),
            http_bind: "0.0.0.0:8443".to_string(),
            online_intel: true,
            public_repositories: Vec::new(),
        }
    }

    /// The same declaration with `names` public, or the refusal by name
    /// ([`public_repositories_refusal`]).
    pub fn with_public_repositories(mut self, names: &[String]) -> Result<Self, String> {
        if let Some(why) = public_repositories_refusal(names) {
            return Err(why);
        }
        self.public_repositories = names.iter().map(|n| n.trim().to_string()).collect();
        Ok(self)
    }

    /// The airgap tier's form: intel only as a signed bundle, never fetched.
    #[must_use]
    pub fn airgapped(mut self) -> Self {
        self.online_intel = false;
        self
    }
}

/// Pure: **why `names` cannot be an estate's public list**, or `None`: every name is one of
/// [`REPOSITORIES`] ([`PUBLIC_REPOSITORY_UNKNOWN`] otherwise), and the sealed slot
/// ([`SEALED_REPOSITORY`], an administrator's) is never public.
#[must_use]
pub fn public_repositories_refusal(names: &[String]) -> Option<String> {
    for n in names.iter().map(|n| n.trim()) {
        if n == SEALED_REPOSITORY {
            return Some(format!("[access-refused] `{n}` is the estate's sealed slot, an administrator's (ron_require_role: Admin): it is never public"));
        }
        if !REPOSITORIES.contains(&n) {
            let open: Vec<&str> = REPOSITORIES
                .iter()
                .copied()
                .filter(|r| *r != SEALED_REPOSITORY)
                .collect();
            return Some(format!("{PUBLIC_REPOSITORY_UNKNOWN} `{n}` is no repository of the estate's declaration (a public list may name: {})", open.join(", ")));
        }
    }
    None
}

/// The repository base URL of `estate`: `https://repo.<estate>`.
#[must_use]
pub fn repo_base_url(estate: &str) -> String {
    format!(
        "https://{REPO_HOST_PREFIX}{}",
        estate.trim().trim_end_matches('.').to_ascii_lowercase()
    )
}

/// Group → (role, duties) the estate grants.
#[must_use]
pub fn group_duties() -> [(&'static str, &'static str, &'static [&'static str]); 5] {
    [
        // The first passkey admin judges and configures; it never imports (lane W7): an
        // upload comes from the console bearer or an invited Importer, so the admin may approve it.
        (
            "holger-admins",
            "Admin",
            &[
                "Developer",
                "SecurityApprover",
                "RepositoryAdmin",
                "Auditor",
            ],
        ),
        ("holger-writers", "Writer", &["Developer", "Importer"]),
        ("holger-readers", "Reader", &["Developer"]),
        (APPROVER_GROUP, "Reader", &["Developer", "SecurityApprover"]),
        (AUDITOR_GROUP, "Reader", &["Developer", "Auditor"]),
    ]
}

/// **The medium form**: every estate's box, its name filled in at boot.
#[must_use]
pub fn medium() -> String {
    render(&EstateRon::on_a_box(None))
}

/// The declaration as the box of `estate` reads it.
#[must_use]
pub fn for_estate(estate: &str) -> String {
    render(&EstateRon::on_a_box(Some(estate)))
}

/// Render the declaration.
#[must_use]
pub fn render(e: &EstateRon) -> String {
    let d = e.data.trim_end_matches('/');
    let a = e.appliance.trim_end_matches('/');
    let base_url = match &e.estate {
        Some(name) => repo_base_url(name),
        None => format!("https://{REPO_HOST_PREFIX}{ESTATE_PLACEHOLDER}"),
    };
    // NIGHT-PUBREPO: the estate's own public repositories say so; no list, no word.
    let vis = |name: &str| {
        if e.public_repositories.iter().any(|p| p == name) {
            ", visibility: Public"
        } else {
            ""
        }
    };
    let raw = |name: &str| {
        format!(
            "        (ron_name: \"{name}\", ron_repo_type: \"raw\", ron_upstreams: [], ron_in: None,\n\
             \x20        ron_out: Some((ron_storage_endpoint: \"store\", ron_exposed_endpoint: \"doors\")),\n\
             \x20        ron_data_dir: Some(\"{d}/store/{name}\"){}),\n",
            vis(name)
        )
    };
    let bare = |xs: &[&str]| xs.join(", ");
    let mut s = String::from(
        "// GENERATED by holger-recipe `estate_ron` (cargo xtask estate-media). Do not edit on the box.\n\
         // The intake chain, the scan, two-person approval, intel, the audit chain,\n\
         // duties and the plugin trust root are on from the first boot (lane W2).\n(\n    repositories: [\n",
    );
    s.push_str(&raw("bundles"));
    s.push_str(&format!(
        "        (ron_name: \"{SEALED_REPOSITORY}\", ron_repo_type: \"raw\", ron_upstreams: [], ron_in: None,\n\
         \x20        ron_out: Some((ron_storage_endpoint: \"store\", ron_exposed_endpoint: \"doors\")),\n\
         \x20        ron_data_dir: Some(\"{d}/store/{SEALED_REPOSITORY}\"), ron_require_auth: true, ron_require_role: Some(Admin){}),\n",
        vis(SEALED_REPOSITORY)
    ));
    for r in INTAKE_REPOS {
        s.push_str(&raw(r));
    }
    s.push_str(&format!(
        "        (ron_name: \"{CARGO_REPOSITORY}\", ron_repo_type: \"rust\", ron_base_url: Some(\"{base_url}\"), ron_upstreams: [], ron_in: None,\n\
         \x20        ron_out: Some((ron_storage_endpoint: \"store\", ron_exposed_endpoint: \"doors\")){}),\n",
        vis(CARGO_REPOSITORY)
    ));
    s.push_str(&format!(
        "        (ron_name: \"{NPM_REPOSITORY}\", ron_repo_type: \"npm\", ron_base_url: Some(\"{base_url}\"), ron_upstreams: [], ron_in: None,\n\
         \x20        ron_out: Some((ron_storage_endpoint: \"store\", ron_exposed_endpoint: \"doors\")){}),\n",
        vis(NPM_REPOSITORY)
    ));
    s.push_str(&format!(
        "        (ron_name: \"{OCI_REPOSITORY}\", ron_repo_type: \"oci\", ron_upstreams: [], ron_in: None,\n\
         \x20        ron_out: Some((ron_storage_endpoint: \"store\", ron_exposed_endpoint: \"doors\")),\n\
         \x20        ron_data_dir: Some(\"{d}/store/{OCI_REPOSITORY}\"){}),\n",
        vis(OCI_REPOSITORY)
    ));
    for (name, ty) in CHAIN_VIEWS {
        s.push_str(&format!(
            "        (ron_name: \"{name}\", ron_repo_type: \"{ty}\", ron_upstreams: [], ron_in: None,\n\
             \x20        ron_out: Some((ron_storage_endpoint: \"store\", ron_exposed_endpoint: \"doors\")){}),\n",
            vis(name)
        ));
    }
    s.push_str("    ],\n");
    s.push_str(&format!(
        "    // insecure: the doors bind on wg0 only (the WireGuard overlay encrypts the wire) and the\n    // estate front terminates TLS for the internet (HOL-NCSC: the choice is written down).\n    // ron_trusted_proxies: the front (its overlay address) names the public face of a link.\n    exposed_endpoints: [\n        (ron_name: \"doors\", ron_url: \"{}\", ron_http_url: Some(\"{}\"), insecure: true, ron_trusted_proxies: [\"{FRONT_TRUSTED_PROXY}\"]),\n    ],\n",
        e.grpc_bind, e.http_bind
    ));
    s.push_str(&format!("    storage_endpoints: [\n        (ron_name: \"store\", ron_storage_type: \"znippy\", ron_path: \"{d}/store\"),\n    ],\n"));
    s.push_str(&format!("    audit: (dir: \"{d}/audit\", enabled: true, checkpoint_every: Some({CHECKPOINT_EVERY})),\n"));
    let groups = group_duties();
    let group_roles = groups
        .iter()
        .map(|(g, r, _)| format!("\"{g}\": {r}"))
        .collect::<Vec<_>>()
        .join(", ");
    let group_duty_map = groups
        .iter()
        .map(|(g, _, ds)| format!("\"{g}\": [{}]", bare(ds)))
        .collect::<Vec<_>>()
        .join(", ");
    s.push_str(&format!(
        "    auth: Some((\n\
         \x20       methods: [StaticToken(subject: \"{CONSOLE_PRINCIPAL}\", token_file: Some(\"{a}/{CONSOLE_TOKEN_FILE}\"))],\n\
         \x20       roles: {{\"{CONSOLE_PRINCIPAL}\": Admin}},\n\
         \x20       group_roles: {{{group_roles}}},\n\
         \x20       require_auth_for_reads: false,\n\
         \x20       duties: {{\"{CONSOLE_PRINCIPAL}\": [{}]}},\n\
         \x20       group_duties: {{{group_duty_map}}},\n\
         \x20   )),\n",
        bare(&CONSOLE_DUTIES)
    ));
    // HCON-5: what is open. An estate is internet-facing: reads need a sign-in; the front page
    // and the sign-up stay open; a repository is made public by its own `visibility: Public`.
    s.push_str("    access: (reads: Gated, front: Open),\n");
    let r = e.release.trim_end_matches('/');
    s.push_str(&format!("    intel: Some((db_dir: \"{d}/intel\", offline: {}, trust_policy: Some(\"{r}/{INTEL_TRUST_STAGED}\"), bundled: Some(\"{r}/{INTEL_BUNDLE_STAGED}\"), release_trust_policy: Some(\"{r}/{INTEL_RELEASE_TRUST_STAGED}\"))),\n", !e.online_intel));
    s.push_str(&format!(
        "    ron_plugin_trust_roots: [\"{r}/{KORP_ROOT_STAGED}\"],\n"
    ));
    let stages = INTAKE_REPOS
        .iter()
        .map(|r| format!("            (name: \"{r}\", repo: \"{r}\"),\n"))
        .collect::<String>();
    let sb = format!("{d}/{SANDBOX_DIR}");
    let korp = format!("{r}/{KORP_ROOT_STAGED}");
    s.push_str(&format!(
        "    promotion: Some((\n\
         \x20       ladder_name: \"intake\",\n\
         \x20       stages: [\n{stages}        ],\n\
         \x20       intake: Some((\n\
         \x20           incoming: \"incoming\", quarantine: \"quarantine\",\n\
         \x20           approved: \"approved\", production: \"production\",\n\
         \x20           scan: Some((required: [{}], provenance: Some((default: prefer, rules: (trust_root: Some(\"{d}/{TRUST_DIR}/{bundle}\")))))),\n\
         \x20           trust_policy: Some(\"{d}/{TRUST_DIR}/{policy}\"),\n\
         \x20           approvals: {APPROVALS},\n\
         \x20           npm: Some(\"{NPM_REPOSITORY}\"),\n\
         \x20           cargo: Some(\"{CARGO_REPOSITORY}\"),\n\
         \x20           bundles: Some(\"bundles\"),\n\
         \x20           bundles_trust_policy: Some(\"{r}/{BUNDLES_TRUST_STAGED}\"),\n\
         \x20           rules: (sandbox: required),\n\
         \x20           sandbox: Some((engine: heimdall, crun: \"{sb}/crun\", rootfs: Some(\"{sb}/worker/rootfs\"), work_dir: Some(\"{sb}/jobs\"), state_dir: Some(\"{sb}/state\"), heimdall: Some((image_layout: \"{sb}/oci\", rootfs_tar: Some(\"{sb}/holger-scan-worker.rootfs.tar\"), shim: Some(\"{sb}/heimdall-container-shim\"), work_dir: Some(\"{sb}/heimdall\"), guests: Some(\"{sb}/heimdall-guests\"), guests_trust_root: Some(\"{korp}\"))))),\n\
         \x20           inspect: (clamav: Some((socket: Some(\"{sb}/clamd/clamd.sock\"), required: true))),\n\
         \x20       )),\n\
         \x20   )),\n",
        bare(&SCAN_REQUIRED),
        bundle = crate::packaging::SIGSTORE_TRUST_BUNDLE,
        policy = crate::packaging::SIGSTORE_TRUST_POLICY,
    ));
    s.push_str("    replication_door: Some((ron_bind: None, ron_advertise: [])),\n)\n");
    s
}

/// **The estate front's address as main and the twin see it** (HOL-DOCFIND): the front dials
/// the boxes' doors from its overlay address (`nordisk_pairing::OVERLAY_FRONT`, `10.44.0.1`),
/// and the doors believe its `X-Forwarded-Proto`/`-Host` from there alone
/// (`ron_trusted_proxies`), so a link a box writes says `https://` and the repository host.
pub const FRONT_TRUSTED_PROXY: &str = "10.44.0.1/32";

#[cfg(test)]
mod tests {
    use super::*;

    /// ★ The estate `test3-holger-rs` (test3.holger.rs): every block the lanes need.
    #[test]
    fn the_test3_estate_turns_every_lane_on() {
        let r = for_estate("test3.holger.rs");
        for repo in INTAKE_REPOS {
            assert!(
                r.contains(&format!("(ron_name: \"{repo}\", ron_repo_type: \"raw\"")),
                "{repo}:\n{r}"
            );
            assert!(
                r.contains(&format!("(name: \"{repo}\", repo: \"{repo}\")")),
                "the ladder names {repo}:\n{r}"
            );
        }
        assert!(r.contains("incoming: \"incoming\", quarantine: \"quarantine\",\n            approved: \"approved\", production: \"production\","), "{r}");
        // HOL-MVP-FORMATS: the provenance scanner is installed (cosign keyless, DSSE, SLSA,
        // verified offline); `default: prefer` records what it finds and refuses nothing for a
        // package that carries no provenance (a source may still `require`).
        assert!(r.contains("scan: Some((required: [vulnerability, sbom], provenance: Some((default: prefer, rules: (trust_root: Some(\"/data/holger/holger-trust/sigstore-trust.holger.znippy\")))))),"), "{r}");
        // HOL-OCI-EVIDENCE: the Sigstore trust root the medium seeds (and a signed bundle import
        // refreshes) is the floor's, verified against the policy seeded beside it, which is the
        // intake's bundle trust policy.
        assert!(
            r.contains("trust_policy: Some(\"/data/holger/holger-trust/bundle-trust.ron\"),"),
            "{r}"
        );
        assert!(r.contains("approvals: 2,"), "{r}");
        // Every scan in the sandbox the medium carried (lane HOLGER-MEDIA): crun over the laid
        // worker rootfs, and clamd in its own sandbox, required.
        assert!(r.contains("rules: (sandbox: required),"), "{r}");
        // Lane HOL-HEIMDALL-03: Heimdall's runner, crun over the laid rootfs its fallback.
        assert!(r.contains("sandbox: Some((engine: heimdall, crun: \"/data/holger/sandbox/crun\", rootfs: Some(\"/data/holger/sandbox/worker/rootfs\"), work_dir: Some(\"/data/holger/sandbox/jobs\"), state_dir: Some(\"/data/holger/sandbox/state\"), heimdall: Some((image_layout: \"/data/holger/sandbox/oci\", rootfs_tar: Some(\"/data/holger/sandbox/holger-scan-worker.rootfs.tar\"), shim: Some(\"/data/holger/sandbox/heimdall-container-shim\"), work_dir: Some(\"/data/holger/sandbox/heimdall\"), guests: Some(\"/data/holger/sandbox/heimdall-guests\"), guests_trust_root: Some(\"/run/korp/release/korp-root-ca.pem\"))))),"), "{r}");
        assert!(r.contains("inspect: (clamav: Some((socket: Some(\"/data/holger/sandbox/clamd/clamd.sock\"), required: true))),"), "{r}");
        // P5: both forms verify a carried intel bundle against the policy the medium stages on
        // the release; without it an airgap box could never import an advisory database.
        // HOL-INTEL-ON-MEDIA: both name the CVE data the medium ships and its release signer.
        assert!(r.contains("intel: Some((db_dir: \"/data/holger/intel\", offline: false, trust_policy: Some(\"/run/korp/release/intel-trust.ron\"), bundled: Some(\"/run/korp/release/intel-bundle.b64\"), release_trust_policy: Some(\"/run/korp/release/intel-release-trust.ron\")))"), "a sold estate refreshes its intel:\n{r}");
        let air = render(&EstateRon::on_a_box(Some("test3.holger.rs")).airgapped());
        assert!(air.contains("intel: Some((db_dir: \"/data/holger/intel\", offline: true, trust_policy: Some(\"/run/korp/release/intel-trust.ron\"), bundled: Some(\"/run/korp/release/intel-bundle.b64\"), release_trust_policy: Some(\"/run/korp/release/intel-release-trust.ron\")))"), "the airgap tier never fetches, and imports signed intel:\n{air}");
        assert!(
            r.contains(
                "audit: (dir: \"/data/holger/audit\", enabled: true, checkpoint_every: Some(256))"
            ),
            "{r}"
        );
        assert!(
            r.contains("duties: {\"console\": [Importer, RepositoryAdmin, Auditor]}"),
            "{r}"
        );
        assert!(
            r.contains("\"holger-security-approvers\": [Developer, SecurityApprover]"),
            "{r}"
        );
        assert!(
            r.contains("ron_plugin_trust_roots: [\"/run/korp/release/korp-root-ca.pem\"]"),
            "the korp root rides the release (lane B1): {r}"
        );
        // F9: the front's sealed slot, Admin only.
        assert!(
            r.contains("(ron_name: \"monetize-backup\", ron_repo_type: \"raw\""),
            "{r}"
        );
        assert!(r.contains("ron_data_dir: Some(\"/data/holger/store/monetize-backup\"), ron_require_auth: true, ron_require_role: Some(Admin))"), "{r}");
        assert!(
            r.contains("token_file: Some(\"/data/holger-console-token\")"),
            "{r}"
        );
        assert!(
            r.contains("ron_base_url: Some(\"https://repo.test3.holger.rs\")"),
            "{r}"
        );
        // HOL-DOCFIND: the doors believe the front's forwarded headers, and nobody else's.
        assert!(
            r.contains(&format!("ron_trusted_proxies: [\"{FRONT_TRUSTED_PROXY}\"]")),
            "the estate's doors name the front as their one trusted proxy: {r}"
        );
        // P5: the chain's npm door, linked under the estate's repository host.
        assert!(r.contains("(ron_name: \"npm\", ron_repo_type: \"npm\", ron_base_url: Some(\"https://repo.test3.holger.rs\")"), "{r}");
        assert!(r.contains("npm: Some(\"npm\"),"), "{r}");
        // HOL-CARGO-PUBLISH-DOOR: the chain's cargo door, no storage of its own.
        assert!(r.contains("(ron_name: \"crates\", ron_repo_type: \"rust\", ron_base_url: Some(\"https://repo.test3.holger.rs\"), ron_upstreams: [], ron_in: None,\n         ron_out: Some((ron_storage_endpoint: \"store\", ron_exposed_endpoint: \"doors\"))),"), "{r}");
        assert!(r.contains("cargo: Some(\"crates\"),"), "{r}");
        assert!(
            !r.contains("crates.znippy"),
            "the door holds nothing of its own:\n{r}"
        );
        assert!(
            !r.contains("repo.holger.rs\"") && !r.contains(ESTATE_PLACEHOLDER),
            "no constant estate name:\n{r}"
        );
        assert!(
            !r.contains("network:"),
            "a sold estate is online: no `network: Offline`:\n{r}"
        );
        // HCON-5: the estate says what is open, online and airgapped alike.
        assert!(
            r.contains("access: (reads: Gated, front: Open),"),
            "a sold estate gates reads, its front open:\n{r}"
        );
        assert!(
            air.contains("access: (reads: Gated, front: Open),"),
            "an airgapped ESTATE is still an estate:\n{air}"
        );
        assert!(
            !r.contains("token:") && !r.contains("token_env"),
            "no secret in the file:\n{r}"
        );
    }

    /// ★ HOL-MVP-FORMATS (owner 2026-10-30): **the estate serves an OCI registry** — Docker/OCI
    /// is an MVP format, and the writable `oci` repository (a Distribution v2 registry under
    /// the store) is the one an MVP box, which never pulls from the internet, can be pushed
    /// to and pulled from (images, and Helm charts as OCI artifacts). Private unless the
    /// estate's public list names it.
    #[test]
    fn the_estate_serves_an_oci_registry() {
        let r = for_estate("test3.holger.rs");
        assert!(
            REPOSITORIES.contains(&OCI_REPOSITORY),
            "the declaration names `{OCI_REPOSITORY}`"
        );
        assert!(
            r.contains(&format!(
                "        (ron_name: \"{OCI_REPOSITORY}\", ron_repo_type: \"oci\", ron_upstreams: [], ron_in: None,\n\
                 \x20        ron_out: Some((ron_storage_endpoint: \"store\", ron_exposed_endpoint: \"doors\")),\n\
                 \x20        ron_data_dir: Some(\"/data/holger/store/{OCI_REPOSITORY}\")),\n"
            )),
            "{r}"
        );
        let public = render(
            &EstateRon::on_a_box(Some("test3.holger.rs"))
                .with_public_repositories(&[OCI_REPOSITORY.to_string()])
                .unwrap(),
        );
        assert!(
            public.contains(&format!(
                "ron_data_dir: Some(\"/data/holger/store/{OCI_REPOSITORY}\"), visibility: Public),"
            )),
            "{public}"
        );
    }

    /// ★ HOL-MVP-FORMATS (owner 2026-10-30: deb and rpm "must work too"): **the estate serves
    /// apt, dnf, Helm, Maven and Go as views of the intake chain** — one archive-less repository
    /// of each type ([`CHAIN_VIEWS`]), which server-lib makes a read-only view of production's
    /// AVAILABLE set under `<name>/` (a package reaches it only through the chain: uploaded
    /// into `incoming` at `<name>/<path>`, scanned, approved by two, sealed). Python is the
    /// chain's own `production/simple/`, npm its npm door, OCI the `oci` registry.
    #[test]
    fn the_estate_serves_apt_dnf_helm_maven_and_go_as_chain_views() {
        let r = for_estate("test3.holger.rs");
        assert_eq!(
            CHAIN_VIEWS.map(|(n, t)| (n, t)),
            [
                ("deb", "deb"),
                ("rpm", "rpm"),
                ("helm", "helm"),
                ("maven", "maven3"),
                ("go", "go")
            ]
        );
        for (name, ty) in CHAIN_VIEWS {
            assert!(
                REPOSITORIES.contains(&name),
                "the declaration names `{name}`"
            );
            let line = format!(
                "        (ron_name: \"{name}\", ron_repo_type: \"{ty}\", ron_upstreams: [], ron_in: None,\n\
                 \x20        ron_out: Some((ron_storage_endpoint: \"store\", ron_exposed_endpoint: \"doors\"))),\n"
            );
            assert!(
                r.contains(&line),
                "`{name}` is an archive-less `{ty}` repository, a view of the chain:\n{r}"
            );
        }
        assert!(
            !r.contains("ron_archive_path"),
            "no view names an archive:\n{r}"
        );
    }

    /// The medium form carries the placeholder, and only there.
    #[test]
    fn the_medium_names_no_estate() {
        let m = medium();
        // The crates and the npm repository link under the estate's host; nothing else names it.
        assert_eq!(m.matches(ESTATE_PLACEHOLDER).count(), 2, "{m}");
        assert_eq!(
            m.replace(ESTATE_PLACEHOLDER, "test3.holger.rs"),
            for_estate("test3.holger.rs")
        );
        assert_eq!(
            repo_base_url(" Test3.Holger.RS. "),
            "https://repo.test3.holger.rs"
        );
    }

    /// An invite by role never lands a person in the approver group.
    #[test]
    fn the_approver_group_sorts_after_the_reader_group() {
        let readers: Vec<&str> = group_duties()
            .iter()
            .filter(|(_, r, _)| *r == "Reader")
            .map(|(g, _, _)| *g)
            .collect();
        let first = readers.iter().min().unwrap();
        assert_eq!(*first, "holger-readers");
    }

    /// The staged korp root is the published one.
    #[test]
    fn the_korp_root_is_the_published_certificate() {
        assert!(
            KORP_ROOT_PEM.starts_with("-----BEGIN CERTIFICATE-----\n")
                && KORP_ROOT_PEM
                    .trim_end()
                    .ends_with("-----END CERTIFICATE-----")
        );
    }

    /// ★ NIGHT-PUBREPO (owner 2026-10-28): **no list, no public repository** — the medium every
    /// Holger shares makes none public, and an empty list renders it byte for byte.
    #[test]
    fn without_a_public_list_no_repository_is_public() {
        let m = medium();
        assert!(
            !m.contains("visibility"),
            "the medium makes nothing public:\n{m}"
        );
        let none = EstateRon::on_a_box(None)
            .with_public_repositories(&[])
            .unwrap();
        assert_eq!(render(&none), m, "an empty list is the medium");
    }

    /// ★ NIGHT-PUBREPO: **the listed repositories are rendered `visibility: Public`**, and only
    /// they (holger.rs: `crates` and `npm`, its public registry).
    #[test]
    fn the_listed_repositories_are_rendered_public() {
        let names = ["crates".to_string(), "npm".to_string()];
        let r = render(
            &EstateRon::on_a_box(Some("holger.rs"))
                .with_public_repositories(&names)
                .unwrap(),
        );
        assert_eq!(r.matches("visibility: Public").count(), 2, "{r}");
        assert!(r.contains("ron_out: Some((ron_storage_endpoint: \"store\", ron_exposed_endpoint: \"doors\")), visibility: Public),\n        (ron_name: \"npm\""), "crates is public:\n{r}");
        assert!(r.contains("ron_out: Some((ron_storage_endpoint: \"store\", ron_exposed_endpoint: \"doors\")), visibility: Public),\n        (ron_name: \"oci\""), "npm is public:\n{r}");
        for private in [
            "bundles",
            "incoming",
            "quarantine",
            "approved",
            "production",
            OCI_REPOSITORY,
        ] {
            assert!(
                r.contains(&format!(
                    "ron_data_dir: Some(\"/data/holger/store/{private}\")),"
                )),
                "{private} stays private:\n{r}"
            );
        }
        let bundles = render(
            &EstateRon::on_a_box(None)
                .with_public_repositories(&["bundles".to_string()])
                .unwrap(),
        );
        assert!(
            bundles.contains(
                "ron_data_dir: Some(\"/data/holger/store/bundles\"), visibility: Public),"
            ),
            "a raw repository takes the word too:\n{bundles}"
        );
        assert_eq!(
            bundles.matches("visibility: Public").count(),
            1,
            "{bundles}"
        );
    }

    /// ★ NIGHT-PUBREPO: **a name the declaration does not have is refused by name**, and the
    /// sealed slot is never public.
    #[test]
    fn an_unknown_or_sealed_public_name_is_refused_by_name() {
        let e = EstateRon::on_a_box(None)
            .with_public_repositories(&["crates".into(), "pypi".into()])
            .unwrap_err();
        assert!(
            e.starts_with(PUBLIC_REPOSITORY_UNKNOWN)
                && e.contains("`pypi`")
                && e.contains("crates, npm"),
            "{e}"
        );
        let e = public_repositories_refusal(&[SEALED_REPOSITORY.to_string()])
            .expect("the sealed slot is refused");
        assert!(
            e.contains("[access-refused]") && e.contains("`monetize-backup`"),
            "{e}"
        );
        assert_eq!(
            public_repositories_refusal(&["crates".into(), "npm".into()]),
            None
        );
        assert_eq!(public_repositories_refusal(&[]), None);
    }
}