返回 CodeWhale
external_agent_quota.rs
根目录 / crates / app-server / src / runtime_api / tests / external_agent_quota.rs
1 use super::*;
2 use reqwest::StatusCode as HttpStatus;
3 use std::collections::BTreeMap;
4
5 const FIXTURE_TOKEN: &str = "cw-fixture-token-7993-do-not-echo";
6
7 fn reasons(body: &Value) -> BTreeMap<String, String> {
8 body["agents"]
9 .as_array()
10 .expect("agents array")
11 .iter()
12 .map(|entry| {
13 assert!(
14 entry["quota"].get("source").is_none(),
15 "no source without a reader: {entry}"
16 );
17 assert_eq!(entry["quota"]["status"], "unknown", "{entry}");
18 (
19 entry["id"].as_str().expect("id").to_string(),
20 entry["quota"]["reason"]
21 .as_str()
22 .expect("reason")
23 .to_string(),
24 )
25 })
26 .collect()
27 }
28
29 fn snapshot(paths: &[PathBuf]) -> Vec<(Vec<u8>, std::time::SystemTime)> {
30 paths
31 .iter()
32 .map(|path| {
33 (
34 fs::read(path).expect("fixture credential"),
35 fs::metadata(path)
36 .and_then(|meta| meta.modified())
37 .expect("mtime"),
38 )
39 })
40 .collect()
41 }
42
43 #[tokio::test]
44 async fn agent_quota_reads_nothing_until_flag_and_consent_and_never_echoes_a_token() -> Result<()> {
45 let _env = lock_test_env();
46 let root = tempfile::tempdir()?;
47 let home = root.path().join("home");
48 let mut credentials = Vec::new();
49 for (dir, file) in [
50 (".claude", ".credentials.json"),
51 (".codex", "auth.json"),
52 (".gemini", "oauth_creds.json"),
53 (".kimi", "credentials.json"),
54 (".grok", "auth.json"),
55 ] {
56 let dir = home.join(dir);
57 fs::create_dir_all(&dir)?;
58 let path = dir.join(file);
59 fs::write(
60 &path,
61 format!(r#"{{"access_token":"{FIXTURE_TOKEN}","refresh_token":"{FIXTURE_TOKEN}"}}"#),
62 )?;
63 credentials.push(path);
64 }
65 let before = snapshot(&credentials);
66 let config_file = root.path().join("config").join("config.toml");
67 fs::create_dir_all(config_file.parent().unwrap())?;
68 fs::write(
69 &config_file,
70 "provider = \"deepseek\"\napi_key = \"runtime-api-test-key\"\nbase_url = \"http://127.0.0.1:1/v1\"\n",
71 )?;
72 let _home = EnvVarGuard::set("HOME", &home);
73 let _config = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", &config_file);
74 let Some((addr, _runtime_threads, handle)) =
75 spawn_test_server_with_config_path(config_file.clone()).await?
76 else {
77 return Ok(());
78 };
79 let client = codewhale_release::tls::reqwest_client();
80 let mut seen = String::new();
81
82 let read = || {
83 let client = client.clone();
84 let url = format!("http://{addr}/v1/agents/external/quota");
85 async move {
86 let text = client
87 .get(url)
88 .send()
89 .await?
90 .error_for_status()?
91 .text()
92 .await?;
93 Ok::<String, anyhow::Error>(text)
94 }
95 };
96 let set = |key: &'static str, value: &'static str| {
97 let client = client.clone();
98 let url = format!("http://{addr}/v1/config");
99 async move {
100 let response = client
101 .post(url)
102 .json(&json!({"key": key, "value": value, "persist": true}))
103 .send()
104 .await?;
105 let status = response.status();
106 Ok::<(HttpStatus, String), anyhow::Error>((status, response.text().await?))
107 }
108 };
109
110 let text = read().await?;
111 seen.push_str(&text);
112 let body: Value = serde_json::from_str(&text)?;
113 assert_eq!(body["default_source"], "agent_reported");
114 let initial = reasons(&body);
115 assert_eq!(initial.len(), codewhale_engine::fleet::agents::AGENTS.len());
116 assert!(
117 initial.values().all(|reason| reason == "flag_off"),
118 "{initial:?}"
119 );
120
121 for (key, value) in [
122 ("agents.quota.claude", "on"),
123 ("agents.quota.codex.consent", "granted"),
124 ] {
125 let (status, text) = set(key, value).await?;
126 seen.push_str(&text);
127 assert_eq!(status, HttpStatus::OK, "{key}: {text}");
128 }
129 let text = read().await?;
130 seen.push_str(&text);
131 let gated = reasons(&serde_json::from_str(&text)?);
132 assert_eq!(gated["claude"], "consent_missing");
133 assert_eq!(gated["codex"], "flag_off");
134 assert_eq!(gated["grok"], "flag_off");
135
136 for (key, value) in [
137 ("agents.quota.claude.consent", "granted"),
138 ("agents.quota.codex", "true"),
139 ] {
140 let (status, text) = set(key, value).await?;
141 seen.push_str(&text);
142 assert_eq!(status, HttpStatus::OK, "{key}: {text}");
143 }
144 let saved = codewhale_runtime::settings::Settings::load_persisted()?;
145 assert!(saved.agents.quota("claude").enabled);
146 assert!(saved.agents.quota("claude").consented_at.is_some());
147 let text = read().await?;
148 seen.push_str(&text);
149 let consented = reasons(&serde_json::from_str(&text)?);
150 assert_eq!(consented["claude"], "not_implemented");
151 assert_eq!(consented["codex"], "not_implemented");
152 assert_eq!(consented["opencode"], "flag_off");
153
154 for (key, value) in [
155 ("agents.quota.claude.consent", "revoked"),
156 ("agents.quota.codex", "off"),
157 ] {
158 let (status, text) = set(key, value).await?;
159 seen.push_str(&text);
160 assert_eq!(status, HttpStatus::OK, "{key}: {text}");
161 }
162 let text = read().await?;
163 seen.push_str(&text);
164 let revoked = reasons(&serde_json::from_str(&text)?);
165 assert_eq!(revoked["claude"], "consent_missing");
166 assert_eq!(revoked["codex"], "flag_off");
167
168 for (key, value) in [
169 ("agents.quota.claude.consent", FIXTURE_TOKEN),
170 ("agents.quota.Claude/../x", "on"),
171 ("agents.quota.claude", FIXTURE_TOKEN),
172 ] {
173 let (status, text) = set(key, value).await?;
174 assert_eq!(status, HttpStatus::BAD_REQUEST, "{key}: {text}");
175 seen.push_str(&text);
176 }
177
178 let (status, text) = set("agents.quota.not-an-agent", "on").await?;
179 seen.push_str(&text);
180 assert_eq!(status, HttpStatus::OK, "{text}");
181 let text = read().await?;
182 seen.push_str(&text);
183 assert_eq!(
184 reasons(&serde_json::from_str(&text)?)["not-an-agent"],
185 "unknown_agent"
186 );
187
188 let settings_file = fs::read_to_string(config_file.with_file_name("settings.toml"))?;
189 assert!(
190 settings_file.contains("[agents.quota.claude]"),
191 "{settings_file}"
192 );
193 assert!(!settings_file.contains(FIXTURE_TOKEN));
194 assert!(
195 !seen.contains(FIXTURE_TOKEN),
196 "a response echoed the fixture token"
197 );
198 assert_eq!(snapshot(&credentials), before, "a credential file changed");
199
200 handle.abort();
201 Ok(())
202 }
203
203 lines RUST