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
//! Integration tests for the v1 REST surface in `src/client.rs`.
//!
//! Each test spins up a `wiremock::MockServer`, points a `DeployerClient`
//! at it, asserts the exact request the CLI puts on the wire, and returns
//! a canned response so the client's deserializer is exercised. Together
//! they pin the v1 wire contract and the `solignition-auth-v1` signing
//! protocol -- if either drifts in `src/client.rs`, one of these goes red.
//!
//! `solignition-cli` is a binary crate (no `[lib]`), so we pull `client.rs`
//! in via `#[path]` rather than `use solignition_cli::client::...`. This
//! recompiles the module once for the test binary; that's fine because it
//! only depends on external crates (no sibling-module imports).

#[path = "../src/client.rs"]
mod client;
mod common;

use client::{DeployerClient, DeploymentInfo, FileUploadInfo, HealthResponse, UploadResponse};
use common::{fixture_keypair, mock_deployer};
use ed25519_dalek::{Signature, Verifier, VerifyingKey};
use sha2::{Digest, Sha256};
use solana_sdk::signer::Signer;
use std::sync::Arc;
use wiremock::matchers::{body_json, header_exists, method, path, query_param};
use wiremock::{Mock, ResponseTemplate};

const AUTH_VERSION_TAG: &str = "solignition-auth-v1";
const EMPTY_BODY_HASH: &str =
    "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";

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

fn require_auth_headers(req: &wiremock::Request) -> (String, String, String, String) {
    let h = |name: &str| -> String {
        req.headers
            .get(name)
            .unwrap_or_else(|| panic!("missing header {name}"))
            .to_str()
            .expect("header is ASCII")
            .to_string()
    };
    (
        h("x-auth-pubkey"),
        h("x-auth-timestamp"),
        h("x-auth-nonce"),
        h("x-auth-signature"),
    )
}

// ─── /health ────────────────────────────────────────────────────────────────

#[tokio::test]
async fn health_parses_slim_v1_body() {
    let (server, uri, _signer) = mock_deployer().await;
    Mock::given(method("GET"))
        .and(path("/health"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "ok"
        })))
        .mount(&server)
        .await;

    let client = DeployerClient::new_anonymous(&uri);
    let h: HealthResponse = client.health().await.expect("health succeeds");
    assert_eq!(h.status, "ok");
    assert!(h.active_loans.is_none());
    assert!(h.total_deployments.is_none());
    assert!(h.timestamp.is_none());
}

#[tokio::test]
async fn health_backward_compat_parses_old_shape() {
    let (server, uri, _signer) = mock_deployer().await;
    Mock::given(method("GET"))
        .and(path("/health"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "healthy",
            "activeLoans": 5,
            "totalDeployments": 42,
            "timestamp": "2025-01-01T00:00:00Z"
        })))
        .mount(&server)
        .await;

    let client = DeployerClient::new_anonymous(&uri);
    let h = client.health().await.expect("legacy /health parses");
    assert_eq!(h.status, "healthy");
    assert_eq!(h.active_loans, Some(5));
    assert_eq!(h.total_deployments, Some(42));
    assert!(h.timestamp.is_some());
}

// ─── GET /v1/uploads/:fileId ────────────────────────────────────────────────

#[tokio::test]
async fn get_upload_hits_v1_path_with_auth_headers() {
    let (server, uri, signer) = mock_deployer().await;
    Mock::given(method("GET"))
        .and(path("/v1/uploads/abc123"))
        .and(header_exists("x-auth-pubkey"))
        .and(header_exists("x-auth-signature"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "fileId": "abc123",
            "borrower": "ExampleBorrowerPubkey1111111111111111111111",
            "fileName": "program.so",
            "fileSize": 1024_u64,
            "binaryHash": EMPTY_BODY_HASH,
            "estimatedCost": 0.5_f64,
            "status": "ready",
            "createdAt": 1_700_000_000_u64,
        })))
        .mount(&server)
        .await;

    let client = DeployerClient::new(&uri, signer);
    let info: FileUploadInfo = client.get_upload("abc123").await.expect("get_upload succeeds");
    assert_eq!(info.file_id, "abc123");
    assert_eq!(info.status, "ready");
}

// ─── GET /v1/uploads?borrower=...  (paginated envelope unwrap) ─────────────

#[tokio::test]
async fn get_uploads_by_borrower_unwraps_paginated_envelope() {
    let (server, uri, signer) = mock_deployer().await;
    Mock::given(method("GET"))
        .and(path("/v1/uploads"))
        .and(query_param("borrower", "WalletA111111111111111111111111111111111111"))
        .and(query_param("limit", "200"))
        .and(query_param("offset", "0"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "uploads": [
                {
                    "fileId": "f1f1f1f1f1f1f1f1",
                    "borrower": "WalletA111111111111111111111111111111111111",
                    "fileName": "a.so",
                    "fileSize": 10_u64,
                    "binaryHash": EMPTY_BODY_HASH,
                    "estimatedCost": 0.1_f64,
                    "status": "ready",
                    "createdAt": 1_700_000_000_u64
                }
            ],
            "total": 1,
            "limit": 200,
            "offset": 0,
            "hasMore": false
        })))
        .mount(&server)
        .await;

    let client = DeployerClient::new(&uri, signer);
    let uploads = client
        .get_uploads_by_borrower("WalletA111111111111111111111111111111111111")
        .await
        .expect("list succeeds");
    assert_eq!(uploads.len(), 1);
    assert_eq!(uploads[0].file_id, "f1f1f1f1f1f1f1f1");
}

// ─── POST /v1/loans (notify_loan) ──────────────────────────────────────────

#[tokio::test]
async fn notify_loan_posts_to_v1_loans_with_full_body() {
    let (server, uri, signer) = mock_deployer().await;
    let expected_body = serde_json::json!({
        "signature": "sig123",
        "borrower":  "BorrowerB1111111111111111111111111111111111",
        "loanId":    "42",
        "fileId":    "abc123"
    });
    Mock::given(method("POST"))
        .and(path("/v1/loans"))
        .and(body_json(expected_body))
        .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
            "success": true,
            "message": "ok",
            "signature": "sig123",
            "fileId": "abc123"
        })))
        .mount(&server)
        .await;

    let client = DeployerClient::new(&uri, signer);
    let resp = client
        .notify_loan(
            "sig123",
            "BorrowerB1111111111111111111111111111111111",
            "42",
            "abc123",
        )
        .await
        .expect("notify_loan succeeds");
    assert!(resp.success);
}

// ─── POST /v1/loans/:loanId/repayments (notify_repaid) ─────────────────────

#[tokio::test]
async fn notify_repaid_puts_loan_id_in_url_not_body() {
    let (server, uri, signer) = mock_deployer().await;
    // Body must NOT contain loanId in v1 -- it's in the URL now.
    let expected_body = serde_json::json!({
        "signature": "sigR",
        "borrower":  "BorrowerC1111111111111111111111111111111111"
    });
    Mock::given(method("POST"))
        .and(path("/v1/loans/42/repayments"))
        .and(body_json(expected_body))
        .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
            "success": true,
            "message": "ok",
            "loanId": "42",
            "auth": "BorrowerC1111111111111111111111111111111111"
        })))
        .mount(&server)
        .await;

    let client = DeployerClient::new(&uri, signer);
    let resp = client
        .notify_repaid("sigR", "BorrowerC1111111111111111111111111111111111", 42)
        .await
        .expect("notify_repaid succeeds");
    assert!(resp.success);
    assert_eq!(resp.loan_id.as_deref(), Some("42"));
}

// ─── GET /v1/deployments/:loanId ───────────────────────────────────────────

#[tokio::test]
async fn get_deployment_parses_response_with_optional_fields() {
    let (server, uri, signer) = mock_deployer().await;
    Mock::given(method("GET"))
        .and(path("/v1/deployments/42"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "loanId":    "42",
            "borrower":  "BorrowerD1111111111111111111111111111111111",
            "status":    "deployed",
            "createdAt": 1_700_000_000_u64,
            "updatedAt": 1_700_000_500_u64,
            "principal": "1000000000",
            "programAccountOpen": true,
            "programId": "ProgIdAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
        })))
        .mount(&server)
        .await;

    let client = DeployerClient::new(&uri, signer);
    let d: DeploymentInfo = client.get_deployment("42").await.expect("get_deployment succeeds");
    assert_eq!(d.status, "deployed");
    assert_eq!(d.program_id.as_deref(), Some("ProgIdAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
}

// ─── GET /v1/deployments?borrower=...  (paginated envelope unwrap) ─────────

#[tokio::test]
async fn get_deployments_by_borrower_unwraps_paginated_envelope() {
    let (server, uri, signer) = mock_deployer().await;
    Mock::given(method("GET"))
        .and(path("/v1/deployments"))
        .and(query_param("borrower", "WalletE111111111111111111111111111111111111"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "deployments": [
                {
                    "loanId": "1",
                    "borrower": "WalletE111111111111111111111111111111111111",
                    "status": "deployed",
                    "createdAt": 1_700_000_000_u64,
                    "updatedAt": 1_700_000_500_u64,
                    "principal": "1000000000",
                    "programAccountOpen": false
                }
            ],
            "total": 1,
            "limit": 200,
            "offset": 0,
            "hasMore": false
        })))
        .mount(&server)
        .await;

    let client = DeployerClient::new(&uri, signer);
    let deployments = client
        .get_deployments_by_borrower("WalletE111111111111111111111111111111111111")
        .await
        .expect("deployments list succeeds");
    assert_eq!(deployments.len(), 1);
    assert_eq!(deployments[0].loan_id, "1");
}

// ─── POST /v1/uploads (multipart with expectedHash) ────────────────────────

#[tokio::test]
async fn upload_sends_multipart_with_expected_hash() {
    let (server, uri, signer) = mock_deployer().await;

    // Pre-compute the file hash the CLI will send.
    let file_bytes = b"hello-world".to_vec();
    let file_hash = sha256_hex(&file_bytes);

    Mock::given(method("POST"))
        .and(path("/v1/uploads"))
        .and(header_exists("x-auth-pubkey"))
        .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
            "success": true,
            "fileId": "newfileid0000000",
            "estimatedCost": 0.5_f64,
            "binaryHash": file_hash.clone(),
            "message": "ok"
        })))
        .mount(&server)
        .await;

    // Write the file to a temp path so DeployerClient::upload_file can read it.
    let tmp = std::env::temp_dir().join("solignition-cli-upload-test.so");
    std::fs::write(&tmp, &file_bytes).expect("write tmp file");

    let client = DeployerClient::new(&uri, signer);
    let resp: UploadResponse = client
        .upload_file(&tmp, "BorrowerF1111111111111111111111111111111111")
        .await
        .expect("upload succeeds");
    assert_eq!(resp.file_id, "newfileid0000000");
    assert_eq!(resp.binary_hash, file_hash);

    // Confirm the multipart body contains all three fields (borrower, file,
    // expectedHash). wiremock exposes the raw request body bytes; checking
    // for the form-field names + the expected hash value is robust against
    // boundary string changes.
    let recorded = server.received_requests().await.unwrap();
    let upload_req = recorded
        .iter()
        .find(|r| r.url.path() == "/v1/uploads")
        .expect("upload request recorded");
    let body_str = std::str::from_utf8(&upload_req.body).unwrap_or("");
    assert!(body_str.contains("name=\"borrower\""), "borrower field present");
    assert!(body_str.contains("name=\"file\""), "file field present");
    assert!(body_str.contains("name=\"expectedHash\""), "expectedHash field present");
    assert!(body_str.contains(&file_hash), "expectedHash value matches computed hash");

    let _ = std::fs::remove_file(&tmp);
}

#[tokio::test]
async fn upload_surfaces_server_side_hash_mismatch_error() {
    let (server, uri, signer) = mock_deployer().await;

    // Server responds with the 422 envelope the deployer's error handler emits.
    Mock::given(method("POST"))
        .and(path("/v1/uploads"))
        .respond_with(ResponseTemplate::new(422).set_body_json(serde_json::json!({
            "error": "Computed sha256 does not match supplied expectedHash",
            "code":  "hash_mismatch",
            "requestId": "req-x"
        })))
        .mount(&server)
        .await;

    let file_bytes = b"corrupted".to_vec();
    let tmp = std::env::temp_dir().join("solignition-cli-upload-mismatch.so");
    std::fs::write(&tmp, &file_bytes).expect("write tmp file");

    let client = DeployerClient::new(&uri, signer);
    let err = client
        .upload_file(&tmp, "BorrowerG1111111111111111111111111111111111")
        .await
        .expect_err("upload must fail when server reports hash_mismatch");
    let msg = err.to_string();
    assert!(msg.contains("422") || msg.contains("hash_mismatch"),
        "error message should surface the server response; got: {msg}");

    let _ = std::fs::remove_file(&tmp);
}

// ─── Auth signature pin (the canary test) ──────────────────────────────────

#[tokio::test]
async fn auth_signature_verifies_against_canonical_message() {
    // Single most important test: capture the X-Auth-* headers from a real
    // request and verify the signature ourselves with ed25519-dalek. If this
    // ever fails, the wire spec drifted -- every authed request in
    // production would be rejected.
    let (server, uri, signer) = mock_deployer().await;
    Mock::given(method("GET"))
        .and(path("/v1/uploads/canary000000000"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "fileId": "canary000000000",
            "borrower": "BorrowerH1111111111111111111111111111111111",
            "fileName": "x.so",
            "fileSize": 0_u64,
            "binaryHash": EMPTY_BODY_HASH,
            "estimatedCost": 0.0_f64,
            "status": "ready",
            "createdAt": 0_u64
        })))
        .mount(&server)
        .await;

    let client = DeployerClient::new(&uri, Arc::clone(&signer));
    let _ = client.get_upload("canary000000000").await.expect("call succeeds");

    let recorded = server.received_requests().await.unwrap();
    let req = recorded
        .iter()
        .find(|r| r.url.path() == "/v1/uploads/canary000000000")
        .expect("auth-canary request recorded");

    let (pubkey_b58, timestamp_ms, nonce_b58, signature_b58) = require_auth_headers(req);

    // Sanity: pubkey header must equal the keypair's pubkey.
    let expected_pubkey = bs58::encode(fixture_keypair().pubkey().to_bytes()).into_string();
    assert_eq!(pubkey_b58, expected_pubkey);

    // Reconstruct exactly what the client signed.
    let canonical = format!(
        "{tag}\n{method}\n{path}\n{ts}\n{nonce}\n{body_hash}",
        tag = AUTH_VERSION_TAG,
        method = "GET",
        path = "/v1/uploads/canary000000000",
        ts = timestamp_ms,
        nonce = nonce_b58,
        body_hash = EMPTY_BODY_HASH,
    );

    let pubkey_bytes_vec = bs58::decode(&pubkey_b58)
        .into_vec()
        .expect("pubkey header is base58");
    let pubkey_bytes: [u8; 32] = pubkey_bytes_vec.try_into().expect("32-byte pubkey");
    let verifying_key = VerifyingKey::from_bytes(&pubkey_bytes).expect("valid ed25519 point");

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

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