sources_ad.rs 1078 lignes · 56236 octets
//! OI-106 — E-009a Sources Active Directory (plan M5, tranche 6) : déclaration des AD à importer
//! dans le cadre E-009, test de connexion depuis le poste contre un faux contrôleur LDAPS du banc,
//! rendu Ansible, puis cartes « Simuler l'import », « Importer », « Basculer » d'E-022 (D-062).
//! Ansible est remplacé par tests/faux/ansible-playbook.

mod commun;

use std::time::{Duration, Instant};

use axum::http::StatusCode;
use commun::*;

const URGENCE: &str = "Urgence-Tres-Longue-2026!";
const MOT_DE_PASSE: &str = "Cheval-Batterie-42";
const COMPOSANTS_AD: &str = "composants=openldap&composants=sauvegarde&composants=lsc_ad";

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, String) {
    let (res, body) = send(&banc.router, get_avec(uri, cookie)).await;
    (res.status(), header(&res, "location").to_owned(), body)
}

fn encoder(texte: &str) -> String {
    form_urlencoded::byte_serialize(texte.as_bytes()).collect()
}

/// Le texte est-il dans la page, apostrophes échappées ou non par askama ?
fn contient(page: &str, texte: &str) -> bool {
    page.contains(texte) || page.contains(&texte.replace('\'', "'"))
}

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

fn secrets_yaml(banc: &Banc) -> String {
    std::fs::read_to_string(banc.etat_dir().join("draft-secrets.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()
}

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

/// Contenu « déchiffré » d'un secrets.yml produit par le faux ansible-vault (base64).
fn dechiffre(chemin: &std::path::Path) -> String {
    use std::io::Write;
    let chiffre = std::fs::read_to_string(chemin).unwrap();
    let mut enfant = std::process::Command::new("base64")
        .arg("-d")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .spawn()
        .unwrap();
    enfant.stdin.take().unwrap().write_all(chiffre.lines().nth(1).unwrap().as_bytes()).unwrap();
    String::from_utf8(enfant.wait_with_output().unwrap().stdout).unwrap()
}

/// Background : l'assistant mené jusqu'à l'étape 8 avec openldap et lsc_ad cochés en E-004.
async fn jusqu_aux_sources(environnement: Vec<(String, String)>) -> (Banc, String, String) {
    let banc = banc_avec(environnement);
    let (cookie, csrf) = session_assistant(&banc).await;
    let comptes = format!(
        "urgence={URGENCE}&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}"
    );
    let mut redirection = String::new();
    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_AD),
        ("/install/securite", "annuaire=annuaire.exemple.fr&tls=interne&preset=anssi"),
        ("/install/comptes", comptes.as_str()),
        ("/install/telemetrie", ""),
    ] {
        let (statut, r, body) = poster(&banc, &cookie, &csrf, uri, form).await;
        assert_eq!(statut, StatusCode::NO_CONTENT, "{uri} : {body}");
        redirection = r;
    }
    assert_eq!(redirection, "/install/parametres", "E-008 mène à l'étape 8");
    (banc, cookie, csrf)
}

fn reussite() -> Vec<(String, String)> {
    vec![("OIAM_FAUX_SCENARIO".into(), "reussite".into())]
}

/// Formulaire de la modale E009a-C3 pour une source qui pointe sur le faux AD du banc.
fn source(nom: &str, port: u16, chaine: &str) -> String {
    format!(
        "ancien=&nom={nom}&url={}&base={}&compte={}&mot_de_passe={}&royaume=&certificat={}&filtre_utilisateurs=&filtre_groupes=",
        encoder(&format!("ldaps://127.0.0.1:{port}")),
        encoder(AD_BASE),
        encoder(AD_COMPTE),
        encoder(AD_MOT_DE_PASSE),
        encoder(chaine),
    )
}

const SOURCES: &str = "/install/parametres/lsc_ad/sources";

/// Ligne du tableau E009a-C1 de la source `nom`.
fn ligne<'a>(table: &'a str, nom: &str) -> &'a str {
    bloc(table, &format!(r#"id="source-{nom}""#), "</tr>")
}

/// Contrôle `controle` du dernier test affiché : `Some(true)` réussi, `Some(false)` en échec.
fn controle(html: &str, controle: &str) -> Option<bool> {
    let balise = html.split(&format!(r#"data-controle="{controle}""#)).nth(1)?.split('>').next()?;
    Some(balise.contains(r#"data-ok="true""#))
}

/// Ajoute la source puis la teste ; renvoie le tableau après le test.
async fn ajouter_et_tester(banc: &Banc, cookie: &str, csrf: &str, nom: &str, port: u16) -> String {
    let (statut, _, body) = poster(banc, cookie, csrf, SOURCES, &source(nom, port, &autorites_ad().ca)).await;
    assert_eq!(statut, StatusCode::OK, "{body}");
    let (statut, _, table) = poster(banc, cookie, csrf, &format!("{SOURCES}/{nom}/test"), "").await;
    assert_eq!(statut, StatusCode::OK, "{table}");
    table
}

// ------------------------------------------------------------------------------- Gherkin E-009a

#[tokio::test]
async fn la_sous_etape_exige_une_source_testee() {
    let (banc, cookie, csrf) = jusqu_aux_sources(reussite()).await;
    let (statut, location, _) = lire(&banc, &cookie, "/install/parametres").await;
    assert_eq!((statut, location.as_str()), (StatusCode::SEE_OTHER, "/install/parametres/lsc_ad"));
    let (statut, _, page) = lire(&banc, &cookie, "/install/parametres/lsc_ad").await;
    assert_eq!(statut, StatusCode::OK, "{page}");
    assert!(page.contains("Paramètres — Synchronisation Active Directory (LSC) (1/1)"), "{page}");
    assert!(contient(&page, "Ajoutez l'Active Directory à importer."), "état vide : {page}");
    assert!(page.contains("-&lt;nom&gt;") || page.contains("-<nom>"), "règle de collision (D-060) : {page}");
    assert!(contient(&page, "Les mots de passe AD ne sont pas copiés"), "rappel D-061 : {page}");
    assert!(page.contains(r#"<option value="15" selected>"#), "fréquence 15 min par défaut : {page}");
    let (statut, _, body) =
        poster(&banc, &cookie, &csrf, "/install/parametres/lsc_ad", "frequence_minutes=15").await;
    assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "{body}");
    assert!(body.contains("Ajoutez au moins un Active Directory et testez sa connexion"), "{body}");
}

#[tokio::test]
async fn declarer_et_tester_une_source() {
    let (port, journal_ad) = faux_ad().await;
    let (banc, cookie, csrf) = jusqu_aux_sources(reussite()).await;
    let (_garde, journal) = journal();
    let (statut, _, modale) = lire(&banc, &cookie, &format!("{SOURCES}/nouvelle")).await;
    assert_eq!(statut, StatusCode::OK);
    assert!(modale.contains(r#"id="form-source""#) && modale.contains(r#"name="mot_de_passe""#), "{modale}");
    assert!(modale.contains("x-data=\"royaumeAd\""), "royaume proposé depuis l'UPN (Alpine) : {modale}");
    assert!(modale.contains("objets système de l'AD"), "exclusion des objets système annoncée : {modale}");

    let (statut, _, reponse) =
        poster(&banc, &cookie, &csrf, SOURCES, &source("ad1", port, &autorites_ad().ca)).await;
    assert_eq!(statut, StatusCode::OK, "{reponse}");
    assert!(reponse.contains("source-enregistree") || reponse.contains(r#"id="sources""#), "{reponse}");
    let brouillon = brouillon_yaml(&banc);
    assert!(brouillon.contains("royaume: AD1.EXEMPLE.LAN"), "royaume proposé depuis l'UPN : {brouillon}");
    assert!(!brouillon.contains(AD_MOT_DE_PASSE), "mot de passe hors du brouillon : {brouillon}");
    assert!(secrets_yaml(&banc).contains(AD_MOT_DE_PASSE), "mot de passe dans les secrets (0600)");
    let (_, _, page) = lire(&banc, &cookie, "/install/parametres/lsc_ad").await;
    assert!(ligne(&page, "ad1").contains("non testé"), "{page}");
    assert!(page.contains("SHA-256"), "empreinte de la chaîne affichée : {page}");
    assert!(!page.contains(AD_MOT_DE_PASSE), "mot de passe jamais renvoyé : {page}");

    let (statut, _, table) = poster(&banc, &cookie, &csrf, &format!("{SOURCES}/ad1/test"), "").await;
    assert_eq!(statut, StatusCode::OK, "{table}");
    for c in ["connexion", "certificat", "bind", "base", "utilisateurs", "groupes"] {
        assert_eq!(controle(&table, c), Some(true), "{c} : {table}");
    }
    assert!(ligne(&table, "ad1").contains("vérifié avec 20 utilisateurs et 4 groupes"), "{table}");
    assert_eq!(journal_ad.lock().unwrap().binds, [AD_COMPTE], "un seul bind, avec le compte de lecture");
    // D-108 (OI-213) : le décompte exclut les objets système de l'AD, comme l'import.
    let recherches = journal_ad.lock().unwrap().recherches.clone();
    assert_eq!(recherches.len(), 2, "une recherche pour les utilisateurs, une pour les groupes");
    for requete in &recherches {
        let filtre = String::from_utf8_lossy(requete);
        assert!(filtre.contains("isCriticalSystemObject") && filtre.contains("TRUE"), "{filtre:?}");
    }
    assert!(brouillon_yaml(&banc).contains("tests_ad:"), "résultat gardé dans le brouillon");
    let (_, _, modale) = lire(&banc, &cookie, &format!("{SOURCES}/ad1")).await;
    assert!(modale.contains("Défini ✓") && !modale.contains(AD_MOT_DE_PASSE), "{modale}");

    let (statut, redirection, body) =
        poster(&banc, &cookie, &csrf, "/install/parametres/lsc_ad", "frequence_minutes=15").await;
    assert_eq!((statut, redirection.as_str()), (StatusCode::NO_CONTENT, "/install/recapitulatif"), "{body}");
    let (_, _, recap) = lire(&banc, &cookie, "/install/recapitulatif").await;
    let carte = bloc(&recap, "Active Directory</h2>", "</section>");
    assert!(carte.contains("ad1") && carte.contains("15 minutes"), "{carte}");
    assert!(!recap.contains(AD_MOT_DE_PASSE));
    let texte = journal.texte();
    assert!(texte.contains(r#"evenement="test_ad""#), "{texte}");
    assert!(!texte.contains(AD_MOT_DE_PASSE), "mot de passe hors du journal : {texte}");
}

#[tokio::test]
async fn un_certificat_inconnu_fait_echouer_le_test() {
    let (port, _) = faux_ad().await;
    let (banc, cookie, csrf) = jusqu_aux_sources(reussite()).await;
    let (statut, _, body) =
        poster(&banc, &cookie, &csrf, SOURCES, &source("ad1", port, &autorites_ad().etrangere)).await;
    assert_eq!(statut, StatusCode::OK, "{body}");
    let (_, _, table) = poster(&banc, &cookie, &csrf, &format!("{SOURCES}/ad1/test"), "").await;
    assert_eq!(controle(&table, "connexion"), Some(true), "{table}");
    assert_eq!(controle(&table, "certificat"), Some(false), "{table}");
    let aide = bloc(&table, r#"data-controle="certificat""#, "</li>");
    assert!(aide.contains("chaîne"), "aide de l'échec : {aide}");
    assert_eq!(controle(&table, "bind"), None, "rien n'est tenté après l'échec TLS : {table}");
    assert!(!ligne(&table, "ad1").contains("vérifié"), "{table}");
    let (statut, _, body) =
        poster(&banc, &cookie, &csrf, "/install/parametres/lsc_ad", "frequence_minutes=15").await;
    assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "la source n'est pas vérifiée : {body}");
}

#[tokio::test]
async fn ldap_en_clair_est_refuse() {
    let (banc, cookie, csrf) = jusqu_aux_sources(reussite()).await;
    let form = source("ad1", 636, &autorites_ad().ca).replace(
        &format!("url={}", encoder("ldaps://127.0.0.1:636")),
        &format!("url={}", encoder("ldap://ad1.exemple.lan")),
    );
    let (statut, _, body) = poster(&banc, &cookie, &csrf, SOURCES, &form).await;
    assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "{body}");
    assert!(body.contains("LDAPS seulement"), "{body}");
    assert!(body.contains(r#"id="form-source""#), "la modale revient avec l'erreur : {body}");
    assert!(!body.contains(AD_MOT_DE_PASSE), "mot de passe non renvoyé : {body}");
    assert!(!brouillon_yaml(&banc).contains("ad1"), "rien n'est enregistré");
}

#[tokio::test]
async fn la_priorite_se_regle() {
    let (port, _) = faux_ad().await;
    let (banc, cookie, csrf) = jusqu_aux_sources(reussite()).await;
    ajouter_et_tester(&banc, &cookie, &csrf, "ad1", port).await;
    let table = ajouter_et_tester(&banc, &cookie, &csrf, "ad2", port).await;
    assert!(table.find(r#"id="source-ad1""#) < table.find(r#"id="source-ad2""#), "ordre de saisie : {table}");
    let (statut, _, table) =
        poster(&banc, &cookie, &csrf, &format!("{SOURCES}/ad2/priorite"), "sens=monter").await;
    assert_eq!(statut, StatusCode::OK, "{table}");
    assert!(table.find(r#"id="source-ad2""#) < table.find(r#"id="source-ad1""#), "ad2 montée : {table}");
    assert!(ligne(&table, "ad2").contains("vérifié"), "monter ne change pas le test : {table}");
    let (statut, _, body) =
        poster(&banc, &cookie, &csrf, "/install/parametres/lsc_ad", "frequence_minutes=15").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    let (_, _, recap) = lire(&banc, &cookie, "/install/recapitulatif").await;
    let carte = bloc(&recap, "Active Directory</h2>", "</section>");
    assert!(carte.find("ad2") < carte.find("ad1"), "E-010 montre l'ordre : {carte}");

    poster(&banc, &cookie, &csrf, "/install/verification", "").await;
    let (statut, _, body) = poster(&banc, &cookie, &csrf, "/install/execution", "").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    attendre_fin(&banc).await;
    let execution = banc.etat.runner.dossier_execution(&banc.etat.runner.derniere().unwrap().id);
    let vars = std::fs::read_to_string(execution.join("inventaire/group_vars/all/config.yml")).unwrap();
    let sources = bloc(&vars, "oiam_ad_sources:", "oiam_");
    let (i2, i1) = (sources.find("nom: !unsafe ad2").unwrap(), sources.find("nom: !unsafe ad1").unwrap());
    assert!(i2 < i1, "oiam_ad_sources rend ad2 avant ad1 : {sources}");
    assert!(sources.contains("priorite: 1") && sources.contains("priorite: 2"), "{sources}");
}

#[tokio::test]
async fn les_secrets_vont_a_ansible_et_nulle_part_ailleurs() {
    let (port, _) = faux_ad().await;
    let (banc, cookie, csrf) = jusqu_aux_sources(reussite()).await;
    let (_garde, journal) = journal();
    ajouter_et_tester(&banc, &cookie, &csrf, "ad1", port).await;
    poster(&banc, &cookie, &csrf, "/install/parametres/lsc_ad", "frequence_minutes=30").await;
    let (_, _, recap) = lire(&banc, &cookie, "/install/recapitulatif").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}");
    attendre_fin(&banc).await;
    let execution = banc.etat.runner.dossier_execution(&banc.etat.runner.derniere().unwrap().id);
    let coffre = dechiffre(&execution.join("inventaire/group_vars/all/secrets.yml"));
    let ligne_secret = bloc(&coffre, "oiam_ad_mots_de_passe:", "\n\n");
    assert!(ligne_secret.contains("ad1: !unsafe") && ligne_secret.contains(AD_MOT_DE_PASSE), "{coffre}");
    let vars = std::fs::read_to_string(execution.join("inventaire/group_vars/all/config.yml")).unwrap();
    assert!(!vars.contains(AD_MOT_DE_PASSE), "{vars}");
    for attendu in [
        "oiam_ad_sources:",
        "url: !unsafe ldaps://127.0.0.1:",
        "compte: !unsafe lecture@ad1.exemple.lan",
        "royaume: !unsafe AD1.EXEMPLE.LAN",
        "BEGIN CERTIFICATE",
        "filtre_utilisateurs: !unsafe (&(objectClass=user)(objectCategory=person))",
        "filtre_groupes: !unsafe (objectClass=group)",
        "frequence_minutes: 30",
        "regle_collision: !unsafe suffixe",
        // OI-103 : rien n'est synchronisé à l'installation (I-09).
        "etat: !unsafe preparee",
    ] {
        assert!(vars.contains(attendu), "{attendu} : {vars}");
    }
    let yaml = std::fs::read_to_string(execution.join("openiam.yaml")).unwrap();
    assert!(yaml.contains("lsc_ad:") && !yaml.contains(AD_MOT_DE_PASSE), "{yaml}");
    assert!(!recap.contains(AD_MOT_DE_PASSE));
    let (_, _, resultat) = lire(&banc, &cookie, "/install/resultat").await;
    assert!(!resultat.contains(AD_MOT_DE_PASSE));
    assert!(
        contient(&resultat, "Faire évoluer l'installation"),
        "E-012 : l'import se lance depuis E-022 : {resultat}"
    );
    let recapitulatif =
        std::fs::read_dir(banc.racine().join("home/open-iam")).unwrap().next().unwrap().unwrap().path();
    assert!(!std::fs::read_to_string(recapitulatif).unwrap().contains(AD_MOT_DE_PASSE));
    let journal_execution = std::fs::read_to_string(execution.join("journal.jsonl")).unwrap();
    assert!(!journal_execution.contains(AD_MOT_DE_PASSE));
    assert!(!journal.texte().contains(AD_MOT_DE_PASSE), "{}", journal.texte());
}

// ------------------------------------------------------------------------------- règles de la modale

#[tokio::test]
async fn une_modification_invalide_le_test_et_garde_le_mot_de_passe() {
    let (port, _) = faux_ad().await;
    let (banc, cookie, csrf) = jusqu_aux_sources(reussite()).await;
    ajouter_et_tester(&banc, &cookie, &csrf, "ad1", port).await;
    // Même source, base modifiée, mot de passe laissé vide : il est conservé, le test est invalidé.
    let form = source("ad1", port, &autorites_ad().ca)
        .replace("ancien=&", "ancien=ad1&")
        .replace(&format!("mot_de_passe={}", encoder(AD_MOT_DE_PASSE)), "mot_de_passe=")
        .replace(
            &format!("base={}", encoder(AD_BASE)),
            &format!("base={}", encoder("OU=Mairie,DC=ad1,DC=exemple,DC=lan")),
        );
    let (statut, _, body) = poster(&banc, &cookie, &csrf, SOURCES, &form).await;
    assert_eq!(statut, StatusCode::OK, "{body}");
    assert!(secrets_yaml(&banc).contains(AD_MOT_DE_PASSE), "mot de passe conservé");
    let (_, _, page) = lire(&banc, &cookie, "/install/parametres/lsc_ad").await;
    assert!(ligne(&page, "ad1").contains("non testé"), "la modification invalide le test : {page}");
    // La base n'existe pas dans le faux AD : « base » échoue après un bind réussi.
    let (_, _, table) = poster(&banc, &cookie, &csrf, &format!("{SOURCES}/ad1/test"), "").await;
    assert_eq!(controle(&table, "bind"), Some(true), "{table}");
    assert_eq!(controle(&table, "base"), Some(false), "{table}");
    assert!(ligne(&table, "ad1").contains("échec"), "{table}");
}

#[tokio::test]
async fn un_mauvais_mot_de_passe_echoue_au_bind() {
    let (port, _) = faux_ad().await;
    let (banc, cookie, csrf) = jusqu_aux_sources(reussite()).await;
    let form = source("ad1", port, &autorites_ad().ca)
        .replace(&format!("mot_de_passe={}", encoder(AD_MOT_DE_PASSE)), "mot_de_passe=Faux-Mot-De-Passe");
    poster(&banc, &cookie, &csrf, SOURCES, &form).await;
    let (_, _, table) = poster(&banc, &cookie, &csrf, &format!("{SOURCES}/ad1/test"), "").await;
    assert_eq!(controle(&table, "certificat"), Some(true), "{table}");
    assert_eq!(controle(&table, "bind"), Some(false), "{table}");
    assert!(bloc(&table, r#"data-controle="bind""#, "</li>").contains("mot de passe"), "{table}");
    assert!(!table.contains("Faux-Mot-De-Passe"));
}

#[tokio::test]
async fn les_champs_de_la_modale_sont_valides_un_par_un() {
    let (banc, cookie, csrf) = jusqu_aux_sources(reussite()).await;
    let base = source("ad1", 636, &autorites_ad().ca);
    for (champ, valeur, attendu) in [
        ("nom", "x", "2 à 30"),
        ("base", "pas un DN", "attribut=valeur"),
        ("compte", "lecture", "UPN"),
        ("certificat", "pas un certificat", "BEGIN CERTIFICATE"),
        ("filtre_utilisateurs", "(objectClass=user", "Filtre"),
        ("mot_de_passe", "", "obligatoire"),
    ] {
        let debut = format!("&{champ}=");
        let avant = base.split(&debut).next().unwrap();
        let apres = base.split(&debut).nth(1).unwrap();
        let reste = apres.split_once('&').map(|(_, r)| format!("&{r}")).unwrap_or_default();
        let form = format!("{avant}{debut}{}{reste}", encoder(valeur));
        let (statut, _, body) = poster(&banc, &cookie, &csrf, SOURCES, &form).await;
        assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "{champ} : {body}");
        assert!(
            body.contains(&format!(r#"id="erreur-{champ}""#)) && body.contains(attendu),
            "{champ} : {body}"
        );
    }
    // Deux sources ne partagent pas un nom.
    poster(&banc, &cookie, &csrf, SOURCES, &base).await;
    let (statut, _, body) = poster(&banc, &cookie, &csrf, SOURCES, &base.replace("nom=ad1", "nom=AD1")).await;
    assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "{body}");
    assert!(body.contains("déjà"), "{body}");
}

#[tokio::test]
async fn retirer_une_source_oublie_son_mot_de_passe() {
    let (banc, cookie, csrf) = jusqu_aux_sources(reussite()).await;
    poster(&banc, &cookie, &csrf, SOURCES, &source("ad1", 636, &autorites_ad().ca)).await;
    let (res, table) = send(&banc.router, delete_avec(&format!("{SOURCES}/ad1"), &cookie, &csrf)).await;
    assert_eq!(res.status(), StatusCode::OK, "{table}");
    assert!(contient(&table, "Ajoutez l'Active Directory à importer."), "{table}");
    assert!(!secrets_yaml(&banc).contains(AD_MOT_DE_PASSE), "mot de passe oublié");
}

#[tokio::test]
async fn la_frequence_se_choisit_parmi_quatre_valeurs() {
    let (port, _) = faux_ad().await;
    let (banc, cookie, csrf) = jusqu_aux_sources(reussite()).await;
    ajouter_et_tester(&banc, &cookie, &csrf, "ad1", port).await;
    let (statut, _, body) =
        poster(&banc, &cookie, &csrf, "/install/parametres/lsc_ad", "frequence_minutes=7").await;
    assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "{body}");
    assert!(body.contains(r#"id="erreur-frequence_minutes""#), "{body}");
    let (statut, _, _) =
        poster(&banc, &cookie, &csrf, "/install/parametres/lsc_ad", "frequence_minutes=60").await;
    assert_eq!(statut, StatusCode::NO_CONTENT);
    assert!(brouillon_yaml(&banc).contains("frequence_minutes: 60"), "{}", brouillon_yaml(&banc));
}

#[tokio::test]
async fn decocher_lsc_ad_retire_la_sous_etape_sans_perdre_les_sources() {
    let (banc, cookie, csrf) = jusqu_aux_sources(reussite()).await;
    poster(&banc, &cookie, &csrf, SOURCES, &source("ad1", 636, &autorites_ad().ca)).await;
    let (statut, _, body) =
        poster(&banc, &cookie, &csrf, "/install/composants", "composants=openldap&composants=sauvegarde")
            .await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    let (_, _, page) = lire(&banc, &cookie, "/install/composants").await;
    assert!(!page.contains("Paramètres — Synchronisation Active Directory"), "{page}");
    assert!(brouillon_yaml(&banc).contains("ad1"), "sources conservées dans le brouillon");
    poster(&banc, &cookie, &csrf, "/install/composants", COMPOSANTS_AD).await;
    let (_, _, page) = lire(&banc, &cookie, "/install/parametres/lsc_ad").await;
    assert!(page.contains(r#"id="source-ad1""#), "la sous-étape réapparaît avec ad1 : {page}");
}

#[tokio::test]
async fn le_test_abandonne_apres_dix_secondes() {
    let port = serveur_muet().await;
    let (banc, cookie, csrf) = jusqu_aux_sources(reussite()).await;
    poster(&banc, &cookie, &csrf, SOURCES, &source("ad1", port, &autorites_ad().ca)).await;
    let debut = Instant::now();
    let (_, _, table) = poster(&banc, &cookie, &csrf, &format!("{SOURCES}/ad1/test"), "").await;
    let duree = debut.elapsed();
    assert!(duree >= Duration::from_secs(9) && duree < Duration::from_secs(13), "{duree:?}");
    assert!(table.contains("10 s"), "délai annoncé : {table}");
    assert!(!ligne(&table, "ad1").contains("vérifié"), "{table}");
}

// ------------------------------------------------------------------------------- E-022 (D-062)

/// Installation menée jusqu'au bout avec lsc_ad (source ad1 testée), puis « Terminer ».
async fn installe_avec_ad() -> Banc {
    let (port, _) = faux_ad().await;
    let (banc, cookie, csrf) = jusqu_aux_sources(reussite()).await;
    ajouter_et_tester(&banc, &cookie, &csrf, "ad1", port).await;
    let (statut, _, body) =
        poster(&banc, &cookie, &csrf, "/install/parametres/lsc_ad", "frequence_minutes=15").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    poster(&banc, &cookie, &csrf, "/install/verification", "").await;
    let (statut, _, body) = poster(&banc, &cookie, &csrf, "/install/execution", "").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    attendre_fin(&banc).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 environnement du faux Ansible.
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 = open_iam_installer::etat::Etat::ouvrir(parametres).unwrap();
    Banc { router: open_iam_installer::app(etat.clone()), etat, dossier }
}

/// `POST /install/migration/{operation}` : « code redirection notification ».
async fn migration(banc: &Banc, cookie: &str, csrf: &str, operation: &str) -> (StatusCode, String, String) {
    let (res, _) =
        send(&banc.router, post_form(&format!("/install/migration/{operation}"), cookie, Some(csrf), ""))
            .await;
    (res.status(), header(&res, "hx-redirect").to_owned(), header(&res, "hx-trigger").to_owned())
}

/// Fin d'une opération réussie : E-012 titré, puis « Terminer » sans case à cocher.
async fn terminer_operation(banc: &Banc, cookie: &str, csrf: &str, titre: &str) {
    let (statut, _, page) = lire(banc, cookie, "/install/resultat").await;
    assert_eq!(statut, StatusCode::OK, "{page}");
    assert!(contient(&page, titre), "{titre} : {page}");
    assert!(!page.contains(r#"name="conserve""#), "aucun récapitulatif à conserver : {page}");
    assert!(!page.contains("/install/resultat/recapitulatif.txt"), "{page}");
    let (_, redirection, _) = poster(banc, cookie, csrf, "/install/terminer", "").await;
    assert_eq!(redirection, "/verrouille");
}

#[tokio::test]
async fn simuler_puis_importer_puis_basculer() {
    let banc = installe_avec_ad().await;
    let base = banc.etat.runner.derniere().unwrap().id;
    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 (_, _, page) = lire(&banc, &cookie, "/install/evolution").await;
    let carte = bloc(&page, r#"id="migration-ad""#, "</section>");
    assert!(carte.contains(r#"hx-post="/install/migration/simulation""#), "{carte}");
    assert!(
        !carte.contains(r#"hx-post="/install/migration/import""#),
        "import indisponible sans simulation : {carte}"
    );
    assert!(contient(carte, "Simulez d'abord l'import"), "{carte}");

    let (statut, _, notification) = migration(&banc, &cookie, &csrf, "import").await;
    assert_eq!(statut, StatusCode::CONFLICT, "« Importer » refusé sans simulation réussie");
    assert!(notification.contains("Simulez"), "{notification}");
    assert_eq!(banc.etat.runner.derniere().unwrap().id, base, "rien n'est lancé");

    let (_garde, journal) = journal();
    let (statut, redirection, _) = migration(&banc, &cookie, &csrf, "simulation").await;
    assert_eq!((statut, redirection.as_str()), (StatusCode::NO_CONTENT, "/install/execution"));
    assert!(journal.texte().contains(r#"evenement="migration_lancee""#), "{}", journal.texte());
    let (_, _, page) = lire(&banc, &cookie, "/install/execution").await;
    assert!(contient(&page, "Simulation de l'import en cours"), "{page}");
    attendre_fin(&banc).await;
    let args = std::fs::read_to_string(&trace).unwrap();
    assert!(args.contains("migration-simulation.yml") && !args.contains("site.yml"), "{args}");
    let execution = banc.etat.runner.derniere().unwrap();
    let coffre = std::fs::read_to_string(
        banc.etat.runner.dossier_execution(&execution.id).join("inventaire/group_vars/all/secrets.yml"),
    )
    .unwrap();
    assert_eq!(coffre.lines().nth(1), Some("e30K"), "coffre vide (« {{}} » chiffré) : {coffre}");
    terminer_operation(&banc, &cookie, &csrf, "Simulation de l'import terminée").await;

    let (_, _, page) = lire(&banc, &cookie, "/install/evolution").await;
    let carte = bloc(&page, r#"id="migration-ad""#, "</section>");
    assert!(
        carte.contains(r#"hx-post="/install/migration/import""#),
        "import proposé après la simulation : {carte}"
    );
    let (statut, _, _) = migration(&banc, &cookie, &csrf, "import").await;
    assert_eq!(statut, StatusCode::NO_CONTENT);
    attendre_fin(&banc).await;
    assert!(std::fs::read_to_string(&trace).unwrap().contains("migration-import.yml"));
    terminer_operation(&banc, &cookie, &csrf, "Import terminé").await;

    let (statut, _, _) = migration(&banc, &cookie, &csrf, "bascule").await;
    assert_eq!(statut, StatusCode::NO_CONTENT);
    attendre_fin(&banc).await;
    assert!(std::fs::read_to_string(&trace).unwrap().contains("migration-bascule.yml"));
    terminer_operation(&banc, &cookie, &csrf, "Migration basculée").await;
    let (statut, _, notification) = migration(&banc, &cookie, &csrf, "simulation").await;
    assert_eq!(statut, StatusCode::CONFLICT, "après la bascule, plus d'opération de migration");
    // Notification en JSON : les accents y sont échappés (« bascul\u00e9e »).
    assert!(notification.contains("La migration est bascul"), "{notification}");
}

#[tokio::test]
async fn pas_d_operation_de_migration_pendant_une_autre() {
    let banc = installe_avec_ad().await;
    let banc = rebrancher(banc, vec![("OIAM_FAUX_SCENARIO".into(), "long".into())]);
    let (cookie, csrf) = session_assistant(&banc).await;
    assert_eq!(migration(&banc, &cookie, &csrf, "simulation").await.0, StatusCode::NO_CONTENT);
    assert_eq!(migration(&banc, &cookie, &csrf, "simulation").await.0, StatusCode::CONFLICT);
    assert_eq!(migration(&banc, &cookie, &csrf, "bascule").await.0, StatusCode::CONFLICT);
    let (_, _, page) = lire(&banc, &cookie, "/install/evolution").await;
    assert!(!bloc(&page, r#"id="migration-ad""#, "</section>").contains("hx-post"), "{page}");
    let (statut, _, _) = poster(&banc, &cookie, &csrf, "/install/execution/interrompre", "").await;
    assert_eq!(statut, StatusCode::ACCEPTED);
    attendre_fin(&banc).await;
    let (_, _, page) = lire(&banc, &cookie, "/install/execution").await;
    assert!(
        page.contains(r#"hx-post="/install/migration/simulation""#),
        "« Relancer » relance la simulation : {page}"
    );
}

#[tokio::test]
async fn sans_lsc_ad_pas_de_migration() {
    let banc = banc_avec(reussite());
    let (cookie, csrf) = session_assistant(&banc).await;
    let comptes = format!(
        "urgence={URGENCE}&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&domaine=exemple.fr&base_dn=&langue=fr&fuseau=Europe%2FParis"),
        ("/install/cibles", "mode=native&topologie=local"),
        ("/install/composants", "composants=openldap&composants=sauvegarde"),
        ("/install/securite", "annuaire=annuaire.exemple.fr&tls=interne&preset=anssi"),
        ("/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;
    poster(&banc, &cookie, &csrf, "/install/terminer", "conserve=on").await;
    let (statut, _, notification) = migration(&banc, &cookie, &csrf, "simulation").await;
    assert_eq!(statut, StatusCode::CONFLICT);
    assert!(notification.contains("Active Directory"), "{notification}");
    let (_, _, page) = lire(&banc, &cookie, "/install/evolution").await;
    assert!(!page.contains(r#"id="migration-ad""#), "{page}");
    let (res, _) = send(&banc.router, post_form("/install/migration/autre", &cookie, Some(&csrf), "")).await;
    assert_eq!(res.status(), StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn en_evolution_les_sources_installees_sont_figees() {
    let banc = installe_avec_ad().await;
    let (cookie, csrf) = session_assistant(&banc).await;
    let (statut, _, body) = poster(&banc, &cookie, &csrf, "/install/evolution", "").await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{body}");
    let (_, _, page) = lire(&banc, &cookie, "/install/parametres/lsc_ad").await;
    assert!(page.contains(r#"id="source-ad1""#), "{page}");
    assert!(!page.contains("/install/parametres/lsc_ad/sources/nouvelle"), "pas d'ajout : {page}");
    assert!(contient(&page, "Fixé à l'installation"), "{page}");
    let (statut, _, _) =
        poster(&banc, &cookie, &csrf, SOURCES, &source("ad2", 636, &autorites_ad().ca)).await;
    assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "sources figées");
    let (statut, _, _) =
        poster(&banc, &cookie, &csrf, &format!("{SOURCES}/ad1/priorite"), "sens=descendre").await;
    assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY);
}

#[tokio::test]
async fn une_evolution_ne_rappelle_l_import_que_si_elle_ajoute_la_synchronisation() {
    let banc = installe_avec_ad().await;
    let (cookie, csrf) = session_assistant(&banc).await;
    for (uri, form) in [
        ("/install/evolution", ""),
        (
            "/install/composants",
            "composants=openldap&composants=sauvegarde&composants=lsc_ad&composants=white_pages",
        ),
        ("/install/securite", "pages=pages.exemple.fr"),
        ("/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;
    let (statut, _, page) = lire(&banc, &cookie, "/install/resultat").await;
    assert_eq!(statut, StatusCode::OK, "{page}");
    assert!(contient(&page, "L'installation a évolué"), "{page}");
    assert!(!page.contains(r#"id="migration-a-lancer""#), "synchronisation déjà installée : {page}");
}

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

/// Formulaire de la modale, champ `champ` remplacé par `valeur`.
fn avec(form: &str, champ: &str, valeur: &str) -> String {
    let debut = format!("&{champ}=");
    let (avant, apres) = form.split_once(&debut).unwrap_or_else(|| panic!("{champ} absent"));
    let reste = apres.split_once('&').map(|(_, r)| format!("&{r}")).unwrap_or_default();
    format!("{avant}{debut}{}{reste}", encoder(valeur))
}

const CHARGE_F11: &str = "(|(&(objectClass=user)(objectCategory=person))(cn=x]]>&quot;+java.lang.Runtime.getRuntime&#40;&#41;.exec&#40;&quot;id&quot;&#41;+&quot;<![CDATA[y))";

#[tokio::test]
async fn f11_un_filtre_qui_ferme_une_section_cdata_est_refuse() {
    let (banc, cookie, csrf) = jusqu_aux_sources(reussite()).await;
    let base = source("ad1", 636, &autorites_ad().ca);
    for (champ, valeur) in [("filtre_utilisateurs", CHARGE_F11), ("filtre_groupes", "(cn=a\nb)")] {
        let (statut, _, body) = poster(&banc, &cookie, &csrf, SOURCES, &avec(&base, champ, valeur)).await;
        assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "{champ} : {body}");
        assert!(body.contains(&format!(r#"id="erreur-{champ}""#)), "{champ} : {body}");
    }
    assert!(!brouillon_yaml(&banc).contains("ad1"), "rien n'est enregistré");
}

#[tokio::test]
async fn f11_l_import_d_un_openiam_yaml_refuse_la_charge() {
    use open_iam_installer::{
        catalogue::ComposantId,
        config::{OpenIamConfig, ParametresLscAd, SourceAd},
    };
    let banc = banc_avec(reussite());
    let (cookie, csrf) = session_assistant(&banc).await;
    let mut config = OpenIamConfig::depuis_yaml(include_str!("donnees/openiam.yaml")).unwrap();
    config.composants.insert(ComposantId::LscAd);
    config.composants_parametres.lsc_ad = Some(ParametresLscAd {
        sources: vec![SourceAd {
            nom: "ad1".into(),
            libelle: "ad1".into(),
            url: "ldaps://ad1.exemple.lan".into(),
            base: AD_BASE.into(),
            compte: AD_COMPTE.into(),
            royaume: "AD1.EXEMPLE.LAN".into(),
            certificat: autorites_ad().ca.clone(),
            filtre_utilisateurs: CHARGE_F11.into(),
            filtre_groupes: "(objectClass=group)".into(),
            priorite: 1,
        }],
        ..Default::default()
    });
    let corps = format!(
        "--LIMITE\r\nContent-Disposition: form-data; name=\"fichier\"; filename=\"openiam.yaml\"\r\nContent-Type: application/yaml\r\n\r\n{}\r\n--LIMITE--\r\n",
        config.vers_yaml()
    );
    let requete = axum::http::Request::post("/install/import")
        .header("cookie", &cookie)
        .header("x-csrf-token", &csrf)
        .header("hx-request", "true")
        .header("content-type", "multipart/form-data; boundary=LIMITE")
        .body(axum::body::Body::from(corps))
        .unwrap();
    let (res, body) = send(&banc.router, requete).await;
    assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY, "{body}");
    assert!(body.contains("filtre_utilisateurs"), "{body}");
    assert!(!banc.etat_dir().join("draft.yaml").exists(), "aucun brouillon créé");
}

#[tokio::test]
async fn f18_changer_la_cible_exige_de_ressaisir_le_mot_de_passe() {
    let (port, journal_ad) = faux_ad().await;
    let (banc, cookie, csrf) = jusqu_aux_sources(reussite()).await;
    ajouter_et_tester(&banc, &cookie, &csrf, "ad1", port).await;
    let modification = source("ad1", port, &autorites_ad().ca).replacen("ancien=&", "ancien=ad1&", 1);
    let modification = avec(&modification, "mot_de_passe", "");
    let (port_pirate, _) = faux_ad().await;
    for (champ, valeur) in [
        ("url", format!("ldaps://127.0.0.1:{port_pirate}")),
        ("compte", "autre@ad1.exemple.lan".to_owned()),
        ("certificat", autorites_ad().etrangere.clone()),
    ] {
        let (statut, _, body) =
            poster(&banc, &cookie, &csrf, SOURCES, &avec(&modification, champ, &valeur)).await;
        assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "{champ} changé sans mot de passe : {body}");
        assert!(
            body.contains(r#"id="erreur-mot_de_passe""#) && body.contains("Ressaisissez"),
            "{champ} : {body}"
        );
    }
    let (_, _, page) = lire(&banc, &cookie, "/install/parametres/lsc_ad").await;
    assert!(page.contains(&format!("ldaps://127.0.0.1:{port}")), "source inchangée : {page}");
    // Le même changement avec le mot de passe ressaisi est accepté.
    let ressaisi =
        avec(&avec(&modification, "compte", "autre@ad1.exemple.lan"), "mot_de_passe", AD_MOT_DE_PASSE);
    let (statut, _, body) = poster(&banc, &cookie, &csrf, SOURCES, &ressaisi).await;
    assert_eq!(statut, StatusCode::OK, "{body}");
    assert_eq!(
        journal_ad.lock().unwrap().binds,
        [AD_COMPTE],
        "aucun bind vers la nouvelle cible sans ressaisie"
    );
}

#[tokio::test]
async fn f18_l_enregistrement_et_le_retrait_d_une_source_sont_journalises() {
    let (banc, cookie, csrf) = jusqu_aux_sources(reussite()).await;
    let (_garde, journal) = journal();
    poster(&banc, &cookie, &csrf, SOURCES, &source("ad1", 636, &autorites_ad().ca)).await;
    send(&banc.router, delete_avec(&format!("{SOURCES}/ad1"), &cookie, &csrf)).await;
    let texte = journal.texte();
    assert!(texte.contains(r#"evenement="source_ad_enregistree""#) && texte.contains("ad1"), "{texte}");
    assert!(texte.contains(r#"evenement="source_ad_retiree""#), "{texte}");
    assert!(!texte.contains(AD_MOT_DE_PASSE), "{texte}");
}

#[tokio::test]
async fn f23_une_chaine_de_plus_de_dix_certificats_est_refusee() {
    let (banc, cookie, csrf) = jusqu_aux_sources(reussite()).await;
    let (statut, _, body) =
        poster(&banc, &cookie, &csrf, SOURCES, &source("ad1", 636, &autorites_ad().ca.repeat(11))).await;
    assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "{body}");
    assert!(bloc(&body, r#"id="erreur-certificat""#, "</p>").contains("10 certificats"), "{body}");
}

#[tokio::test]
async fn f23_le_resume_de_la_chaine_est_calcule_une_fois_a_l_enregistrement() {
    let (banc, cookie, csrf) = jusqu_aux_sources(reussite()).await;
    poster(&banc, &cookie, &csrf, SOURCES, &source("ad1", 636, &autorites_ad().ca)).await;
    let (_, _, page) = lire(&banc, &cookie, "/install/parametres/lsc_ad").await;
    let resume = bloc(ligne(&page, "ad1"), "SHA-256 ", " ").to_owned();
    assert!(resume.len() >= 64, "empreinte affichée : {page}");
    // La chaîne du brouillon devient illisible : le tableau garde le résumé calculé à l'enregistrement.
    let premiere = autorites_ad().ca.lines().nth(1).unwrap().to_owned();
    let brouillon = brouillon_yaml(&banc);
    assert!(brouillon.contains(&premiere), "{brouillon}");
    std::fs::write(
        banc.etat_dir().join("draft.yaml"),
        brouillon.replace(&premiere, &"A".repeat(premiere.len())),
    )
    .unwrap();
    let (_, _, page) = lire(&banc, &cookie, "/install/parametres/lsc_ad").await;
    assert!(ligne(&page, "ad1").contains(&format!("SHA-256 {resume}")), "aucune analyse au rendu : {page}");
}

#[tokio::test]
async fn i16_tester_une_source_sans_mot_de_passe_enregistre_est_refuse() {
    let (port, journal_ad) = faux_ad().await;
    let (banc, cookie, csrf) = jusqu_aux_sources(reussite()).await;
    poster(&banc, &cookie, &csrf, SOURCES, &source("ad1", port, &autorites_ad().ca)).await;
    // Source importée d'un openiam.yaml : aucun mot de passe enregistré.
    let chemin = banc.etat_dir().join("draft-secrets.yaml");
    let mut secrets: serde_norway::Value =
        serde_norway::from_str(&std::fs::read_to_string(&chemin).unwrap()).unwrap();
    secrets.as_mapping_mut().unwrap().remove("ad_mots_de_passe");
    std::fs::write(&chemin, serde_norway::to_string(&secrets).unwrap()).unwrap();
    let (statut, _, body) = poster(&banc, &cookie, &csrf, &format!("{SOURCES}/ad1/test"), "").await;
    assert_eq!(statut, StatusCode::UNPROCESSABLE_ENTITY, "{body}");
    assert!(journal_ad.lock().unwrap().binds.is_empty(), "aucun bind avec un mot de passe vide");
    assert!(!brouillon_yaml(&banc).contains("tests_ad:"), "aucun résultat gardé");
}

#[tokio::test]
async fn i10_le_compte_lsc_a_un_mot_de_passe_genere_dans_le_coffre() {
    let (port, _) = faux_ad().await;
    let (banc, cookie, csrf) = jusqu_aux_sources(reussite()).await;
    ajouter_et_tester(&banc, &cookie, &csrf, "ad1", port).await;
    poster(&banc, &cookie, &csrf, "/install/parametres/lsc_ad", "frequence_minutes=15").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}");
    attendre_fin(&banc).await;
    let execution = banc.etat.runner.dossier_execution(&banc.etat.runner.derniere().unwrap().id);
    let coffre = dechiffre(&execution.join("inventaire/group_vars/all/secrets.yml"));
    let mdp = bloc(&coffre, "oiam_lsc_mot_de_passe: !unsafe ", "\n").trim_matches(['\'', '"']).to_owned();
    assert_eq!(mdp.chars().count(), 32, "{coffre}");
    assert!(!std::fs::read_to_string(execution.join("journal.jsonl")).unwrap().contains(&mdp));
    let recapitulatif =
        std::fs::read_dir(banc.racine().join("home/open-iam")).unwrap().next().unwrap().unwrap().path();
    let contenu = std::fs::read_to_string(recapitulatif).unwrap();
    assert!(contenu.contains("cn=lsc,ou=applications") && contenu.contains(&mdp), "{contenu}");
}

// ------------------------------------------------------------------------------- OI-103, OI-105 : état de la migration

/// `etat:` de `oiam_migration` dans le `config.yml` de la dernière exécution.
fn etat_rendu(banc: &Banc) -> String {
    let execution = banc.etat.runner.dossier_execution(&banc.etat.runner.derniere().unwrap().id);
    let vars = std::fs::read_to_string(execution.join("inventaire/group_vars/all/config.yml")).unwrap();
    bloc(bloc(&vars, "oiam_migration:", "\noiam_"), "etat: !unsafe ", "\n").trim().to_owned()
}

/// Évolution menée jusqu'au bout (`formulaires` après E-004), puis « Terminer ».
async fn evoluer(banc: &Banc, cookie: &str, csrf: &str, composants: &str, formulaires: &[(&str, &str)]) {
    let composants = format!("{COMPOSANTS_AD}&{composants}");
    let mut etapes = vec![("/install/evolution", ""), ("/install/composants", composants.as_str())];
    etapes.extend_from_slice(formulaires);
    etapes.extend([("/install/verification", ""), ("/install/execution", "")]);
    for (uri, form) in etapes {
        let (statut, _, body) = poster(banc, cookie, csrf, uri, form).await;
        assert!(statut.is_success(), "{uri} : {statut} {body}");
    }
    attendre_fin(banc).await;
    let (_, redirection, _) = poster(banc, cookie, csrf, "/install/terminer", "conserve=on").await;
    assert_eq!(redirection, "/verrouille");
}

/// Opération de migration menée jusqu'au bout, puis « Terminer ».
async fn operer(banc: &Banc, cookie: &str, csrf: &str, operation: &str) {
    let (statut, _, notification) = migration(banc, cookie, csrf, operation).await;
    assert_eq!(statut, StatusCode::NO_CONTENT, "{operation} : {notification}");
    attendre_fin(banc).await;
    let (_, redirection, _) = poster(banc, cookie, csrf, "/install/terminer", "").await;
    assert_eq!(redirection, "/verrouille");
}

/// Carte E-022 d'une opération : `Some(raison)` désactivée, `None` active.
async fn carte(banc: &Banc, cookie: &str, operation: &str) -> Option<String> {
    let (_, _, page) = lire(banc, cookie, "/install/evolution").await;
    let carte = bloc(&page, &format!(r#"id="migration-{operation}""#), "</div>").to_owned();
    if carte.contains(&format!(r#"hx-post="/install/migration/{operation}""#)) { None } else { Some(carte) }
}

async fn etat_affiche(banc: &Banc, cookie: &str) -> String {
    let (_, _, page) = lire(banc, cookie, "/install/evolution").await;
    bloc(&page, r#"id="etat-migration""#, "</p>").to_owned()
}

#[tokio::test]
async fn l_installation_rend_l_etat_preparee() {
    let banc = installe_avec_ad().await;
    assert_eq!(etat_rendu(&banc), "preparee", "aucune synchronisation à l'installation (I-09)");
}

#[tokio::test]
async fn en_evolution_l_etat_derive_des_operations_reussies() {
    let banc = installe_avec_ad().await;
    let (cookie, csrf) = session_assistant(&banc).await;
    assert!(etat_affiche(&banc, &cookie).await.contains("préparée"));
    operer(&banc, &cookie, &csrf, "simulation").await;
    assert_eq!(etat_rendu(&banc), "preparee", "la simulation ne change pas l'état");
    operer(&banc, &cookie, &csrf, "import").await;
    assert_eq!(etat_rendu(&banc), "preparee", "le play d'import passe lui-même l'état à transition");
    assert!(etat_affiche(&banc, &cookie).await.contains("en transition"));

    // Évolution après l'import : la synchronisation continue (transition).
    evoluer(
        &banc,
        &cookie,
        &csrf,
        "composants=white_pages",
        &[("/install/securite", "pages=pages.exemple.fr")],
    )
    .await;
    assert_eq!(etat_rendu(&banc), "transition");
    assert!(carte(&banc, &cookie, "simulation").await.is_none(), "« Simuler » possible avant la bascule");
    let import = carte(&banc, &cookie, "import").await.expect("import désactivé après l'évolution");
    assert!(import.contains("Simulez"), "simulation postérieure à l'évolution exigée : {import}");
    assert!(
        carte(&banc, &cookie, "bascule").await.is_none(),
        "« Basculer » après un import réussi, même antérieur"
    );

    operer(&banc, &cookie, &csrf, "bascule").await;
    // Évolution après la bascule : l'état reste basculée, plus aucune opération.
    evoluer(
        &banc,
        &cookie,
        &csrf,
        // White Pages, ajouté par la première évolution, est désormais installé.
        "composants=white_pages&composants=ssp",
        &[
            ("/install/securite", "mdp=mdp.exemple.fr"),
            (
                "/install/messagerie",
                "hote=smtp.exemple.fr&port=587&chiffrement=starttls&expediteur=noreply%40exemple.fr&nom=Mairie",
            ),
        ],
    )
    .await;
    assert_eq!(etat_rendu(&banc), "basculee");
    assert!(etat_affiche(&banc, &cookie).await.contains("basculée"));
    for operation in ["simulation", "import", "bascule"] {
        let raison = carte(&banc, &cookie, operation)
            .await
            .unwrap_or_else(|| panic!("{operation} active après la bascule"));
        assert!(raison.contains("basculée"), "{operation} : {raison}");
    }
}

#[tokio::test]
async fn les_cartes_suivent_l_etat_de_la_migration() {
    let banc = installe_avec_ad().await;
    let (cookie, csrf) = session_assistant(&banc).await;
    assert!(carte(&banc, &cookie, "simulation").await.is_none());
    assert!(carte(&banc, &cookie, "import").await.is_some_and(|r| r.contains("Simulez")));
    assert!(carte(&banc, &cookie, "bascule").await.is_some_and(|r| r.contains("Importez")));
    operer(&banc, &cookie, &csrf, "simulation").await;
    assert!(
        carte(&banc, &cookie, "import").await.is_none(),
        "import après une simulation postérieure à l'installation"
    );
    assert!(carte(&banc, &cookie, "bascule").await.is_some(), "pas de bascule sans import");
    operer(&banc, &cookie, &csrf, "import").await;
    assert!(carte(&banc, &cookie, "simulation").await.is_none(), "simuler encore pendant la transition");
    assert!(carte(&banc, &cookie, "bascule").await.is_none());
}

#[tokio::test]
async fn e012_de_la_simulation_affiche_le_rapport_et_les_collisions() {
    let banc = installe_avec_ad().await;
    let recapitulatifs = std::fs::read_dir(banc.racine().join("home/open-iam")).unwrap().count();
    let (cookie, csrf) = session_assistant(&banc).await;
    assert_eq!(migration(&banc, &cookie, &csrf, "simulation").await.0, StatusCode::NO_CONTENT);
    attendre_fin(&banc).await;
    let rapport = banc
        .etat
        .runner
        .dossier_execution(&banc.etat.runner.derniere().unwrap().id)
        .join("migration/simulation.txt");
    assert!(rapport.is_file(), "rapport déposé par le faux Ansible dans le dossier d'exécution");
    let (statut, _, page) = lire(&banc, &cookie, "/install/resultat").await;
    assert_eq!(statut, StatusCode::OK, "{page}");
    let section = bloc(&page, r#"id="rapport-simulation""#, "</section>");
    assert!(
        section.contains("<pre") && section.contains("gpetit-ad2") && section.contains("ad2 perd le mail"),
        "{section}"
    );
    assert!(
        bloc(section, r#"id="collisions""#, "</p>").contains("3 collisions d&#39;identifiant")
            || bloc(section, r#"id="collisions""#, "</p>").contains("3 collisions d'identifiant"),
        "{section}"
    );
    // Rapport absent : E-012 le dit.
    std::fs::remove_file(&rapport).unwrap();
    let (_, _, page) = lire(&banc, &cookie, "/install/resultat").await;
    let section = bloc(&page, r#"id="rapport-simulation""#, "</section>");
    assert!(section.contains("Aucun rapport") && !section.contains("<pre"), "{section}");
    let (_, redirection, _) = poster(&banc, &cookie, &csrf, "/install/terminer", "").await;
    assert_eq!(redirection, "/verrouille");
    assert_eq!(
        std::fs::read_dir(banc.racine().join("home/open-iam")).unwrap().count(),
        recapitulatifs,
        "aucun récapitulatif"
    );
}

#[tokio::test]
async fn e012_de_la_bascule_affiche_le_rapport_des_liens() {
    // OI-105 : rapport `migration/bascule.txt` rapatrié par Ansible, comme celui de la simulation.
    let banc = installe_avec_ad().await;
    let (cookie, csrf) = session_assistant(&banc).await;
    operer(&banc, &cookie, &csrf, "simulation").await;
    operer(&banc, &cookie, &csrf, "import").await;
    assert_eq!(migration(&banc, &cookie, &csrf, "bascule").await.0, StatusCode::NO_CONTENT);
    attendre_fin(&banc).await;
    let rapport = banc
        .etat
        .runner
        .dossier_execution(&banc.etat.runner.derniere().unwrap().id)
        .join("migration/bascule.txt");
    assert!(rapport.is_file(), "rapport déposé par le faux Ansible dans le dossier d'exécution");
    let (statut, _, page) = lire(&banc, &cookie, "/install/resultat").await;
    assert_eq!(statut, StatusCode::OK, "{page}");
    assert!(!page.contains(r#"id="rapport-simulation""#), "{page}");
    let section = bloc(&page, r#"id="rapport-bascule""#, "</section>");
    assert!(section.contains("<pre") && section.contains("bmartin, cmoreau"), "{section}");
    assert!(
        (section.contains("Mairie &#60;test&#62;") || section.contains("Mairie &lt;test&gt;"))
            && !section.contains("Mairie <test>"),
        "texte échappé : {section}"
    );
    assert!(contient(bloc(section, r#"id="liens-envoyes""#, "</p>"), "Liens envoyés : 17"), "{section}");
    let sans = bloc(section, r#"id="sans-adresse""#, "</p>");
    assert!(contient(sans, "Sans adresse : 2") && contient(sans, "Service Desk"), "{sans}");
    // Rapport absent : E-012 le dit, sans bloc préformaté.
    std::fs::remove_file(&rapport).unwrap();
    let (_, _, page) = lire(&banc, &cookie, "/install/resultat").await;
    let section = bloc(&page, r#"id="rapport-bascule""#, "</section>");
    assert!(
        contient(section, "Aucun rapport")
            && section.contains("migration/bascule.txt")
            && !section.contains("<pre"),
        "{section}"
    );
    assert!(contient(&page, "Migration basculée"), "{page}");
}

#[tokio::test]
async fn e012_de_l_import_et_de_la_bascule_dit_l_etat() {
    let banc = installe_avec_ad().await;
    let recapitulatifs = std::fs::read_dir(banc.racine().join("home/open-iam")).unwrap().count();
    let (cookie, csrf) = session_assistant(&banc).await;
    operer(&banc, &cookie, &csrf, "simulation").await;
    assert_eq!(migration(&banc, &cookie, &csrf, "import").await.0, StatusCode::NO_CONTENT);
    attendre_fin(&banc).await;
    let (_, _, page) = lire(&banc, &cookie, "/install/resultat").await;
    let phrase = bloc(&page, r#"id="etat-migration-resultat""#, "</p>");
    assert!(phrase.contains("toutes les 15 minutes jusqu") && phrase.contains("bascule"), "{phrase}");
    assert!(!page.contains(r#"id="rapport-simulation""#), "{page}");
    poster(&banc, &cookie, &csrf, "/install/terminer", "").await;
    assert_eq!(migration(&banc, &cookie, &csrf, "bascule").await.0, StatusCode::NO_CONTENT);
    attendre_fin(&banc).await;
    let (_, _, page) = lire(&banc, &cookie, "/install/resultat").await;
    let phrase = bloc(&page, r#"id="etat-migration-resultat""#, "</p>");
    assert!(phrase.contains("peuvent être arrêtés"), "{phrase}");
    poster(&banc, &cookie, &csrf, "/install/terminer", "").await;
    assert_eq!(
        std::fs::read_dir(banc.racine().join("home/open-iam")).unwrap().count(),
        recapitulatifs,
        "aucun récapitulatif"
    );
}