use std::time::Duration;
use serde_json::{Value, json};
use super::*;
use crate::kimi_fixture::{Captured, Mock, assert_same_request, fixture, request};
use crate::meta_auth::{
self, GoMap, MetaAuth, TokenStorage, credential_file_name, encode_token_file, go_map_from_json, login_with,
};
use cpa_common::json as gj;
struct TempDir(std::path::PathBuf);
impl TempDir {
fn new() -> Self {
let path = std::env::temp_dir().join(format!("cpa-meta-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&path).unwrap();
Self(path)
}
fn path(&self) -> &std::path::Path {
&self.0
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn cfg() -> Config {
Config::parse("").unwrap()
}
fn go_origin(fx: &Value) -> Option<String> {
let text = fx.to_string();
let start = text.find("http://127.0.0.1:")?;
let rest = &text[start + "http://127.0.0.1:".len()..];
let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
Some(format!("http://127.0.0.1:{digits}"))
}
fn replace_origin(value: &Value, origin: &str, url: &str) -> Value {
match value {
Value::String(s) => Value::String(s.replace(origin, url)),
Value::Array(items) => Value::Array(items.iter().map(|v| replace_origin(v, origin, url)).collect()),
Value::Object(map) => Value::Object(
map.iter()
.map(|(k, v)| (k.clone(), replace_origin(v, origin, url)))
.collect(),
),
other => other.clone(),
}
}
fn meta_credential(fx: &Value, origin: &str, url: &str) -> Credential {
let metadata = replace_origin(&fx["credential"], origin, url)
.as_object()
.cloned()
.unwrap_or_default();
let mut c = Credential {
id: "meta-fixture.json".into(),
provider: PROVIDER.into(),
source: Source::File("/fixture/meta-fixture.json".into()),
disabled: false,
label: String::new(),
attributes: Default::default(),
metadata,
revision: 0,
next_refresh_after: None,
};
c.refresh_derived();
c.attributes = replace_origin(&fx["attributes"], origin, url)
.as_object()
.map(|attrs| {
attrs
.iter()
.map(|(k, v)| (k.clone(), v.as_str().unwrap_or_default().to_owned()))
.collect()
})
.unwrap_or_default();
if c.attributes.get("source").is_some_and(|s| s.starts_with("config:")) {
c.label = format!("{PROVIDER}-apikey");
}
c
}
struct Run {
usage: std::sync::Arc<crate::kimi_fixture::UsageLog>,
capture: std::sync::Arc<crate::kimi_fixture::CaptureLog>,
fx: Value,
origin: String,
url: String,
credential: Credential,
captured: Vec<Captured>,
body: Option<String>,
chunks: Vec<String>,
error: Option<ExecError>,
}
async fn run(name: &str) -> Run {
let fx = fixture("meta", name);
let origin = go_origin(&fx).expect("fixture names its capture server");
let mock = Mock::start_replacing(&fx["responses"], Some(&origin)).await;
let credential = meta_credential(&fx, &origin, &mock.url);
let exec = MetaExecutor::with_client(default_client()).with_mint_url(&format!("{}/muse-code/key", mock.url));
let (mut body, mut chunks, mut error) = (None, Vec::new(), None);
let cfg = Config::parse(fx["request"]["config"].as_str().unwrap_or_default()).unwrap();
let usage = std::sync::Arc::new(crate::kimi_fixture::UsageLog::default());
let capture = std::sync::Arc::new(crate::kimi_fixture::CaptureLog::default());
let mut req = request(&fx, "");
req.usage = usage.sink().with_capture(capture.sink());
match exec.execute(&credential, req, &cfg).await {
Err(e) => error = Some(e),
Ok(response) => match response.body {
ResponseBody::Buffered(b) => body = Some(String::from_utf8(b.to_vec()).unwrap()),
ResponseBody::Stream(mut s) => {
while let Some(item) = s.next().await {
match item {
Ok(chunk) => chunks.push(String::from_utf8(chunk.to_vec()).unwrap()),
Err(e) => error = Some(e),
}
}
}
},
}
Run {
usage,
capture,
captured: mock.captured(),
url: mock.url,
fx,
origin,
credential,
body,
chunks,
error,
}
}
fn assert_upstream(r: &Run, name: &str) {
let go: Vec<Captured> = r.fx["upstream"]
.as_array()
.map(Vec::as_slice)
.unwrap_or_default()
.iter()
.map(|c| Captured::from_fixture(&replace_origin(c, &r.origin, &r.url)))
.collect();
assert_eq!(r.captured.len(), go.len(), "{name}: upstream request count");
for (go, rust) in go.iter().zip(&r.captured) {
assert_same_request(name, go, rust, &["Host"]);
}
}
fn assert_downstream(r: &Run, name: &str) {
let down = &r.fx["downstream"];
if let Some(body) = down["body"].as_str().filter(|b| !b.is_empty()) {
assert_eq!(r.body.as_deref(), Some(body), "{name}: response body");
}
let key = if r.fx["request"]["source"] == "openai-response" {
"frames"
} else {
"chunks"
};
let go_frames: Vec<&str> = down[key]
.as_array()
.map(|c| c.iter().filter_map(Value::as_str).collect())
.unwrap_or_default();
assert_eq!(r.chunks, go_frames, "{name}: stream frames");
let go_error = down["stream_err"].as_str().or(down["err_body"].as_str());
match (&r.error, down["err_status"].as_i64()) {
(None, None) => {}
(Some(e), Some(-1)) => {
let rust = String::from_utf8_lossy(&e.body);
assert_eq!(e.status, 500, "{name}: plain errors are 500");
assert!(
go_error.unwrap().starts_with(&format!("{rust}: ")),
"{name}: {rust:?} must be Go's message without the upstream body"
);
}
(Some(e), Some(status)) => {
assert_eq!(i64::from(e.status), status, "{name}: error status");
assert_eq!(
String::from_utf8_lossy(&e.body),
go_error.unwrap(),
"{name}: error body"
);
}
(rust, go) => panic!("{name}: rust error {rust:?}, go status {go:?}"),
}
}
#[tokio::test]
async fn execution_matches_go_byte_for_byte() {
for name in [
"responses-nonstream-collected",
"responses-stream",
"responses-nonstream-json-body",
"error-429-subscription-quota",
"error-429-plain",
"error-404-model",
"error-404-resets",
"stream-error-event",
"stream-error-after-data-only",
"nonstream-response-failed",
"nonstream-incomplete-fallback-items",
"nonstream-disconnect-before-completed",
"stream-plain-json-lines",
"compact-rejected",
"count-tokens",
"config-apikey-headers",
"payload-rules-and-headers",
"config-apikey-dca-only",
"remint-from-dca",
"remint-access-token-dca-minted-base",
"remint-failure",
"apply-patch-stream",
"apply-patch-nonstream",
"apply-patch-invalid-stream",
"apply-patch-invalid-nonstream",
"apply-patch-eof-stream",
"stream-completed-then-error",
"stream-done-only",
"apply-patch-stream-event-lines",
"stream-tier-merge",
"stream-nbsp-data",
"claude-stream-input-estimate",
] {
let r = run(name).await;
assert_upstream(&r, name);
assert_downstream(&r, name);
}
}
#[tokio::test]
async fn error_signals_follow_go_scopes_and_retry_hints() {
for name in [
"error-429-subscription-quota",
"error-429-plain",
"error-404-model",
"error-404-resets",
"stream-error-event",
"nonstream-response-failed",
] {
let r = run(name).await;
let e = r.error.as_ref().unwrap_or_else(|| panic!("{name}: error expected"));
let extra = &r.fx["extra"];
let credential_scoped = extra["credential_scoped"].as_bool().unwrap();
let expected_scope = match (e.status, credential_scoped) {
(_, true) => FailureScope::Credential,
(404 | 429, false) => FailureScope::Model,
_ => FailureScope::Credential,
};
assert_eq!(e.scope, expected_scope, "{name}: scope");
match extra["retry_after_secs"].as_f64() {
None => assert_eq!(e.retry_after, None, "{name}: no retry hint"),
Some(300.0) => assert_eq!(e.retry_after, Some(Duration::from_secs(300)), "{name}"),
Some(go_secs) => {
let elapsed = chrono::Utc::now().timestamp() - extra["now_unix"].as_i64().unwrap();
let expected = go_secs - elapsed as f64;
let got = e.retry_after.unwrap().as_secs_f64();
assert!((got - expected).abs() < 5.0, "{name}: retry {got} vs {expected}");
}
}
}
}
fn minted(r: &Run, index: usize) -> MintedKey {
let body = replace_origin(&r.fx["responses"][index]["body"], &r.origin, &r.url);
MintedKey::decode(body.as_str().unwrap().as_bytes()).unwrap()
}
fn assert_metadata_after(r: &Run, name: &str, patch: &MetadataPatch) {
let mut after = r.credential.metadata.clone();
patch.apply(&mut after);
let mut go = replace_origin(&r.fx["extra"]["metadata_after"], &r.origin, &r.url)
.as_object()
.cloned()
.unwrap();
let stamp = after.remove("last_refresh").and_then(|v| v.as_str().map(str::to_owned));
assert!(
stamp.is_some_and(|s| chrono::DateTime::parse_from_rfc3339(&s).is_ok()),
"{name}: last_refresh is RFC3339"
);
go.remove("last_refresh");
assert_eq!(
Value::Object(after),
Value::Object(go),
"{name}: metadata after refresh"
);
}
#[tokio::test]
async fn remint_patch_matches_go_metadata() {
for name in ["remint-from-dca", "remint-access-token-dca-minted-base"] {
let r = run(name).await;
let dca = dca_token(&r.credential).unwrap();
let patch = refresh_patch(&r.credential, &dca, &minted(&r, 0), "2026-10-02T00:00:00Z".into());
assert_metadata_after(&r, name, &patch);
}
}
#[tokio::test]
async fn prepare_remints_and_matches_go_refresh() {
let fx = fixture("meta", "refresh-direct");
let origin = go_origin(&fx).unwrap();
let mock = Mock::start_replacing(&fx["responses"], Some(&origin)).await;
let credential = meta_credential(&fx, &origin, &mock.url);
let exec = MetaExecutor::with_client(default_client()).with_mint_url(&format!("{}/muse-code/key", mock.url));
assert!(
!exec.needs_prepare(&credential, &cfg()),
"a usable key and no refresh interval: nothing to prepare (RefreshLead nil)"
);
let patch = exec.prepare(&credential, &cfg()).await.unwrap();
let r = Run {
usage: Default::default(),
capture: Default::default(),
captured: mock.captured(),
url: mock.url,
fx,
origin,
credential,
body: None,
chunks: Vec::new(),
error: None,
};
assert_upstream(&r, "refresh-direct");
assert_metadata_after(&r, "refresh-direct", &patch);
}
#[test]
fn needs_prepare_matches_should_prepare_request_auth() {
let cred = |meta: Value, attrs: &[(&str, &str)]| {
let mut c = Credential::from_file(
std::path::Path::new("/a"),
std::path::Path::new("/a/meta.json"),
meta.as_object().unwrap().clone(),
)
.unwrap();
c.provider = PROVIDER.into();
c.attributes = attrs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
c
};
let exec = MetaExecutor::default();
let cfg = cfg();
assert!(!exec.needs_prepare(&cred(json!({"type":"meta"}), &[("api_key", "exists")]), &cfg));
assert!(!exec.needs_prepare(&cred(json!({"type":"meta"}), &[]), &cfg));
let config_dca = cred(
json!({"type":"meta"}),
&[("api_key", "dca:invalid-for-config"), ("source", "config:meta[0]")],
);
assert!(is_config_api_key(&config_dca));
for (attrs, want) in [
(&[("auth_kind", "apikey"), ("source_backend", "CONFİG")][..], true),
(&[("auth_kind", "apikey"), ("source", "CONFİG:meta[0]")][..], true),
(&[("auth_kind", "apikey"), ("source", " Config ")][..], true),
(
&[("auth_kind", "apikey"), ("source", "config"), ("runtime_only", "TRUE")][..],
false,
),
(
&[
("auth_kind", "apikey"),
("source", "config:meta[0]"),
("source_backend", "Fİle"),
][..],
false,
),
] {
assert_eq!(
is_config_api_key(&cred(json!({"type":"meta"}), attrs)),
want,
"{attrs:?}"
);
}
assert!(!exec.needs_prepare(&config_dca, &cfg));
assert!(exec.needs_prepare(
&cred(
json!({"type":"meta","dca_token":"dca:valid","auth_kind":"oauth"}),
&[("base_url", "http://x")]
),
&cfg
));
assert!(exec.needs_prepare(
&cred(
json!({"type":"meta","api_key":"k","dca_token":"dca:v","refresh_interval":60,"last_refresh":"2020-01-01T00:00:00Z"}),
&[]
),
&cfg
));
}
#[test]
fn creds_resolution_matches_go() {
let mut c = Credential::from_file(
std::path::Path::new("/a"),
std::path::Path::new("/a/meta.json"),
json!({"type":"meta"}).as_object().unwrap().clone(),
)
.unwrap();
c.attributes.insert("api_key".into(), "attr-key".into());
c.attributes
.insert("base_url".into(), "https://custom.meta.com/v1".into());
assert_eq!(creds(&c), ("https://custom.meta.com/v1".into(), "attr-key".into()));
c.attributes.clear();
c.metadata.insert("access_token".into(), "meta-oauth-token".into());
assert_eq!(creds(&c), (DEFAULT_API_BASE_URL.into(), "meta-oauth-token".into()));
c.metadata.insert("access_token".into(), " dca:x ".into());
c.metadata.insert("api_base_url".into(), "https://alt/v1".into());
assert_eq!(creds(&c), ("https://alt/v1".into(), String::new()));
assert_eq!(dca_token(&c).as_deref(), Some("dca:x"));
}
#[test]
fn retry_hint_follows_resets_at() {
let future = chrono::Utc::now().timestamp() + 45 * 60;
let body = format!(
r#"{{"error":{{"code":"rate_limit_exceeded","message":"Subscription quota exhausted.","resets_at":{future},"type":"rate_limit_error"}}}}"#
);
let e = upstream_error(429, body.as_bytes());
let secs = e.retry_after.unwrap().as_secs();
assert!((40 * 60..=50 * 60).contains(&secs));
assert_eq!(e.scope, FailureScope::Credential);
let past = chrono::Utc::now().timestamp() - 600;
let e = upstream_error(429, format!(r#"{{"error":{{"resets_at":{past}}}}}"#).as_bytes());
assert_eq!(e.retry_after, None);
assert_eq!(e.scope, FailureScope::Model);
assert_eq!(upstream_error(400, body.as_bytes()).retry_after, None);
}
#[test]
fn file_names_and_writer_match_go() {
let fx = fixture("meta", "writer");
for case in fx["extra"]["file_names"].as_array().unwrap() {
assert_eq!(
credential_file_name(case["email"].as_str().unwrap(), case["sub"].as_str().unwrap()),
case["out"].as_str().unwrap()
);
}
let dir = TempDir::new();
for case in fx["extra"]["cases"].as_array().unwrap() {
let name = case["name"].as_str().unwrap();
let storage: TokenStorage = serde_json::from_value(case["storage"].clone()).unwrap();
let snapshot: Option<GoMap> = case["snapshot"]
.as_object()
.map(|m| go_map_from_json(&serde_json::to_vec(m).unwrap()).unwrap().0);
let disk = case["disk"].as_str().unwrap();
let out = case["out"].as_str().unwrap();
assert_eq!(
encode_token_file(&storage, snapshot.as_ref(), Some(disk.as_bytes())),
out,
"{name}"
);
let path = dir.path().join(format!("{name}.json"));
std::fs::write(&path, disk).unwrap();
meta_auth::save_token_file(&path, &storage, snapshot.as_ref()).unwrap();
assert_eq!(std::fs::read_to_string(&path).unwrap(), out, "{name}: file");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
}
}
let leftovers: Vec<_> = std::fs::read_dir(dir.path())
.unwrap()
.filter_map(|e| e.ok())
.filter(|e| e.file_name().to_string_lossy().starts_with('.'))
.collect();
assert!(leftovers.is_empty(), "no temporary files survive");
}
fn login_auth(url: &str) -> MetaAuth {
MetaAuth::new(default_client())
.with_auth_host(url)
.with_mint_url(&format!("{url}/muse-code/key"))
.with_poll_unit(Duration::from_millis(10))
}
#[tokio::test]
async fn login_matches_go_requests_and_file() {
for name in ["login", "login-no-mint"] {
let fx = fixture("meta", name);
let mock = Mock::start(&fx["responses"]).await;
let dir = TempDir::new();
let go_file = fx["extra"]["file_name"].as_str().unwrap();
if let Some(stale) = fx["request"]["stale_file"].as_str().filter(|s| !s.is_empty()) {
std::fs::write(dir.path().join(go_file), stale).unwrap();
}
let go_raw = fx["extra"]["file_raw"].as_str().unwrap();
let stamp = gj::get(go_raw.as_bytes(), "last_refresh").str().into_owned();
let now = chrono::DateTime::parse_from_rfc3339(&stamp).unwrap().to_utc();
let outcome = login_with(login_auth(&mock.url).with_fixed_now(now), dir.path(), true)
.await
.unwrap();
let go: Vec<Captured> = fx["upstream"]
.as_array()
.unwrap()
.iter()
.map(Captured::from_fixture)
.collect();
let rust = mock.captured();
assert_eq!(rust.len(), go.len(), "{name}: request count");
for (go, rust) in go.iter().zip(&rust) {
assert_same_request(name, go, rust, &["Host"]);
}
assert_eq!(outcome.path, dir.path().join(go_file), "{name}: file name");
assert_eq!(outcome.label, fx["extra"]["label"].as_str().unwrap(), "{name}: label");
assert_eq!(
std::fs::read_to_string(&outcome.path).unwrap(),
go_raw,
"{name}: file bytes"
);
}
}
#[tokio::test]
async fn failed_login_mint_logs_no_response_body() {
let fx = fixture("meta", "login-no-mint");
let mut responses = fx["responses"].clone();
let secret = "sk-mint-SECRET-0123456789";
responses[2]["body"] = json!(format!(r#"{{"error":"bad","api_key":"{secret}"}}"#));
let mock = Mock::start(&responses).await;
let dir = TempDir::new();
let capture = crate::kimi_fixture::LogCapture::default();
let guard = capture.install();
let outcome = login_with(login_auth(&mock.url), dir.path(), true).await;
drop(guard);
assert!(outcome.is_ok(), "a failed mint does not fail the login");
let logs = capture.0.lock().unwrap().clone();
assert!(
logs.iter()
.any(|l| l.contains("could not mint api_key from dca_token: meta auth: mint key failed (HTTP 500)")),
"the mint failure is logged: {logs:?}"
);
for line in &logs {
assert!(
!line.contains(secret) && !line.contains("\"bad\""),
"body logged: {line}"
);
}
}
#[tokio::test]
async fn device_flow_errors_and_slow_down_follow_go() {
let device = json!({"status":200,"body":r#"{"device_code":"d","user_code":"u","interval":1,"expires_in":600}"#});
let poll = |status: u16, body: &str| json!({"status":status,"body":body});
let cases = [
(
poll(400, r#"{"error":"access_denied"}"#),
"meta auth: access was denied by user",
),
(
poll(400, r#"{"error":"expired_token"}"#),
"meta auth: device code has expired",
),
(
poll(400, r#"{"error":"invalid_client","error_description":"bad client"}"#),
"meta auth: error from authorization server: invalid_client: bad client",
),
(
poll(200, r#"{"token_type":"bearer"}"#),
"meta auth: response missing access_token",
),
];
for (answer, message) in cases {
let mock = Mock::start(&json!([device, answer])).await;
let auth = login_auth(&mock.url);
let code = auth.start_device_flow().await.unwrap();
assert_eq!(auth.wait_for_authorization(&code).await.unwrap_err(), message);
}
let mock = Mock::start(&json!([
device,
poll(400, r#"{"error":"slow_down"}"#),
poll(502, "bad gateway"),
poll(200, r#"{"access_token":"dca:t","expires_in":0}"#),
poll(500, "mint down"),
]))
.await;
let auth = login_auth(&mock.url);
let code = auth.start_device_flow().await.unwrap();
let started = tokio::time::Instant::now();
let bundle = auth.wait_for_authorization(&code).await.unwrap();
assert!(
started.elapsed() >= Duration::from_millis(10 + 60 + 60),
"slow_down widened the interval"
);
assert_eq!(bundle.token.access_token, "dca:t");
assert_eq!(bundle.minted, None, "a failed mint keeps the DCA-only bundle");
let mock = Mock::start(&json!([
{"status":200,"body":r#"{"device_code":"d","user_code":"u","interval":1,"expires_in":3}"#},
poll(400, r#"{"error":"authorization_pending"}"#),
poll(400, r#"{"error":"authorization_pending"}"#),
poll(400, r#"{"error":"authorization_pending"}"#),
]))
.await;
let auth = login_auth(&mock.url);
let code = auth.start_device_flow().await.unwrap();
assert_eq!(
auth.wait_for_authorization(&code).await.unwrap_err(),
"meta auth: authorization timed out or canceled: context deadline exceeded"
);
let mock = Mock::start(&json!([
poll(400, " nope "),
poll(200, r#"{"device_code":"d","user_code":" "}"#),
poll(200, r#"{"device_code":"d","user_code":"u","interval":1.5}"#),
]))
.await;
let auth = login_auth(&mock.url);
crate::kimi_fixture::assert_go_message_without_body(
"device flow 400",
&auth.start_device_flow().await.unwrap_err(),
"meta device flow failed (HTTP 400): nope",
);
assert_eq!(
auth.start_device_flow().await.unwrap_err(),
"meta device flow: response missing required device_code or user_code"
);
assert!(
auth.start_device_flow()
.await
.unwrap_err()
.starts_with("meta device flow: parse response: ")
);
}
#[test]
fn auth_records_decode_like_go_json_unmarshal() {
let fx = fixture("meta", "decode");
let string = |v: &Value, k: &str| v[k].as_str().unwrap_or_default().to_owned();
let int = |v: &Value, k: &str| v[k].as_i64().unwrap_or_default();
let boolean = |v: &Value, k: &str| v[k].as_bool().unwrap_or_default();
for case in fx["extra"]["cases"].as_array().unwrap() {
let input = case["input"].as_str().unwrap();
let raw = input.as_bytes();
let err = |r: &Value| r["err"].as_str().unwrap().to_owned();
let go = &case["device"];
match crate::meta_auth::DeviceCode::decode_for_test(raw) {
Ok(c) => {
assert_eq!(err(go), "", "device {input}");
let v = &go["value"];
assert_eq!(
(
c.device_code,
c.user_code,
c.verification_uri,
c.verification_uri_complete
),
(
string(v, "device_code"),
string(v, "user_code"),
string(v, "verification_uri"),
string(v, "verification_uri_complete")
),
"device {input}"
);
assert_eq!(
(c.expires_in, c.interval),
(int(v, "expires_in"), int(v, "interval")),
"device {input}"
);
}
Err(e) => assert_eq!(e, err(go), "device {input}"),
}
let go = &case["token"];
let (t, result) = crate::meta_auth::TokenData::decode_for_test(raw);
assert_eq!(result.err().unwrap_or_default(), err(go), "token {input}");
let v = &go["value"];
assert_eq!(
(t.access_token, t.token_type, t.error, t.error_description),
(
string(v, "access_token"),
string(v, "token_type"),
string(v, "error"),
string(v, "error_description")
),
"token {input}"
);
assert_eq!(
(t.expires_in, t.expires_at),
(int(v, "expires_in"), int(v, "expires_at")),
"token {input}"
);
let go = &case["mint"];
match MintedKey::decode(raw) {
Ok(m) => {
assert_eq!(err(go), "", "mint {input}");
let v = &go["value"];
assert_eq!(
(
m.api_key,
m.base_url,
m.user_email,
m.user_full_name,
m.subs_tier_name,
m.subs_tier_id
),
(
string(v, "api_key"),
string(v, "base_url"),
string(v, "user_email"),
string(v, "user_full_name"),
string(v, "subs_tier_name"),
string(v, "subs_tier_id")
),
"mint {input}"
);
assert_eq!(
(
m.is_subs_active,
m.has_payment_method,
m.require_payment,
m.can_subscribe
),
(
boolean(v, "is_subs_active"),
boolean(v, "has_payment_method"),
boolean(v, "require_payment"),
boolean(v, "can_subscribe")
),
"mint {input}"
);
}
Err(e) => assert_eq!(e, err(go), "mint {input}"),
}
}
}
#[test]
fn syntax_errors_quote_every_byte_like_go() {
let fx = fixture("meta", "decode");
for case in fx["extra"]["bytes"].as_array().unwrap() {
let byte = case["byte"].as_u64().unwrap() as u8;
let go = case["err"].as_str().unwrap();
let rust = crate::meta_wire::check_valid(&[byte]);
if go.starts_with("json: cannot unmarshal") {
assert_eq!(rust, Ok(()), "byte {byte}");
} else {
assert_eq!(rust.unwrap_err(), go, "byte {byte}");
}
}
}
#[tokio::test]
async fn poll_errors_use_go_partial_decoding_and_key_folding() {
let device = json!({"status":200,"body":r#"{"DEVICE_CODE":"d","User_Code":"u","interval":1}"#});
let mock = Mock::start(&json!([device, {"status":400,"body":r#"{"error":5,"ERROR":"access_denied"}"#}])).await;
let auth = login_auth(&mock.url);
let code = auth.start_device_flow().await.unwrap();
assert_eq!(
auth.wait_for_authorization(&code).await.unwrap_err(),
"meta auth: access was denied by user"
);
let mock = Mock::start(
&json!([{"status":200,"body":"null"}, {"status":200,"body":r#"{"api_key":"first","api_key":"second"}"#}]),
)
.await;
let auth = login_auth(&mock.url);
assert_eq!(
auth.mint_api_key("dca:n").await.unwrap_err().to_string(),
"meta auth: mint response missing api_key"
);
assert_eq!(auth.mint_api_key("dca:d").await.unwrap().api_key, "second");
}
#[tokio::test]
async fn failed_error_body_read_is_not_classified_by_status() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
tokio::spawn(async move {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let (mut socket, _) = listener.accept().await.unwrap();
let mut buf = vec![0u8; 65536];
let _ = socket.read(&mut buf).await;
let body = r#"{"error":{"message":"subscription quota exhausted","resets_at":4102444800}}"#;
let head = format!(
"HTTP/1.1 429 Too Many Requests\r\nContent-Length: {}\r\n\r\n",
body.len() + 100
);
let _ = socket.write_all(head.as_bytes()).await;
let _ = socket.write_all(body.as_bytes()).await;
});
let fx = fixture("meta", "error-429-subscription-quota");
let origin = go_origin(&fx).unwrap();
let credential = meta_credential(&fx, &origin, &url);
let error = MetaExecutor::with_client(default_client())
.execute(&credential, request(&fx, ""), &cfg())
.await
.err()
.unwrap();
assert_ne!(error.status, 429);
assert_eq!(error.scope, FailureScope::Transport);
assert_eq!(error.retry_after, None);
}
#[tokio::test]
async fn empty_original_request_falls_back_to_the_payload() {
let fx = fixture("meta", "responses-stream");
let origin = go_origin(&fx).unwrap();
let mock = Mock::start(&json!([{"status":200,"headers":[["Content-Type","text/event-stream"]],"body":"data: {\"type\":\"response.created\",\"response\":{}}\n\n"}])).await;
let credential = meta_credential(&fx, &origin, &mock.url);
let mut req = request(&fx, "");
req.original_body = Bytes::new();
let response = MetaExecutor::with_client(default_client())
.execute(&credential, req, &cfg())
.await
.unwrap();
let ResponseBody::Stream(mut stream) = response.body else {
panic!("stream expected");
};
let first = stream.next().await.unwrap().unwrap();
assert_eq!(
String::from_utf8(first.to_vec()).unwrap(),
"data: {\"type\":\"response.created\",\"response\":{\"model\":\"muse-spark-1.3(high)\"}}\n\n"
);
}
#[test]
fn login_merge_skips_an_existing_file_go_cannot_decode() {
let dir = TempDir::new();
let bundle = meta_auth::Bundle {
token: meta_auth::TokenData {
access_token: "dca:x".into(),
..Default::default()
},
..Default::default()
};
let name = credential_file_name("", "dca:x");
std::fs::write(dir.path().join(&name), r#"{"type":"meta","custom":1e400,"prefix":"p"}"#).unwrap();
let now = chrono::DateTime::parse_from_rfc3339("2026-10-02T00:00:00Z")
.unwrap()
.to_utc();
let outcome = meta_auth::save_login(dir.path(), &bundle, now).unwrap();
let written = std::fs::read_to_string(&outcome.path).unwrap();
assert!(serde_json::from_str::<Value>(&written).is_ok(), "valid JSON: {written}");
assert!(!written.contains("prefix") && !written.contains("custom"), "{written}");
let storage = TokenStorage {
access_token: "a".into(),
..Default::default()
};
assert_eq!(
encode_token_file(&storage, None, Some(br#"{"custom":1e400,"n":1.0}"#)),
"{\n \"access_token\": \"a\",\n \"auth_kind\": \"oauth\",\n \"custom\": null,\n \"n\": 1,\n \"type\": \"meta\"\n}\n"
);
}
#[tokio::test]
async fn login_skips_existing_file_with_an_overwritten_overflow() {
let fx = fixture("meta", "login-existing-overflow");
let mock = Mock::start(&fx["responses"]).await;
let dir = TempDir::new();
let go_file = fx["extra"]["file_name"].as_str().unwrap();
std::fs::write(dir.path().join(go_file), fx["request"]["stale_file"].as_str().unwrap()).unwrap();
let go_raw = fx["extra"]["file_raw"].as_str().unwrap();
let now = chrono::DateTime::parse_from_rfc3339(&gj::get(go_raw.as_bytes(), "last_refresh").str())
.unwrap()
.to_utc();
let outcome = login_with(login_auth(&mock.url).with_fixed_now(now), dir.path(), true)
.await
.unwrap();
let written = std::fs::read_to_string(&outcome.path).unwrap();
let strip = |s: &str| {
let mut v: Value = serde_json::from_str(s).unwrap();
for key in ["dca_expired", "dca_expires_at"] {
v.as_object_mut().unwrap().remove(key);
}
v
};
assert_eq!(strip(&written), strip(go_raw));
}
#[test]
fn strict_error_body_read_surfaces_errors_past_the_kept_prefix() {
let chunks: Vec<Result<Bytes, ExecError>> = vec![
Ok(Bytes::from_static(b"0123456789")),
Ok(Bytes::from_static(b"abcdef")),
Err(ExecError::local(502, FailureScope::Transport, "unexpected EOF")),
];
let body = futures_util::stream::iter(chunks).boxed();
let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
let error = rt.block_on(crate::kimi_http::read_all_strict(body, 4)).unwrap_err();
assert_eq!(error.scope, FailureScope::Transport);
let ok = futures_util::stream::iter(vec![Ok(Bytes::from_static(b"0123456789"))]).boxed();
assert_eq!(rt.block_on(crate::kimi_http::read_all_strict(ok, 4)).unwrap(), "0123");
}
#[tokio::test]
async fn mint_errors_follow_go() {
let mock = Mock::start(&json!([
{"status":200,"body":r#"{"api_key":""}"#},
{"status":200,"body":r#"{"api_key":"k","is_subs_active":"yes"}"#},
{"status":403,"body":" denied "},
]))
.await;
let auth = login_auth(&mock.url);
assert_eq!(
auth.mint_api_key("dca:1").await.unwrap_err().to_string(),
"meta auth: mint response missing api_key"
);
assert!(
auth.mint_api_key("dca:2")
.await
.unwrap_err()
.to_string()
.starts_with("meta auth: parse mint response: ")
);
let e = auth.mint_api_key("dca:3").await.unwrap_err();
crate::kimi_fixture::assert_go_message_without_body(
"mint 403",
&e.to_string(),
"meta auth: mint key failed (HTTP 403): denied",
);
assert_eq!(e.redacted(), e.to_string());
assert!(!format!("{e:?}").contains("denied"));
assert_eq!(
auth.mint_api_key(" ").await.unwrap_err().to_string(),
"meta auth: missing dca token"
);
}
#[tokio::test]
async fn apply_patch_failures_end_meta_streams_like_go() {
async fn run(lines: Vec<&'static str>, fail_on_finalize: bool) -> (Vec<String>, Vec<String>) {
let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let translator = Box::new(crate::kimi_fixture::PatchProbe {
failed: false,
fail_on_finalize,
log: log.clone(),
});
let upstream =
futures_util::stream::iter(lines.into_iter().map(|l| Ok(Bytes::from_static(l.as_bytes())))).boxed();
let inactive = cpa_translate::apply_patch_responses::State::new(Format::OpenAIResponse, b"{}", b"{}");
let out: Vec<String> = stream_events(
upstream,
translator,
crate::gemini_stream::ClaudeInputTokens::new(
Format::OpenAIResponse,
Format::Codex,
Format::OpenAIResponse,
Bytes::new(),
),
false,
inactive,
Default::default(),
Default::default(),
)
.map(|item| match item {
Ok(b) => String::from_utf8(b.to_vec()).unwrap(),
Err(e) => format!("ERR {} {}", e.status, String::from_utf8_lossy(&e.body)),
})
.collect()
.await;
let log = log.lock().unwrap().clone();
(out, log)
}
let patch = format!("ERR 502 {}", cpa_translate::APPLY_PATCH_UPSTREAM_ERROR);
let (out, log) = run(
vec!["data: {\"a\":1}", "data: {\"BAD_PATCH\":1}", "data: {\"c\":1}"],
false,
)
.await;
assert_eq!(
out,
[
"frame data: {\"a\":1}",
"frame data: {\"BAD_PATCH\":1}",
"flushed",
patch.as_str()
]
);
assert_eq!(log.len(), 2);
let (out, log) = run(vec!["data: {\"a\":1}"], true).await;
assert_eq!(out, ["frame data: {\"a\":1}", "finished"]);
assert_eq!(log, ["event data: {\"a\":1}", "finish"]);
}
#[tokio::test]
async fn usage_reports_match_go_records() {
for name in [
"responses-nonstream-collected",
"responses-stream",
"responses-nonstream-json-body",
"stream-error-event",
"nonstream-response-failed",
"nonstream-incomplete-fallback-items",
"payload-rules-and-headers",
"remint-from-dca",
"error-429-plain",
"apply-patch-stream",
"apply-patch-nonstream",
"apply-patch-invalid-stream",
"apply-patch-invalid-nonstream",
"apply-patch-eof-stream",
"stream-completed-then-error",
"stream-done-only",
"apply-patch-stream-event-lines",
"stream-tier-merge",
"stream-nbsp-data",
"claude-stream-input-estimate",
] {
let r = run(name).await;
let failure = r.error.as_ref().map(crate::kimi_fixture::go_failure);
crate::kimi_fixture::assert_usage_like_go(name, &r.fx, &r.usage, failure.as_ref());
}
}
#[tokio::test]
async fn request_capture_matches_go() {
let names = crate::kimi_fixture::captured_fixtures("meta");
assert!(names.len() >= 30, "{names:?}");
for name in names.iter().filter(|n| n.as_str() != "refresh-direct") {
let r = run(name).await;
crate::kimi_fixture::assert_capture_like_go(name, &r.fx, &r.capture, &r.url, &["Host"]);
}
}
#[tokio::test]
async fn a_refused_baseline_alone_does_not_refuse_the_request() {
let fx = fixture("meta", "responses-nonstream-collected");
let origin = go_origin(&fx).unwrap();
let hi = br#"{"model":"muse-spark-1.3","max_tokens":16,"messages":[{"role":"user","content":[{"type":"text","text":"hi"}]}]}"#;
let refused = br#"{"model":"muse-spark-1.3","max_tokens":16,"messages":[{"role":"user","content":[{"type":"container_upload","source":{"type":"file","file_id":"f1"}}]}]}"#;
for baseline_only in [true, false] {
let mock = Mock::start(&fx["responses"]).await;
let credential = meta_credential(&fx, &origin, &mock.url);
let mut req = request(&fx, "");
req.source_format = Format::Claude;
req.response_format = Format::Claude;
let (body, original): (&'static [u8], &'static [u8]) =
if baseline_only { (hi, refused) } else { (refused, hi) };
req.body = Bytes::from_static(body);
req.original_body = Bytes::from_static(original);
let result = MetaExecutor::with_client(default_client())
.execute(&credential, req, &cfg())
.await;
assert_eq!(result.is_ok(), baseline_only, "baseline_only={baseline_only}");
let captured = mock.captured();
assert_eq!(captured.len(), usize::from(baseline_only));
if let Some(sent) = captured.first() {
assert!(String::from_utf8_lossy(&sent.body).contains(r#""text":"hi""#));
}
}
}