@smbcloud / smbcloud-ascapi Mirror · read-only / commits / 2e63ad6
Fork 0

Read-only mirror of github.com/smbcloudXYZ/smbcloud-ascapi.

Mirrored from https://github.com/smbcloudXYZ/smbcloud-ascapi.git

Synced Nov 25, 09:15 UTC

Handle empty lists, home lookup, bad auth_uri and split redirects

An absent items key in a list response is now an empty list instead of a decode error. default_path falls back to USERPROFILE and errors when no home directory is set, rather than caching under a relative path. An unparseable auth_uri fails login instead of printing an empty URL. The loopback read loops until the request line is complete. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Co-Authored-By: siGit Code v1.7.6 <noreply@sigit.si>

Seto Elkahfi committed Nov 10, 2026 at 00:07 UTC 2e63ad6b299266c9d1f0e1312930f0ac20e0f671
3 files changed +61 -21
crates/admob/src/auth.rs
+43 -14
@@ -140,12 +140,21 @@ impl std::fmt::Debug for StoredToken {
140 }
141
142 impl StoredToken {
143 - /// `~/.config/asc/admob-token.json`.
144 - pub fn default_path() -> PathBuf {
143 + /// `~/.config/asc/admob-token.json`. Falls back to `USERPROFILE` where
144 + /// `HOME` is unset (Windows). Errors rather than caching under a
145 + /// relative path that depends on the working directory.
146 + pub fn default_path() -> Result<PathBuf> {
147 let home = std::env::var_os("HOME")
148 + .filter(|h| !h.is_empty())
149 + .or_else(|| std::env::var_os("USERPROFILE").filter(|h| !h.is_empty()))
150 .map(PathBuf::from)
147 - .unwrap_or_default();
148 - home.join(".config").join("asc").join("admob-token.json")
151 + .ok_or_else(|| {
152 + Error::Authorization(
153 + "cannot locate the home directory: neither HOME nor USERPROFILE is set"
154 + .to_string(),
155 + )
156 + })?;
157 + Ok(home.join(".config").join("asc").join("admob-token.json"))
158 }
159
160 pub fn save(&self, path: &Path) -> Result<()> {
@@ -214,7 +223,7 @@ pub fn authorization_url(
223 redirect_uri: &str,
224 pkce: &Pkce,
225 state: &str,
217 -) -> String {
226 +) -> Result<String> {
227 reqwest::Url::parse_with_params(
228 &client.auth_uri,
229 &[
@@ -231,7 +240,7 @@ pub fn authorization_url(
240 ],
241 )
242 .map(|url| url.to_string())
234 - .unwrap_or_default()
243 + .map_err(|_| Error::ClientInvalid)
244 }
245
246 /// Pull the authorization code out of the loopback request line
@@ -289,7 +298,7 @@ pub async fn login(client: &OAuthClient, token_path: &Path) -> Result<()> {
298 let redirect_uri = format!("http://127.0.0.1:{port}");
299 let pkce = Pkce::generate();
300 let state = random_string(32);
292 - let url = authorization_url(client, &redirect_uri, &pkce, &state);
301 + let url = authorization_url(client, &redirect_uri, &pkce, &state)?;
302
303 eprintln!("Opening the browser to sign in to AdMob. If it does not open, visit:\n{url}");
304 open_browser(&url);
@@ -299,12 +308,22 @@ pub async fn login(client: &OAuthClient, token_path: &Path) -> Result<()> {
308 .accept()
309 .await
310 .map_err(|e| Error::Authorization(e.to_string()))?;
302 - let mut buf = vec![0u8; 8192];
303 - let n = socket
304 - .read(&mut buf)
305 - .await
306 - .map_err(|e| Error::Authorization(e.to_string()))?;
307 - let request = String::from_utf8_lossy(&buf[..n]).into_owned();
311 + // The request line may arrive split across segments: read until it
312 + // ends (or the headers do), with a cap so a stray client cannot
313 + // grow the buffer without bound.
314 + let mut buf = Vec::new();
315 + let mut chunk = [0u8; 1024];
316 + while !buf.contains(&b'\n') && buf.len() < 16 * 1024 {
317 + let n = socket
318 + .read(&mut chunk)
319 + .await
320 + .map_err(|e| Error::Authorization(e.to_string()))?;
321 + if n == 0 {
322 + break;
323 + }
324 + buf.extend_from_slice(&chunk[..n]);
325 + }
326 + let request = String::from_utf8_lossy(&buf).into_owned();
327 let line = request.lines().next().unwrap_or_default();
328 let parsed = parse_callback(line, &state);
329 let body = if parsed.is_ok() {
@@ -479,7 +498,7 @@ mod tests {
498 fn authorization_url_carries_pkce_scopes_and_offline_access() {
499 let client = OAuthClient::from_json(CLIENT_JSON).unwrap();
500 let pkce = Pkce::from_verifier("v".repeat(43));
482 - let url = authorization_url(&client, "http://127.0.0.1:5000", &pkce, "st");
501 + let url = authorization_url(&client, "http://127.0.0.1:5000", &pkce, "st").unwrap();
502 assert!(url.starts_with("https://accounts.google.com/o/oauth2/v2/auth?"));
503 assert!(url.contains("code_challenge_method=S256"));
504 assert!(url.contains("access_type=offline"));
@@ -488,6 +507,16 @@ mod tests {
507 assert!(!url.contains("SECRET"));
508 }
509
510 + #[test]
511 + fn an_unparseable_auth_uri_is_an_error_not_an_empty_url() {
512 + let client = OAuthClient::from_json(
513 + r#"{"installed":{"client_id":"a","client_secret":"b","auth_uri":"not a url"}}"#,
514 + )
515 + .unwrap();
516 + let pkce = Pkce::from_verifier("v".repeat(43));
517 + assert!(authorization_url(&client, "http://127.0.0.1:1", &pkce, "s").is_err());
518 + }
519 +
520 #[test]
521 fn callback_yields_the_code_and_rejects_a_wrong_state() {
522 assert_eq!(
crates/admob/src/client.rs
+16 -5
@@ -48,12 +48,16 @@ pub struct AdmobClient {
48
49 impl AdmobClient {
50 /// `token_path` defaults to `~/.config/asc/admob-token.json`.
51 - pub fn new(oauth: OAuthClient, token_path: Option<PathBuf>) -> Self {
52 - Self {
51 + pub fn new(oauth: OAuthClient, token_path: Option<PathBuf>) -> Result<Self> {
52 + let token_path = match token_path {
53 + Some(path) => path,
54 + None => StoredToken::default_path()?,
55 + };
56 + Ok(Self {
57 http: reqwest::Client::new(),
54 - auth: Authenticator::new(oauth, token_path.unwrap_or_else(StoredToken::default_path)),
58 + auth: Authenticator::new(oauth, token_path),
59 root: API_ROOT.to_string(),
56 - }
60 + })
61 }
62
63 async fn request<T: DeserializeOwned>(
@@ -99,7 +103,14 @@ impl AdmobClient {
103 };
104 let value: serde_json::Value = self.request(Method::GET, &target, None::<&()>).await?;
105 let mut shaped = serde_json::Map::new();
102 - shaped.insert("items".into(), value.get(key).cloned().unwrap_or_default());
106 + // proto3 JSON omits empty repeated fields; an absent key is an empty
107 + // list, and `Value::Null` would not deserialize as a `Vec`.
108 + let items = value
109 + .get(key)
110 + .filter(|v| !v.is_null())
111 + .cloned()
112 + .unwrap_or_else(|| serde_json::Value::Array(Vec::new()));
113 + shaped.insert("items".into(), items);
114 if let Some(next) = value.get("nextPageToken") {
115 shaped.insert("nextPageToken".into(), next.clone());
116 }
crates/frontend/src/admob.rs
+2 -2
@@ -33,13 +33,13 @@ fn oauth_client(path: Option<&Path>) -> Result<OAuthClient, String> {
33 /// Resolve the AdMob client. `path` wins; then `ADMOB_OAUTH_CLIENT_JSON_PATH`.
34 /// Per call, so an unconfigured MCP server still lists its tools.
35 pub fn admob_client(path: Option<&Path>) -> Result<AdmobClient, String> {
36 - Ok(AdmobClient::new(oauth_client(path)?, None))
36 + AdmobClient::new(oauth_client(path)?, None).map_err(err)
37 }
38
39 /// Run the browser sign-in and cache the refresh token.
40 pub async fn login(path: Option<&Path>) -> Result<String, String> {
41 let client = oauth_client(path)?;
42 - let token_path = StoredToken::default_path();
42 + let token_path = StoredToken::default_path().map_err(err)?;
43 auth::login(&client, &token_path).await.map_err(err)?;
44 Ok(format!(
45 "signed in; token cached at {}",