Read-only mirror of github.com/smbcloudXYZ/smbcloud-ascapi.
Mirrored from https://github.com/smbcloudXYZ/smbcloud-ascapi.git
Synced Nov 25, 09:15 UTC
Add an appgallery crate with Service Account auth
smbcloud-ascapi-appgallery signs the PS256 JWT that AppGallery Connect takes as its bearer token, from the key_id, private_key and sub_account in a Service Account credential file. AppGalleryClient sends it to connect-api.cloud.huawei.com and turns non-2xx replies into an error. The Publishing API calls (app info, language info) are not in yet. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Seto Elkahfi committed
Oct 27, 2026 at 15:17 UTC
817eaffdaa9bd85da711dd748c9d6801152fd71a
8 files changed
+337
Cargo.lock
+13
@@ -1755,6 +1755,19 @@ version = "1.16.1"
1755
source = "registry+https://github.com/rust-lang/crates.io-index"
1756
checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891"
1757
1758
+[[package]]
1759
+name = "smbcloud-ascapi-appgallery"
1760
+version = "0.3.0"
1761
+dependencies = [
1762
+ "jsonwebtoken",
1763
+ "rand 0.8.8",
1764
+ "reqwest",
1765
+ "rsa",
1766
+ "serde",
1767
+ "serde_json",
1768
+ "thiserror",
1769
+]
1770
+
1771
[[package]]
1772
name = "smbcloud-ascapi-aso"
1773
version = "0.3.0"
Cargo.toml
+2
@@ -4,6 +4,7 @@ members = [
4
"crates/core",
5
"crates/aso",
6
"crates/play",
7
+ "crates/appgallery",
8
"crates/signing",
9
"crates/pricing",
10
"crates/reports",
@@ -23,6 +24,7 @@ repository = "https://github.com/smbcloudXYZ/smbcloud-ascapi"
24
smbcloud-ascapi-core = { version = "0.3.0", path = "crates/core" }
25
smbcloud-ascapi-aso = { version = "0.3.0", path = "crates/aso" }
26
smbcloud-ascapi-play = { version = "0.3.0", path = "crates/play" }
27
+smbcloud-ascapi-appgallery = { version = "0.3.0", path = "crates/appgallery" }
28
smbcloud-ascapi-signing = { version = "0.3.0", path = "crates/signing" }
29
smbcloud-ascapi-pricing = { version = "0.3.0", path = "crates/pricing" }
30
smbcloud-ascapi-reports = { version = "0.3.0", path = "crates/reports" }
crates/appgallery/Cargo.toml
new
+23
@@ -0,0 +1,23 @@
1
+[package]
2
+name = "smbcloud-ascapi-appgallery"
3
+version.workspace = true
4
+edition.workspace = true
5
+authors.workspace = true
6
+license.workspace = true
7
+repository.workspace = true
8
+description = "Huawei AppGallery Connect API: Service Account (PS256 JWT) authentication and the HTTP client the Publishing API calls build on."
9
+readme = "README.md"
10
+
11
+[lib]
12
+path = "src/lib.rs"
13
+
14
+[dependencies]
15
+jsonwebtoken = { workspace = true }
16
+reqwest = { workspace = true, features = ["json", "rustls-tls-native-roots"] }
17
+serde = { workspace = true, features = ["derive"] }
18
+serde_json = { workspace = true }
19
+thiserror = { workspace = true }
20
+
21
+[dev-dependencies]
22
+rand = { workspace = true }
23
+rsa = { workspace = true, features = ["pem"] }
crates/appgallery/README.md
new
+22
@@ -0,0 +1,22 @@
1
+# smbcloud-ascapi-appgallery
2
+
3
+Huawei AppGallery Connect API. A sibling of `smbcloud-ascapi-play`: it shares
4
+nothing with `smbcloud-ascapi-core` and has its own credentials and error
5
+envelope.
6
+
7
+Authentication is Service Account mode, the mode Huawei recommends. Create a
8
+developer-level Service Account under Users and permissions > API key >
9
+Connect API, with a role that may publish (Administrator, App administrator or
10
+Operations). Its `*private.json` credential file holds `key_id`,
11
+`private_key`, `sub_account` and `token_uri`. The JWT signed from it is itself
12
+the token: `Authorization: Bearer <jwt>` to `connect-api.cloud.huawei.com`.
13
+
14
+```rust
15
+use smbcloud_ascapi_appgallery::{AppGalleryClient, ServiceAccount};
16
+
17
+let account = ServiceAccount::from_json_file("xxxprivate.json")?;
18
+let client = AppGalleryClient::new(account);
19
+```
20
+
21
+Status: authentication and the client are in. The Publishing API calls
22
+(app info, language info) are not.
crates/appgallery/src/auth.rs
new
+168
@@ -0,0 +1,168 @@
1
+use std::path::Path;
2
+
3
+use jsonwebtoken::{Algorithm, EncodingKey, Header};
4
+use serde::{Deserialize, Serialize};
5
+
6
+use crate::error::{Error, Result};
7
+
8
+/// The `aud` Huawei requires in the JWT.
9
+pub const TOKEN_URI: &str = "https://oauth-login.cloud.huawei.com/oauth2/v3/token";
10
+/// Huawei's JWT lifetime: `exp` is 3600 seconds after `iat`.
11
+const JWT_LIFETIME_SECS: u64 = 3600;
12
+
13
+/// The fields of an AppGallery Connect Service Account credential file
14
+/// (`*private.json`) this crate uses.
15
+#[derive(Clone, Deserialize)]
16
+pub struct ServiceAccount {
17
+ pub key_id: String,
18
+ private_key: String,
19
+ pub sub_account: String,
20
+}
21
+
22
+// Hand-written so `{:?}` can never print the private key.
23
+impl std::fmt::Debug for ServiceAccount {
24
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25
+ f.debug_struct("ServiceAccount")
26
+ .field("key_id", &self.key_id)
27
+ .field("sub_account", &self.sub_account)
28
+ .field("private_key", &"<redacted>")
29
+ .finish()
30
+ }
31
+}
32
+
33
+impl ServiceAccount {
34
+ pub fn from_json(json: &str) -> Result<Self> {
35
+ let account: Self = serde_json::from_str(json).map_err(|_| Error::ServiceAccountInvalid)?;
36
+ if account.key_id.is_empty()
37
+ || account.private_key.is_empty()
38
+ || account.sub_account.is_empty()
39
+ {
40
+ return Err(Error::ServiceAccountInvalid);
41
+ }
42
+ Ok(account)
43
+ }
44
+
45
+ pub fn from_json_file(path: impl AsRef<Path>) -> Result<Self> {
46
+ let path = path.as_ref();
47
+ let json = std::fs::read_to_string(path).map_err(|source| Error::ServiceAccountRead {
48
+ path: path.display().to_string(),
49
+ source,
50
+ })?;
51
+ Self::from_json(&json)
52
+ }
53
+
54
+ /// Sign the PS256 JWT that serves as the bearer token. `now_secs` is Unix
55
+ /// time in seconds; Huawei needs the local clock to be accurate.
56
+ pub fn assertion(&self, now_secs: u64) -> Result<String> {
57
+ let claims = Claims::new(&self.sub_account, now_secs);
58
+ let mut header = Header::new(Algorithm::PS256);
59
+ header.typ = Some("JWT".to_string());
60
+ header.kid = Some(self.key_id.clone());
61
+ let key = EncodingKey::from_rsa_pem(self.private_key.as_bytes())?;
62
+ Ok(jsonwebtoken::encode(&header, &claims, &key)?)
63
+ }
64
+}
65
+
66
+#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
67
+pub(crate) struct Claims {
68
+ pub aud: String,
69
+ pub iss: String,
70
+ pub exp: u64,
71
+ pub iat: u64,
72
+}
73
+
74
+impl Claims {
75
+ pub(crate) fn new(sub_account: &str, now_secs: u64) -> Self {
76
+ Self {
77
+ aud: TOKEN_URI.to_string(),
78
+ iss: sub_account.to_string(),
79
+ exp: now_secs + JWT_LIFETIME_SECS,
80
+ iat: now_secs,
81
+ }
82
+ }
83
+}
84
+
85
+#[cfg(test)]
86
+mod tests {
87
+ use super::*;
88
+ use jsonwebtoken::{decode, decode_header, DecodingKey, Validation};
89
+ use rsa::pkcs8::{EncodePrivateKey, EncodePublicKey, LineEnding};
90
+ use rsa::RsaPrivateKey;
91
+
92
+ fn json_with_key(pem: &str) -> String {
93
+ serde_json::json!({
94
+ "key_id": "kid-1",
95
+ "private_key": pem,
96
+ "sub_account": "1099",
97
+ })
98
+ .to_string()
99
+ }
100
+
101
+ #[test]
102
+ fn claims_carry_audience_issuer_and_one_hour_lifetime() {
103
+ let claims = Claims::new("1099", 1000);
104
+ assert_eq!(
105
+ claims.aud,
106
+ "https://oauth-login.cloud.huawei.com/oauth2/v3/token"
107
+ );
108
+ assert_eq!(claims.iss, "1099");
109
+ assert_eq!(claims.iat, 1000);
110
+ assert_eq!(claims.exp, 4600);
111
+ }
112
+
113
+ #[test]
114
+ fn the_jwt_is_ps256_with_kid_and_verifies_against_the_public_key() {
115
+ let mut rng = rand::thread_rng();
116
+ let key = RsaPrivateKey::new(&mut rng, 2048).unwrap();
117
+ let private_pem = key.to_pkcs8_pem(LineEnding::LF).unwrap();
118
+ let public_pem = key
119
+ .to_public_key()
120
+ .to_public_key_pem(LineEnding::LF)
121
+ .unwrap();
122
+
123
+ let account = ServiceAccount::from_json(&json_with_key(&private_pem)).unwrap();
124
+ let now = std::time::SystemTime::now()
125
+ .duration_since(std::time::UNIX_EPOCH)
126
+ .unwrap()
127
+ .as_secs();
128
+ let jwt = account.assertion(now).unwrap();
129
+
130
+ let header = decode_header(&jwt).unwrap();
131
+ assert_eq!(header.alg, Algorithm::PS256);
132
+ assert_eq!(header.kid.as_deref(), Some("kid-1"));
133
+ assert_eq!(header.typ.as_deref(), Some("JWT"));
134
+
135
+ let mut validation = Validation::new(Algorithm::PS256);
136
+ validation.set_audience(&[TOKEN_URI]);
137
+ let decoded = decode::<Claims>(
138
+ &jwt,
139
+ &DecodingKey::from_rsa_pem(public_pem.as_bytes()).unwrap(),
140
+ &validation,
141
+ )
142
+ .unwrap();
143
+ assert_eq!(decoded.claims.iss, "1099");
144
+ }
145
+
146
+ #[test]
147
+ fn a_key_file_missing_the_key_is_rejected_without_echoing_it() {
148
+ let err = ServiceAccount::from_json(&json_with_key(""))
149
+ .unwrap_err()
150
+ .to_string();
151
+ assert!(!err.contains("kid-1"));
152
+ assert!(ServiceAccount::from_json("not json").is_err());
153
+ }
154
+
155
+ #[test]
156
+ fn debug_output_never_contains_the_private_key() {
157
+ let account = ServiceAccount::from_json(&json_with_key("SECRET")).unwrap();
158
+ let shown = format!("{account:?}");
159
+ assert!(!shown.contains("SECRET"));
160
+ assert!(shown.contains("kid-1"));
161
+ }
162
+
163
+ #[test]
164
+ fn a_malformed_pem_fails_to_sign_instead_of_panicking() {
165
+ let account = ServiceAccount::from_json(&json_with_key("nope")).unwrap();
166
+ assert!(account.assertion(0).is_err());
167
+ }
168
+}
crates/appgallery/src/client.rs
new
+65
@@ -0,0 +1,65 @@
1
+use std::time::{SystemTime, UNIX_EPOCH};
2
+
3
+use reqwest::Method;
4
+
5
+use crate::auth::ServiceAccount;
6
+use crate::error::{Error, Result};
7
+
8
+const API_ROOT: &str = "https://connect-api.cloud.huawei.com";
9
+
10
+/// A signed-in AppGallery Connect client. Every request carries a freshly
11
+/// signed JWT as its bearer token; signing is local, so there is no token
12
+/// exchange to cache.
13
+pub struct AppGalleryClient {
14
+ http: reqwest::Client,
15
+ account: ServiceAccount,
16
+ root: String,
17
+}
18
+
19
+impl AppGalleryClient {
20
+ pub fn new(account: ServiceAccount) -> Self {
21
+ Self {
22
+ http: reqwest::Client::new(),
23
+ account,
24
+ root: API_ROOT.to_string(),
25
+ }
26
+ }
27
+
28
+ /// The Service Account's key id, for diagnostics.
29
+ pub fn key_id(&self) -> &str {
30
+ &self.account.key_id
31
+ }
32
+
33
+ /// Send an authenticated request and return the response when it is a
34
+ /// 2xx, otherwise [`Error::Api`]. `path_and_query` starts with `/`. The
35
+ /// typed Publishing API calls build on this.
36
+ pub async fn send(
37
+ &self,
38
+ method: Method,
39
+ path_and_query: &str,
40
+ json_body: Option<&serde_json::Value>,
41
+ ) -> Result<reqwest::Response> {
42
+ let now = SystemTime::now()
43
+ .duration_since(UNIX_EPOCH)
44
+ .map(|d| d.as_secs())
45
+ .unwrap_or(0);
46
+ let token = self.account.assertion(now)?;
47
+ let mut request = self
48
+ .http
49
+ .request(method, format!("{}{path_and_query}", self.root))
50
+ .bearer_auth(token);
51
+ if let Some(body) = json_body {
52
+ request = request.json(body);
53
+ }
54
+ let response = request.send().await?;
55
+ let status = response.status();
56
+ if status.is_success() {
57
+ Ok(response)
58
+ } else {
59
+ Err(Error::Api {
60
+ status: status.as_u16(),
61
+ detail: response.text().await.unwrap_or_default(),
62
+ })
63
+ }
64
+ }
65
+}
crates/appgallery/src/error.rs
new
+30
@@ -0,0 +1,30 @@
1
+use thiserror::Error;
2
+
3
+#[derive(Debug, Error)]
4
+pub enum Error {
5
+ #[error("failed to read the service account file {path}: {source}")]
6
+ ServiceAccountRead {
7
+ path: String,
8
+ #[source]
9
+ source: std::io::Error,
10
+ },
11
+
12
+ /// Deliberately carries no part of the file: a parse error could
13
+ /// otherwise quote key material.
14
+ #[error("the service account JSON is not valid or lacks key_id/private_key/sub_account")]
15
+ ServiceAccountInvalid,
16
+
17
+ #[error("failed to sign the service account JWT: {0}")]
18
+ Jwt(#[from] jsonwebtoken::errors::Error),
19
+
20
+ #[error("http request failed: {0}")]
21
+ Http(#[from] reqwest::Error),
22
+
23
+ #[error("failed to decode JSON response: {0}")]
24
+ Json(#[from] serde_json::Error),
25
+
26
+ #[error("AppGallery Connect API returned {status}: {detail}")]
27
+ Api { status: u16, detail: String },
28
+}
29
+
30
+pub type Result<T> = std::result::Result<T, Error>;
crates/appgallery/src/lib.rs
new
+14
@@ -0,0 +1,14 @@
1
+//! Huawei AppGallery Connect API.
2
+//!
3
+//! Service Account mode: the credential file's `private_key` signs a PS256 JWT
4
+//! that is sent as the bearer token (see [`ServiceAccount::assertion`]).
5
+//! [`AppGalleryClient`] holds the account and the HTTP client the Publishing
6
+//! API calls are built on.
7
+
8
+pub mod auth;
9
+pub mod client;
10
+pub mod error;
11
+
12
+pub use auth::ServiceAccount;
13
+pub use client::AppGalleryClient;
14
+pub use error::{Error, Result};