Skip to content
1        10        20        30        40        50        60        70        80        90        100       110       120       130       140       1501use std::{2    collections::HashMap,3    io::Cursor,4    sync::Mutex,5    time::{Duration, Instant},6};78use anyhow::{Context, bail};9use reqwest::Url;1011use crate::{12    api::{ApiBody, ApiMethod, ApiRequest, ApiResponse, ApiRoot, TwigApi},13    api_command::{ApiCommand, ContentCommand, request_for},14    auth::{15        BrowserOpener, DeviceAuthorization, DeviceAuthorizationStart, DevicePollResponse, connect,16    },17    credential::{CredentialOperation, run_credential_helper},18    credential_store::CredentialStore,19    git_config::GitConfigurator,20    server_url::TwigUrl,21    status::{StatusReport, TwigHealth, TwigProbe, TwigVersion, inspect},22};2324pub const SIMULATION_URL: &str = "https://twig.testing.invalid/";25const SIMULATED_TOKEN: &str = "twigt_testing_only";26const SIMULATED_DEVICE_CODE: &str =27    "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";2829pub struct ScriptedDeviceAuthorization {30    verification_uri: String,31    poll_response: Mutex<Option<DevicePollResponse>>,32}3334impl ScriptedDeviceAuthorization {35    pub fn authorized() -> Self {36        Self::with_response(37            "/auth/device",38            DevicePollResponse::Authorized {39                access_token: SIMULATED_TOKEN.to_owned(),40            },41        )42    }4344    fn denied() -> Self {45        Self::with_response("/auth/device", DevicePollResponse::Denied)46    }4748    fn with_response(verification_uri: &str, poll_response: DevicePollResponse) -> Self {49        Self {50            verification_uri: verification_uri.to_owned(),51            poll_response: Mutex::new(Some(poll_response)),52        }53    }54}5556impl DeviceAuthorization for ScriptedDeviceAuthorization {57    async fn start(&self) -> anyhow::Result<DeviceAuthorizationStart> {58        Ok(DeviceAuthorizationStart {59            device_code: SIMULATED_DEVICE_CODE.to_owned(),60            user_code: "WQJH-8K2M".to_owned(),61            verification_uri: self.verification_uri.clone(),62            expires_in: 600,63            interval: 0,64        })65    }6667    async fn poll(&self, _device_code: &str) -> anyhow::Result<DevicePollResponse> {68        self.poll_response69            .lock()70            .expect("simulation response lock")71            .take()72            .context("simulation authorization was polled more than once")73    }7475    fn is_simulation(&self) -> bool {76        true77    }78}7980#[derive(Default)]81pub struct FakeBrowser {82    pub opened: Mutex<Option<Url>>,83}8485impl BrowserOpener for FakeBrowser {86    fn open(&self, url: &Url) -> anyhow::Result<()> {87        *self.opened.lock().expect("simulation browser lock") = Some(url.clone());88        Ok(())89    }90}9192#[derive(Default)]93pub struct FakeCredentialStore {94    tokens: Mutex<HashMap<String, String>>,95}9697impl FakeCredentialStore {98    pub fn with_fake_token(server: &TwigUrl) -> Self {99        let store = Self::default();100        store101            .tokens102            .lock()103            .expect("simulation credential lock")104            .insert(105                server.as_url().as_str().to_owned(),106                SIMULATED_TOKEN.to_owned(),107            );108        store109    }110}111112impl CredentialStore for FakeCredentialStore {113    fn check_available(&self) -> anyhow::Result<()> {114        Ok(())115    }116117    fn get(&self, server: &TwigUrl) -> anyhow::Result<Option<String>> {118        Ok(self119            .tokens120            .lock()121            .expect("simulation credential lock")122            .get(server.as_url().as_str())123            .cloned())124    }125126    fn put(&self, server: &TwigUrl, token: &str) -> anyhow::Result<()> {127        self.tokens128            .lock()129            .expect("simulation credential lock")130            .insert(server.as_url().as_str().to_owned(), token.to_owned());131        Ok(())132    }133134    fn erase(&self, server: &TwigUrl) -> anyhow::Result<()> {135        self.tokens136            .lock()137            .expect("simulation credential lock")138            .remove(server.as_url().as_str());139        Ok(())140    }141}142143#[derive(Default)]144pub struct FakeGitConfigurator {145    configured_servers: Mutex<Vec<String>>,146}147148impl GitConfigurator for FakeGitConfigurator {149    fn check_git_available(&self) -> anyhow::Result<()> {150        Ok(())151    }152153    fn ensure_tree_helper(&self, server: &TwigUrl) -> anyhow::Result<()> {154        self.configured_servers155            .lock()156            .expect("simulation Git lock")157            .push(server.as_url().as_str().to_owned());158        Ok(())159    }160}161162#[derive(Default)]163pub struct FakeTwigStatusProbe;164165impl TwigProbe for FakeTwigStatusProbe {166    async fn health(&self, server: &TwigUrl) -> TwigHealth {167        match server.as_url().host_str() {168            Some("twig.testing.invalid") => TwigHealth::Healthy,169            Some(_) => TwigHealth::UnexpectedStatus(503),170            None => TwigHealth::Unavailable,171        }172    }173174    async fn version(&self, server: &TwigUrl, _token: &str) -> TwigVersion {175        match server.as_url().host_str() {176            Some("twig.testing.invalid") => TwigVersion::Available("0.1.104".to_owned()),177            Some(_) => TwigVersion::UnexpectedStatus(503),178            None => TwigVersion::Unavailable,179        }180    }181}182183pub struct FakeTwigApi {184    token: String,185    pub requests: Mutex<Vec<ApiRequest>>,186}187188impl FakeTwigApi {189    pub fn new(token: String) -> anyhow::Result<Self> {190        if token.is_empty() {191            bail!("simulation API requires its fake token");192        }193        Ok(Self {194            token,195            requests: Mutex::new(Vec::new()),196        })197    }198}199200impl TwigApi for FakeTwigApi {201    async fn execute(&self, request: ApiRequest) -> anyhow::Result<ApiResponse> {202        if self.token != SIMULATED_TOKEN {203            bail!("simulation API rejected a non-simulation credential");204        }205        let (content_type, body) = if request.root == ApiRoot::Root206            && request.path_segments == ["version"]207        {208            ("application/json", br#"{"version":"0.1.104"}"#.to_vec())209        } else if request.path_segments == ["me"] {210            (211                "application/json",212                br#"{"id":1,"username":"simulation","email":"simulation@example.invalid"}"#213                    .to_vec(),214            )215        } else if request.method == ApiMethod::Get216            && request217                .path_segments218                .last()219                .is_some_and(|part| part == "binaries")220        {221            ("application/json", b"[]".to_vec())222        } else if request.path_segments.iter().any(|part| part == "binaries")223            && request.method == ApiMethod::Get224        {225            ("application/octet-stream", vec![0, 255, 10])226        } else if request227            .path_segments228            .last()229            .is_some_and(|part| part == "contents")230            && request.method == ApiMethod::Get231        {232            (233                "application/json",234                br#"{"path":"README.md","reference":"main","encoding":"base64","content":"aGk=","object_id":"simulation-head","size_bytes":2}"#.to_vec(),235            )236        } else if matches!(request.body, ApiBody::Binary(_)) {237            (238                "application/json",239                br#"{"version":"1.0.0","uploaded":true}"#.to_vec(),240            )241        } else {242            (243                "application/json",244                br#"{"ok":true,"simulation":true}"#.to_vec(),245            )246        };247        self.requests248            .lock()249            .expect("simulation API request lock")250            .push(request);251        Ok(ApiResponse {252            status: 200,253            content_type: Some(content_type.to_owned()),254            body,255        })256    }257}258259pub enum ScenarioOutcome {260    Passed,261    Failed(String),262}263264pub struct ScenarioResult {265    pub name: &'static str,266    pub outcome: ScenarioOutcome,267}268269pub struct SimulationSuiteReport {270    pub scenarios: Vec<ScenarioResult>,271    pub elapsed: Duration,272}273274impl SimulationSuiteReport {275    pub fn passed(&self) -> usize {276        self.scenarios277            .iter()278            .filter(|scenario| matches!(scenario.outcome, ScenarioOutcome::Passed))279            .count()280    }281282    pub fn failed(&self) -> usize {283        self.scenarios284            .iter()285            .filter(|scenario| matches!(scenario.outcome, ScenarioOutcome::Failed(_)))286            .count()287    }288289    pub fn print(&self) {290        for scenario in &self.scenarios {291            match &scenario.outcome {292                ScenarioOutcome::Passed => println!("test {} ... ok", scenario.name),293                ScenarioOutcome::Failed(error) => {294                    println!("test {} ... FAILED: {error}", scenario.name);295                }296            }297        }298        println!(299            "Summary [{:.3}s] {} tests run: {} passed, {} failed, 0 skipped",300            self.elapsed.as_secs_f64(),301            self.scenarios.len(),302            self.passed(),303            self.failed()304        );305    }306307    pub fn ensure_success(&self) -> anyhow::Result<()> {308        if self.failed() > 0 {309            bail!("{} simulation scenario(s) failed", self.failed());310        }311        Ok(())312    }313}314315pub async fn run_simulation_suite() -> SimulationSuiteReport {316    let started = Instant::now();317    let scenarios = vec![318        scenario_result(319            "successful_authorization_stores_fake_token_and_requests_git_setup",320            run_successful_authorization().await,321        ),322        scenario_result(323            "denied_authorization_does_not_store_or_configure",324            run_denied_authorization().await,325        ),326        scenario_result(327            "cross_origin_verification_url_is_rejected_before_side_effects",328            run_cross_origin_rejection().await,329        ),330        scenario_result(331            "credential_get_returns_token_only_for_matching_server_and_path",332            run_credential_get(),333        ),334        scenario_result(335            "credential_erase_removes_only_the_matching_fake_entry",336            run_credential_erase(),337        ),338        scenario_result(339            "credential_store_discards_git_supplied_password",340            run_credential_store(),341        ),342        scenario_result(343            "status_reports_fake_authentication_twig_health_and_version",344            run_status().await,345        ),346        scenario_result(347            "api_identity_read_uses_fake_credentials_and_transport",348            run_api_identity().await,349        ),350        scenario_result(351            "api_content_mutation_keeps_expected_head_in_fake_transport",352            run_api_content_mutation().await,353        ),354        scenario_result(355            "api_binary_download_returns_original_fake_bytes",356            run_api_binary_download().await,357        ),358    ];359360    SimulationSuiteReport {361        scenarios,362        elapsed: started.elapsed(),363    }364}365366fn scenario_result(name: &'static str, result: anyhow::Result<()>) -> ScenarioResult {367    ScenarioResult {368        name,369        outcome: match result {370            Ok(()) => ScenarioOutcome::Passed,371            Err(error) => ScenarioOutcome::Failed(format!("{error:#}")),372        },373    }374}375376async fn run_successful_authorization() -> anyhow::Result<()> {377    let server = TwigUrl::parse(SIMULATION_URL)?;378    let authorization = ScriptedDeviceAuthorization::authorized();379    let browser = FakeBrowser::default();380    let credentials = FakeCredentialStore::default();381    let git = FakeGitConfigurator::default();382383    connect(server.clone(), &authorization, &browser, &credentials, &git).await?;384385    let token = credentials386        .get(&server)?387        .context("simulated auth flow did not store its token")?;388    if token != SIMULATED_TOKEN {389        bail!("simulated auth flow stored an unexpected token");390    }391    let opened = browser392        .opened393        .lock()394        .expect("simulation browser lock")395        .clone()396        .context("simulated auth flow did not request browser opening")?;397    if opened.path() != "/auth/device" {398        bail!("simulated auth flow opened an unexpected verification path");399    }400    if opened401        .query_pairs()402        .find(|(key, _)| key == "user_code")403        .map(|(_, value)| value)404        .as_deref()405        != Some("WQJH-8K2M")406    {407        bail!("simulated auth flow did not include its user code in the URL");408    }409    let configured = git.configured_servers.lock().expect("simulation Git lock");410    if configured.as_slice() != [SIMULATION_URL] {411        bail!("simulated auth flow did not request scoped Git setup");412    }413    Ok(())414}415416async fn run_denied_authorization() -> anyhow::Result<()> {417    let server = TwigUrl::parse(SIMULATION_URL)?;418    let authorization = ScriptedDeviceAuthorization::denied();419    let browser = FakeBrowser::default();420    let credentials = FakeCredentialStore::default();421    let git = FakeGitConfigurator::default();422423    let result = connect(server.clone(), &authorization, &browser, &credentials, &git).await;424    let error = result425        .expect_err("denied authorization unexpectedly succeeded")426        .to_string();427    if !error.contains("was denied") {428        bail!("denied authorization returned an unexpected error: {error}");429    }430    if credentials.get(&server)?.is_some() {431        bail!("denied authorization stored a token");432    }433    if !git434        .configured_servers435        .lock()436        .expect("simulation Git lock")437        .is_empty()438    {439        bail!("denied authorization configured Git");440    }441    Ok(())442}443444async fn run_cross_origin_rejection() -> anyhow::Result<()> {445    let server = TwigUrl::parse(SIMULATION_URL)?;446    let authorization = ScriptedDeviceAuthorization::with_response(447        "https://attacker.example/auth/device",448        DevicePollResponse::Authorized {449            access_token: SIMULATED_TOKEN.to_owned(),450        },451    );452    let browser = FakeBrowser::default();453    let credentials = FakeCredentialStore::default();454    let git = FakeGitConfigurator::default();455456    let error = connect(server.clone(), &authorization, &browser, &credentials, &git)457        .await458        .expect_err("cross-origin verification URL was accepted")459        .to_string();460    if !error.contains("different origin") {461        bail!("cross-origin verification URL returned an unexpected error: {error}");462    }463    if browser464        .opened465        .lock()466        .expect("simulation browser lock")467        .is_some()468    {469        bail!("cross-origin verification URL reached the browser adapter");470    }471    if credentials.get(&server)?.is_some()472        || !git473            .configured_servers474            .lock()475            .expect("simulation Git lock")476            .is_empty()477    {478        bail!("cross-origin verification URL caused a credential or Git side effect");479    }480    Ok(())481}482483async fn run_status() -> anyhow::Result<()> {484    let server = TwigUrl::parse(SIMULATION_URL)?;485    let credentials = FakeCredentialStore::with_fake_token(&server);486    let probe = FakeTwigStatusProbe;487    let report = inspect(&server, &credentials, &probe).await?;488    let expected = StatusReport {489        authenticated: true,490        twig: TwigHealth::Healthy,491        version: TwigVersion::Available("0.1.104".to_owned()),492    };493    if report != expected {494        bail!(495            "status returned an unexpected simulated report: {}",496            report.render()497        );498    }499    if report.render()500        != "Authentication: authenticated\nTwig /up: healthy (HTTP 200)\nTwig /api/version: 0.1.104"501    {502        bail!("status output did not include all simulated results");503    }504    Ok(())505}506507fn fake_api(server: &TwigUrl) -> anyhow::Result<FakeTwigApi> {508    let credentials = FakeCredentialStore::with_fake_token(server);509    let token = credentials510        .get(server)?511        .context("simulation credential store did not return its fake token")?;512    FakeTwigApi::new(token)513}514515async fn run_api_identity() -> anyhow::Result<()> {516    let server = TwigUrl::parse(SIMULATION_URL)?;517    let api = fake_api(&server)?;518    let request = request_for(&ApiCommand::Me)?;519    let response = api.execute(request).await?.ensure_success()?;520    let identity: serde_json::Value = serde_json::from_slice(&response.body)?;521    if identity["username"] != "simulation" {522        bail!("fake API returned an unexpected identity");523    }524    if api525        .requests526        .lock()527        .expect("simulation API request lock")528        .len()529        != 1530    {531        bail!("identity command did not make exactly one fake API call");532    }533    Ok(())534}535536async fn run_api_content_mutation() -> anyhow::Result<()> {537    let server = TwigUrl::parse(SIMULATION_URL)?;538    let api = fake_api(&server)?;539    let request = request_for(&ApiCommand::Content(ContentCommand::Put {540        namespace: "acme".into(),541        repository: "tooling".into(),542        reference: "main".into(),543        path: "README.md".into(),544        text: Some("hello\n".into()),545        file: None,546        message: "Update README".into(),547        expected_head: "simulation-head".into(),548    }))?;549    let ApiBody::Json(body) = &request.body else {550        bail!("content mutation did not create a JSON request");551    };552    if body["expected_head"] != "simulation-head" || body["encoding"] != "utf8" {553        bail!("content mutation omitted its concurrency guard or encoding");554    }555    api.execute(request).await?.ensure_success()?;556    Ok(())557}558559async fn run_api_binary_download() -> anyhow::Result<()> {560    let server = TwigUrl::parse(SIMULATION_URL)?;561    let api = fake_api(&server)?;562    let request = ApiRequest::new(563        ApiMethod::Get,564        [565            "namespaces",566            "acme",567            "repositories",568            "tooling",569            "binaries",570            "latest",571            "tool",572        ]573        .into_iter()574        .map(str::to_owned)575        .collect(),576    );577    let response = api.execute(request).await?.ensure_success()?;578    if response.body != [0, 255, 10] {579        bail!(580            "fake API did not preserve arbitrary binary bytes: {:?}",581            response.body582        );583    }584    Ok(())585}586587fn run_credential_get() -> anyhow::Result<()> {588    let server = TwigUrl::parse("https://twig.testing.invalid/twig/")?;589    let credentials = FakeCredentialStore::with_fake_token(&server);590    let request = "protocol=https\nhost=twig.testing.invalid\npath=twig/ns/repo.git\n\n";591    let mut output = Vec::new();592    run_credential_helper(593        CredentialOperation::Get,594        &server,595        Cursor::new(request),596        &mut output,597        &credentials,598    )?;599    let output = String::from_utf8(output).context("credential helper output was not UTF-8")?;600    if output != format!("username=tree\npassword={SIMULATED_TOKEN}\n\n") {601        bail!("matching credential request did not return the fake token");602    }603604    let mut wrong_path_output = Vec::new();605    run_credential_helper(606        CredentialOperation::Get,607        &server,608        Cursor::new("protocol=https\nhost=twig.testing.invalid\npath=other/repo.git\n\n"),609        &mut wrong_path_output,610        &credentials,611    )?;612    if !wrong_path_output.is_empty() {613        bail!("credential helper returned a token for a nonmatching path");614    }615616    let mut wrong_server_output = Vec::new();617    run_credential_helper(618        CredentialOperation::Get,619        &server,620        Cursor::new("protocol=https\nhost=other.testing.invalid\npath=ns/repo.git\n\n"),621        &mut wrong_server_output,622        &credentials,623    )?;624    if !wrong_server_output.is_empty() {625        bail!("credential helper returned a token for a nonmatching server");626    }627    Ok(())628}629630fn run_credential_erase() -> anyhow::Result<()> {631    let server = TwigUrl::parse(SIMULATION_URL)?;632    let other = TwigUrl::parse("https://other.testing.invalid/")?;633    let credentials = FakeCredentialStore::with_fake_token(&server);634    credentials.put(&other, "twigt_other_fake")?;635636    run_credential_helper(637        CredentialOperation::Erase,638        &server,639        Cursor::new("protocol=https\nhost=twig.testing.invalid\npath=ns/repo.git\n\n"),640        Vec::new(),641        &credentials,642    )?;643    if credentials.get(&server)?.is_some() {644        bail!("credential erase kept the matching fake token");645    }646    if credentials.get(&other)?.as_deref() != Some("twigt_other_fake") {647        bail!("credential erase removed an unrelated fake token");648    }649    Ok(())650}651652fn run_credential_store() -> anyhow::Result<()> {653    let server = TwigUrl::parse(SIMULATION_URL)?;654    let credentials = FakeCredentialStore::default();655    run_credential_helper(656        CredentialOperation::Store,657        &server,658        Cursor::new(659            "protocol=https\nhost=twig.testing.invalid\nusername=someone\npassword=plaintext\n\n",660        ),661        Vec::new(),662        &credentials,663    )?;664    if credentials.get(&server)?.is_some() {665        bail!("credential store persisted a Git-supplied password");666    }667    Ok(())668}669670#[cfg(test)]671mod tests {672    use super::*;673674    #[tokio::test]675    async fn suite_runs_all_ten_scenarios() {676        let report = run_simulation_suite().await;677678        assert_eq!(report.scenarios.len(), 10);679        assert_eq!(report.passed(), 10);680        assert_eq!(report.failed(), 0);681        report682            .ensure_success()683            .expect("all simulation scenarios pass");684    }685686    #[test]687    fn suite_report_fails_if_any_scenario_failed() {688        let report = SimulationSuiteReport {689            scenarios: vec![ScenarioResult {690                name: "injected_failure",691                outcome: ScenarioOutcome::Failed("expected test failure".to_owned()),692            }],693            elapsed: Duration::ZERO,694        };695696        assert_eq!(report.passed(), 0);697        assert_eq!(report.failed(), 1);698        assert!(report.ensure_success().is_err());699    }700}