@smbcloud / smbcloud-ascapi Mirror · read-only / commits / fa5574f
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

Keep a created unit when the read-back fails, name the sign-in remedy

A failed or inconclusive list after a successful create is now a warning in the result instead of an error, so a retrying script cannot create a duplicate unit. A 400 invalid_grant on refresh says to delete the token cache and log in again. The several-accounts message no longer mentions a CLI flag, since the MCP tools use a request field. 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 08:56 UTC fa5574fa63d4215782c8d8efd34aa76f8b439eda
4 files changed +63 -13
crates/admob/src/auth.rs
+28 -1
@@ -370,6 +370,17 @@ pub async fn login(client: &OAuthClient, token_path: &Path) -> Result<()> {
370 StoredToken { refresh_token }.save(token_path)
371 }
372
373 +/// A revoked or long-expired refresh token: Google answers 400 with
374 +/// `"error": "invalid_grant"`.
375 +pub(crate) fn is_invalid_grant(status: u16, detail: &str) -> bool {
376 + status == 400
377 + && serde_json::from_str::<serde_json::Value>(detail)
378 + .ok()
379 + .and_then(|v| v.get("error").and_then(|e| e.as_str().map(str::to_owned)))
380 + .as_deref()
381 + == Some("invalid_grant")
382 +}
383 +
384 /// Turns the cached refresh token into short-lived access tokens.
385 pub(crate) struct Authenticator {
386 client: OAuthClient,
@@ -406,9 +417,15 @@ impl Authenticator {
417 .await?;
418 let status = response.status();
419 if !status.is_success() {
420 + let detail = response.text().await.unwrap_or_default();
421 + if is_invalid_grant(status.as_u16(), &detail) {
422 + return Err(Error::SignInExpired {
423 + path: self.token_path.display().to_string(),
424 + });
425 + }
426 return Err(Error::Token {
427 status: status.as_u16(),
411 - detail: response.text().await.unwrap_or_default(),
428 + detail,
429 });
430 }
431 let body: TokenResponse = response.json().await?;
@@ -517,6 +534,16 @@ mod tests {
534 assert!(authorization_url(&client, "http://127.0.0.1:1", &pkce, "s").is_err());
535 }
536
537 + #[test]
538 + fn invalid_grant_is_recognized_only_for_a_400_with_that_error() {
539 + let body =
540 + r#"{"error":"invalid_grant","error_description":"Token has been expired or revoked."}"#;
541 + assert!(is_invalid_grant(400, body));
542 + assert!(!is_invalid_grant(500, body));
543 + assert!(!is_invalid_grant(400, r#"{"error":"invalid_client"}"#));
544 + assert!(!is_invalid_grant(400, "not json"));
545 + }
546 +
547 #[test]
548 fn callback_yields_the_code_and_rejects_a_wrong_state() {
549 assert_eq!(
crates/admob/src/error.rs
+6
@@ -39,6 +39,12 @@ pub enum Error {
39 #[error("Google OAuth token exchange returned {status}: {detail}")]
40 Token { status: u16, detail: String },
41
42 + #[error(
43 + "Google rejected the cached sign-in (invalid_grant: revoked or expired). Delete {path} and \
44 + run `asc admob login` again"
45 + )]
46 + SignInExpired { path: String },
47 +
48 #[error("AdMob API returned {status}: {detail}")]
49 Api { status: u16, detail: String },
50
crates/frontend/src/admob.rs
+28 -11
@@ -64,7 +64,7 @@ pub async fn resolve_account(
64 [only] => Ok(only.name.clone()),
65 [] => Err("this Google user has no AdMob account".to_string()),
66 many => Err(format!(
67 - "several AdMob accounts ({}); pass --account",
67 + "several AdMob accounts ({}); specify the account",
68 many.iter()
69 .map(|a| a.name.as_str())
70 .collect::<Vec<_>>()
@@ -117,11 +117,18 @@ pub fn plan_create(
117 #[derive(Debug, Serialize)]
118 pub struct CreatedAdUnit {
119 pub created: AdUnit,
120 - /// Set after reading the units back with `adunits list`.
120 + /// Whether the unit showed up when the list was read back.
121 pub confirmed_in_list: bool,
122 + /// Set when the read-back failed or did not show the unit. The create
123 + /// itself succeeded, so this is never an error: a caller that retried on
124 + /// failure would create a duplicate.
125 + #[serde(skip_serializing_if = "Option::is_none")]
126 + pub warning: Option<String>,
127 }
128
124 -/// Create the unit, then read the list back and confirm it is there.
129 +/// Create the unit, then read the list back to confirm it is there. Only a
130 +/// failed create is an error; a failed or inconclusive read-back is reported
131 +/// in the result.
132 pub async fn create_ad_unit(
133 client: &AdmobClient,
134 account: Option<&str>,
@@ -129,17 +136,27 @@ pub async fn create_ad_unit(
136 ) -> Result<CreatedAdUnit, String> {
137 let account = resolve_account(client, account).await?;
138 let created = client.create_ad_unit(&account, body).await.map_err(err)?;
132 - let listed = client.list_ad_units(&account).await.map_err(err)?;
133 - let confirmed_in_list = listed.iter().any(|u| u.name == created.name);
134 - if !confirmed_in_list {
135 - return Err(format!(
136 - "AdMob accepted the create ({}) but the unit is not in the list yet; run `asc admob adunits list`",
137 - created.name
138 - ));
139 - }
139 + let (confirmed_in_list, warning) = match client.list_ad_units(&account).await {
140 + Ok(listed) if listed.iter().any(|u| u.name == created.name) => (true, None),
141 + Ok(_) => (
142 + false,
143 + Some(format!(
144 + "created {}, but it is not in the list yet; run `asc admob adunits list` before retrying",
145 + created.name
146 + )),
147 + ),
148 + Err(e) => (
149 + false,
150 + Some(format!(
151 + "created {}, but reading the list back failed ({e}); run `asc admob adunits list` before retrying",
152 + created.name
153 + )),
154 + ),
155 + };
156 Ok(CreatedAdUnit {
157 created,
158 confirmed_in_list,
159 + warning,
160 })
161 }
162
docs/admob.md
+1 -1
@@ -36,7 +36,7 @@ asc admob adunits create --app ca-app-pub-...~... --name "Karaoke rewarded" \
36
37 `--account` defaults to the only account the user has. `--dry-run` on `create`
38 prints the request body and needs neither credentials nor a sign-in. After a
39 -real create, `asc` reads the units back and fails if the new one is missing.
39 +real create, `asc` reads the units back to confirm. If that read fails or the unit is not listed yet, the create still counts as done and the result carries a `warning`, so check `adunits list` before retrying.
40
41 The MCP server exposes `admob_apps_list` and `admob_adunits_list`, both
42 read-only. They never open a browser; without a cached sign-in they say to run