Luigit
repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by admin

smith-harness/src/oauth/lifecycle_tests.rs

Raw
//! Rotating refresh crash boundaries (`SMH-SPEC-SPEC0001`, `SMH-SPEC-PLUG0001`).
use super::*;
use serde_json::json;
use std::path::PathBuf;
use std::sync::mpsc;

const DEADLINE: Duration = Duration::from_secs(3);

fn stored(issuer: &str) -> (PathBuf, ProfileStore, LoginPolicy) {
    let root = std::env::temp_dir().join(format!("oauth-rotation-{}", smith::id::SessionId::new()));
    let store = ProfileStore::at(root.clone());
    store.host_id().unwrap();
    let policy = LoginPolicy {
        flow: super::LoginFlow::DynamicOidc,
        connection_id: "openai-chatgpt-plan".into(),
        token_origin: issuer.into(),
        issuer: issuer.into(),
        resource: format!("{issuer}/v1"),
        initial_client: "dynamic_agent_client".into(),
        issued_prefix: "oaiapp_".into(),
        authorization_path: "/authorize".into(),
        token_path: "/token".into(),
        agent_name: "Smith".into(),
        scopes: vec!["openid".into(), "chatgpt.tokens.use.direct".into()],
        required_scopes: vec!["openid".into(), "chatgpt.tokens.use.direct".into()],
    };
    store
        .save(Profile {
            metadata: ProfileMetadata {
                flow: super::LoginFlow::DynamicOidc,
                connection_id: "openai-chatgpt-plan".into(),
                id: "a".repeat(64),
                issuer: issuer.into(),
                subject: "subject".into(),
                client_id: "oaiapp_fixture".into(),
                workspace: None,
                code_assist_project: None,
                label: "fixture".into(),
                scopes: policy.scopes.clone(),
                expires_at: 0,
            },
            tokens: Some(TokenSet {
                access: "fixture-old-access".into(),
                refresh: "fixture-old-refresh".into(),
                identity: "fixture-old-identity".into(),
            }),
            refresh_pending: false,
        })
        .unwrap();
    (root, store, policy)
}

fn accept(listener: &TcpListener) -> (TcpStream, String) {
    let (mut stream, _) = listener.accept().unwrap();
    stream.set_read_timeout(Some(DEADLINE)).unwrap();
    stream.set_write_timeout(Some(DEADLINE)).unwrap();
    let mut bytes = Vec::new();
    loop {
        let mut byte = [0];
        stream.read_exact(&mut byte).unwrap();
        bytes.push(byte[0]);
        assert!(bytes.len() <= 8192);
        if bytes.ends_with(b"\r\n\r\n") {
            break;
        }
    }
    let head = String::from_utf8(bytes).unwrap();
    let length = head
        .lines()
        .filter_map(|line| line.split_once(':'))
        .find(|(name, _)| name.eq_ignore_ascii_case("content-length"))
        .map_or(0, |(_, length)| length.trim().parse::<usize>().unwrap());
    assert!(length <= 8192);
    let mut body = vec![0; length];
    stream.read_exact(&mut body).unwrap();
    (stream, head + &String::from_utf8(body).unwrap())
}

fn respond(stream: &mut TcpStream, status: &str, value: &Value) {
    let bytes = serde_json::to_vec(value).unwrap();
    write!(
        stream,
        "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
        bytes.len()
    )
    .unwrap();
    stream.write_all(&bytes).unwrap();
}

#[test]
fn refresh_pending_precedes_dispatch_serializes_parallel_calls_and_prevents_replay_after_response_loss()
 {
    for invalid_grant in [false, true] {
        let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)).unwrap();
        let issuer = format!("http://{}", listener.local_addr().unwrap());
        let (root, store, policy) = stored(&issuer);
        let (sent, dispatched) = mpsc::sync_channel(1);
        let (release, released) = mpsc::sync_channel(1);
        let server = std::thread::spawn(move || {
            let (mut stream, request) = accept(&listener);
            assert!(request.starts_with("GET /.well-known/openid-configuration "));
            respond(
                &mut stream,
                "200 OK",
                &json!({"issuer":issuer,"jwks_uri":format!("{issuer}/keys")}),
            );
            drop(stream);
            let (mut stream, request) = accept(&listener);
            assert!(request.starts_with("POST /token "));
            assert!(request.contains("refresh_token=fixture-old-refresh"));
            sent.send(()).unwrap();
            released.recv_timeout(DEADLINE).unwrap();
            if invalid_grant {
                respond(
                    &mut stream,
                    "400 Bad Request",
                    &json!({"error":"invalid_grant"}),
                );
            }
            drop(stream);
            listener
        });
        let worker_store = store.clone();
        let worker_policy = policy.clone();
        let worker = std::thread::spawn(move || {
            worker_store.renew(&"a".repeat(64), &worker_policy, &CancelHandle::new())
        });
        dispatched.recv_timeout(DEADLINE).unwrap();
        let bytes = std::fs::read(root.join("profiles.json")).unwrap();
        let pending: Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(pending["profiles"][0]["refresh_pending"], true);
        assert!(matches!(
            store.renew(&"a".repeat(64), &policy, &CancelHandle::new()),
            Err(AuthorizationFault::Storage(
                "OAuth profile store busy; no exchange started"
            ))
        ));
        release.send(()).unwrap();
        assert_eq!(
            worker.join().unwrap().err().unwrap(),
            if invalid_grant {
                AuthorizationFault::ReauthenticationRequired
            } else {
                AuthorizationFault::ExchangeUncertain
            }
        );
        let listener = server.join().unwrap();
        assert_eq!(
            store
                .renew(&"a".repeat(64), &policy, &CancelHandle::new())
                .err()
                .unwrap(),
            AuthorizationFault::ReauthenticationRequired
        );
        listener.set_nonblocking(true).unwrap();
        assert_eq!(
            listener.accept().err().unwrap().kind(),
            std::io::ErrorKind::WouldBlock
        );
        let reopened: Value =
            serde_json::from_slice(&std::fs::read(root.join("profiles.json")).unwrap()).unwrap();
        assert_eq!(reopened["profiles"][0]["refresh_pending"], true);
        assert_eq!(reopened["profiles"][0]["tokens"].is_null(), invalid_grant);
        assert_eq!(store.list().unwrap().len(), 1);
        std::fs::remove_dir_all(root).unwrap();
    }
}

#[test]
fn renewable_module_policy_must_match_selected_host_authority_before_io() {
    let (root, store, policy) = stored("https://issuer.example");
    let mut authority = LoginAuthority::new(policy.clone(), store)
        .unwrap()
        .select_profile(&"a".repeat(64))
        .unwrap();
    authority.begin_dispatch(CancelHandle::new());
    let mut foreign = policy;
    foreign.resource = "https://foreign.example/v1".into();
    assert_eq!(
        authority
            .renew_for_dispatch(&"a".repeat(64), &foreign)
            .unwrap_err(),
        AuthorizationFault::Authority
    );
    assert!(authority.take_credential().is_none());
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn logout_after_preflight_still_blocks_renewal_without_network() {
    let (root, store, policy) = stored("https://issuer.example");
    let id = "a".repeat(64);
    store.renewable_profile_available(&id).unwrap();

    let path = root.join("profiles.json");
    let mut profile: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
    profile["profiles"][0]["tokens"] = Value::Null;
    std::fs::write(&path, serde_json::to_vec(&profile).unwrap()).unwrap();

    assert!(matches!(
        store.renew(&id, &policy, &CancelHandle::new()),
        Err(AuthorizationFault::ReauthenticationRequired)
    ));
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn unexpired_identity_only_profile_cannot_dispatch_plan_usage() {
    let (root, store, policy) = stored("https://issuer.example");
    let path = root.join("profiles.json");
    let mut profile: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
    profile["profiles"][0]["metadata"]["expires_at"] = json!(4_102_444_800_u64);
    profile["profiles"][0]["metadata"]["scopes"] = json!(["openid"]);
    std::fs::write(&path, serde_json::to_vec(&profile).unwrap()).unwrap();
    assert!(matches!(
        store.renew(&"a".repeat(64), &policy, &CancelHandle::new()),
        Err(AuthorizationFault::ReauthenticationRequired)
    ));
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn malformed_or_legacy_host_identity_fails_actionably_without_replacing_host() {
    let (root, store, _) = stored("https://issuer.example");
    let path = root.join("profiles.json");
    let mut value: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
    for identity in [
        "12345678-1234-4234-8234-123456789012",
        "urn:uuid:zzzzzzzz-1234-4234-8234-123456789012",
        "urn:uuid:12345678-1234-1234-8234-123456789012",
    ] {
        value["host_id"] = json!(identity);
        let bytes = serde_json::to_vec(&value).unwrap();
        std::fs::write(&path, &bytes).unwrap();
        assert!(
            store
                .host_id()
                .err()
                .unwrap()
                .contains("restore the original store")
        );
        assert_eq!(std::fs::read(&path).unwrap(), bytes);
    }
    #[cfg(target_arch = "x86_64")]
    {
        assert_eq!(std::mem::size_of::<AuthorizationFault>(), 24);
        assert_eq!(std::mem::size_of::<TokenSet>(), 72);
        assert_eq!(
            std::mem::size_of::<crate::protocol::ResolvedCredential>(),
            72
        );
    }
    std::fs::remove_dir_all(root).unwrap();
}