machines.rs 939 lignes · 45276 octets
//! OI-154 (plan M8, tranche 5b) — E-036 Création des machines : travaux OpenTofu (calcul du plan,
//! création) dans le runner, avec le faux tests/faux/tofu et le fournisseur témoin. Le fournisseur
//! et la machine prévue sont posés dans le brouillon par le dépôt (E-034 et E-035 : tranches 6 et 7).

mod commun;

use std::time::Duration;

use axum::http::StatusCode;
use commun::*;
use open_iam_installer::{
    catalogue::RoleHote,
    config::{
        Adressage, Fournisseur, Hote, Machine, TypeFournisseur,
        fournisseurs::{Confiance, Disque},
    },
    runner::{Playbook, StatutExecution},
};

const PLAN: &str = "/install/cibles/machines/plan";
const EXECUTION: &str = "/install/cibles/machines/execution";

async fn attendre_fin(banc: &Banc) {
    tokio::time::timeout(Duration::from_secs(20), async {
        while banc.etat.runner.en_cours() {
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
    })
    .await
    .expect("fin du travail");
}

async fn poster(
    banc: &Banc,
    cookie: &str,
    csrf: &str,
    uri: &str,
    form: &str,
) -> (StatusCode, String, String) {
    let (res, body) = send(&banc.router, post_form(uri, cookie, Some(csrf), form)).await;
    // Le message d'un refus (409, 422) voyage dans l'en-tête HX-Trigger, le corps est vide.
    let notification = header(&res, "hx-trigger").to_owned();
    (res.status(), header(&res, "hx-redirect").to_owned(), format!("{body}{notification}"))
}

async fn lire(banc: &Banc, cookie: &str, uri: &str) -> (StatusCode, String) {
    let (res, body) = send(&banc.router, get_avec(uri, cookie)).await;
    (res.status(), body)
}

/// Machine prévue sur « pool-1 », avec le modèle, le réseau et le stockage du catalogue du témoin : le
/// contrôle préalable (tranche 19b) les cherche chez le fournisseur.
fn machine_prevue() -> Machine {
    Machine {
        fournisseur: "temoin".into(),
        emplacement: [("pool".to_owned(), "pool-1".to_owned())].into(),
        modele: Some("tpl-debian-13-pool-1".into()),
        image: None,
        cpu: 2,
        memoire_mo: 4096,
        disques: vec![Disque { stockage: "sr-pool-1".into(), taille_go: 20 }],
        reseau: "net-pool-1".into(),
        adressage: Adressage::Fixe {
            cidr: "192.0.2.10/24".into(),
            passerelle: "192.0.2.1".into(),
            dns: vec!["192.0.2.53".into()],
        },
        mac: None,
        id: None,
    }
}

/// Background : brouillon à l'étape 2 (organisation validée), « Plusieurs serveurs », fournisseur
/// témoin et annuaire.exemple.fr prévu (machine sans identifiant). `env` : scénario du faux tofu.
async fn pret(env: &[(&str, &str)]) -> (Banc, String, String) {
    let mut environnement = vec![("OIAM_FAUX_SCENARIO".to_owned(), "reussite".to_owned())];
    environnement.extend(env.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())));
    let banc = banc_avec(environnement);
    let (cookie, csrf) = session_assistant(&banc).await;
    for (uri, form) in [
        ("/install/commencer", ""),
        (
            "/install/organisation",
            "nom=Mairie+d%27Exemple&domaine=exemple.fr&base_dn=&langue=fr&fuseau=Europe%2FParis",
        ),
    ] {
        let (statut, _, body) = poster(&banc, &cookie, &csrf, uri, form).await;
        assert!(statut.is_success(), "{uri} : {statut} {body}");
    }
    let (mut brouillon, secrets) = banc.etat.depot.charger().unwrap().unwrap();
    brouillon.fournisseurs = vec![Fournisseur {
        nom: "temoin".into(),
        type_: TypeFournisseur::Temoin,
        url: "https://temoin.invalid".into(),
        tls: Confiance::default(),
    }];
    brouillon.poser_hote(Hote {
        nom: "annuaire.exemple.fr".into(),
        adresse: "192.0.2.10".into(),
        port: 22,
        utilisateur: "root".into(),
        roles: [RoleHote::Annuaire].into(),
        local: false,
        machine: Some(machine_prevue()),
    });
    banc.etat.depot.sauver(&brouillon, &secrets).unwrap();
    (banc, cookie, csrf)
}

fn racine_temoin(banc: &Banc) -> std::path::PathBuf {
    banc.etat_dir().join("machines/temoin/racines/temoin")
}

fn machine_du_brouillon(banc: &Banc) -> Machine {
    let (b, _) = banc.etat.depot.charger().unwrap().unwrap();
    b.deploiement
        .unwrap()
        .hotes
        .iter()
        .find(|h| h.nom == "annuaire.exemple.fr")
        .unwrap()
        .machine
        .clone()
        .unwrap()
}

async fn planifier(banc: &Banc, cookie: &str, csrf: &str) {
    let (statut, redirection, body) = poster(banc, cookie, csrf, PLAN, "").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    assert_eq!(redirection, PLAN);
    attendre_fin(banc).await;
}

#[tokio::test]
async fn calculer_le_plan_lance_un_travail_sous_le_verrou_du_runner() {
    let (banc, cookie, csrf) = pret(&[("OIAM_FAUX_TOFU_ATTENTE", "1")]).await;
    let (statut, redirection, body) = poster(&banc, &cookie, &csrf, PLAN, "").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    assert_eq!(redirection, PLAN);
    assert!(banc.etat.runner.en_cours(), "un travail MachinesPlan tourne");
    let (statut, _, body) = poster(&banc, &cookie, &csrf, PLAN, "").await;
    assert_eq!(statut, StatusCode::CONFLICT, "un second calcul pendant le travail : {body}");
    // derniere() ne désigne pas ce travail : E-011 et E-012 ne montrent jamais les travaux machines.
    assert!(banc.etat.runner.derniere().is_none());
    let machines = banc.etat.runner.derniere_machines().expect("travail machines");
    assert_eq!(machines.playbook, Some(Playbook::MachinesPlan));
    assert_eq!(machines.fournisseur.as_deref(), Some("temoin"));
    let (statut, _) = lire(&banc, &cookie, "/install/execution").await;
    assert_eq!(statut, StatusCode::SEE_OTHER, "E-011 sans exécution Ansible renvoie au récapitulatif");
    attendre_fin(&banc).await;
    assert_eq!(banc.etat.runner.derniere_machines().unwrap().statut, StatutExecution::Reussie);
    // La MAC a été posée au premier plan, la machine n'a pas encore d'identifiant.
    let m = machine_du_brouillon(&banc);
    assert!(m.mac.as_deref().is_some_and(|mac| mac.starts_with("02:")), "{m:?}");
    assert!(m.id.is_none());
    // Le dossier de travail porte tfvars (avec le cloud-init de la machine prévue) et le plan enregistré.
    let tfvars = std::fs::read_to_string(racine_temoin(&banc).join("terraform.tfvars.json")).unwrap();
    assert!(tfvars.contains("#cloud-config") && tfvars.contains("ssh_keys"), "{tfvars}");
    assert!(racine_temoin(&banc).join("plan.json").is_file());
}

#[tokio::test]
async fn le_plan_pret_s_affiche_se_confirme_et_cree_la_machine() {
    let trace = tempfile::tempdir().unwrap();
    let trace_tofu = trace.path().join("trace-tofu");
    let (banc, cookie, csrf) = pret(&[("OIAM_FAUX_TRACE_TOFU", trace_tofu.to_str().unwrap())]).await;
    planifier(&banc, &cookie, &csrf).await;
    let (statut, page) = lire(&banc, &cookie, PLAN).await;
    assert_eq!(statut, StatusCode::OK);
    assert!(page.contains("annuaire.exemple.fr") && page.contains("créer"), "{page}");
    assert!(page.contains("Confirmer la création"), "{page}");
    assert!(!page.contains("refus-plan"), "{page}");

    let (statut, redirection, body) = poster(&banc, &cookie, &csrf, EXECUTION, "").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    assert_eq!(redirection, EXECUTION);
    attendre_fin(&banc).await;
    let trace_texte = std::fs::read_to_string(&trace_tofu).unwrap();
    assert!(
        trace_texte.contains("args=apply -input=false -json plan.tfplan"),
        "le plan enregistré est appliqué tel quel : {trace_texte}"
    );
    assert!(trace_texte.contains("TF_VAR_cle_etat=") && trace_texte.contains("TF_INPUT=0"), "{trace_texte}");
    let derniere = banc.etat.runner.derniere_machines().unwrap();
    assert_eq!((derniere.playbook, derniere.statut), (Some(Playbook::Machines), StatutExecution::Reussie));

    // Suivi : phases, lignes, fin ; flux SSE avec reprise par Last-Event-ID.
    let (statut, page) = lire(&banc, &cookie, EXECUTION).await;
    assert_eq!(statut, StatusCode::OK);
    assert!(page.contains("Création des machines") && page.contains("annuaire.exemple.fr"), "{page}");
    assert!(page.contains("Machines créées."), "{page}");
    assert!(!page.contains("sse-connect"), "plus de flux une fois le travail terminé");
    let (res, flux) = send(&banc.router, get_avec(&format!("{EXECUTION}/flux"), &cookie)).await;
    assert!(header(&res, "content-type").starts_with("text/event-stream"));
    assert!(
        flux.contains("event: ligne") && flux.contains("event: fin") && flux.contains("id: 1\n"),
        "{flux}"
    );
    let mut req = get_avec(&format!("{EXECUTION}/flux"), &cookie);
    req.headers_mut().insert("last-event-id", "2".parse().unwrap());
    let (_, reprise) = send(&banc.router, req).await;
    assert!(
        !reprise.contains("id: 1\n") && !reprise.contains("id: 2\n") && reprise.contains("id: 3\n"),
        "{reprise}"
    );

    // E-003 : la machine est créée, avec l'identifiant rendu par outputs ; known_hosts prérempli.
    let (statut, page) = lire(&banc, &cookie, "/install/cibles").await;
    assert_eq!(statut, StatusCode::OK);
    assert!(page.contains("créée"), "{page}");
    let m = machine_du_brouillon(&banc);
    assert_eq!(m.id.as_deref(), Some("faux-annuaire.exemple.fr"));
    let known_hosts = std::fs::read_to_string(banc.etat_dir().join("ssh/known_hosts")).unwrap();
    assert!(known_hosts.lines().any(|l| l.starts_with("192.0.2.10 ssh-ed25519 ")), "{known_hosts}");
    // Plan et user_data oubliés (D-084) ; la clé de l'état reste.
    let racine = racine_temoin(&banc);
    assert!(!racine.join("plan.tfplan").exists() && !racine.join("plan.json").exists());
    let tfvars = std::fs::read_to_string(racine.join("terraform.tfvars.json")).unwrap();
    assert!(!tfvars.contains("#cloud-config"), "{tfvars}");
    assert!(banc.etat_dir().join("machines/etat.cle").is_file());
}

#[tokio::test]
async fn un_plan_perime_se_recalcule() {
    let (banc, cookie, csrf) = pret(&[]).await;
    planifier(&banc, &cookie, &csrf).await;
    let plan_json = racine_temoin(&banc).join("plan.json");
    let original = std::fs::read_to_string(&plan_json).unwrap();
    // Plus de quinze minutes.
    let mut plan: serde_json::Value = serde_json::from_str(&original).unwrap();
    plan["horodatage"] = serde_json::json!(plan["horodatage"].as_u64().unwrap() - 16 * 60);
    std::fs::write(&plan_json, plan.to_string()).unwrap();
    let (statut, _, body) = poster(&banc, &cookie, &csrf, EXECUTION, "").await;
    assert_eq!(statut, StatusCode::CONFLICT, "{body}");
    assert!(body.contains("recalculez-le"), "{body}");
    assert!(!banc.etat.runner.en_cours(), "rien n'est lancé");
    let (_, page) = lire(&banc, &cookie, PLAN).await;
    assert!(page.contains("plus de quinze minutes") && !page.contains("Confirmer la création"), "{page}");
    std::fs::write(&plan_json, &original).unwrap();
    // Brouillon modifié depuis le plan.
    let (mut b, s) = banc.etat.depot.charger().unwrap().unwrap();
    let mut d = b.deploiement.clone().unwrap();
    d.hotes[0].machine.as_mut().unwrap().cpu = 4;
    b.deploiement = Some(d);
    banc.etat.depot.sauver(&b, &s).unwrap();
    let (statut, _, body) = poster(&banc, &cookie, &csrf, EXECUTION, "").await;
    assert_eq!(statut, StatusCode::CONFLICT, "{body}");
    assert!(!banc.etat.runner.en_cours());
}

#[tokio::test]
async fn le_garde_fou_bloque_avant_toute_confirmation() {
    let (banc, cookie, csrf) = pret(&[("OIAM_FAUX_TOFU", "remplacement")]).await;
    planifier(&banc, &cookie, &csrf).await;
    let (statut, page) = lire(&banc, &cookie, PLAN).await;
    assert_eq!(statut, StatusCode::OK);
    assert!(page.contains("refus-plan") && page.contains("annuaire.exemple.fr (remplacer)"), "{page}");
    assert!(!page.contains("Confirmer la création"), "{page}");
    let (statut, _, body) = poster(&banc, &cookie, &csrf, EXECUTION, "").await;
    assert_eq!(statut, StatusCode::CONFLICT, "{body}");
    assert!(body.contains("remplacerait"), "{body}");
    assert!(!banc.etat.runner.en_cours());
}

#[tokio::test]
async fn pendant_un_travail_machines_l_assistant_renvoie_vers_e036_et_rien_ne_fuit() {
    let (banc, cookie, csrf) = pret(&[("OIAM_FAUX_TOFU", "secret"), ("OIAM_FAUX_TOFU_ATTENTE", "1")]).await;
    let (statut, _, body) = poster(&banc, &cookie, &csrf, PLAN, "").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    let (res, _) = send(&banc.router, get_avec("/install/composants", &cookie)).await;
    assert_eq!(res.status(), StatusCode::SEE_OTHER);
    assert_eq!(header(&res, "location"), EXECUTION);
    let (statut, _, body) = poster(&banc, &cookie, &csrf, "/install/cibles/hotes/test", "").await;
    assert_eq!(statut, StatusCode::CONFLICT, "{body}");
    let (statut, page) = lire(&banc, &cookie, EXECUTION).await;
    assert_eq!(statut, StatusCode::OK);
    assert!(page.contains("sse-connect=\"/install/cibles/machines/execution/flux"), "{page}");
    attendre_fin(&banc).await;
    let cle = std::fs::read_to_string(banc.etat_dir().join("machines/etat.cle")).unwrap();
    assert_eq!(cle.len(), 64);
    let id = banc.etat.runner.derniere_machines().unwrap().id;
    let journal =
        std::fs::read_to_string(banc.etat.runner.dossier_execution(&id).join("journal.jsonl")).unwrap();
    assert!(!journal.contains(&cle), "la clé de l'état ne figure pas dans le journal");
    assert!(journal.contains("cle=••••••"), "{journal}");
    let (_, flux) = send(&banc.router, get_avec(&format!("{EXECUTION}/flux"), &cookie)).await;
    assert!(!flux.contains(&cle) && flux.contains("••••••"), "{flux}");
}

#[tokio::test]
async fn terminer_purge_le_plan_enregistre_jamais_la_cle_de_l_etat() {
    use std::os::unix::fs::PermissionsExt;
    let (banc, cookie, csrf) = pret(&[]).await;
    planifier(&banc, &cookie, &csrf).await;
    let racine = racine_temoin(&banc);
    assert!(racine.join("plan.tfplan").is_file() && racine.join("plan.json").is_file());
    // Ce que « Terminer » demande au runner (F-04), ici sans installation complète.
    banc.etat.runner.purger_secrets().unwrap();
    assert!(
        !racine.join("plan.tfplan").exists()
            && !racine.join("plan.json").exists()
            && !racine.join("plan-show.json").exists()
    );
    let tfvars = std::fs::read_to_string(racine.join("terraform.tfvars.json")).unwrap();
    assert!(!tfvars.contains("#cloud-config") && !tfvars.contains("PRIVATE KEY"), "{tfvars}");
    let cle = banc.etat_dir().join("machines/etat.cle");
    assert!(cle.is_file());
    assert_eq!(std::fs::metadata(&cle).unwrap().permissions().mode() & 0o777, 0o600);
}

#[tokio::test]
async fn une_creation_echouee_se_relance_par_un_nouveau_plan() {
    let (banc, cookie, csrf) = pret(&[("OIAM_FAUX_TOFU", "echec")]).await;
    planifier(&banc, &cookie, &csrf).await;
    let (statut, _, body) = poster(&banc, &cookie, &csrf, EXECUTION, "").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    attendre_fin(&banc).await;
    let derniere = banc.etat.runner.derniere_machines().unwrap();
    assert_eq!(derniere.statut, StatutExecution::Echouee);
    let (_, page) = lire(&banc, &cookie, EXECUTION).await;
    assert!(
        page.contains("La création des machines a échoué.") && page.contains("quota du pool dépassé"),
        "{page}"
    );
    assert!(page.contains("Recalculer le plan"), "{page}");
    assert!(machine_du_brouillon(&banc).id.is_none(), "rien n'est intégré après un échec");
}

// ------------------------------------------- OI-156 (tranche 7a) : travail d'un fournisseur Xen Orchestra

use open_iam_installer::config::Secret;

/// Background 7a : comme `pret`, mais le fournisseur « labo » est un Xen Orchestra (le faux du banc),
/// avec la confiance `tls` et le jeton donnés ; `url` remplace celle du faux si fournie.
async fn pret_xo(
    env: &[(&str, &str)],
    tls: Confiance,
    jeton: Option<&str>,
    url: Option<String>,
) -> (Banc, String, String, FauxXo) {
    let (banc, cookie, csrf) = pret(env).await;
    let xo = faux_xo(XO_JETON).await;
    let (mut brouillon, mut secrets) = banc.etat.depot.charger().unwrap().unwrap();
    brouillon.fournisseurs = vec![Fournisseur {
        nom: "labo".into(),
        type_: TypeFournisseur::XenOrchestra,
        url: url.unwrap_or_else(|| xo.url.clone()),
        tls,
    }];
    let mut d = brouillon.deploiement.clone().unwrap();
    let machine = d.hotes[0].machine.as_mut().unwrap();
    machine.fournisseur = "labo".into();
    // Identifiant du modèle dans le catalogue du faux Xen Orchestra (tranche 19b).
    machine.modele = Some("tpl-pool-1".into());
    brouillon.deploiement = Some(d);
    if let Some(j) = jeton {
        secrets.fournisseurs.insert("labo".into(), Secret::new(j));
    }
    banc.etat.depot.sauver(&brouillon, &secrets).unwrap();
    (banc, cookie, csrf, xo)
}

fn empreinte_confirmee() -> Confiance {
    Confiance { empreinte_sha256: Some(certificat_xo().empreinte.clone()), autorite: None }
}

fn racine_xo(banc: &Banc) -> std::path::PathBuf {
    banc.etat_dir().join("machines/labo/racines/xcp-ng")
}

#[tokio::test]
async fn le_travail_recoit_le_jeton_et_la_confiance_par_l_environnement_jamais_par_les_fichiers() {
    let trace = tempfile::tempdir().unwrap();
    let trace_tofu = trace.path().join("trace-tofu");
    let (banc, cookie, csrf, xo) = pret_xo(
        &[("OIAM_FAUX_TRACE_TOFU", trace_tofu.to_str().unwrap())],
        empreinte_confirmee(),
        Some(XO_JETON),
        None,
    )
    .await;
    planifier(&banc, &cookie, &csrf).await;
    assert_eq!(banc.etat.runner.derniere_machines().unwrap().statut, StatutExecution::Reussie);
    let trace_texte = std::fs::read_to_string(&trace_tofu).unwrap();
    let confiance = banc.etat_dir().join("machines/labo/confiance.pem");
    assert!(trace_texte.contains(&format!("TF_VAR_jeton={XO_JETON}")), "{trace_texte}");
    assert!(trace_texte.contains(&format!("SSL_CERT_FILE={}", confiance.display())), "{trace_texte}");
    // confiance.pem : le certificat relevé à l'instant, celui dont l'empreinte est confirmée.
    assert_eq!(std::fs::read_to_string(&confiance).unwrap().trim(), certificat_xo().pem().trim());
    // tfvars : connexion en wss://, et ni le jeton ni la clé de l'état.
    let tfvars = std::fs::read_to_string(racine_xo(&banc).join("terraform.tfvars.json")).unwrap();
    let v: serde_json::Value = serde_json::from_str(&tfvars).unwrap();
    assert_eq!(v["connexion"]["url"], xo.url.replacen("https://", "wss://", 1));
    assert_eq!(
        v["machines"]["annuaire.exemple.fr"]["mac"].as_str().map(|m| m.starts_with("02:")),
        Some(true),
        "{tfvars}"
    );
    assert!(!tfvars.contains(XO_JETON));
    let cle = std::fs::read_to_string(banc.etat_dir().join("machines/etat.cle")).unwrap();
    assert!(!tfvars.contains(&cle));
    assert!(racine_xo(&banc).join("plan.json").is_file());
    // L'installeur a vérifié la connexion lui-même avant de lancer tofu.
    let requetes = xo.journal.lock().unwrap().requetes.clone();
    assert!(
        requetes.iter().any(|(c, j)| c == "/rest/v0/users/me" && j.as_deref() == Some(XO_JETON)),
        "{requetes:?}"
    );
}

/// Bloc de la trace du faux tofu pour la commande `cmd` (dernier appel) : arguments et variables.
fn appel_tofu(trace: &str, cmd: &str) -> String {
    trace
        .split("--\n")
        .filter(|bloc| bloc.starts_with(&format!("args={cmd} ")))
        .last()
        .unwrap_or_default()
        .to_owned()
}

// ------------------------------------------------ OI-166 (tranche 17a) : confiance TLS à la création confirmée

#[tokio::test]
async fn la_creation_confirmee_recoit_le_fichier_de_confiance_et_le_jeton() {
    let trace = tempfile::tempdir().unwrap();
    let trace_tofu = trace.path().join("trace-tofu");
    let (banc, cookie, csrf, _xo) = pret_xo(
        &[("OIAM_FAUX_TRACE_TOFU", trace_tofu.to_str().unwrap())],
        empreinte_confirmee(),
        Some(XO_JETON),
        None,
    )
    .await;
    planifier(&banc, &cookie, &csrf).await;
    let (statut, _, body) = poster(&banc, &cookie, &csrf, EXECUTION, "").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    attendre_fin(&banc).await;
    let apply = appel_tofu(&std::fs::read_to_string(&trace_tofu).unwrap(), "apply");
    let confiance = banc.etat_dir().join("machines/labo/confiance.pem");
    assert!(apply.contains(&format!("SSL_CERT_FILE={}", confiance.display())), "apply : {apply}");
    assert!(apply.contains(&format!("TF_VAR_jeton={XO_JETON}")), "apply : {apply}");
    assert_eq!(std::fs::read_to_string(&confiance).unwrap().trim(), certificat_xo().pem().trim());
}

#[tokio::test]
async fn un_certificat_change_depuis_le_plan_arrete_la_creation_avant_tofu() {
    let trace = tempfile::tempdir().unwrap();
    let trace_tofu = trace.path().join("trace-tofu");
    let (banc, cookie, csrf, _xo) = pret_xo(
        &[("OIAM_FAUX_TRACE_TOFU", trace_tofu.to_str().unwrap())],
        empreinte_confirmee(),
        Some(XO_JETON),
        None,
    )
    .await;
    planifier(&banc, &cookie, &csrf).await;
    // Le fournisseur présente désormais un autre certificat que celui dont l'empreinte est confirmée.
    let (mut brouillon, secrets) = banc.etat.depot.charger().unwrap().unwrap();
    brouillon.fournisseurs[0].tls.empreinte_sha256 = Some("AA:".repeat(31) + "AA");
    banc.etat.depot.sauver(&brouillon, &secrets).unwrap();
    let (statut, _, notification) = poster(&banc, &cookie, &csrf, EXECUTION, "").await;
    assert_eq!(statut, StatusCode::CONFLICT, "{notification}");
    assert!(notification.contains("Reconfirmer le certificat"), "{notification}");
    let derniere = banc.etat.runner.derniere_machines().unwrap();
    assert_eq!(derniere.playbook, Some(Playbook::MachinesPlan), "aucune création lancée");
    assert!(appel_tofu(&std::fs::read_to_string(&trace_tofu).unwrap(), "apply").is_empty());
}

#[tokio::test]
async fn un_certificat_change_ou_qui_ne_couvre_pas_l_hote_arrete_le_plan_avant_tofu() {
    // Empreinte confirmée qui n'est pas celle du serveur.
    let fausse = Confiance { empreinte_sha256: Some("AA:".repeat(31) + "AA"), autorite: None };
    let (banc, cookie, csrf, _xo) = pret_xo(&[], fausse, Some(XO_JETON), None).await;
    let (statut, _, notification) = poster(&banc, &cookie, &csrf, PLAN, "").await;
    assert_eq!(statut, StatusCode::CONFLICT, "{notification}");
    assert!(notification.contains("reconfirmez") || notification.contains("Reconfirmer"), "{notification}");
    assert!(!banc.etat.runner.en_cours() && banc.etat.runner.derniere_machines().is_none(), "aucun travail");
    assert!(!banc.etat_dir().join("machines/labo/confiance.pem").exists());

    // Certificat qui ne porte pas l'hôte de l'URL (localhost n'est pas dans ses noms alternatifs).
    let xo = faux_xo(XO_JETON).await;
    let url = xo.url.replacen("127.0.0.1", "localhost", 1);
    let (banc, cookie, csrf, _) = pret_xo(&[], empreinte_confirmee(), Some(XO_JETON), Some(url)).await;
    let (statut, _, notification) = poster(&banc, &cookie, &csrf, PLAN, "").await;
    assert_eq!(statut, StatusCode::CONFLICT, "{notification}");
    assert!(notification.contains("localhost") && notification.contains("xo.exemple.lan"), "{notification}");
    assert!(!banc.etat.runner.en_cours() && banc.etat.runner.derniere_machines().is_none());
}

#[tokio::test]
async fn une_autorite_interne_fournie_tient_lieu_de_confiance() {
    let trace = tempfile::tempdir().unwrap();
    let trace_tofu = trace.path().join("trace-tofu");
    // L'autorité interne qui a signé le certificat du faux, telle qu'un administrateur la colle en E-034.
    let autorite = Confiance { empreinte_sha256: None, autorite: Some(certificat_xo().ca.clone()) };
    let (banc, cookie, csrf, _xo) =
        pret_xo(&[("OIAM_FAUX_TRACE_TOFU", trace_tofu.to_str().unwrap())], autorite, Some(XO_JETON), None)
            .await;
    planifier(&banc, &cookie, &csrf).await;
    assert_eq!(banc.etat.runner.derniere_machines().unwrap().statut, StatutExecution::Reussie);
    let confiance = banc.etat_dir().join("machines/labo/confiance.pem");
    assert_eq!(
        std::fs::read_to_string(&confiance).unwrap(),
        certificat_xo().ca,
        "confiance.pem est l'autorité fournie"
    );
    assert!(
        std::fs::read_to_string(&trace_tofu)
            .unwrap()
            .contains(&format!("SSL_CERT_FILE={}", confiance.display()))
    );

    // Autorité étrangère : le certificat du fournisseur n'est pas signé par elle.
    let etrangere = Confiance { empreinte_sha256: None, autorite: Some(autorites_ad().etrangere.clone()) };
    let (banc, cookie, csrf, _) = pret_xo(&[], etrangere, Some(XO_JETON), None).await;
    let (statut, _, notification) = poster(&banc, &cookie, &csrf, PLAN, "").await;
    assert_eq!(statut, StatusCode::CONFLICT, "{notification}");
    assert!(notification.contains("pas sign") && notification.contains("autorit"), "{notification}");
    assert!(!banc.etat.runner.en_cours() && banc.etat.runner.derniere_machines().is_none());
}

// ------------------------------------------------ OI-157 (tranche 8a) : disponibilité des machines créées

/// Réglages du faux ssh pour ce banc (il part d'un environnement blanc : lus dans <état>/faux-serveurs/ssh.env).
fn regler_faux_ssh(banc: &Banc, reglages: &str) {
    let dossier = banc.etat_dir().join("faux-serveurs");
    std::fs::create_dir_all(&dossier).unwrap();
    std::fs::write(dossier.join("ssh.env"), reglages).unwrap();
}

async fn creer(banc: &Banc, cookie: &str, csrf: &str) -> open_iam_installer::runner::EtatExecution {
    planifier(banc, cookie, csrf).await;
    let (statut, _, body) = poster(banc, cookie, csrf, EXECUTION, "").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    attendre_fin(banc).await;
    banc.etat.runner.derniere_machines().unwrap()
}

fn known_hosts(banc: &Banc) -> String {
    std::fs::read_to_string(banc.etat_dir().join("ssh/known_hosts")).unwrap_or_default()
}

#[tokio::test]
async fn la_machine_creee_est_attendue_sondee_en_mode_strict_puis_disponible() {
    let (banc, cookie, csrf) = pret(&[]).await;
    let trace = banc.etat_dir().join("faux-serveurs/trace-ssh");
    regler_faux_ssh(&banc, &format!("OIAM_FAUX_SSH_ATTENTE=2\nOIAM_FAUX_TRACE={}\n", trace.display()));
    let derniere = creer(&banc, &cookie, &csrf).await;
    assert_eq!(
        derniere.statut,
        StatutExecution::Reussie,
        "{}",
        banc.etat.runner.journal_texte(&derniere.id).unwrap()
    );
    // known_hosts porte la clé injectée, posée avant toute connexion ; la sonde est stricte.
    let kh = known_hosts(&banc);
    assert_eq!(kh.lines().filter(|l| l.starts_with("192.0.2.10 ssh-ed25519 ")).count(), 1, "{kh}");
    let trace_texte = std::fs::read_to_string(&trace).unwrap();
    assert!(trace_texte.contains("StrictHostKeyChecking=yes"), "{trace_texte}");
    assert!(!trace_texte.contains("accept-new"), "{trace_texte}");
    // Les deux premiers essais refusés ont été rejoués.
    let essais: u32 = std::fs::read_to_string(banc.etat_dir().join("faux-serveurs/essais-192.0.2.10"))
        .unwrap()
        .trim()
        .parse()
        .unwrap();
    assert!(essais >= 3, "{essais}");
    let journal = banc.etat.runner.journal_texte(&derniere.id).unwrap();
    assert!(journal.contains("en attente de la machine") && journal.contains("Conformité"), "{journal}");
    // E-003 : créée, connexion vérifiée, conformité ; « Continuer » n'exige pas de retest.
    let (_, page) = lire(&banc, &cookie, "/install/cibles").await;
    assert!(page.contains("créée") && page.contains("connexion vérifiée"), "{page}");
    assert!(
        page.contains("Conformité : cloud-init terminé, root sans mot de passe, pas de mot de passe SSH"),
        "{page}"
    );
    let (statut, _, body) =
        poster(&banc, &cookie, &csrf, "/install/cibles", "mode=native&topologie=multi").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
}

#[tokio::test]
async fn une_cle_d_hote_differente_de_celle_injectee_est_refusee() {
    let (banc, cookie, csrf) = pret(&[]).await;
    regler_faux_ssh(&banc, "OIAM_FAUX_SSH_CLE_DIFFERENTE=1\n");
    let derniere = creer(&banc, &cookie, &csrf).await;
    assert_eq!(derniere.statut, StatutExecution::Echouee);
    let journal = banc.etat.runner.journal_texte(&derniere.id).unwrap();
    assert!(
        journal.contains("n'est pas celle connue de l'installeur") && journal.contains("celle injectée"),
        "{journal}"
    );
    // La machine reste créée (identifiant gardé) ; la ligne known_hosts injectée est intacte.
    let (_, page) = lire(&banc, &cookie, "/install/cibles").await;
    assert_eq!(machine_du_brouillon(&banc).id.as_deref(), Some("faux-annuaire.exemple.fr"));
    assert!(page.contains("créée") && page.contains("échec"), "{page}");
    assert_eq!(known_hosts(&banc).lines().filter(|l| l.starts_with("192.0.2.10 ssh-ed25519 ")).count(), 1);
}

#[tokio::test]
async fn une_machine_non_conforme_est_signalee_sans_etre_detruite() {
    let (banc, cookie, csrf) = pret(&[]).await;
    regler_faux_ssh(&banc, "OIAM_FAUX_SSH_CONFORMITE='cloud_init=done root_mdp=P pwauth=yes agent=absent'\n");
    let derniere = creer(&banc, &cookie, &csrf).await;
    assert_eq!(derniere.statut, StatutExecution::Echouee);
    let (_, page) = lire(&banc, &cookie, "/install/cibles").await;
    assert!(
        page.contains("Conformité")
            && page.contains("root a un mot de passe utilisable")
            && page.contains("mot de passe est permise"),
        "{page}"
    );
    assert!(page.contains("pas durci"), "{page}");
    assert_eq!(machine_du_brouillon(&banc).id.as_deref(), Some("faux-annuaire.exemple.fr"));
}

#[tokio::test]
async fn en_dhcp_l_adresse_vient_du_fournisseur_et_l_agent_invite_est_exige() {
    let (banc, cookie, csrf) = pret(&[]).await;
    let (mut b, s) = banc.etat.depot.charger().unwrap().unwrap();
    let mut d = b.deploiement.clone().unwrap();
    d.hotes[0].adresse = String::new();
    d.hotes[0].machine.as_mut().unwrap().adressage = Adressage::Dhcp;
    b.deploiement = Some(d);
    banc.etat.depot.sauver(&b, &s).unwrap();
    // Sans agent invité : l'adresse vient du témoin (après deux interrogations) mais la conformité l'exige.
    let derniere = creer(&banc, &cookie, &csrf).await;
    let journal = banc.etat.runner.journal_texte(&derniere.id).unwrap();
    assert_eq!(derniere.statut, StatutExecution::Echouee, "{journal}");
    assert!(journal.contains("en attente de l'adresse") && journal.contains("192.0.2.77"), "{journal}");
    assert!(journal.contains("agent invité absent"), "{journal}");
    lire(&banc, &cookie, "/install/cibles").await;
    let (b, _) = banc.etat.depot.charger().unwrap().unwrap();
    let hote = b.deploiement.unwrap().hotes.into_iter().find(|h| h.nom == "annuaire.exemple.fr").unwrap();
    assert_eq!(hote.adresse, "192.0.2.77");
    assert!(known_hosts(&banc).lines().any(|l| l.starts_with("192.0.2.77 ssh-ed25519 ")));
    // Avec l'agent invité : disponible.
    let (banc, cookie, csrf) = pret(&[]).await;
    let (mut b, s) = banc.etat.depot.charger().unwrap().unwrap();
    let mut d = b.deploiement.clone().unwrap();
    d.hotes[0].adresse = String::new();
    d.hotes[0].machine.as_mut().unwrap().adressage = Adressage::Dhcp;
    b.deploiement = Some(d);
    banc.etat.depot.sauver(&b, &s).unwrap();
    regler_faux_ssh(&banc, "OIAM_FAUX_SSH_CONFORMITE='cloud_init=done root_mdp=L pwauth=no agent=present'\n");
    let derniere = creer(&banc, &cookie, &csrf).await;
    assert_eq!(
        derniere.statut,
        StatutExecution::Reussie,
        "{}",
        banc.etat.runner.journal_texte(&derniere.id).unwrap()
    );
    let (_, page) = lire(&banc, &cookie, "/install/cibles").await;
    assert!(page.contains("192.0.2.77") && page.contains("agent invité présent"), "{page}");
}

#[tokio::test]
async fn l_attente_a_une_fin() {
    let (banc, cookie, csrf) = pret(&[]).await;
    regler_faux_ssh(&banc, "OIAM_FAUX_SSH_ATTENTE=100000\n");
    let debut = std::time::Instant::now();
    let derniere = creer(&banc, &cookie, &csrf).await;
    assert_eq!(derniere.statut, StatutExecution::Echouee);
    assert!(debut.elapsed() < Duration::from_secs(15), "délai court du banc : {:?}", debut.elapsed());
    let journal = banc.etat.runner.journal_texte(&derniere.id).unwrap();
    assert!(journal.contains("n'a pas répondu en"), "{journal}");
    lire(&banc, &cookie, "/install/cibles").await;
    assert_eq!(
        machine_du_brouillon(&banc).id.as_deref(),
        Some("faux-annuaire.exemple.fr"),
        "la machine reste créée"
    );
}

// ------------------------------------------------- OI-159 (tranche 10) : retrait et orphelins

async fn creer_machine(banc: &Banc, cookie: &str, csrf: &str) {
    let derniere = creer(banc, cookie, csrf).await;
    assert_eq!(
        derniere.statut,
        StatutExecution::Reussie,
        "{}",
        banc.etat.runner.journal_texte(&derniere.id).unwrap()
    );
    lire(banc, cookie, "/install/cibles").await;
    assert_eq!(machine_du_brouillon(banc).id.as_deref(), Some("faux-annuaire.exemple.fr"));
}

#[tokio::test]
async fn le_retrait_passe_par_un_plan_de_destruction_confirme_par_le_nom() {
    let (banc, cookie, csrf) = pret(&[]).await;
    creer_machine(&banc, &cookie, &csrf).await;
    let (_, page) = lire(&banc, &cookie, "/install/cibles").await;
    assert!(page.contains(r#"hx-post="/install/cibles/machines/annuaire.exemple.fr/retrait""#), "{page}");
    assert!(
        !page.contains(r#"hx-delete="/install/cibles/hotes/annuaire.exemple.fr""#),
        "une machine créée n'a que « Retirer » : {page}"
    );
    assert!(known_hosts(&banc).contains("192.0.2.10 ssh-ed25519 "));

    let (statut, redirection, body) =
        poster(&banc, &cookie, &csrf, "/install/cibles/machines/annuaire.exemple.fr/retrait", "").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    assert_eq!(redirection, PLAN);
    attendre_fin(&banc).await;
    let (statut, page) = lire(&banc, &cookie, PLAN).await;
    assert_eq!(statut, StatusCode::OK);
    assert!(
        page.contains("détruire")
            && page.contains(r#"id="retrait-plan""#)
            && page.contains(r#"name="confirmation""#),
        "{page}"
    );
    assert!(page.contains("Confirmer le retrait") && !page.contains("refus-plan"), "{page}");
    // Sans le nom exact : rien n'est lancé.
    for saisie in ["", "confirmation=autre.exemple.fr"] {
        let (statut, _, body) = poster(&banc, &cookie, &csrf, EXECUTION, saisie).await;
        assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "{saisie} : {body}");
        assert!(!banc.etat.runner.en_cours());
    }
    let (statut, _, body) =
        poster(&banc, &cookie, &csrf, EXECUTION, "confirmation=annuaire.exemple.fr").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    attendre_fin(&banc).await;
    let derniere = banc.etat.runner.derniere_machines().unwrap();
    assert_eq!(
        derniere.statut,
        StatutExecution::Reussie,
        "{}",
        banc.etat.runner.journal_texte(&derniere.id).unwrap()
    );
    assert!(banc.etat.runner.journal_texte(&derniere.id).unwrap().contains("destruction"));
    let (_, page) = lire(&banc, &cookie, "/install/cibles").await;
    let (b, _) = banc.etat.depot.charger().unwrap().unwrap();
    assert!(
        !b.deploiement.unwrap().hotes.iter().any(|h| h.nom == "annuaire.exemple.fr"),
        "serveur retiré : {page}"
    );
    assert!(!known_hosts(&banc).contains("192.0.2.10 "), "{}", known_hosts(&banc));
    // Le fournisseur (faux état du faux tofu) ne la connaît plus.
    let etat_faux: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(racine_temoin(&banc).join("terraform.tfstate")).unwrap(),
    )
    .unwrap();
    assert!(etat_faux.get("annuaire.exemple.fr").is_none(), "{etat_faux}");
}

#[tokio::test]
async fn un_serveur_ssh_ou_une_machine_prevue_ne_se_detruit_pas_chez_le_fournisseur() {
    let (banc, cookie, csrf) = pret(&[]).await;
    // Machine seulement prévue.
    let (statut, _, body) =
        poster(&banc, &cookie, &csrf, "/install/cibles/machines/annuaire.exemple.fr/retrait", "").await;
    assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "{body}");
    assert!(body.contains("Supprimer"), "{body}");
    // Serveur déclaré en SSH.
    let (mut b, s) = banc.etat.depot.charger().unwrap().unwrap();
    b.poser_hote(Hote {
        nom: "outils.exemple.fr".into(),
        adresse: "ok.exemple.fr".into(),
        port: 22,
        utilisateur: "root".into(),
        roles: [RoleHote::Outils].into(),
        local: false,
        machine: None,
    });
    banc.etat.depot.sauver(&b, &s).unwrap();
    let (statut, _, body) =
        poster(&banc, &cookie, &csrf, "/install/cibles/machines/outils.exemple.fr/retrait", "").await;
    assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "{body}");
    let (_, page) = lire(&banc, &cookie, "/install/cibles").await;
    assert!(!page.contains("/retrait\""), "aucun bouton Retirer sans machine créée : {page}");
    assert!(
        !banc.etat.runner.en_cours() && banc.etat.runner.derniere_machines().is_none(),
        "aucun plan calculé"
    );
}

#[tokio::test]
async fn les_orphelins_sont_listes_jamais_detruits_d_office() {
    let (banc, cookie, csrf) = pret(&[]).await;
    let dossier = banc.etat_dir().join("machines/temoin");
    std::fs::create_dir_all(&dossier).unwrap();
    std::fs::write(dossier.join("orphelins.json"), r#"[{"id":"vm-orpheline","nom":"vieille.exemple.fr"}]"#)
        .unwrap();
    planifier(&banc, &cookie, &csrf).await;
    let (statut, page) = lire(&banc, &cookie, PLAN).await;
    assert_eq!(statut, StatusCode::OK);
    assert!(
        page.contains(r#"id="orphelins""#)
            && page.contains("vieille.exemple.fr")
            && page.contains("vm-orpheline"),
        "{page}"
    );
    assert!(page.contains("ne seront pas détruites"), "{page}");
    // Le plan ne la touche pas : elle n'est pas dans le résumé, et la création se confirme normalement.
    let lignes_plan = page.split(r#"aria-label="Plan par machine""#).nth(1).unwrap_or_default();
    assert!(!lignes_plan.contains("vieille.exemple.fr"), "{lignes_plan}");
    assert!(page.contains("Confirmer la création"), "{page}");
}

// ------------------------------------------------ OI-166 (tranche 17c) : fin d'un travail

#[tokio::test]
async fn la_fin_d_un_travail_retire_interrompre_et_le_titre_en_cours() {
    let (banc, cookie, csrf) = pret(&[]).await;
    planifier(&banc, &cookie, &csrf).await;
    let (statut, _, body) = poster(&banc, &cookie, &csrf, EXECUTION, "").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    attendre_fin(&banc).await;
    // Rechargement : titre terminé, plus de bouton « Interrompre ».
    let (_, page) = lire(&banc, &cookie, EXECUTION).await;
    assert!(page.contains(r#"id="titre-travail""#) && page.contains(">Création des machines</h1>"), "{page}");
    assert!(!page.contains("Création des machines en cours"), "{page}");
    assert!(!page.contains("Interrompre"), "{page}");
    // En direct : l'événement « fin » remplace le titre et vide le bloc d'interruption, hors bande.
    let (_, flux) = send(&banc.router, get_avec(&format!("{EXECUTION}/flux"), &cookie)).await;
    let fin = flux.split("event: fin").nth(1).unwrap_or_default();
    assert!(fin.contains(r#"id="titre-travail" hx-swap-oob="true""#), "{fin}");
    assert!(fin.contains(">Création des machines</h1>"), "{fin}");
    assert!(fin.contains(r#"<div id="interruption" hx-swap-oob="true"></div>"#), "{fin}");
}

// ---------------------- OI-212 (tranche 19b) : contrôle des machines prévues avant le plan

/// Machine prévue sur « pool-2 » du témoin, dont le modèle exige 2048 Mo (stockage de 100 Go libres).
fn machine_pool_2(memoire_mo: u32) -> Machine {
    Machine {
        emplacement: [("pool".to_owned(), "pool-2".to_owned())].into(),
        modele: Some("tpl-debian-13-pool-2".into()),
        memoire_mo,
        disques: vec![Disque { stockage: "sr-pool-2".into(), taille_go: 20 }],
        reseau: "net-pool-2".into(),
        ..machine_prevue()
    }
}

/// Remplace la machine de `nom` (ou ajoute ce serveur, annuaire) dans le brouillon.
fn poser_machine(banc: &Banc, nom: &str, machine: Machine) {
    let (mut brouillon, secrets) = banc.etat.depot.charger().unwrap().unwrap();
    brouillon.poser_hote(Hote {
        nom: nom.into(),
        adresse: "192.0.2.10".into(),
        port: 22,
        utilisateur: "root".into(),
        roles: [RoleHote::Annuaire].into(),
        local: false,
        machine: Some(machine),
    });
    banc.etat.depot.sauver(&brouillon, &secrets).unwrap();
}

/// « Créer les machines prévues » refusé par le contrôle : 422 affiché sous le bouton.
async fn refus_du_controle(banc: &Banc, cookie: &str, csrf: &str) -> String {
    let (res, body) = send(&banc.router, post_form(PLAN, cookie, Some(csrf), "")).await;
    assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY, "{body}");
    assert_eq!(header(&res, "hx-retarget"), "#controle-machines", "{body}");
    assert_eq!(header(&res, "hx-reswap"), "innerHTML", "{body}");
    assert!(!banc.etat.runner.en_cours() && banc.etat.runner.derniere_machines().is_none(), "aucun plan");
    body
}

#[tokio::test]
async fn t19b_une_memoire_sous_le_minimum_du_modele_bloque_le_plan_avant_toute_preparation() {
    let (banc, cookie, csrf) = pret(&[]).await;
    poser_machine(&banc, "annuaire.exemple.fr", machine_pool_2(1024));
    let body = refus_du_controle(&banc, &cookie, &csrf).await;
    assert!(body.contains("annuaire.exemple.fr"), "{body}");
    assert!(body.contains("1024 Mo demandés") && body.contains("au moins 2048 Mo"), "{body}");
    assert!(body.contains("Dans la demande") && body.contains("Chez le fournisseur"), "{body}");
    // Rien n'est préparé : ni MAC, ni tfvars.
    assert!(machine_du_brouillon(&banc).mac.is_none(), "aucune MAC posée");
    assert!(!racine_temoin(&banc).join("terraform.tfvars.json").exists(), "aucun tfvars écrit");
}

#[tokio::test]
async fn t19b_tous_les_problemes_sont_listes_en_une_fois() {
    let (banc, cookie, csrf) = pret(&[]).await;
    poser_machine(&banc, "annuaire.exemple.fr", machine_pool_2(1024));
    poser_machine(&banc, "outils.exemple.fr", machine_pool_2(1024));
    let body = refus_du_controle(&banc, &cookie, &csrf).await;
    assert!(body.contains("annuaire.exemple.fr") && body.contains("outils.exemple.fr"), "{body}");
    assert!(body.contains("2 problèmes"), "{body}");
}

#[tokio::test]
async fn t19b_un_element_disparu_du_pool_bloque_le_plan() {
    type Disparition = (&'static str, fn(&mut Machine));
    let disparitions: [Disparition; 3] = [
        ("modèle", |m| m.modele = Some("tpl-parti".into())),
        ("réseau", |m| m.reseau = "net-parti".into()),
        ("stockage", |m| m.disques[0].stockage = "sr-parti".into()),
    ];
    for (element, faire_disparaitre) in disparitions {
        let (banc, cookie, csrf) = pret(&[]).await;
        let mut m = machine_prevue();
        faire_disparaitre(&mut m);
        poser_machine(&banc, "annuaire.exemple.fr", m);
        let body = refus_du_controle(&banc, &cookie, &csrf).await;
        assert!(
            body.contains(&format!("{element} :")) && body.contains("existe plus sur le pool"),
            "{element} : {body}"
        );
        assert!(body.contains(&format!("choisissez un autre {element}")), "{element} : {body}");
        assert!(body.contains(&format!("recréez ce {element}")), "{element} : {body}");
    }
}

#[tokio::test]
async fn t19b_des_disques_au_dela_de_l_espace_libre_avertissent_sans_bloquer() {
    let (banc, cookie, csrf) = pret(&[]).await;
    let soixante = |memoire| Machine {
        disques: vec![Disque { stockage: "sr-pool-2".into(), taille_go: 60 }],
        ..machine_pool_2(memoire)
    };
    poser_machine(&banc, "annuaire.exemple.fr", soixante(2048));
    poser_machine(&banc, "outils.exemple.fr", soixante(4096));
    planifier(&banc, &cookie, &csrf).await;
    let (statut, page) = lire(&banc, &cookie, PLAN).await;
    assert_eq!(statut, StatusCode::OK);
    assert!(page.contains("avertissements-plan"), "{page}");
    assert!(page.contains("120 Go de disques prévus") && page.contains("100 Go libres"), "{page}");
    assert!(page.contains("Confirmer la création"), "l'avertissement ne bloque pas : {page}");
}

#[tokio::test]
async fn t19b_une_machine_deja_creee_n_est_pas_recontrolee() {
    let (banc, cookie, csrf) = pret(&[]).await;
    let creee = Machine {
        modele: Some("tpl-parti".into()),
        mac: Some("02:4f:00:00:00:01".into()),
        id: Some("faux-ancienne.exemple.fr".into()),
        ..machine_prevue()
    };
    poser_machine(&banc, "ancienne.exemple.fr", creee);
    planifier(&banc, &cookie, &csrf).await;
    let (_, page) = lire(&banc, &cookie, PLAN).await;
    assert!(page.contains("Confirmer la création") && !page.contains("avertissements-plan"), "{page}");
}