cpa-exec 0.4.2

Part of cliproxy: upstream provider executors
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! Expected values come from `tests/fixtures/codex_go.json`, generated by running the Go
//! Codex OAuth service and executor refresh against the same scripted mock replies.

use super::*;
use crate::codex_testkit::{GO, Mock, json};
use std::path::Path;

fn go_exchange(name: &str) -> &'static Value {
    GO["oauth"]["exchanges"]
        .as_array()
        .unwrap()
        .iter()
        .find(|e| e["name"] == name)
        .unwrap_or_else(|| panic!("fixture {name}"))
}

fn token_body() -> String {
    format!(
        r#"{{"access_token":"at-FAKE","refresh_token":"rt-FAKE-2","id_token":{},"token_type":"Bearer","expires_in":3600}}"#,
        serde_json::to_string(GO["oauth"]["id_token"].as_str().unwrap()).unwrap()
    )
}

/// The request fields Go's client puts on the wire (headers it sets plus its transport's
/// Accept-Encoding and default User-Agent).
fn assert_same_request(rust: &crate::codex_testkit::Captured, go: &Value) {
    assert_eq!(rust.method, go["method"].as_str().unwrap());
    assert_eq!(rust.path, go["path"].as_str().unwrap());
    assert_eq!(String::from_utf8_lossy(&rust.body), go["body"].as_str().unwrap());
    for name in ["content-type", "accept", "user-agent", "accept-encoding"] {
        assert_eq!(rust.header(name), go["headers"][name][0].as_str().unwrap(), "{name}");
    }
}

fn tokens_json(t: &Tokens) -> Value {
    json!({"id_token": t.id_token, "access_token": t.access_token, "refresh_token": t.refresh_token,
        "account_id": t.account_id, "email": t.email, "plan_type": t.plan_type})
}

async fn oauth(mock: &Mock) -> CodexOAuth {
    CodexOAuth::with_endpoints(
        wreq::Client::new(),
        &format!("{}/oauth/token", mock.url),
        &format!("{}/api/accounts/deviceauth/usercode", mock.url),
        &format!("{}/api/accounts/deviceauth/token", mock.url),
    )
    .with_retry_delay(Duration::from_millis(1))
}

#[test]
fn jwt_claims_file_names_and_authorize_url_match_go() {
    for case in GO["oauth"]["jwt"].as_array().unwrap() {
        let parsed = parse_jwt(case["token"].as_str().unwrap());
        assert_eq!(parsed.is_some(), case["ok"].as_bool().unwrap(), "{case}");
        if let Some(c) = parsed {
            assert_eq!(c.email, case["email"].as_str().unwrap());
            assert_eq!(c.account_id, case["account_id"].as_str().unwrap());
            assert_eq!(c.plan_type(), case["plan_type"].as_str().unwrap());
        }
    }
    for case in GO["oauth"]["file_names"].as_array().unwrap() {
        let s = |k: &str| case[k].as_str().unwrap();
        assert_eq!(credential_file_name(s("email"), s("plan"), s("hash")), s("out"));
    }
    assert_eq!(
        authorize_url("state-FAKE", "challenge-FAKE", DEFAULT_CALLBACK_PORT),
        GO["oauth"]["auth_url"].as_str().unwrap()
    );
}

#[test]
fn login_file_bytes_match_go_storage_serializer() {
    let tokens = Tokens {
        id_token: GO["oauth"]["id_token"].as_str().unwrap().into(),
        access_token: "at-<FAKE>&".into(),
        refresh_token: "rt-FAKE-2".into(),
        account_id: "acct-FAKE-1".into(),
        email: "user@example.invalid".into(),
        plan_type: "Pro Plus".into(),
        expired: "2026-10-12T12:00:00Z".into(),
    };
    let (name, record) = login_record(&tokens, "2026-10-02T12:00:00Z").unwrap();
    assert_eq!(
        encode_go_json(&Value::Object(record)),
        GO["oauth"]["auth_file"].as_str().unwrap()
    );
    let device = go_exchange("device");
    assert_eq!(name, device["result"]["id"].as_str().unwrap());
}

#[tokio::test]
async fn existing_file_keeps_user_fields_but_never_old_tokens() {
    let dir = std::env::temp_dir().join(format!("codex-login-{}", random_state().unwrap()));
    let tokens = Tokens {
        id_token: String::new(),
        access_token: "at-new".into(),
        refresh_token: "rt-new".into(),
        account_id: String::new(),
        email: "user@example.invalid".into(),
        plan_type: String::new(),
        expired: "2026-10-12T12:00:00Z".into(),
    };
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("codex-user@example.invalid-free.json");
    std::fs::write(
        &path,
        r#"{"access_token":"at-old","prefix":"team","disabled":true,"note":"mine"}"#,
    )
    .unwrap();
    let written = write_login(&dir, &tokens).unwrap();
    assert_eq!(written, path);
    let saved: Map<String, Value> = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
    assert_eq!(saved["access_token"], "at-new");
    assert_eq!(saved["prefix"], "team");
    assert_eq!(saved["note"], "mine");
    assert_eq!(
        saved["disabled"], true,
        "re-login keeps an explicitly disabled account disabled"
    );
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
    }
    std::fs::remove_dir_all(dir).unwrap();
}

#[tokio::test]
async fn exchange_and_refresh_wire_and_results_match_go() {
    let mock = Mock::start().await;
    let oauth = oauth(&mock).await;
    mock.script("/oauth/token", vec![json(200, &token_body())]);
    let tokens = oauth
        .exchange("code-FAKE", &redirect_uri(DEFAULT_CALLBACK_PORT), "verifier-FAKE")
        .await
        .unwrap();
    let go = go_exchange("exchange");
    assert_same_request(&mock.take()[0], &go["requests"][0]);
    assert_eq!(tokens_json(&tokens), go["result"]);

    mock.script("/oauth/token", vec![json(200, &token_body())]);
    let tokens = oauth.refresh("rt-FAKE-1").await.unwrap();
    let go = go_exchange("refresh");
    assert_same_request(&mock.take()[0], &go["requests"][0]);
    assert_eq!(tokens_json(&tokens), go["result"]);
}

#[tokio::test]
async fn refresh_retry_policy_matches_go_attempt_counts() {
    let mock = Mock::start().await;
    for (name, replies, refresh) in [
        (
            "refresh_retry",
            vec![json(500, r#"{"error":"server_error"}"#), json(200, &token_body())],
            "rt-a",
        ),
        (
            "refresh_reused",
            vec![
                json(400, r#"{"error":"refresh_token_reused"}"#),
                json(200, &token_body()),
            ],
            "rt-b",
        ),
        (
            "refresh_invalid_grant",
            vec![json(400, r#"{"error":"invalid_grant"}"#); 3],
            "rt-c",
        ),
    ] {
        let oauth = oauth(&mock).await;
        mock.script("/oauth/token", replies);
        let result = oauth.refresh(refresh).await;
        let go = go_exchange(name);
        assert_eq!(
            mock.take().len(),
            go["requests"].as_array().unwrap().len(),
            "{name} attempts"
        );
        match go["error"].as_str() {
            None => assert!(result.is_ok(), "{name}"),
            Some(go_error) => {
                let error = result.unwrap_err();
                let text = String::from_utf8_lossy(&error.body).into_owned();
                // Go appends the raw body; only its OAuth error code is kept here.
                let prefix = go_error.split(": {").next().unwrap();
                assert!(text.starts_with(prefix), "{name}: {text} vs {go_error}");
                assert_eq!(error.status, 401, "a rejected grant marks the credential unusable");
                assert_eq!(error.scope, FailureScope::Credential);
            }
        }
    }
}

/// Go reports `failed to parse token response: <decoder error>`; the decoder can quote
/// response values, so only Go's prefix is reported.
#[tokio::test]
async fn token_parse_failure_keeps_go_prefix_without_the_decoder_diagnostic() {
    let mock = Mock::start().await;
    let oauth = oauth(&mock).await;
    mock.script(
        "/oauth/token",
        vec![json(
            200,
            r#"{"access_token":"at-SECRET-FAKE","expires_in":"rt-SECRET-FAKE"}"#,
        )],
    );
    let error = oauth
        .exchange("code-FAKE", &redirect_uri(DEFAULT_CALLBACK_PORT), "verifier-FAKE")
        .await
        .unwrap_err();
    assert_eq!(String::from_utf8_lossy(&error.body), "failed to parse token response");
    assert_eq!(error.status, 502);
}

#[tokio::test]
async fn concurrent_refreshes_of_one_token_share_one_exchange() {
    let mock = Mock::start().await;
    let oauth = oauth(&mock).await;
    mock.script("/oauth/token", vec![json(200, &token_body())]);
    let results = futures_util::future::join_all((0..8).map(|_| oauth.refresh("rt-shared"))).await;
    assert!(results.iter().all(|r| r.as_ref().unwrap().refresh_token == "rt-FAKE-2"));
    assert_eq!(mock.take().len(), 1);
}

#[tokio::test]
async fn device_flow_polls_through_pending_and_exchanges_like_go() {
    let mock = Mock::start().await;
    let oauth = oauth(&mock).await;
    mock.script(
        "/api/accounts/deviceauth/usercode",
        vec![json(
            200,
            r#"{"device_auth_id":"dev-FAKE","usercode":"ABCD-EFGH","interval":"1"}"#,
        )],
    );
    mock.script(
        "/api/accounts/deviceauth/token",
        vec![
            json(403, "{}"),
            json(
                200,
                r#"{"authorization_code":"devcode-FAKE","code_verifier":"devverifier-FAKE","code_challenge":"devchallenge"}"#,
            ),
        ],
    );
    mock.script("/oauth/token", vec![json(200, &token_body())]);
    let code = oauth.device_code().await.unwrap();
    assert_eq!(code.interval, Duration::from_secs(1));
    let tokens = oauth.device_poll(&code, Duration::from_secs(5)).await.unwrap();
    let go = go_exchange("device");
    let captured = mock.take();
    assert_eq!(captured.len(), go["requests"].as_array().unwrap().len());
    for (rust, go) in captured.iter().zip(go["requests"].as_array().unwrap()) {
        assert_same_request(rust, go);
    }
    let (name, record) = login_record(&tokens, "t").unwrap();
    assert_eq!(name, go["result"]["id"].as_str().unwrap());
    assert_eq!(record["plan_type"], go["result"]["metadata"]["plan_type"]);
}

#[tokio::test]
async fn refresh_patch_matches_go_executor_refresh() {
    let mock = Mock::start().await;
    let oauth = oauth(&mock).await;
    mock.script("/oauth/token", vec![json(200, &token_body())]);
    let mut metadata: Map<String, Value> = serde_json::from_value(json!({
        "type": "codex", "refresh_token": "rt-FAKE-1", "access_token": "old",
        "email": "old@example.invalid", "custom": "kept"
    }))
    .unwrap();
    oauth.refresh_patch("rt-FAKE-1").await.unwrap().apply(&mut metadata);
    for key in ["expired", "last_refresh"] {
        let value = metadata[key].as_str().unwrap();
        assert!(DateTime::parse_from_rfc3339(value).is_ok(), "{key}={value}");
        metadata.insert(key.into(), "<time>".into());
    }
    assert_eq!(Value::Object(metadata), go_exchange("executor_refresh")["result"]);
}

fn credential(meta: Value) -> Credential {
    Credential::from_file(
        Path::new("/fake"),
        Path::new("/fake/codex.json"),
        meta.as_object().unwrap().clone(),
    )
    .unwrap()
}

fn jwt_with_exp(exp: i64) -> String {
    let engine = base64::engine::general_purpose::URL_SAFE_NO_PAD;
    format!(
        "{}.{}.sig",
        engine.encode(r#"{"alg":"none"}"#),
        engine.encode(format!(r#"{{"exp":{exp}}}"#))
    )
}

#[test]
fn refresh_due_uses_jwt_exp_before_metadata_and_a_96h_lead() {
    let now = Utc::now();
    let soon = (now + chrono::TimeDelta::hours(95)).timestamp();
    let later = (now + chrono::TimeDelta::hours(97)).timestamp();
    let far = (now + chrono::TimeDelta::days(9)).to_rfc3339();
    // JWT exp wins over a distant metadata expiry.
    let c = credential(json!({"type":"codex","refresh_token":"r","access_token":jwt_with_exp(soon),"expired":far}));
    assert!(refresh_due(&c, now));
    let c = credential(json!({"type":"codex","refresh_token":"r","access_token":jwt_with_exp(later)}));
    assert!(!refresh_due(&c, now));
    let c = credential(json!({"type":"codex","refresh_token":"r","access_token":"opaque","expired":far}));
    assert!(!refresh_due(&c, now));
    let c = credential(json!({"type":"codex","access_token":jwt_with_exp(soon)}));
    assert!(!refresh_due(&c, now), "no refresh token, nothing to do");
    let c = credential(
        json!({"type":"codex","refresh_token":"r","access_token":"opaque","last_refresh":(now - chrono::TimeDelta::hours(97)).to_rfc3339()}),
    );
    assert!(refresh_due(&c, now));
    let c =
        credential(json!({"type":"codex","refresh_token":"r","access_token":"opaque","last_refresh":now.to_rfc3339()}));
    assert!(!refresh_due(&c, now));
    let c = credential(json!({"type":"codex","refresh_token":"r","access_token":"opaque"}));
    assert!(refresh_due(&c, now), "no expiry and no last refresh");
    // Millisecond and numeric-string expiries normalise like Go's parseTimeValue.
    let c = credential(
        json!({"type":"codex","refresh_token":"r","access_token":"opaque","expired":(now.timestamp()+3600)*1000}),
    );
    assert!(refresh_due(&c, now));
    assert!(access_usable(&c, now));
    let c = credential(json!({"type":"codex","access_token":"opaque","expired":(now.timestamp()-5).to_string()}));
    assert!(!access_usable(&c, now));
}

#[test]
fn callback_routes_match_go_listener() {
    // Go's handler trims the issued SIWC client ID, not the code or state.
    let (response, result) =
        route_callback(b"GET /auth/callback?code=c1&state=s1&client_id=%20cid%20 HTTP/1.1\r\n\r\n");
    assert!(response.starts_with("HTTP/1.1 302 Found") && response.contains("Location: /success"));
    assert_eq!(
        result,
        Some(Callback {
            code: "c1".into(),
            state: "s1".into(),
            error: None,
            client_id: "cid".into(),
        })
    );
    let (response, result) = route_callback(b"GET /auth/callback?error=access_denied HTTP/1.1\r\n\r\n");
    assert!(response.starts_with("HTTP/1.1 400") && response.contains("OAuth error: access_denied"));
    assert_eq!(result.unwrap().error.as_deref(), Some("access_denied"));
    assert_eq!(
        route_callback(b"GET /auth/callback?code=c HTTP/1.1\r\n\r\n")
            .1
            .unwrap()
            .error
            .as_deref(),
        Some("no_state")
    );
    assert!(
        route_callback(b"POST /auth/callback?code=c&state=s HTTP/1.1\r\n\r\n")
            .0
            .starts_with("HTTP/1.1 405")
    );
    assert!(
        route_callback(b"GET /success HTTP/1.1\r\n\r\n")
            .0
            .contains("Authentication")
    );
    assert!(
        route_callback(b"GET /other HTTP/1.1\r\n\r\n")
            .0
            .starts_with("HTTP/1.1 404")
    );
}

#[test]
fn pasted_callbacks_parse_like_go() {
    for case in GO["oauth"]["callbacks"].as_array().unwrap() {
        let parsed = parse_manual_callback(case["input"].as_str().unwrap());
        assert_eq!(parsed.is_ok(), case["ok"].as_bool().unwrap(), "{case}");
        if let Ok(parsed) = parsed {
            assert_eq!(parsed.code, case["code"].as_str().unwrap(), "{case}");
            assert_eq!(parsed.state, case["state"].as_str().unwrap(), "{case}");
            assert_eq!(
                parsed.error.unwrap_or_default(),
                case["error"].as_str().unwrap(),
                "{case}"
            );
        }
    }
}

#[tokio::test]
async fn existing_non_boolean_disabled_is_reset_like_go() {
    let dir = std::env::temp_dir().join(format!("codex-login-{}", random_state().unwrap()));
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("codex-u@example.invalid-free.json");
    std::fs::write(&path, r#"{"disabled":"true"}"#).unwrap();
    let tokens = Tokens {
        id_token: String::new(),
        access_token: "a".into(),
        refresh_token: "r".into(),
        account_id: String::new(),
        email: "u@example.invalid".into(),
        plan_type: String::new(),
        expired: "2026-10-12T12:00:00Z".into(),
    };
    write_login(&dir, &tokens).unwrap();
    let saved: Map<String, Value> = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
    assert_eq!(saved["disabled"], false);
    std::fs::remove_dir_all(dir).unwrap();
}

#[tokio::test]
async fn retained_results_never_block_a_new_refresh() {
    let mock = Mock::start().await;
    let oauth = oauth(&mock).await;
    mock.script(
        "/oauth/token",
        vec![json(200, &token_body()); MAX_RETAINED_REFRESHES + 1],
    );
    for i in 0..MAX_RETAINED_REFRESHES {
        oauth.refresh(&format!("rt-{i}")).await.unwrap();
    }
    oauth
        .refresh("rt-extra")
        .await
        .expect("a 65th distinct token still reaches OAuth");
    assert_eq!(mock.take().len(), MAX_RETAINED_REFRESHES + 1);
    assert!(oauth.refreshes.outer.lock().unwrap().len() <= MAX_RETAINED_REFRESHES);
    // The newest result is still deduplicated.
    oauth.refresh("rt-extra").await.unwrap();
    assert!(mock.take().is_empty());
}

#[test]
fn abandoned_prompt_does_not_block_runtime_shutdown() {
    let (done_tx, done_rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let runtime = tokio::runtime::Runtime::new().unwrap();
        runtime.block_on(async {
            // A read that never returns, like stdin held open.
            let blocked = prompt_line("", || {
                std::thread::park();
                Ok(String::new())
            });
            tokio::select! {
                _ = blocked => unreachable!(),
                _ = tokio::time::sleep(Duration::from_millis(10)) => {}
            }
        });
        drop(runtime);
        done_tx.send(()).unwrap();
    });
    done_rx
        .recv_timeout(Duration::from_secs(5))
        .expect("runtime shut down without waiting for the prompt");
}