evolution.rs 1431 lignes · 69810 octets
//! OI-072 (D-047) — E-022 Faire évoluer l'installation : l'assistant rejoué sur une installation
//! verrouillée (plan M3, tranche C). Ansible est remplacé par tests/faux/ansible-playbook.

mod commun;

use std::{collections::BTreeSet, path::PathBuf, time::Duration};

use axum::http::StatusCode;
use commun::*;
use open_iam_installer::{
    catalogue::ComposantId,
    config::{Hote, Mode, OpenIamConfig, TlsMode, Topologie},
    etat::Etat,
};

const URGENCE: &str = "Urgence-Tres-Longue-2026!";
const MOT_DE_PASSE: &str = "Cheval-Batterie-42";
const VERSION: &str = env!("CARGO_PKG_VERSION");

// ------------------------------------------------------------------------------- fixtures

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 d'exécution");
}

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;
    (res.status(), header(&res, "hx-redirect").to_owned(), body)
}

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)
}

/// Installation réussie de base (Background) : openldap, sauvegarde et ssp sur « Tout sur cette
/// machine », messagerie sans identifiant, puis « Terminer » (secrets purgés). Sans `terminer`,
/// l'installation reste « non terminée » (arbitrage 10).
async fn installe_sans_terminer() -> (Banc, String, String) {
    let banc = banc_avec(vec![("OIAM_FAUX_SCENARIO".into(), "reussite".into())]);
    let (cookie, csrf) = session_assistant(&banc).await;
    let comptes = format!(
        "urgence={URGENCE}&urgence_genere=1&uid=jean.dupont&prenom=Jean&nom=Dupont&email=jean.dupont%40exemple.fr&mode_mdp=saisir&mot_de_passe={MOT_DE_PASSE}&confirmation={MOT_DE_PASSE}"
    );
    for (uri, form) in [
        ("/install/commencer", ""),
        (
            "/install/organisation",
            "nom=Mairie+d%27Exemple&domaine=exemple.fr&base_dn=&langue=fr&fuseau=Europe%2FParis",
        ),
        ("/install/cibles", "mode=native&topologie=local"),
        ("/install/composants", "composants=openldap&composants=sauvegarde&composants=ssp"),
        ("/install/securite", "annuaire=annuaire.exemple.fr&mdp=mdp.exemple.fr&tls=interne&preset=anssi"),
        (
            "/install/messagerie",
            "hote=smtp.exemple.fr&port=587&chiffrement=starttls&expediteur=noreply%40exemple.fr&nom=Mairie",
        ),
        ("/install/comptes", comptes.as_str()),
        ("/install/telemetrie", ""),
        ("/install/verification", ""),
        ("/install/execution", ""),
    ] {
        let (statut, _, body) = poster(&banc, &cookie, &csrf, uri, form).await;
        assert!(statut.is_success(), "{uri} : {statut} {body}");
    }
    attendre_fin(&banc).await;
    assert!(banc.etat.installe(), "installation de base réussie et verrouillée");
    (banc, cookie, csrf)
}

async fn installe() -> Banc {
    let (banc, cookie, csrf) = installe_sans_terminer().await;
    let (_, redirection, _) = poster(&banc, &cookie, &csrf, "/install/terminer", "conserve=on").await;
    assert_eq!(redirection, "/verrouille");
    banc
}

/// Même répertoire d'état, installeur redémarré avec un autre scénario du faux Ansible (et sa trace).
fn rebrancher(banc: Banc, environnement: Vec<(String, String)>) -> Banc {
    let Banc { dossier, etat, .. } = banc;
    let mut parametres = etat.parametres.clone();
    parametres.outils.environnement = environnement;
    drop(etat);
    let etat = Etat::ouvrir(parametres).unwrap();
    Banc { router: open_iam_installer::app(etat.clone()), etat, dossier }
}

/// Identifiant de la dernière exécution (celle de l'installation de base, juste après).
fn derniere_execution(banc: &Banc) -> String {
    banc.etat.runner.derniere().unwrap().id
}

/// Modifie la configuration de base telle que la dernière exécution réussie l'a enregistrée
/// (`executions/<id>/openiam.yaml` et `<état>/openiam.yaml`).
fn modifier_base(banc: &Banc, modifier: impl Fn(&mut OpenIamConfig)) {
    let id = derniere_execution(banc);
    for chemin in
        [banc.etat.runner.dossier_execution(&id).join("openiam.yaml"), banc.etat_dir().join("openiam.yaml")]
    {
        let mut config: OpenIamConfig =
            serde_norway::from_str(&std::fs::read_to_string(&chemin).unwrap()).unwrap();
        modifier(&mut config);
        std::fs::write(&chemin, config.vers_yaml()).unwrap();
    }
}

/// Session ouverte par jeton après le verrou, puis évolution commencée (POST /install/evolution).
async fn evolution(banc: &Banc) -> (String, String) {
    let (cookie, csrf) = session_assistant(banc).await;
    let (statut, redirection, body) = poster(banc, &cookie, &csrf, "/install/evolution", "").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    assert_eq!(redirection, "/install/composants");
    (cookie, csrf)
}

fn brouillon_yaml(banc: &Banc) -> String {
    std::fs::read_to_string(banc.etat_dir().join("draft.yaml")).unwrap_or_default()
}

/// Bloc HTML qui suit `debut`, jusqu'à `fin` exclu.
fn bloc<'a>(html: &'a str, debut: &str, fin: &str) -> &'a str {
    html.split(debut).nth(1).unwrap_or_else(|| panic!("{debut} absent : {html}")).split(fin).next().unwrap()
}

/// Balise `<input …>` dont l'identifiant est `id`.
fn champ<'a>(html: &'a str, id: &str) -> &'a str {
    bloc(html, &format!(r#"id="{id}""#), ">")
}

fn etat_dans_le_stepper(html: &str, libelle: &str, etat: &str) -> bool {
    html.contains(&format!(r#"{libelle} <span class="sr-only">({etat})</span>"#))
}

/// Fichiers récapitulatifs écrits, du plus ancien au plus récent.
fn recapitulatifs(banc: &Banc) -> Vec<PathBuf> {
    let mut fichiers: Vec<PathBuf> =
        std::fs::read_dir(banc.racine().join("home/open-iam")).unwrap().map(|e| e.unwrap().path()).collect();
    fichiers.sort();
    fichiers
}

/// Mot de passe du compte de service `cn` dans un fichier récapitulatif.
fn mot_de_passe_de(recapitulatif: &str, cn: &str) -> String {
    bloc(bloc(recapitulatif, &format!("cn={cn},"), "\n\n"), "Mot de passe : ", "\n").to_owned()
}

/// Ajoute White Pages au brouillon d'évolution et valide E-005 : le récapitulatif est prêt.
async fn ajouter_white_pages(banc: &Banc, cookie: &str, csrf: &str) {
    let (statut, redirection, body) = poster(
        banc,
        cookie,
        csrf,
        "/install/composants",
        "composants=openldap&composants=sauvegarde&composants=ssp&composants=white_pages",
    )
    .await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    assert_eq!(redirection, "/install/securite");
    let (statut, redirection, body) =
        poster(banc, cookie, csrf, "/install/securite", "pages=pages.exemple.fr").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    assert_eq!(redirection, "/install/recapitulatif", "E-006, E-007 et E-008 ne sont pas rejouées");
}

// ------------------------------------------------------------------------------- scénarios

#[tokio::test]
async fn e092_mene_a_e022_qui_decrit_l_installation() {
    let banc = installe().await;
    let (res, page) = send(&banc.router, get("/verrouille")).await;
    assert_eq!(res.status(), StatusCode::OK);
    assert!(
        page.contains(r#"href="/install/evolution""#) && page.contains("Faire évoluer l'installation"),
        "{page}"
    );
    assert!(!page.contains("console"), "texte obsolète (D-045) : {page}");

    let (cookie, _) = session_assistant(&banc).await;
    let (statut, page) = lire(&banc, &cookie, "/install/evolution").await;
    assert_eq!(statut, StatusCode::OK, "{page}");
    let installation = bloc(&page, r#"id="installation-actuelle""#, "</section>");
    for attendu in
        ["exemple.fr", "Annuaire OpenLDAP (LTB)", "Sauvegardes chiffrées", "Self Service Password", VERSION]
    {
        assert!(installation.contains(attendu), "{attendu} : {installation}");
    }
    assert!(!installation.contains("White Pages"), "{installation}");
    let id = derniere_execution(&banc);
    let date = format!("{}/{}/{}", &id[6..8], &id[4..6], &id[0..4]);
    assert!(installation.contains(&date), "date de la dernière exécution réussie {date} : {installation}");
    let impossible = bloc(&page, r#"id="evolution-impossible""#, "</ul>");
    for attendu in ["retirer", "domaine", "mode", "topologie", "serveur installé"] {
        assert!(impossible.contains(attendu), "{attendu} : {impossible}");
    }
    assert!(page.contains(r#"hx-post="/install/evolution""#), "bouton « Commencer l'évolution » : {page}");
    assert!(page.contains("Mettre à jour les composants"), "carte E022-C8 : {page}");
    assert!(!banc.etat_dir().join("draft.yaml").exists(), "GET sans effet de bord");
}

#[tokio::test]
async fn un_jeton_donne_acces_a_e022_apres_le_verrou() {
    let banc = installe().await;
    let (cookie, _) = session(&banc.router).await;
    let jeton = open_iam_installer::acces::generer(&banc.etat_dir()).unwrap();
    let (res, _) = send(&banc.router, get_avec(&format!("/acces?jeton={jeton}"), &cookie)).await;
    assert_eq!(res.status(), StatusCode::SEE_OTHER);
    assert_eq!(header(&res, "location"), "/install/evolution");

    let (cookie, csrf) = session(&banc.router).await;
    let jeton = open_iam_installer::acces::generer(&banc.etat_dir()).unwrap();
    let (res, _) =
        send(&banc.router, post_form("/acces", &cookie, Some(&csrf), &format!("jeton={jeton}"))).await;
    assert_eq!(header(&res, "hx-redirect"), "/install/evolution");
    let cookie = nouveau_cookie(&res).unwrap();
    assert_eq!(lire(&banc, &cookie, "/install/evolution").await.0, StatusCode::OK);
}

#[tokio::test]
async fn commencer_l_evolution_cree_un_brouillon_fige_sur_la_base() {
    let banc = installe().await;
    let base = derniere_execution(&banc);
    let (_garde, journal) = journal();
    let (cookie, csrf) = evolution(&banc).await;
    assert!(journal.texte().contains(r#"evenement="evolution_commencee""#), "{}", journal.texte());
    let brouillon = brouillon_yaml(&banc);
    assert!(brouillon.contains("evolution:") && brouillon.contains(&base), "{brouillon}");

    let (statut, page) = lire(&banc, &cookie, "/install/composants").await;
    assert_eq!(statut, StatusCode::OK);
    for cle in ["openldap", "sauvegarde", "ssp"] {
        let case = champ(&page, &format!("composant-{cle}"));
        assert!(case.contains("checked") && case.contains("disabled"), "{cle} : {case}");
        let carte = bloc(&page, &format!(r#"id="desc-{cle}""#), "</label>");
        assert!(carte.contains("Déjà installé"), "{cle} : {carte}");
    }
    assert!(!champ(&page, "composant-white_pages").contains("disabled"), "un ajout reste possible");

    let (statut, page) = lire(&banc, &cookie, "/install/organisation").await;
    assert_eq!(statut, StatusCode::OK);
    assert!(champ(&page, "domaine").contains("disabled") && page.contains("Fixé à l'installation"), "{page}");
    let (statut, _, body) = poster(
        &banc,
        &cookie,
        &csrf,
        "/install/organisation",
        "nom=Mairie+d%27Exemple&domaine=autre.fr&base_dn=&langue=fr&fuseau=Europe%2FParis",
    )
    .await;
    assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "{body}");
    assert!(body.contains("Une évolution ne peut qu&#39;ajouter"), "{body}");
    assert!(
        brouillon_yaml(&banc).contains("domaine: exemple.fr") && !brouillon_yaml(&banc).contains("autre.fr")
    );
}

#[tokio::test]
async fn ajouter_white_pages_ne_rejoue_que_ce_qu_il_exige() {
    let banc = installe().await;
    let (cookie, csrf) = evolution(&banc).await;
    let (_, redirection, _) = poster(
        &banc,
        &cookie,
        &csrf,
        "/install/composants",
        "composants=openldap&composants=sauvegarde&composants=ssp&composants=white_pages",
    )
    .await;
    assert_eq!(redirection, "/install/securite");

    let (statut, page) = lire(&banc, &cookie, "/install/securite").await;
    assert_eq!(statut, StatusCode::OK);
    assert!(etat_dans_le_stepper(&page, "Sécurité", "à revoir"), "{page}");
    let pages = champ(&page, "pages");
    assert!(pages.contains(r#"value="pages.exemple.fr""#) && !pages.contains("disabled"), "{pages}");
    for fige in ["annuaire", "mdp"] {
        assert!(champ(&page, fige).contains("disabled"), "{fige} figé : {}", champ(&page, fige));
    }
    let (statut, _, body) =
        poster(&banc, &cookie, &csrf, "/install/securite", "pages=pages.exemple.fr&mdp=autre.exemple.fr")
            .await;
    assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "nom d'un service existant : {body}");

    let (statut, redirection, body) =
        poster(&banc, &cookie, &csrf, "/install/securite", "pages=pages.exemple.fr").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    assert_eq!(redirection, "/install/recapitulatif", "E-006 sans identifiant n'est pas rejouée");

    let (statut, page) = lire(&banc, &cookie, "/install/recapitulatif").await;
    assert_eq!(statut, StatusCode::OK, "{page}");
    let installe = bloc(&page, r#"id="deja-installe""#, "</ul>");
    let ajoute = bloc(&page, r#"id="a-ajouter""#, "</ul>");
    for cle in ["openldap", "sauvegarde", "ssp"] {
        assert!(
            installe.contains(cle) && !ajoute.contains(&format!(">{cle}<")),
            "{cle} : {installe} / {ajoute}"
        );
    }
    assert!(ajoute.contains("white_pages") && !installe.contains("white_pages"), "{ajoute}");
    assert!(page.contains("White Pages (ajout)"), "nouvelle phase du plan marquée « ajout » : {page}");
    assert!(page.contains("Lancer l'évolution"), "{page}");
}

#[tokio::test]
async fn retirer_un_composant_installe_est_impossible() {
    let banc = installe().await;
    let (cookie, csrf) = evolution(&banc).await;
    let (_garde, journal) = journal();
    let (statut, _, body) = poster(
        &banc,
        &cookie,
        &csrf,
        "/install/composants",
        "composants=openldap&composants=sauvegarde&composants=white_pages",
    )
    .await;
    assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "{body}");
    assert!(body.contains("Self Service Password ne peut pas être retiré"), "{body}");
    assert!(journal.texte().contains(r#"evenement="evolution_refusee""#), "{}", journal.texte());
    assert!(brouillon_yaml(&banc).contains("- ssp"), "brouillon inchangé");
    assert!(!brouillon_yaml(&banc).contains("white_pages"), "brouillon inchangé");
    let (_, page) = lire(&banc, &cookie, "/install/composants").await;
    assert!(champ(&page, "composant-ssp").contains("checked"), "ssp reste coché");

    let (statut, _, body) = poster(
        &banc,
        &cookie,
        &csrf,
        "/install/composants",
        "composants=openldap&composants=sauvegarde&composants=ssp",
    )
    .await;
    assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY);
    assert!(body.contains("Choisissez au moins un composant à ajouter."), "{body}");
}

#[tokio::test]
async fn une_messagerie_authentifiee_demande_son_mot_de_passe() {
    let banc = installe().await;
    modifier_base(&banc, |c| c.smtp.as_mut().unwrap().utilisateur = Some("envoi@exemple.fr".into()));
    let (cookie, csrf) = evolution(&banc).await;
    let (_, redirection, _) = poster(
        &banc,
        &cookie,
        &csrf,
        "/install/composants",
        "composants=openldap&composants=sauvegarde&composants=ssp&composants=service_desk",
    )
    .await;
    assert_eq!(redirection, "/install/securite");
    let (_, redirection, body) =
        poster(&banc, &cookie, &csrf, "/install/securite", "support=support.exemple.fr").await;
    assert_eq!(redirection, "/install/messagerie", "{body}");

    let (statut, page) = lire(&banc, &cookie, "/install/messagerie").await;
    assert_eq!(statut, StatusCode::OK);
    assert!(etat_dans_le_stepper(&page, "Messagerie", "à revoir"), "{page}");
    for (id, valeur) in [("hote", "smtp.exemple.fr"), ("port", "587"), ("utilisateur", "envoi@exemple.fr")] {
        let c = champ(&page, id);
        assert!(c.contains("disabled") && c.contains(valeur), "{id} figé : {c}");
    }
    assert!(page.contains("Fixé à l'installation"), "{page}");
    assert!(!champ(&page, "mot_de_passe").contains("disabled"), "mot de passe à ressaisir");

    let (statut, _, _) = poster(&banc, &cookie, &csrf, "/install/messagerie", "").await;
    assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "mot de passe exigé");
    let (statut, _, body) = poster(
        &banc,
        &cookie,
        &csrf,
        "/install/messagerie",
        "hote=autre.exemple.fr&mot_de_passe=Secret-SMTP-2026",
    )
    .await;
    assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "relais figé : {body}");
    let (statut, _, body) =
        poster(&banc, &cookie, &csrf, "/install/messagerie", "mot_de_passe=Secret-SMTP-2026").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    assert!(brouillon_yaml(&banc).contains("hote: smtp.exemple.fr"));
    assert!(!brouillon_yaml(&banc).contains("Secret-SMTP-2026"), "le secret n'est pas dans le brouillon");
}

#[tokio::test]
async fn les_certificats_fournis_sont_redeposes() {
    let banc = installe().await;
    modifier_base(&banc, |c| c.tls.mode = TlsMode::Fourni);
    // Ce que « Terminer » laisse d'un dépôt (F-04) : la chaîne et l'analyse, pas la clé.
    let tls = open_iam_installer::certificats::Depot::new(&banc.etat_dir());
    std::fs::create_dir_all(&tls.dossier).unwrap();
    std::fs::write(tls.chaine(), "-----BEGIN CERTIFICATE-----").unwrap();
    std::fs::write(
        tls.analyse(),
        r#"{"sujet":"CN=exemple.fr","emetteur":"CN=AC","noms":["*.exemple.fr"],"expiration_epoch":4102444800,"jours_restants":4000,"certificats":2,"cle":"RSA 2048 bits","cle_correspond":true}"#,
    )
    .unwrap();

    let (cookie, csrf) = evolution(&banc).await;
    let (_, page) = lire(&banc, &cookie, "/install/composants").await;
    assert!(etat_dans_le_stepper(&page, "Sécurité", "à revoir"), "{page}");
    assert!(tls.derniere().is_none(), "l'ancien dépôt ne vaut plus");
    ajouter_composant(&banc, &cookie, &csrf, "white_pages").await;
    let (statut, _, body) =
        poster(&banc, &cookie, &csrf, "/install/securite", "pages=pages.exemple.fr").await;
    assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "{body}");
    assert!(body.contains("Déposez la chaîne de certificats et la clé privée"), "{body}");
}

async fn ajouter_composant(banc: &Banc, cookie: &str, csrf: &str, cle: &str) {
    let (statut, _, body) = poster(
        banc,
        cookie,
        csrf,
        "/install/composants",
        &format!("composants=openldap&composants=sauvegarde&composants=ssp&composants={cle}"),
    )
    .await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
}

#[tokio::test]
async fn le_lancement_rejoue_site_yml_et_complete_le_recapitulatif() {
    let banc = installe().await;
    let ancien = recapitulatifs(&banc);
    assert_eq!(ancien.len(), 1);
    let ancien_contenu = std::fs::read_to_string(&ancien[0]).unwrap();
    let trace = banc.racine().join("trace-ansible");
    let banc = rebrancher(
        banc,
        vec![
            ("OIAM_FAUX_SCENARIO".into(), "reussite".into()),
            ("OIAM_FAUX_TRACE".into(), trace.display().to_string()),
        ],
    );
    let (cookie, csrf) = evolution(&banc).await;
    ajouter_white_pages(&banc, &cookie, &csrf).await;
    let (statut, _, fragment) = poster(&banc, &cookie, &csrf, "/install/verification", "").await;
    assert_eq!(statut, StatusCode::OK);
    assert!(
        fragment.contains("Lancer l'évolution") && fragment.contains("ajout de White Pages"),
        "{fragment}"
    );
    assert!(
        fragment.contains("Vérification réussie"),
        "le mot de passe d'urgence n'est pas exigé : {fragment}"
    );

    let (_garde, journal) = journal();
    let (statut, redirection, body) = poster(&banc, &cookie, &csrf, "/install/execution", "").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    assert_eq!(redirection, "/install/execution");
    assert!(journal.texte().contains(r#"evenement="evolution_lancee""#), "{}", journal.texte());
    let (_, page) = lire(&banc, &cookie, "/install/execution").await;
    assert!(page.contains("Évolution en cours"), "{page}");
    attendre_fin(&banc).await;

    let execution = banc.etat.runner.derniere().unwrap();
    assert!(std::fs::read_to_string(&trace).unwrap().contains("site.yml"));
    let rejouee: OpenIamConfig =
        serde_norway::from_str(&banc.etat.runner.configuration(&execution.id).unwrap()).unwrap();
    let attendus: BTreeSet<ComposantId> =
        [ComposantId::Openldap, ComposantId::Sauvegarde, ComposantId::Ssp, ComposantId::WhitePages].into();
    assert_eq!(rejouee.composants, attendus, "les quatre composants");

    let (statut, page) = lire(&banc, &cookie, "/install/resultat").await;
    assert_eq!(statut, StatusCode::OK, "{page}");
    assert!(page.contains("L'installation a évolué"), "{page}");
    let ajoutes = bloc(&page, r#"id="composants-ajoutes""#, "</p>");
    assert!(ajoutes.contains("White Pages"), "{ajoutes}");
    let fichiers = recapitulatifs(&banc);
    assert_eq!(fichiers.len(), 2, "nouveau fichier récapitulatif : {fichiers:?}");
    let nouveau = fichiers.iter().find(|f| **f != ancien[0]).unwrap();
    assert!(page.contains(&nouveau.display().to_string()), "E-012 nomme le nouveau fichier : {page}");
    assert_eq!(std::fs::read_to_string(&ancien[0]).unwrap(), ancien_contenu, "l'ancien n'est pas touché");
    let contenu = std::fs::read_to_string(nouveau).unwrap();
    assert!(contenu.contains("Évolution du") && contenu.contains("ajout de White Pages"), "{contenu}");
    assert!(contenu.contains("inchangé, voir le récapitulatif de l'installation"), "{contenu}");
    assert!(contenu.contains("cn=white-pages,ou=applications"), "nouveau compte de service : {contenu}");
    assert_ne!(
        mot_de_passe_de(&contenu, "ssp"),
        mot_de_passe_de(&ancien_contenu, "ssp"),
        "les comptes de service existants sont renouvelés (arbitrage 3)"
    );
    assert!(!page.contains(URGENCE) && !journal.texte().contains(&mot_de_passe_de(&contenu, "ssp")));
    let verrou = std::fs::read_to_string(banc.etat_dir().join("installed.lock")).unwrap();
    assert!(verrou.contains(VERSION), "verrou réécrit avec la version : {verrou}");

    let (_, redirection, _) = poster(&banc, &cookie, &csrf, "/install/terminer", "conserve=on").await;
    assert_eq!(redirection, "/verrouille");
    assert!(
        !banc.etat_dir().join("draft-secrets.yaml").exists() && !banc.etat_dir().join("vault.pass").exists()
    );
    assert!(!banc.etat_dir().join("draft.yaml").exists());
}

#[tokio::test]
async fn une_evolution_deja_en_preparation_est_reprise_ou_abandonnee() {
    let banc = installe().await;
    let (cookie, csrf) = evolution(&banc).await;
    let (_, page) = lire(&banc, &cookie, "/install/evolution").await;
    let carte = bloc(&page, r#"id="evolution-en-preparation""#, "</section>");
    assert!(carte.contains(r#"href="/install/composants""#) && carte.contains("Reprendre"), "{carte}");
    assert!(
        carte.contains("Abandonner l'évolution") && carte.contains(r#"hx-delete="/install/evolution""#),
        "{carte}"
    );
    assert!(!page.contains(r#"hx-post="/install/evolution""#), "pas de second « Commencer » : {page}");
    let (statut, _, _) = poster(&banc, &cookie, &csrf, "/install/evolution", "").await;
    assert_eq!(statut, StatusCode::CONFLICT);

    let (_garde, journal) = journal();
    let (res, _) = send(&banc.router, delete_avec("/install/evolution", &cookie, &csrf)).await;
    assert_eq!(res.status(), StatusCode::NO_CONTENT);
    assert_eq!(header(&res, "hx-redirect"), "/verrouille");
    assert!(journal.texte().contains(r#"evenement="evolution_abandonnee""#), "{}", journal.texte());
    assert!(
        !banc.etat_dir().join("draft.yaml").exists() && !banc.etat_dir().join("draft-secrets.yaml").exists()
    );
    assert!(banc.etat.installe(), "verrou inchangé");
}

#[tokio::test]
async fn un_binaire_plus_ancien_est_refuse() {
    let banc = installe().await;
    let chemin = banc.etat.runner.dossier_execution(&derniere_execution(&banc)).join("etat.json");
    let mut etat: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&chemin).unwrap()).unwrap();
    assert_eq!(etat["version"], VERSION, "version enregistrée avec l'exécution (arbitrage 8)");
    etat["version"] = "99.0.0".into();
    std::fs::write(&chemin, etat.to_string()).unwrap();

    let (cookie, csrf) = session_assistant(&banc).await;
    let (statut, page) = lire(&banc, &cookie, "/install/evolution").await;
    assert_eq!(statut, StatusCode::OK);
    assert!(page.contains("99.0.0") && page.contains(VERSION), "{page}");
    assert!(!page.contains(r#"hx-post="/install/evolution""#), "{page}");
    let (statut, _, _) = poster(&banc, &cookie, &csrf, "/install/evolution", "").await;
    assert_eq!(statut, StatusCode::CONFLICT);
    assert!(!banc.etat_dir().join("draft.yaml").exists());
}

#[tokio::test]
async fn pendant_une_execution_e022_n_offre_rien() {
    let banc = installe().await;
    let banc = rebrancher(banc, vec![("OIAM_FAUX_SCENARIO".into(), "long".into())]);
    let (cookie, csrf) = evolution(&banc).await;
    ajouter_white_pages(&banc, &cookie, &csrf).await;
    poster(&banc, &cookie, &csrf, "/install/verification", "").await;
    let (statut, _, body) = poster(&banc, &cookie, &csrf, "/install/execution", "").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");

    let (statut, page) = lire(&banc, &cookie, "/install/evolution").await;
    assert_eq!(statut, StatusCode::OK, "E-022 affiche l'état");
    assert!(page.contains(r#"href="/install/execution""#) && page.contains("en cours"), "{page}");
    assert!(!page.contains(r#"hx-post="/install/evolution""#) && !page.contains("hx-delete"), "{page}");
    let (statut, _, _) = poster(&banc, &cookie, &csrf, "/install/evolution", "").await;
    assert_eq!(statut, StatusCode::CONFLICT);
    let (res, _) = send(&banc.router, delete_avec("/install/evolution", &cookie, &csrf)).await;
    assert_eq!(res.status(), StatusCode::CONFLICT);

    let (statut, _, _) = poster(&banc, &cookie, &csrf, "/install/execution/interrompre", "").await;
    assert_eq!(statut, StatusCode::ACCEPTED);
    attendre_fin(&banc).await;
}

#[tokio::test]
async fn non_regression_du_verrou() {
    let banc = installe().await;
    // Une évolution est en préparation dans une autre session : elle n'ouvre rien aux autres.
    evolution(&banc).await;
    let (res, _) = send(&banc.router, get("/install/evolution")).await;
    assert_eq!(header(&res, "location"), "/acces");
    for chemin in ["/install", "/install/organisation", "/install/composants", "/install/recapitulatif"] {
        let (res, _) = send(&banc.router, get(chemin)).await;
        assert_eq!(header(&res, "location"), "/verrouille", "{chemin}");
    }
}

#[tokio::test]
async fn mode_compose() {
    let banc = installe().await;
    modifier_base(&banc, |c| {
        c.deploiement.mode = Mode::Compose;
    });
    let (cookie, csrf) = evolution(&banc).await;
    ajouter_white_pages(&banc, &cookie, &csrf).await;
    let compose = std::fs::read_to_string(
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../ansible/roles/compose/templates/compose.yml.j2"),
    )
    .unwrap();
    assert!(
        compose.contains(":/usr/local/openldap/etc/openldap"),
        "volume de la configuration de l'annuaire : {compose}"
    );

    // Une appliance installée avant ce volume (version non enregistrée) n'est pas rejouée.
    let banc = installe().await;
    modifier_base(&banc, |c| c.deploiement.mode = Mode::Compose);
    let chemin = banc.etat.runner.dossier_execution(&derniere_execution(&banc)).join("etat.json");
    let mut etat: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&chemin).unwrap()).unwrap();
    etat.as_object_mut().unwrap().remove("version");
    std::fs::write(&chemin, etat.to_string()).unwrap();
    std::fs::write(banc.etat_dir().join("installed.lock"), "2026-01-01").unwrap();
    let (cookie, csrf) = session_assistant(&banc).await;
    let (_, page) = lire(&banc, &cookie, "/install/evolution").await;
    assert!(page.contains("ne gardait pas la configuration de l"), "{page}");
    assert_eq!(poster(&banc, &cookie, &csrf, "/install/evolution", "").await.0, StatusCode::CONFLICT);
}

// ------------------------------------------------------------------------------- arbitrages

#[tokio::test]
async fn sans_verrou_e022_et_e092_menent_a_l_assistant_normal() {
    let banc = banc();
    let (cookie, _) = session_assistant(&banc).await;
    let (res, _) = send(&banc.router, get_avec("/install/evolution", &cookie)).await;
    assert_eq!(header(&res, "location"), "/install");
    let (res, _) = send(&banc.router, get("/verrouille")).await;
    assert_eq!(header(&res, "location"), "/install", "E-092 n'est servi qu'après le verrou");
}

#[tokio::test]
async fn sans_configuration_de_base_aucun_bouton_commencer() {
    let banc = banc();
    std::fs::write(banc.etat_dir().join("installed.lock"), "").unwrap();
    let (cookie, csrf) = session_assistant(&banc).await;
    let (statut, page) = lire(&banc, &cookie, "/install/evolution").await;
    assert_eq!(statut, StatusCode::OK);
    assert!(page.contains("ne retrouve pas la configuration") && page.contains("--etat"), "{page}");
    assert!(!page.contains(r#"hx-post="/install/evolution""#), "{page}");
    assert_eq!(poster(&banc, &cookie, &csrf, "/install/evolution", "").await.0, StatusCode::CONFLICT);
}

#[tokio::test]
async fn les_secrets_d_une_installation_non_terminee_sont_purges_avant_l_evolution() {
    // Arbitrage 10 : « Terminer » jamais fait, le coffre et le brouillon d'installation subsistent.
    let (banc, _, _) = installe_sans_terminer().await;
    assert!(banc.etat_dir().join("vault.pass").is_file());
    let (cookie, csrf) = session_assistant(&banc).await;
    let (_, page) = lire(&banc, &cookie, "/install/evolution").await;
    let alerte = bloc(&page, r#"id="installation-non-terminee""#, "</section>");
    assert!(alerte.contains("Effacer ces secrets et continuer"), "{alerte}");
    assert!(alerte.contains("open-iam-exemple.fr-"), "chemin du récapitulatif rappelé : {alerte}");
    let (statut, redirection, body) = poster(&banc, &cookie, &csrf, "/install/evolution", "").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    assert_eq!(redirection, "/install/composants");
    assert!(!banc.etat_dir().join("vault.pass").exists(), "coffre purgé");
    assert!(!std::fs::read_to_string(banc.etat_dir().join("draft-secrets.yaml")).unwrap().contains(URGENCE));
    assert!(brouillon_yaml(&banc).contains("evolution:"));
}

#[tokio::test]
async fn plusieurs_serveurs_un_role_manquant_s_attribue_a_un_serveur_declare() {
    // Arbitrage 5 : attribuer un rôle manquant est permis (test SSH exigé) ; ajouter ou retirer un
    // serveur est refusé.
    let banc = installe().await;
    modifier_base(&banc, |c| {
        c.deploiement.topologie = Topologie::Multi;
        c.deploiement.hotes = vec![Hote {
            nom: "ldap1.exemple.fr".into(),
            adresse: "ok.exemple.fr".into(),
            port: 22,
            utilisateur: "root".into(),
            roles: [
                open_iam_installer::catalogue::RoleHote::Annuaire,
                open_iam_installer::catalogue::RoleHote::Outils,
            ]
            .into(),
            local: false,
            machine: None,
        }];
    });
    let (cookie, csrf) = evolution(&banc).await;
    let (statut, _, body) = poster(
        &banc,
        &cookie,
        &csrf,
        "/install/composants",
        "composants=openldap&composants=sauvegarde&composants=ssp&composants=supervision",
    )
    .await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    let (_, page) = lire(&banc, &cookie, "/install/cibles").await;
    assert!(etat_dans_le_stepper(&page, "Mode et cibles", "à revoir"), "{page}");
    // D-081 (OI-152) : un serveur peut s'ajouter pour un rôle absent ; le bouton est donc proposé.
    assert!(page.contains(r#"data-dialogue="dialogue-hote""#), "l'ajout d'un serveur est proposé : {page}");
    // Les boutons d'attribution occupent une ligne pleine largeur sous le serveur : dans la dernière
    // colonne, un tableau plus large que l'écran (empreinte SSH) les rendait invisibles.
    let ligne = page.split(r#"colspan="5""#).nth(1).and_then(|s| s.split("</td>").next()).unwrap_or_default();
    assert!(
        ligne.contains("Rôles à attribuer") && ligne.contains("Attribuer le rôle supervision"),
        "ligne des rôles à attribuer : {page}"
    );

    let hote = "nom=ldap1.exemple.fr&adresse=ok.exemple.fr&port=22&utilisateur=root&roles_annuaire=on&roles_outils=on";
    let (statut, _, _) = poster(
        &banc,
        &cookie,
        &csrf,
        "/install/cibles/hotes",
        "nom=sup1.exemple.fr&adresse=ok.exemple.fr&port=22&utilisateur=root&roles_annuaire=on",
    )
    .await;
    assert_eq!(
        statut,
        StatusCode::UNPROCESSABLE_ENTITY,
        "ajouter un serveur pour un rôle déjà porté est refusé (D-081)"
    );
    let (res, _) =
        send(&banc.router, delete_avec("/install/cibles/hotes/ldap1.exemple.fr", &cookie, &csrf)).await;
    assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY, "retirer un serveur est refusé");
    let (statut, _, _) = poster(
        &banc,
        &cookie,
        &csrf,
        "/install/cibles/hotes",
        "nom=ldap1.exemple.fr&adresse=ok.exemple.fr&port=22&utilisateur=root&roles_supervision=on",
    )
    .await;
    assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "retirer un rôle est refusé");

    let (statut, _, body) =
        poster(&banc, &cookie, &csrf, "/install/cibles/hotes", &format!("{hote}&roles_supervision=on")).await;
    assert_eq!(statut, StatusCode::OK, "{body}");
    let (statut, _, _) = poster(&banc, &cookie, &csrf, "/install/cibles", "").await;
    assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "test SSH exigé");
    let (_, _, fragment) = poster(&banc, &cookie, &csrf, "/install/cibles/hotes/test", "").await;
    // Le détail du test (empreinte SSH insécable) passe à la ligne au lieu d'élargir le tableau.
    assert!(
        fragment.contains(r#"<ul class="mt-xs flex flex-col gap-xxs text-xs wrap-anywhere">"#),
        "{fragment}"
    );
    let (statut, _, _) =
        poster(&banc, &cookie, &csrf, "/install/cibles", "mode=native&topologie=local").await;
    assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "topologie figée");
    let (statut, _, body) = poster(&banc, &cookie, &csrf, "/install/cibles", "").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    assert!(brouillon_yaml(&banc).contains("- supervision"));

    // E022-C4 : état des serveurs de l'installation, informatif, rien n'est enregistré.
    let (_, page) = lire(&banc, &cookie, "/install/evolution").await;
    assert!(page.contains(r#"hx-post="/install/evolution/serveurs""#), "{page}");
    let avant = brouillon_yaml(&banc);
    let (statut, _, fragment) = poster(&banc, &cookie, &csrf, "/install/evolution/serveurs", "").await;
    assert_eq!(statut, StatusCode::OK);
    assert!(fragment.contains("ldap1.exemple.fr") && fragment.contains("connexion vérifiée"), "{fragment}");
    assert_eq!(brouillon_yaml(&banc), avant);
}

#[tokio::test]
async fn les_comptes_ne_se_ressaisissent_pas_en_evolution() {
    // Arbitrage 4 : le mot de passe d'urgence n'est jamais demandé en OI-072.
    let banc = installe().await;
    let (cookie, csrf) = evolution(&banc).await;
    let (statut, page) = lire(&banc, &cookie, "/install/comptes").await;
    assert_eq!(statut, StatusCode::OK);
    assert!(!page.contains("/install/comptes/generer") && champ(&page, "uid").contains("disabled"), "{page}");
    let (statut, _, _) =
        poster(&banc, &cookie, &csrf, "/install/comptes", &format!("urgence={URGENCE}")).await;
    assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY);
    assert!(
        !std::fs::read_to_string(banc.etat_dir().join("draft-secrets.yaml"))
            .unwrap_or_default()
            .contains(URGENCE)
    );
}

#[tokio::test]
async fn oi134_un_serveur_qui_ne_porte_plus_l_installation_est_refuse() {
    // Le 2026-11-13, une évolution a appliqué la configuration nuage.ebii sur des serveurs remis à
    // blanc puis réinstallés par la recette exemple.fr. La marque d'installation (posée par
    // site.yml, ici par le faux ansible-playbook) est comparée avant tout lancement.
    let banc = installe().await;
    modifier_base(&banc, |c| {
        c.deploiement.topologie = Topologie::Multi;
        c.deploiement.hotes = vec![Hote {
            nom: "ldap1.exemple.fr".into(),
            adresse: "ok.exemple.fr".into(),
            port: 22,
            utilisateur: "root".into(),
            roles: [
                open_iam_installer::catalogue::RoleHote::Annuaire,
                open_iam_installer::catalogue::RoleHote::Outils,
            ]
            .into(),
            local: false,
            machine: None,
        }];
    });
    let (cookie, csrf) = session_assistant(&banc).await;
    let (_, _, fragment) = poster(&banc, &cookie, &csrf, "/install/evolution/serveurs", "").await;
    assert!(fragment.contains("celle de cet installeur (exemple.fr, dc=exemple,dc=fr)"), "{fragment}");
    assert!(fragment.contains("connexion vérifiée"), "{fragment}");

    // Serveur remis à blanc : plus de marque, rien n'est lancé.
    std::fs::remove_file(banc.etat_dir().join("faux-serveurs/installation")).unwrap();
    let (_, _, fragment) = poster(&banc, &cookie, &csrf, "/install/evolution/serveurs", "").await;
    assert!(fragment.contains("aucune installation Open IAM sur ce serveur"), "{fragment}");
    let (statut, redirection, notification) = mettre_a_jour(&banc, &cookie, &csrf).await;
    assert_eq!((statut, redirection.as_str()), (StatusCode::CONFLICT, ""), "{notification}");
    assert!(
        notification.contains("ldap1.exemple.fr") && notification.contains("Installation Open IAM"),
        "{notification}"
    );

    // Serveur d'une autre installation : nommée, refusée.
    modifier_base(&banc, |c| c.deploiement.hotes[0].adresse = "autre.exemple.fr".into());
    let (_, _, fragment) = poster(&banc, &cookie, &csrf, "/install/evolution/serveurs", "").await;
    assert!(fragment.contains("autre installation Open IAM (exemple.org, dc=exemple,dc=org"), "{fragment}");
    assert_eq!(mettre_a_jour(&banc, &cookie, &csrf).await.0, StatusCode::CONFLICT);
}

// ------------------------------------------------------------------------------- OI-077 : mise à jour

/// Confirmation de la mise à jour (E022-C8) : « code redirection notification ».
async fn mettre_a_jour(banc: &Banc, cookie: &str, csrf: &str) -> (StatusCode, String, String) {
    let (res, _) = send(&banc.router, post_form("/install/mise-a-jour", cookie, Some(csrf), "")).await;
    (res.status(), header(&res, "hx-redirect").to_owned(), header(&res, "hx-trigger").to_owned())
}

#[tokio::test]
async fn la_carte_de_mise_a_jour_explique_ce_qui_sera_fait() {
    let banc = installe().await;
    let (cookie, _) = session_assistant(&banc).await;
    let (_, page) = lire(&banc, &cookie, "/install/evolution").await;
    let carte = bloc(&page, r#"id="mise-a-jour""#, "</section>");
    for attendu in ["sauvegarde", "paquets des composants installés", "redémarr"] {
        assert!(carte.contains(attendu), "{attendu} : {carte}");
    }
    assert!(carte.contains(r#"hx-post="/install/mise-a-jour""#), "carte active : {carte}");
    assert!(!carte.contains("Bientôt disponible"), "{carte}");
}

#[tokio::test]
async fn confirmer_lance_update_yml() {
    let banc = installe().await;
    let verrou = std::fs::read_to_string(banc.etat_dir().join("installed.lock")).unwrap();
    let base = derniere_execution(&banc);
    let trace = banc.racine().join("trace-ansible");
    let banc = rebrancher(
        banc,
        vec![
            ("OIAM_FAUX_SCENARIO".into(), "reussite".into()),
            ("OIAM_FAUX_TRACE".into(), trace.display().to_string()),
        ],
    );
    let (cookie, csrf) = session_assistant(&banc).await;
    let (_garde, journal) = journal();
    let (statut, redirection, _) = mettre_a_jour(&banc, &cookie, &csrf).await;
    assert_eq!(statut, StatusCode::NO_CONTENT);
    assert_eq!(redirection, "/install/execution");
    assert!(journal.texte().contains(r#"evenement="mise_a_jour_lancee""#), "{}", journal.texte());
    let (_, page) = lire(&banc, &cookie, "/install/execution").await;
    assert!(page.contains("Mise à jour en cours"), "{page}");
    attendre_fin(&banc).await;

    let execution = banc.etat.runner.derniere().unwrap();
    assert_ne!(execution.id, base);
    let args = std::fs::read_to_string(&trace).unwrap();
    assert!(args.contains("update.yml") && !args.contains("site.yml"), "{args}");
    let dossier = banc.etat.runner.dossier_execution(&execution.id);
    let rejouee: OpenIamConfig =
        serde_norway::from_str(&std::fs::read_to_string(dossier.join("openiam.yaml")).unwrap()).unwrap();
    assert_eq!(rejouee.composants, [ComposantId::Openldap, ComposantId::Sauvegarde, ComposantId::Ssp].into());
    let coffre = std::fs::read_to_string(dossier.join("inventaire/group_vars/all/secrets.yml")).unwrap();
    assert_eq!(coffre.lines().nth(1), Some("e30K"), "coffre vide (« {{}} » chiffré) : {coffre}");

    let (statut, page) = lire(&banc, &cookie, "/install/resultat").await;
    assert_eq!(statut, StatusCode::OK, "{page}");
    assert!(page.contains("Composants mis à jour"), "{page}");
    let bilan = bloc(&page, r#"id="taches-changees""#, "</p>");
    assert!(bilan.contains('2'), "2 tâches changées par le faux Ansible : {bilan}");
    assert!(page.contains(r#"href="/install/execution/journal.txt""#), "{page}");
    assert!(!page.contains("/install/resultat/recapitulatif.txt"), "pas de récapitulatif : {page}");
    assert_eq!(std::fs::read_to_string(banc.etat_dir().join("installed.lock")).unwrap(), verrou);
    assert_eq!(recapitulatifs(&banc).len(), 1, "aucun nouveau fichier récapitulatif");

    // E-022 décrit toujours l'installation : la mise à jour n'en change ni la version ni la base.
    let (_, page) = lire(&banc, &cookie, "/install/evolution").await;
    assert!(page.contains("Dernière mise à jour"), "{page}");
    let (_, redirection, _) = poster(&banc, &cookie, &csrf, "/install/terminer", "").await;
    assert_eq!(redirection, "/verrouille", "« Terminer » sans récapitulatif à conserver");
    assert!(!banc.etat_dir().join("vault.pass").exists());
}

#[tokio::test]
async fn un_serveur_injoignable_bloque_la_mise_a_jour() {
    use open_iam_installer::catalogue::RoleHote;
    let banc = installe().await;
    let hote = |nom: &str, adresse: &str, roles: &[RoleHote]| Hote {
        nom: nom.into(),
        adresse: adresse.into(),
        port: 22,
        utilisateur: "root".into(),
        roles: roles.iter().copied().collect(),
        local: false,
        machine: None,
    };
    modifier_base(&banc, |c| {
        c.deploiement.topologie = Topologie::Multi;
        c.deploiement.hotes = vec![
            hote("ldap1.exemple.fr", "ok.exemple.fr", &[RoleHote::Annuaire, RoleHote::Outils]),
            hote("sup1.exemple.fr", "injoignable.exemple.fr", &[RoleHote::Supervision]),
        ];
    });
    let base = derniere_execution(&banc);
    let (cookie, csrf) = session_assistant(&banc).await;
    let (statut, _, notification) = mettre_a_jour(&banc, &cookie, &csrf).await;
    assert_eq!(statut, StatusCode::CONFLICT);
    assert!(notification.contains("sup1.exemple.fr"), "{notification}");
    assert!(!notification.contains("ldap1.exemple.fr"), "{notification}");
    assert_eq!(derniere_execution(&banc), base, "rien n'est lancé");
}

#[tokio::test]
async fn pas_de_mise_a_jour_pendant_une_autre_operation() {
    // Une évolution en préparation.
    let banc = installe().await;
    let (cookie, csrf) = evolution(&banc).await;
    assert_eq!(mettre_a_jour(&banc, &cookie, &csrf).await.0, StatusCode::CONFLICT);
    let (_, page) = lire(&banc, &cookie, "/install/evolution").await;
    assert!(!bloc(&page, r#"id="mise-a-jour""#, "</section>").contains("hx-post"), "{page}");

    // Une exécution en cours.
    let banc = installe().await;
    let banc = rebrancher(banc, vec![("OIAM_FAUX_SCENARIO".into(), "long".into())]);
    let (cookie, csrf) = session_assistant(&banc).await;
    assert_eq!(mettre_a_jour(&banc, &cookie, &csrf).await.0, StatusCode::NO_CONTENT);
    assert_eq!(mettre_a_jour(&banc, &cookie, &csrf).await.0, StatusCode::CONFLICT);
    let (statut, _, _) = poster(&banc, &cookie, &csrf, "/install/execution/interrompre", "").await;
    assert_eq!(statut, StatusCode::ACCEPTED, "le lanceur peut interrompre la mise à jour");
    attendre_fin(&banc).await;
    let (_, page) = lire(&banc, &cookie, "/install/execution").await;
    assert!(
        page.contains(r#"hx-post="/install/mise-a-jour""#),
        "« Relancer » relance la mise à jour : {page}"
    );
}

#[tokio::test]
async fn sans_installation_la_mise_a_jour_mene_a_l_assistant() {
    let banc = banc();
    let (cookie, csrf) = session_assistant(&banc).await;
    let (_, redirection, _) = mettre_a_jour(&banc, &cookie, &csrf).await;
    assert_eq!(redirection, "/install");
    let (res, _) = send(&banc.router, get_avec("/install/evolution", &cookie)).await;
    assert_eq!(header(&res, "location"), "/install");
}

// ------------------------------------------------------------------------------- revue M4-M5 (OI-109)

#[tokio::test]
async fn f19_seule_la_session_qui_a_lance_l_execution_en_voit_le_resultat() {
    let banc = installe().await;
    let (a, csrf_a) = session_assistant(&banc).await;
    let (b, csrf_b) = session_assistant(&banc).await;
    assert_eq!(mettre_a_jour(&banc, &a, &csrf_a).await.0, StatusCode::NO_CONTENT);
    attendre_fin(&banc).await;
    assert_eq!(lire(&banc, &a, "/install/resultat").await.0, StatusCode::OK, "le lanceur voit son résultat");
    assert_eq!(mettre_a_jour(&banc, &b, &csrf_b).await.0, StatusCode::NO_CONTENT);
    attendre_fin(&banc).await;
    // A a lancé une exécution antérieure : ni résultat, ni récapitulatif, ni « Terminer » de celle de B.
    for uri in ["/install/resultat", "/install/resultat/recapitulatif.txt", "/install/execution"] {
        let (res, _) = send(&banc.router, get_avec(uri, &a)).await;
        assert_eq!(header(&res, "location"), "/verrouille", "{uri} pour A");
    }
    let (statut, redirection, _) = poster(&banc, &a, &csrf_a, "/install/terminer", "").await;
    assert_eq!(
        (statut, redirection.as_str()),
        (StatusCode::SEE_OTHER, "/verrouille"),
        "« Terminer » refusé à A"
    );
    assert_eq!(
        lire(&banc, &b, "/install/resultat").await.0,
        StatusCode::OK,
        "B voit le résultat de sa mise à jour"
    );
    let (statut, _) = lire(&banc, &b, "/install/resultat/recapitulatif.txt").await;
    assert_eq!(statut, StatusCode::NOT_FOUND, "une opération n'a pas de récapitulatif téléchargeable");
    let (statut, redirection, _) = poster(&banc, &b, &csrf_b, "/install/terminer", "").await;
    assert_eq!((statut, redirection.as_str()), (StatusCode::NO_CONTENT, "/verrouille"));
}

#[tokio::test]
async fn f19_une_autre_session_n_interrompt_pas_l_execution() {
    let banc = installe().await;
    let banc = rebrancher(banc, vec![("OIAM_FAUX_SCENARIO".into(), "long".into())]);
    let (a, csrf_a) = session_assistant(&banc).await;
    let (b, csrf_b) = session_assistant(&banc).await;
    assert_eq!(mettre_a_jour(&banc, &a, &csrf_a).await.0, StatusCode::NO_CONTENT);
    let (statut, _, _) = poster(&banc, &a, &csrf_a, "/install/execution/interrompre", "").await;
    assert_eq!(statut, StatusCode::ACCEPTED);
    attendre_fin(&banc).await;
    assert_eq!(mettre_a_jour(&banc, &b, &csrf_b).await.0, StatusCode::NO_CONTENT);
    let (statut, redirection, _) = poster(&banc, &a, &csrf_a, "/install/execution/interrompre", "").await;
    assert_eq!(
        (statut, redirection.as_str()),
        (StatusCode::SEE_OTHER, "/verrouille"),
        "A n'interrompt pas B"
    );
    assert!(banc.etat.runner.en_cours());
    let (statut, _, _) = poster(&banc, &b, &csrf_b, "/install/execution/interrompre", "").await;
    assert_eq!(statut, StatusCode::ACCEPTED);
    attendre_fin(&banc).await;
}

#[tokio::test]
async fn f19_le_telechargement_du_recapitulatif_est_journalise_et_une_operation_n_affiche_pas_l_urgence() {
    let (banc, cookie, csrf) = installe_sans_terminer().await;
    let (_garde, journal) = journal();
    let (statut, contenu) = lire(&banc, &cookie, "/install/resultat/recapitulatif.txt").await;
    assert_eq!(statut, StatusCode::OK);
    assert!(contenu.contains(URGENCE), "le récapitulatif de l'installation porte le mot de passe d'urgence");
    let texte = journal.texte();
    assert!(texte.contains(r#"evenement="recapitulatif_telecharge""#), "{texte}");
    assert!(!texte.contains(URGENCE), "{texte}");
    // Une mise à jour lancée avant « Terminer » : son résultat ne montre pas le mot de passe d'urgence.
    assert_eq!(mettre_a_jour(&banc, &cookie, &csrf).await.0, StatusCode::NO_CONTENT);
    attendre_fin(&banc).await;
    let (statut, page) = lire(&banc, &cookie, "/install/resultat").await;
    assert_eq!(statut, StatusCode::OK, "{page}");
    assert!(page.contains("Composants mis à jour") && !page.contains(URGENCE), "{page}");
}

#[tokio::test]
async fn i17_pas_de_sonde_des_serveurs_pendant_une_execution() {
    let banc = installe().await;
    let banc = rebrancher(banc, vec![("OIAM_FAUX_SCENARIO".into(), "long".into())]);
    let (cookie, csrf) = session_assistant(&banc).await;
    assert_eq!(mettre_a_jour(&banc, &cookie, &csrf).await.0, StatusCode::NO_CONTENT);
    let (statut, _, _) = poster(&banc, &cookie, &csrf, "/install/evolution/serveurs", "").await;
    assert_eq!(statut, StatusCode::CONFLICT);
    poster(&banc, &cookie, &csrf, "/install/execution/interrompre", "").await;
    attendre_fin(&banc).await;
}

// ------------------------------------------------- OI-152 (D-081) : un serveur de plus en évolution

/// Background de la tranche 3 du plan M8 : installation « Plusieurs serveurs » réussie, iam1
/// (annuaire, outils) avec OpenLDAP et SSP, puis une évolution qui ajoute la supervision.
async fn base_multi_puis_evolution_supervision() -> (Banc, String, String) {
    use open_iam_installer::catalogue::RoleHote;
    let banc = installe().await;
    modifier_base(&banc, |c| {
        c.deploiement.topologie = Topologie::Multi;
        c.deploiement.hotes = vec![Hote {
            nom: "iam1.exemple.fr".into(),
            adresse: "ok.exemple.fr".into(),
            port: 22,
            utilisateur: "root".into(),
            roles: [RoleHote::Annuaire, RoleHote::Outils].into(),
            local: false,
            machine: None,
        }];
    });
    let (cookie, csrf) = evolution(&banc).await;
    let (statut, _, body) = poster(
        &banc,
        &cookie,
        &csrf,
        "/install/composants",
        "composants=openldap&composants=sauvegarde&composants=ssp&composants=supervision",
    )
    .await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    (banc, cookie, csrf)
}

/// Ajouter la supervision rouvre E-005 (nom de son service) et E-008 : les valider après E-003.
async fn valider_securite_et_supervision(banc: &Banc, cookie: &str, csrf: &str) {
    let (statut, redirection, body) =
        poster(banc, cookie, csrf, "/install/securite", "supervision=grafana.exemple.fr").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "E-005 : {body}");
    assert_eq!(redirection, "/install/telemetrie", "E-008 rouverte par la supervision");
    let (statut, redirection, body) = poster(
        banc,
        cookie,
        csrf,
        "/install/telemetrie",
        "retention_metriques_jours=30&retention_journaux_jours=90&alertes_emails=",
    )
    .await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "E-008 : {body}");
    assert_eq!(redirection, "/install/recapitulatif");
}

/// Serveur neuf (`vierge.exemple.fr` : aucune marque d'installation) pour le seul rôle nouveau.
const SERVEUR_NEUF: &str =
    "nom=supervision.exemple.fr&adresse=vierge.exemple.fr&port=22&utilisateur=root&roles_supervision=on";
// Sans l'apostrophe du début, échappée en HTML (&#39;).
const REFUS_SERVEUR: &str = "ajouter un serveur pour un rôle absent et exigé.";

#[tokio::test]
async fn d081_un_serveur_s_ajoute_pour_le_seul_role_nouveau() {
    let (banc, cookie, csrf) = base_multi_puis_evolution_supervision().await;
    let (_, page) = lire(&banc, &cookie, "/install/cibles").await;
    assert!(etat_dans_le_stepper(&page, "Mode et cibles", "à revoir"), "{page}");
    assert!(page.contains(r#"data-dialogue="dialogue-hote""#), "l'ajout d'un serveur est proposé : {page}");
    let (statut, _, body) = poster(&banc, &cookie, &csrf, "/install/cibles/hotes", SERVEUR_NEUF).await;
    assert_eq!(statut, StatusCode::OK, "{body}");
    let (_, _, fragment) = poster(&banc, &cookie, &csrf, "/install/cibles/hotes/test", "").await;
    assert!(fragment.contains("supervision.exemple.fr"), "{fragment}");
    let (statut, redirection, body) = poster(&banc, &cookie, &csrf, "/install/cibles", "").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "E-003 se valide : {body}");
    assert_eq!(redirection, "/install/securite");
    valider_securite_et_supervision(&banc, &cookie, &csrf).await;
    // valider_evolution ne relève rien et E-010 annonce le nouveau serveur.
    let (statut, page) = lire(&banc, &cookie, "/install/recapitulatif").await;
    assert_eq!(statut, StatusCode::OK);
    assert!(page.contains("supervision.exemple.fr (nouveau serveur)"), "{page}");
    assert!(!page.contains("Une évolution ne peut qu'ajouter"), "{page}");
}

// OI-170, scénario : Ajouter la console en évolution sur un nouveau serveur (plan M9, tranche 2).
#[tokio::test]
async fn oi170_la_console_s_ajoute_en_evolution_sur_un_nouveau_serveur() {
    use open_iam_installer::catalogue::RoleHote;
    use open_iam_installer::config::Service;
    let banc = installe().await;
    modifier_base(&banc, |c| {
        c.deploiement.topologie = Topologie::Multi;
        c.deploiement.hotes = vec![Hote {
            nom: "iam1.exemple.fr".into(),
            adresse: "ok.exemple.fr".into(),
            port: 22,
            utilisateur: "root".into(),
            roles: [RoleHote::Annuaire, RoleHote::Outils, RoleHote::Sso].into(),
            local: false,
            machine: None,
        }];
        c.composants.insert(ComposantId::Lemonldap);
        c.services.insert(Service::Auth, "auth.exemple.fr".into());
        c.services.insert(Service::SsoAdmin, "admin-sso.exemple.fr".into());
    });
    let (cookie, csrf) = evolution(&banc).await;
    let (statut, _, body) = poster(
        &banc,
        &cookie,
        &csrf,
        "/install/composants",
        "composants=openldap&composants=sauvegarde&composants=ssp&composants=lemonldap&composants=console",
    )
    .await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    // Aucun rôle n'est ajouté d'office à un serveur installé : E-003 est à revoir.
    let (_, page) = lire(&banc, &cookie, "/install/cibles").await;
    assert!(etat_dans_le_stepper(&page, "Mode et cibles", "à revoir"), "{page}");
    let srv4 = "nom=srv4.exemple.fr&adresse=vierge.exemple.fr&port=22&utilisateur=root&roles_console=on";
    let (statut, _, body) = poster(&banc, &cookie, &csrf, "/install/cibles/hotes", srv4).await;
    assert_eq!(statut, StatusCode::OK, "{body}");
    poster(&banc, &cookie, &csrf, "/install/cibles/hotes/test", "").await;
    let (statut, redirection, body) = poster(&banc, &cookie, &csrf, "/install/cibles", "").await;
    assert_eq!((statut, redirection.as_str()), (StatusCode::NO_CONTENT, "/install/securite"), "{body}");
    let (statut, redirection, body) =
        poster(&banc, &cookie, &csrf, "/install/securite", "console=console.exemple.fr").await;
    assert_eq!((statut, redirection.as_str()), (StatusCode::NO_CONTENT, "/install/recapitulatif"), "{body}");
    let (statut, page) = lire(&banc, &cookie, "/install/recapitulatif").await;
    assert_eq!(statut, StatusCode::OK);
    assert!(page.contains("srv4.exemple.fr (nouveau serveur)"), "{page}");
    assert!(!page.contains("Une évolution ne peut qu'ajouter"), "{page}");
}

#[tokio::test]
async fn d081_un_role_deja_porte_ou_inutile_est_refuse() {
    let (banc, cookie, csrf) = base_multi_puis_evolution_supervision().await;
    // annuaire : déjà porté par iam1 ; sso : exigé par aucun composant (pas de LemonLDAP::NG) ;
    // outils : déjà porté, même accompagné du rôle nouveau.
    for roles in ["roles_annuaire=on", "roles_sso=on", "roles_supervision=on&roles_outils=on"] {
        let (statut, _, body) = poster(
            &banc,
            &cookie,
            &csrf,
            "/install/cibles/hotes",
            &format!("nom=s2.exemple.fr&adresse=vierge.exemple.fr&port=22&utilisateur=root&{roles}"),
        )
        .await;
        assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "{roles} : {body}");
        assert!(body.contains(REFUS_SERVEUR), "{roles} : {body}");
    }
    assert!(!brouillon_yaml(&banc).contains("s2.exemple.fr"));
}

#[tokio::test]
async fn d081_la_marque_n_est_exigee_que_des_serveurs_installes() {
    let (banc, cookie, csrf) = base_multi_puis_evolution_supervision().await;
    let (statut, _, body) = poster(&banc, &cookie, &csrf, "/install/cibles/hotes", SERVEUR_NEUF).await;
    assert_eq!(statut, StatusCode::OK, "{body}");
    // iam1 porte la marque (ok.exemple.fr) ; le serveur neuf n'en porte aucune et n'en a pas besoin.
    let (_, _, fragment) = poster(&banc, &cookie, &csrf, "/install/cibles/hotes/test", "").await;
    assert!(fragment.contains("celle de cet installeur"), "{fragment}");
    assert!(!fragment.contains("aucune installation Open IAM"), "{fragment}");
    let (statut, _, body) = poster(&banc, &cookie, &csrf, "/install/cibles", "").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    // Serveur installé remis à blanc : lui seul est refusé.
    let marque = banc.etat_dir().join("faux-serveurs/installation");
    let contenu = std::fs::read(&marque).unwrap();
    std::fs::remove_file(&marque).unwrap();
    let (_, _, fragment) = poster(&banc, &cookie, &csrf, "/install/cibles/hotes/test", "").await;
    assert_eq!(fragment.matches("aucune installation Open IAM").count(), 1, "{fragment}");
    let (iam1, neuf, refus) = (
        fragment.find("iam1.exemple.fr").unwrap(),
        fragment.find("supervision.exemple.fr").unwrap(),
        fragment.find("aucune installation Open IAM").unwrap(),
    );
    assert!(iam1 < refus && refus < neuf, "le refus porte sur iam1 seul : {fragment}");
    std::fs::write(&marque, contenu).unwrap();
    // Lancement : la vérification préalable passe, et hosts.yml ne dispense de la marque que le
    // serveur neuf (variable d'hôte oiam_marque_exigee: false, lue par roles/common/tasks/marque.yml).
    for uri in ["/install/cibles/hotes/test", "/install/cibles"] {
        let (statut, _, body) = poster(&banc, &cookie, &csrf, uri, "").await;
        assert!(statut.is_success(), "{uri} : {statut} {body}");
    }
    valider_securite_et_supervision(&banc, &cookie, &csrf).await;
    let (statut, _, fragment) = poster(&banc, &cookie, &csrf, "/install/verification", "").await;
    assert_eq!(statut, StatusCode::OK);
    assert!(fragment.contains("Vérification réussie"), "{fragment}");
    let (statut, _, body) = poster(&banc, &cookie, &csrf, "/install/execution", "").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    attendre_fin(&banc).await;
    let id = derniere_execution(&banc);
    let hosts = std::fs::read_to_string(banc.etat.runner.dossier_execution(&id).join("inventaire/hosts.yml"))
        .unwrap();
    let inv: serde_norway::Value = serde_norway::from_str(&hosts).unwrap();
    let hotes = &inv["all"]["hosts"];
    assert_eq!(
        hotes["supervision.exemple.fr"]["oiam_marque_exigee"],
        serde_norway::Value::Bool(false),
        "{hosts}"
    );
    assert!(hotes["iam1.exemple.fr"].get("oiam_marque_exigee").is_none(), "{hosts}");
}

#[tokio::test]
async fn d081_un_serveur_installe_ne_se_retire_pas_un_serveur_ajoute_si() {
    let (banc, cookie, csrf) = base_multi_puis_evolution_supervision().await;
    let (statut, _, body) = poster(&banc, &cookie, &csrf, "/install/cibles/hotes", SERVEUR_NEUF).await;
    assert_eq!(statut, StatusCode::OK, "{body}");
    let (_, page) = lire(&banc, &cookie, "/install/cibles").await;
    assert!(page.contains(r#"hx-delete="/install/cibles/hotes/supervision.exemple.fr""#), "{page}");
    assert!(!page.contains(r#"hx-delete="/install/cibles/hotes/iam1.exemple.fr""#), "{page}");
    let (res, _) =
        send(&banc.router, delete_avec("/install/cibles/hotes/iam1.exemple.fr", &cookie, &csrf)).await;
    assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY, "retirer un serveur installé est refusé");
    let (res, _) =
        send(&banc.router, delete_avec("/install/cibles/hotes/supervision.exemple.fr", &cookie, &csrf)).await;
    assert_eq!(res.status(), StatusCode::OK, "retirer le serveur ajouté est accepté");
    assert!(!brouillon_yaml(&banc).contains("supervision.exemple.fr"));
}

#[tokio::test]
async fn d081_une_installation_locale_reste_locale() {
    let banc = installe().await;
    let (cookie, csrf) = evolution(&banc).await;
    let (statut, _, body) = poster(
        &banc,
        &cookie,
        &csrf,
        "/install/composants",
        "composants=openldap&composants=sauvegarde&composants=ssp&composants=supervision",
    )
    .await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    let (_, page) = lire(&banc, &cookie, "/install/cibles").await;
    assert!(
        !page.contains(r#"data-dialogue="dialogue-hote""#),
        "aucun ajout en « Tout sur cette machine » : {page}"
    );
    let (statut, _, _) = poster(&banc, &cookie, &csrf, "/install/cibles/hotes", SERVEUR_NEUF).await;
    assert_ne!(statut, StatusCode::OK, "l'ajout est refusé");
    assert!(!brouillon_yaml(&banc).contains("supervision.exemple.fr"));
}

// ------------------------------------------------- OI-159 (D-085) : une machine installée ne se détruit pas

#[tokio::test]
async fn d085_une_machine_installee_ne_se_detruit_pas_chez_le_fournisseur() {
    use open_iam_installer::config::{
        Adressage, Fournisseur, Machine, TypeFournisseur,
        fournisseurs::{Confiance, Disque},
    };
    let banc = installe().await;
    // L'installation de base comprend une machine créée par l'installeur chez le témoin.
    modifier_base(&banc, |c| {
        c.deploiement.topologie = Topologie::Multi;
        c.fournisseurs = vec![Fournisseur {
            nom: "temoin".into(),
            type_: TypeFournisseur::Temoin,
            url: "https://temoin.invalid".into(),
            tls: Confiance::default(),
        }];
        c.deploiement.hotes = vec![Hote {
            nom: "iam1.exemple.fr".into(),
            adresse: "ok.exemple.fr".into(),
            port: 22,
            utilisateur: "root".into(),
            roles: [
                open_iam_installer::catalogue::RoleHote::Annuaire,
                open_iam_installer::catalogue::RoleHote::Outils,
            ]
            .into(),
            local: false,
            machine: Some(Machine {
                fournisseur: "temoin".into(),
                emplacement: [("pool".to_owned(), "pool-1".to_owned())].into(),
                modele: Some("tpl".into()),
                image: None,
                cpu: 2,
                memoire_mo: 4096,
                disques: vec![Disque { stockage: "sr".into(), taille_go: 20 }],
                reseau: "net".into(),
                adressage: Adressage::Fixe {
                    cidr: "192.0.2.10/24".into(),
                    passerelle: "192.0.2.1".into(),
                    dns: vec![],
                },
                mac: Some("02:4f:00:00:00:01".into()),
                id: Some("faux-iam1.exemple.fr".into()),
            }),
        }];
    });
    let (cookie, csrf) = evolution(&banc).await;
    // Le message d'un refus voyage dans l'en-tête HX-Trigger (notification).
    let (res, _) = send(
        &banc.router,
        post_form("/install/cibles/machines/iam1.exemple.fr/retrait", &cookie, Some(&csrf), ""),
    )
    .await;
    let notification = header(&res, "hx-trigger").to_owned();
    assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY, "{notification}");
    assert!(notification.contains("install") && notification.contains("rien n"), "{notification}");
    assert!(!banc.etat.runner.en_cours(), "aucun plan calculé");
    let (_, page) = lire(&banc, &cookie, "/install/cibles").await;
    assert!(!page.contains("/retrait\""), "aucun bouton Retirer sur une machine installée : {page}");
}

// OI-209, scénario : En évolution, la case du journal modifiable reste modifiable (plan M9,
// tranche 9). Base avec la console, verrou exigé ; l'évolution ajoute White Pages et coche la case.
#[tokio::test]
async fn oi209_en_evolution_la_case_du_journal_modifiable_se_coche() {
    use open_iam_installer::catalogue::RoleHote;
    use open_iam_installer::config::Service;
    let banc = installe().await;
    modifier_base(&banc, |c| {
        c.deploiement.topologie = Topologie::Multi;
        c.deploiement.hotes = vec![Hote {
            nom: "iam1.exemple.fr".into(),
            adresse: "ok.exemple.fr".into(),
            port: 22,
            utilisateur: "root".into(),
            roles: [RoleHote::Annuaire, RoleHote::Outils, RoleHote::Sso, RoleHote::Console].into(),
            local: false,
            machine: None,
        }];
        c.composants.extend([ComposantId::Lemonldap, ComposantId::Console]);
        c.services.insert(Service::Auth, "auth.exemple.fr".into());
        c.services.insert(Service::SsoAdmin, "admin-sso.exemple.fr".into());
        c.services.insert(Service::Console, "console.exemple.fr".into());
    });
    let (cookie, csrf) = evolution(&banc).await;
    let composants = "composants=openldap&composants=sauvegarde&composants=ssp&composants=lemonldap&composants=console&composants=white_pages";
    let (statut, _, body) = poster(&banc, &cookie, &csrf, "/install/composants", composants).await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    let (_, page) = lire(&banc, &cookie, "/install/securite").await;
    let case = bloc(&page, r#"name="console_journal_modifiable""#, ">");
    assert!(!case.contains("checked") && !case.contains("disabled"), "non figée, décochée : {case}");
    let (statut, _, body) = poster(
        &banc,
        &cookie,
        &csrf,
        "/install/securite",
        "pages=pages.exemple.fr&console_journal_modifiable=on",
    )
    .await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "l'évolution accepte la case cochée : {body}");
    assert!(brouillon_yaml(&banc).contains("journal_sans_ajout_seul: true"), "{}", brouillon_yaml(&banc));
    let (statut, page) = lire(&banc, &cookie, "/install/recapitulatif").await;
    assert_eq!(statut, StatusCode::OK);
    assert!(page.contains("modifiable accepté si le serveur refuse le verrou"), "{page}");
    assert!(!page.contains("Une évolution ne peut qu"), "{page}");
}

// OI-211, scénario : En évolution, un fournisseur de l'installation retrouve son jeton (plan M8,
// tranche 18, D-082). « Terminer » a effacé le jeton ; l'évolution le ressaisit et le teste.
#[tokio::test]
async fn oi211_en_evolution_un_fournisseur_de_l_installation_retrouve_son_jeton() {
    use open_iam_installer::config::{Fournisseur, TypeFournisseur, fournisseurs::Confiance};
    let xo = faux_xo(XO_JETON).await;
    let banc = installe().await;
    modifier_base(&banc, |c| {
        c.fournisseurs = vec![Fournisseur {
            nom: "labo".into(),
            type_: TypeFournisseur::XenOrchestra,
            url: xo.url.clone(),
            tls: Confiance { empreinte_sha256: Some(certificat_xo().empreinte.clone()), autorite: None },
        }];
    });
    let (cookie, csrf) = evolution(&banc).await;
    let (_, avant) = lire(&banc, &cookie, "/install/cibles/fournisseurs").await;
    assert!(avant.contains("Saisir le jeton de labo"), "{avant}");
    let (_, _, tableau) = poster(&banc, &cookie, &csrf, "/install/cibles/fournisseurs/labo/test", "").await;
    assert!(
        tableau.contains("Saisissez-le avec « Saisir le jeton »") && !tableau.contains("connexion vérifiée"),
        "{tableau}"
    );
    let (statut, _, corps) = poster(
        &banc,
        &cookie,
        &csrf,
        "/install/cibles/fournisseurs/labo/jeton",
        &format!("jeton={XO_JETON}"),
    )
    .await;
    assert_eq!(statut, StatusCode::OK, "{corps}");
    let (_, _, tableau) = poster(&banc, &cookie, &csrf, "/install/cibles/fournisseurs/labo/test", "").await;
    assert!(tableau.contains("connexion vérifiée"), "{tableau}");
    assert!(
        tableau.contains("Nouvelle machine chez ce fournisseur"),
        "la création redevient possible : {tableau}"
    );
}