solignition-cli 2.0.0

CLI tool for deploying Solana programs via the Solignition lending protocol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
// Response structs intentionally expose every field returned by the deployer
// service for forward compatibility and Debug output, even when not all
// fields are read by the CLI today.
#![allow(dead_code)]

use anyhow::{anyhow, Context, Result};
use rand::RngCore;
use reqwest::header::{HeaderMap, HeaderValue};
use reqwest::multipart;
use serde::Deserialize;
use sha2::{Digest, Sha256};
use solana_sdk::signature::Keypair;
use solana_sdk::signer::Signer;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;

/// Wire-format version tag for the shared CLI/frontend auth spec.
const AUTH_VERSION_TAG: &str = "solignition-auth-v1";

/// SHA-256 of the empty string, in lowercase hex. Used as `BODY_HASH_HEX` for
/// GET requests and any other body-less request.
const EMPTY_BODY_HASH: &str =
    "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";

/// Auth headers produced by signing the canonical request message.
#[derive(Debug)]
struct AuthHeaders {
    pubkey_b58: String,
    timestamp_ms: String,
    nonce_b58: String,
    signature_b58: String,
}

impl AuthHeaders {
    fn apply(self, mut req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
        req = req.header("X-Auth-Pubkey", self.pubkey_b58);
        req = req.header("X-Auth-Timestamp", self.timestamp_ms);
        req = req.header("X-Auth-Nonce", self.nonce_b58);
        req = req.header("X-Auth-Signature", self.signature_b58);
        req
    }
}

fn sha256_hex(bytes: &[u8]) -> String {
    let digest = Sha256::digest(bytes);
    hex::encode(digest)
}

// ─── Response Types ──────────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
pub struct UploadResponse {
    pub success: bool,
    #[serde(rename = "fileId")]
    pub file_id: String,
    #[serde(rename = "estimatedCost")]
    pub estimated_cost: f64,
    #[serde(rename = "binaryHash")]
    pub binary_hash: String,
    pub message: String,
}

#[derive(Debug, Deserialize)]
pub struct FileUploadInfo {
    #[serde(rename = "fileId")]
    pub file_id: String,
    pub borrower: String,
    #[serde(rename = "fileName")]
    pub file_name: String,
    #[serde(rename = "fileSize")]
    pub file_size: u64,
    #[serde(rename = "binaryHash")]
    pub binary_hash: String,
    #[serde(rename = "estimatedCost")]
    pub estimated_cost: f64,
    pub status: String,
    #[serde(rename = "createdAt")]
    pub created_at: u64,
}

#[derive(Debug, Deserialize)]
pub struct NotifyLoanResponse {
    pub success: bool,
    pub message: String,
    pub signature: Option<String>,
    #[serde(rename = "fileId")]
    pub file_id: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct NotifyRepaidResponse {
    pub success: bool,
    pub message: String,
    pub tx: Option<String>,
    #[serde(rename = "loanId")]
    pub loan_id: Option<String>,
}

#[derive(Debug, Deserialize, Clone)]
pub struct DeploymentInfo {
    #[serde(rename = "loanId")]
    pub loan_id: String,
    pub borrower: String,
    #[serde(rename = "programId")]
    pub program_id: Option<String>,
    #[serde(rename = "deploymentCost")]
    pub deployment_cost: Option<f64>,
    #[serde(rename = "deployTxSignature")]
    pub deploy_tx_signature: Option<String>,
    #[serde(rename = "setDeployedTxSignature")]
    pub set_deployed_tx_signature: Option<String>,
    #[serde(rename = "recoveryTxSignature")]
    pub recovery_tx_signature: Option<String>,
    pub status: String,
    pub error: Option<String>,
    #[serde(rename = "createdAt")]
    pub created_at: u64,
    #[serde(rename = "updatedAt")]
    pub updated_at: u64,
    #[serde(rename = "binaryHash")]
    pub binary_hash: Option<String>,
    pub principal: Option<String>,
    #[serde(rename = "programAccountOpen")]
    pub program_account_open: Option<bool>,
}

#[derive(Debug, Deserialize)]
pub struct HealthResponse {
    pub status: String,
    // The v1 /health body is `{"status":"ok"}` only -- counts and timestamp
    // moved to /metrics. Kept as Option here so the existing health display
    // path still compiles; the CLI display unwraps with sensible fallbacks.
    #[serde(rename = "activeLoans")]
    pub active_loans: Option<u64>,
    #[serde(rename = "totalDeployments")]
    pub total_deployments: Option<u64>,
    pub timestamp: Option<String>,
}

/// Paginated envelope returned by `GET /v1/uploads`.
#[derive(Debug, Deserialize)]
struct PaginatedUploads {
    uploads: Vec<FileUploadInfo>,
    #[allow(dead_code)]
    total: u64,
    #[serde(rename = "hasMore")]
    #[allow(dead_code)]
    has_more: bool,
}

/// Paginated envelope returned by `GET /v1/deployments`.
#[derive(Debug, Deserialize)]
struct PaginatedDeployments {
    deployments: Vec<DeploymentInfo>,
    #[allow(dead_code)]
    total: u64,
    #[serde(rename = "hasMore")]
    #[allow(dead_code)]
    has_more: bool,
}

#[derive(Debug, Deserialize)]
pub struct ErrorResponse {
    pub error: String,
}

// ─── Client ──────────────────────────────────────────────────────────────────

pub struct DeployerClient {
    client: reqwest::Client,
    base_url: String,
    /// Signer used to produce `X-Auth-*` headers. `None` only for the anonymous
    /// `/health` call site (constructed via `new_anonymous`).
    signer: Option<Arc<Keypair>>,
}

impl DeployerClient {
    fn build_client() -> reqwest::Client {
        let mut default_headers = HeaderMap::new();
        default_headers.insert(
            "ngrok-skip-browser-warning",
            HeaderValue::from_static("true"),
        );

        reqwest::Client::builder()
            .user_agent(concat!("solignition-cli/", env!("CARGO_PKG_VERSION")))
            .default_headers(default_headers)
            .timeout(Duration::from_secs(60))
            .connect_timeout(Duration::from_secs(10))
            .build()
            .expect("failed to build HTTP client")
    }

    pub fn new(base_url: &str, signer: Arc<Keypair>) -> Self {
        Self {
            client: Self::build_client(),
            base_url: base_url.trim_end_matches('/').to_string(),
            signer: Some(signer),
        }
    }

    /// Anonymous client for endpoints that don't require auth (e.g. `/health`).
    pub fn new_anonymous(base_url: &str) -> Self {
        Self {
            client: Self::build_client(),
            base_url: base_url.trim_end_matches('/').to_string(),
            signer: None,
        }
    }

    fn signer(&self) -> Result<&Keypair> {
        self.signer
            .as_deref()
            .ok_or_else(|| anyhow!("DeployerClient was constructed anonymously; cannot sign request"))
    }

    /// Build the `X-Auth-*` headers for a request per the shared auth spec.
    ///
    /// `body_hash_hex` must be the lowercase-hex SHA-256 of the exact body bytes
    /// the client will write to the wire (file bytes for multipart, raw JSON bytes
    /// for JSON, `EMPTY_BODY_HASH` for body-less requests).
    fn sign_request(&self, method: &str, path: &str, body_hash_hex: &str) -> Result<AuthHeaders> {
        let signer = self.signer()?;

        let timestamp_ms = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis().to_string())
            .unwrap_or_else(|_| "0".to_string());

        let mut nonce_bytes = [0u8; 16];
        rand::thread_rng().fill_bytes(&mut nonce_bytes);
        let nonce_b58 = bs58::encode(nonce_bytes).into_string();

        let canonical = format!(
            "{tag}\n{method}\n{path}\n{ts}\n{nonce}\n{body_hash}",
            tag = AUTH_VERSION_TAG,
            method = method,
            path = path,
            ts = timestamp_ms,
            nonce = nonce_b58,
            body_hash = body_hash_hex,
        );

        let signature = signer.sign_message(canonical.as_bytes());
        let signature_b58 = bs58::encode(signature.as_ref()).into_string();

        Ok(AuthHeaders {
            pubkey_b58: signer.pubkey().to_string(),
            timestamp_ms,
            nonce_b58,
            signature_b58,
        })
    }

    /// Upload a .so binary file.
    ///
    /// Signs the request with the borrower's keypair and verifies the deployer's
    /// returned `binary_hash` matches the local SHA-256 — guards against silent
    /// transit corruption or a substituted binary.
    pub async fn upload_file(&self, file_path: &Path, borrower: &str) -> Result<UploadResponse> {
        let file_name = file_path
            .file_name()
            .unwrap_or_default()
            .to_string_lossy()
            .to_string();

        let file_bytes = tokio::fs::read(file_path).await
            .with_context(|| format!("Failed to read file: {}", file_path.display()))?;

        let local_hash = sha256_hex(&file_bytes);

        // For multipart `POST /v1/uploads`, the body hash is sha256(file_bytes)
        // only -- the `borrower` and `expectedHash` form fields are enforced
        // separately (authz match + server-side hash recompute respectively).
        let auth = self.sign_request("POST", "/v1/uploads", &local_hash)?;

        let file_part = multipart::Part::bytes(file_bytes)
            .file_name(file_name)
            .mime_str("application/octet-stream")?;

        // Hash-pin the upload: the deployer rejects 422 `hash_mismatch` when
        // its computed hash disagrees with the client-supplied value. Cheap
        // integrity check for transit corruption and wrong-file mix-ups.
        let form = multipart::Form::new()
            .text("borrower", borrower.to_string())
            .text("expectedHash", local_hash.clone())
            .part("file", file_part);

        let req = self
            .client
            .post(format!("{}/v1/uploads", self.base_url))
            .multipart(form);

        let resp = auth
            .apply(req)
            .send()
            .await
            .context("Failed to connect to deployer API")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Upload failed ({}): {}", status, body);
        }

        let parsed: UploadResponse = resp
            .json()
            .await
            .context("Failed to parse upload response")?;

        if !parsed.binary_hash.eq_ignore_ascii_case(&local_hash) {
            anyhow::bail!(
                "Upload integrity check failed: deployer reported binary_hash `{}` but local file hash is `{}`",
                parsed.binary_hash,
                local_hash,
            );
        }

        Ok(parsed)
    }

    /// Get upload info by file ID
    pub async fn get_upload(&self, file_id: &str) -> Result<FileUploadInfo> {
        let path = format!("/v1/uploads/{}", file_id);
        let auth = self.sign_request("GET", &path, EMPTY_BODY_HASH)?;

        let req = self.client.get(format!("{}{}", self.base_url, path));
        let resp = auth
            .apply(req)
            .send()
            .await
            .context("Failed to connect to deployer API")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Failed to get upload ({}): {}", status, body);
        }

        resp.json::<FileUploadInfo>()
            .await
            .context("Failed to parse upload info")
    }

    /// Get all uploads for a borrower (first page, up to 200).
    ///
    /// v1 endpoint is paginated: `GET /v1/uploads?borrower=...&limit=200&offset=0`
    /// returning `{uploads, total, hasMore}`. We unwrap the envelope to keep
    /// the public signature stable; callers needing further pages should
    /// migrate to a paginated method when one exists.
    ///
    /// Auth signing MUST include the query string because the deployer
    /// hashes `req.originalUrl` (path + query) -- see deployer/src/auth.ts.
    pub async fn get_uploads_by_borrower(&self, borrower: &str) -> Result<Vec<FileUploadInfo>> {
        let path = format!("/v1/uploads?borrower={}&limit=200&offset=0", borrower);
        let auth = self.sign_request("GET", &path, EMPTY_BODY_HASH)?;

        let req = self.client.get(format!("{}{}", self.base_url, path));
        let resp = auth
            .apply(req)
            .send()
            .await
            .context("Failed to connect to deployer API")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Failed to get uploads ({}): {}", status, body);
        }

        let env: PaginatedUploads = resp
            .json()
            .await
            .context("Failed to parse uploads envelope")?;
        Ok(env.uploads)
    }

    /// Notify deployer about a new loan request
    pub async fn notify_loan(
        &self,
        signature: &str,
        borrower: &str,
        loan_id: &str,
        file_id: &str,
    ) -> Result<NotifyLoanResponse> {
        let body = serde_json::json!({
            "signature": signature,
            "borrower": borrower,
            "loanId": loan_id,
            "fileId": file_id,
        });

        // Serialize once and sign over the exact bytes we'll write to the wire.
        // Using `.json(&body)` would let reqwest re-serialize and produce
        // potentially different bytes than what we hashed.
        let body_bytes = serde_json::to_vec(&body)
            .context("Failed to serialize notify-loan body")?;
        let body_hash = sha256_hex(&body_bytes);
        let auth = self.sign_request("POST", "/v1/loans", &body_hash)?;

        let req = self
            .client
            .post(format!("{}/v1/loans", self.base_url))
            .header(reqwest::header::CONTENT_TYPE, "application/json")
            .body(body_bytes);

        let resp = auth
            .apply(req)
            .send()
            .await
            .context("Failed to connect to deployer API")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Failed to notify loan ({}): {}", status, body);
        }

        resp.json::<NotifyLoanResponse>()
            .await
            .context("Failed to parse notify response")
    }

    /// Notify deployer that a loan has been repaid.
    ///
    /// v1 endpoint is `POST /v1/loans/:loanId/repayments` -- loanId moved
    /// into the URL and dropped from the body. The body is now just the
    /// transaction signature + borrower pubkey.
    pub async fn notify_repaid(
        &self,
        signature: &str,
        borrower: &str,
        loan_id: u64,
    ) -> Result<NotifyRepaidResponse> {
        let body = serde_json::json!({
            "signature": signature,
            "borrower": borrower,
        });

        let body_bytes = serde_json::to_vec(&body)
            .context("Failed to serialize notify-repaid body")?;
        let body_hash = sha256_hex(&body_bytes);

        let path = format!("/v1/loans/{}/repayments", loan_id);
        let auth = self.sign_request("POST", &path, &body_hash)?;

        let req = self
            .client
            .post(format!("{}{}", self.base_url, path))
            .header(reqwest::header::CONTENT_TYPE, "application/json")
            .body(body_bytes);

        let resp = auth
            .apply(req)
            .send()
            .await
            .context("Failed to connect to deployer API")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Failed to notify repaid ({}): {}", status, body);
        }

        resp.json::<NotifyRepaidResponse>()
            .await
            .context("Failed to parse repaid response")
    }

    /// Get deployment status
    pub async fn get_deployment(&self, loan_id: &str) -> Result<DeploymentInfo> {
        let path = format!("/v1/deployments/{}", loan_id);
        let auth = self.sign_request("GET", &path, EMPTY_BODY_HASH)?;

        let req = self.client.get(format!("{}{}", self.base_url, path));
        let resp = auth
            .apply(req)
            .send()
            .await
            .context("Failed to connect to deployer API")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Failed to get deployment ({}): {}", status, body);
        }

        resp.json::<DeploymentInfo>()
            .await
            .context("Failed to parse deployment info")
    }

    /// Get all deployments for a borrower (first page, up to 200).
    ///
    /// v1 endpoint is paginated: `GET /v1/deployments?borrower=...&limit=200&offset=0`
    /// returning `{deployments, total, hasMore}`. We unwrap the envelope to
    /// keep the public signature stable.
    pub async fn get_deployments_by_borrower(
        &self,
        borrower: &str,
    ) -> Result<Vec<DeploymentInfo>> {
        let path = format!("/v1/deployments?borrower={}&limit=200&offset=0", borrower);
        let auth = self.sign_request("GET", &path, EMPTY_BODY_HASH)?;

        let req = self.client.get(format!("{}{}", self.base_url, path));
        let resp = auth
            .apply(req)
            .send()
            .await
            .context("Failed to connect to deployer API")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Failed to get deployments ({}): {}", status, body);
        }

        let env: PaginatedDeployments = resp
            .json()
            .await
            .context("Failed to parse deployments envelope")?;
        Ok(env.deployments)
    }

    /// Health check
    pub async fn health(&self) -> Result<HealthResponse> {
        let resp = self
            .client
            .get(format!("{}/health", self.base_url))
            .send()
            .await
            .context("Failed to connect to deployer API — is the service running?")?;

        resp.json::<HealthResponse>()
            .await
            .context("Failed to parse health response")
    }
}

// ─── Unit tests ─────────────────────────────────────────────────────────────
//
// Network-free coverage of the pure functions: SHA-256 helpers, the canonical
// auth message layout, and the sign-then-verify round trip. Integration tests
// that exercise the actual HTTP surface live in `tests/v1_client.rs`.
#[cfg(test)]
mod tests {
    use super::*;
    use ed25519_dalek::{Signature, Verifier, VerifyingKey};
    use solana_sdk::signature::{Keypair, SeedDerivable};
    use std::sync::Arc;

    /// Deterministic 32-byte seed → Keypair, so failing signatures are diffable
    /// in CI logs. The seed itself isn't a secret -- tests run in-process.
    fn fixture_keypair() -> Keypair {
        let mut seed = [0u8; 32];
        for (i, b) in seed.iter_mut().enumerate() {
            *b = (i as u8).wrapping_mul(7).wrapping_add(13);
        }
        Keypair::from_seed(&seed).expect("valid 32-byte seed")
    }

    #[test]
    fn sha256_hex_empty_string_matches_constant() {
        // Catches a one-character typo in EMPTY_BODY_HASH: if this fails the
        // entire auth scheme drifts for GET / bodyless requests.
        assert_eq!(sha256_hex(b""), EMPTY_BODY_HASH);
    }

    #[test]
    fn sha256_hex_known_vector() {
        // NIST FIPS 180-2 known answer: sha256("abc").
        assert_eq!(
            sha256_hex(b"abc"),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
        );
    }

    #[test]
    fn canonical_message_has_exact_six_line_layout() {
        // We rebuild the canonical string with the same template the client
        // signs against, then assert structure. This pins the wire spec --
        // a refactor that drops a `\n` or reorders fields would flip this red.
        let timestamp_ms = "1700000000000";
        let nonce_b58 = "11111111111111111111";
        let canonical = format!(
            "{tag}\n{method}\n{path}\n{ts}\n{nonce}\n{body_hash}",
            tag = AUTH_VERSION_TAG,
            method = "POST",
            path = "/v1/uploads",
            ts = timestamp_ms,
            nonce = nonce_b58,
            body_hash = EMPTY_BODY_HASH,
        );
        let lines: Vec<&str> = canonical.split('\n').collect();
        assert_eq!(lines.len(), 6, "canonical must be exactly 6 newline-separated lines");
        assert_eq!(lines[0], "solignition-auth-v1");
        assert_eq!(lines[1], "POST");
        assert_eq!(lines[2], "/v1/uploads");
        assert_eq!(lines[3], "1700000000000");
        assert_eq!(lines[4], "11111111111111111111");
        assert_eq!(lines[5], EMPTY_BODY_HASH);
    }

    #[test]
    fn sign_request_round_trip_verifies() {
        // The most important test in this module: produce a signature via
        // the real sign_request() and verify it ourselves with ed25519-dalek,
        // not via solana-sdk. If this fails, an off-by-one byte somewhere is
        // about to break every authed request in production.
        let keypair = fixture_keypair();
        let client = DeployerClient::new("http://localhost:0", Arc::new(keypair));
        // We don't keep the original keypair, so rebuild a parallel one with
        // the same seed for verification.
        let verify_keypair = fixture_keypair();
        let pubkey_bytes: [u8; 32] = verify_keypair.pubkey().to_bytes();
        let verifying_key = VerifyingKey::from_bytes(&pubkey_bytes)
            .expect("pubkey is a valid ed25519 point");

        let body_hash = sha256_hex(b"{\"hello\":\"world\"}");
        let headers = client
            .sign_request("POST", "/v1/loans", &body_hash)
            .expect("sign_request must succeed for an authenticated client");

        // Reconstruct the exact canonical message the client signed.
        let canonical = format!(
            "{tag}\n{method}\n{path}\n{ts}\n{nonce}\n{body_hash}",
            tag = AUTH_VERSION_TAG,
            method = "POST",
            path = "/v1/loans",
            ts = headers.timestamp_ms,
            nonce = headers.nonce_b58,
            body_hash = body_hash,
        );

        let sig_bytes_vec = bs58::decode(&headers.signature_b58)
            .into_vec()
            .expect("signature is valid base58");
        let sig_bytes: [u8; 64] = sig_bytes_vec
            .try_into()
            .expect("signature is 64 bytes");
        let signature = Signature::from_bytes(&sig_bytes);

        verifying_key
            .verify(canonical.as_bytes(), &signature)
            .expect("signature must verify against the same canonical bytes");

        // And: the pubkey in the headers must match the signer.
        let header_pubkey_bytes_vec = bs58::decode(&headers.pubkey_b58)
            .into_vec()
            .expect("pubkey header is valid base58");
        assert_eq!(header_pubkey_bytes_vec.as_slice(), pubkey_bytes.as_slice());
    }

    #[test]
    fn sign_request_fails_on_anonymous_client() {
        // The anonymous constructor is for /health only; trying to sign with
        // it should surface a clear error rather than silently mis-signing.
        let client = DeployerClient::new_anonymous("http://localhost:0");
        let err = client
            .sign_request("GET", "/v1/uploads/abc", EMPTY_BODY_HASH)
            .expect_err("anonymous sign_request must fail");
        assert!(
            err.to_string().contains("anonymously"),
            "error message must explain the anonymous-client mistake; got: {err}"
        );
    }
}