Skip to main content

instapi360_cloud/
signing.rs

1//! Request signing.
2//!
3//! Reverse-engineering status (see project plan, Steps 2–3):
4//! `studio_worker.dll` computes the signature with **HMAC-SHA256**
5//! (OpenSSL `HMAC_Init_ex/Update/Final` + `EVP_sha256`) over an ordered
6//! query-style param string. A verbatim template found in the binary:
7//!
8//! ```text
9//! %1?share_type=pc&client_key=%2&nonce_str=%3&timestamp=%4&signature=%5&...
10//! ```
11//!
12//! i.e. `signature = HMAC_SHA256(sign_key, canonical_params)`, hex-encoded.
13//!
14//! Two things still need confirming against a live capture before signed
15//! endpoints will succeed: (1) the exact **key** (`ClientConfig::sign_key`),
16//! and (2) the exact **param set + ordering** that goes into the canonical
17//! string. This module centralizes both so a single edit finalizes signing.
18
19use hmac::{Hmac, Mac};
20use sha2::Sha256;
21
22use crate::config::ClientConfig;
23use crate::error::{Error, Result};
24
25type HmacSha256 = Hmac<Sha256>;
26
27/// Parameters that vary per request and feed the canonical string.
28#[derive(Debug, Clone)]
29pub struct SignParams {
30    pub client_key: String,
31    pub nonce: String,
32    pub timestamp: String,
33}
34
35/// A computed signature plus the nonce/timestamp that produced it, so the
36/// caller can attach all three to the request consistently.
37#[derive(Debug, Clone)]
38pub struct Signature {
39    pub signature: String,
40    pub nonce: String,
41    pub timestamp: String,
42}
43
44/// Builds request signatures from the static [`ClientConfig`] material.
45#[derive(Debug, Clone)]
46pub struct Signer {
47    app_key: String,
48    sign_key: String,
49    can_sign: bool,
50}
51
52impl Signer {
53    pub fn new(cfg: &ClientConfig) -> Self {
54        Signer {
55            app_key: cfg.app_key.clone(),
56            sign_key: cfg.sign_key.clone(),
57            can_sign: cfg.can_sign(),
58        }
59    }
60
61    /// Build the canonical string that gets HMAC'd.
62    ///
63    /// Param ordering mirrors the template recovered from the binary. This is
64    /// the single place to adjust once capture pins down the full field list.
65    fn canonical(&self, p: &SignParams) -> String {
66        // NOTE: keep keys in the exact recovered order; do NOT sort.
67        format!(
68            "share_type=pc&client_key={}&nonce_str={}&timestamp={}",
69            p.client_key, p.nonce, p.timestamp
70        )
71    }
72
73    /// Compute `HMAC_SHA256(sign_key, canonical)` as lowercase hex.
74    ///
75    /// `nonce` and `timestamp` are caller-supplied so they can be reproduced in
76    /// tests against captured fixtures; production code uses [`Self::sign_now`].
77    pub fn sign(&self, nonce: &str, timestamp: &str) -> Result<Signature> {
78        if !self.can_sign {
79            return Err(Error::Signing(
80                "app_key/sign_key not configured — recover them via capture (plan Steps 2–3)"
81                    .into(),
82            ));
83        }
84        let params = SignParams {
85            client_key: self.app_key.clone(),
86            nonce: nonce.to_string(),
87            timestamp: timestamp.to_string(),
88        };
89        let canonical = self.canonical(&params);
90        let mut mac = HmacSha256::new_from_slice(self.sign_key.as_bytes())
91            .map_err(|e| Error::Signing(format!("bad hmac key: {e}")))?;
92        mac.update(canonical.as_bytes());
93        let sig = hex::encode(mac.finalize().into_bytes());
94        Ok(Signature {
95            signature: sig,
96            nonce: nonce.to_string(),
97            timestamp: timestamp.to_string(),
98        })
99    }
100
101    /// Whether this signer has the material needed to produce a signature.
102    pub fn is_ready(&self) -> bool {
103        self.can_sign
104    }
105}
106
107/// A random-ish nonce string. Uses the timestamp plus a process-local counter;
108/// nonces only need to be unique per request, not cryptographically strong.
109/// Retained for the share-link endpoints, which do use the HMAC scheme.
110#[allow(dead_code)]
111pub fn make_nonce(seed: u64) -> String {
112    // 16 hex chars derived from the seed via a splitmix step.
113    let mut x = seed.wrapping_add(0x9E37_79B9_7F4A_7C15);
114    x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
115    x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
116    x ^= x >> 31;
117    format!("{x:016x}")
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123
124    fn cfg_with(app_key: &str, sign_key: &str) -> ClientConfig {
125        let mut c = ClientConfig::windows(crate::config::Region::Global);
126        c.app_key = app_key.to_string();
127        c.sign_key = sign_key.to_string();
128        c
129    }
130
131    #[test]
132    fn unconfigured_signer_refuses() {
133        let signer = Signer::new(&ClientConfig::windows(crate::config::Region::Global));
134        assert!(!signer.is_ready());
135        assert!(signer.sign("abc", "123").is_err());
136    }
137
138    #[test]
139    fn hmac_is_deterministic() {
140        let signer = Signer::new(&cfg_with("APPKEY", "secret"));
141        let a = signer.sign("nonce1", "1700000000").unwrap();
142        let b = signer.sign("nonce1", "1700000000").unwrap();
143        assert_eq!(a.signature, b.signature);
144        // Different nonce -> different signature.
145        let c = signer.sign("nonce2", "1700000000").unwrap();
146        assert_ne!(a.signature, c.signature);
147    }
148
149    // Placeholder for the byte-for-byte fixture test (plan Verification #3):
150    // once a real request is captured, assert the recovered algorithm
151    // reproduces its `signature` exactly.
152    #[test]
153    #[ignore = "needs captured request fixture (plan Step 2)"]
154    fn reproduces_captured_signature() {
155        // let signer = Signer::new(&cfg_with(REAL_APP_KEY, REAL_SIGN_KEY));
156        // let s = signer.sign(CAPTURED_NONCE, CAPTURED_TS).unwrap();
157        // assert_eq!(s.signature, CAPTURED_SIGNATURE);
158    }
159}