sdkt-cli 2.7.0

Command Line Interface (CLI) application combining core Soroban DevKit components.
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
//! Integration tests for `sdkt audit --format sarif`.
//!
//! Acceptance criteria covered:
//!  - `--format sarif` emits a valid SARIF 2.1.0 document
//!  - Each finding maps to a result with the correct `level`
//!  - The audited file path appears as the artifact location URI
//!  - Rule ids appear in the `runs[0].tool.driver.rules` array
//!  - The document validates against the pinned SARIF 2.1.0 JSON-schema
//!  - Empty-findings case: valid SARIF with zero results
//!  - Existing pretty/JSON output is unchanged (regression guard)

use assert_cmd::Command;
use std::io::Write;
use tempfile::TempDir;

fn sdkt() -> Command {
    Command::cargo_bin("sdkt").unwrap()
}

fn write_fixture(dir: &TempDir, name: &str, content: &str) -> std::path::PathBuf {
    let p = dir.path().join(name);
    let mut f = std::fs::File::create(&p).unwrap();
    f.write_all(content.as_bytes()).unwrap();
    p
}

/// Load the pinned SARIF 2.1.0 schema bundled as a test fixture.
fn sarif_schema() -> serde_json::Value {
    let schema_bytes = include_bytes!("fixtures/sarif-2.1.0.json");
    serde_json::from_slice(schema_bytes).expect("fixture is valid JSON")
}

/// Validate a JSON value against the bundled SARIF 2.1.0 schema.
fn assert_valid_sarif(doc: &serde_json::Value) {
    let schema = sarif_schema();
    let validator = jsonschema::validator_for(&schema).expect("schema compiles");
    if let Err(e) = validator.validate(doc) {
        panic!("SARIF document failed schema validation: {e}");
    }
}

// ── Document structure ────────────────────────────────────────────────────────

#[test]
fn sarif_output_has_version_and_schema_fields() {
    let dir = TempDir::new().unwrap();
    let path = write_fixture(&dir, "bad.rs", "pub fn mint(to: Address) { }\n");
    let out = sdkt()
        .args(["audit", path.to_str().unwrap(), "--format", "sarif"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let v: serde_json::Value = serde_json::from_slice(&out).expect("sarif output is valid JSON");

    assert_eq!(v["version"], "2.1.0", "SARIF version must be 2.1.0");
    assert!(
        v["$schema"].as_str().unwrap_or("").contains("sarif"),
        "$schema URI must reference sarif"
    );
    assert!(v["runs"].is_array(), "runs array present");
    assert_eq!(v["runs"].as_array().unwrap().len(), 1, "exactly one run");
}

#[test]
fn sarif_output_has_tool_driver() {
    let dir = TempDir::new().unwrap();
    let path = write_fixture(
        &dir,
        "ok.rs",
        "pub fn balance(who: Address) -> u32 { require_auth(); 0 }\n",
    );
    let out = sdkt()
        .args(["audit", path.to_str().unwrap(), "--format", "sarif"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
    let driver = &v["runs"][0]["tool"]["driver"];
    assert_eq!(driver["name"], "sdkt", "tool name is sdkt");
    assert!(driver["version"].is_string(), "tool version is a string");
    assert!(
        driver["informationUri"].is_string(),
        "informationUri is a string"
    );
}

// ── Findings → results mapping ────────────────────────────────────────────────

#[test]
fn sarif_each_finding_becomes_a_result() {
    let dir = TempDir::new().unwrap();
    // AUTH-001 and AUTH-003 both fire on this source
    let path = write_fixture(
        &dir,
        "bad.rs",
        "pub fn initialize(admin: Address) { }\npub fn mint(to: Address) { }\n",
    );
    let out = sdkt()
        .args(["audit", path.to_str().unwrap(), "--format", "sarif"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
    let results = v["runs"][0]["results"].as_array().expect("results array");
    assert!(
        !results.is_empty(),
        "source with issues must produce results"
    );
    for result in results {
        assert!(result["ruleId"].is_string(), "ruleId present");
        assert!(result["level"].is_string(), "level present");
        assert!(
            result["message"]["text"].is_string(),
            "message.text present"
        );
        assert!(result["locations"].is_array(), "locations array present");
    }
}

#[test]
fn sarif_critical_severity_maps_to_error_level() {
    let dir = TempDir::new().unwrap();
    let path = write_fixture(&dir, "bad.rs", "pub fn mint(to: Address) { }\n");
    let out = sdkt()
        .args(["audit", path.to_str().unwrap(), "--format", "sarif"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
    let results = v["runs"][0]["results"].as_array().unwrap();
    let auth001 = results.iter().find(|r| r["ruleId"] == "AUTH-001");
    let result = auth001.expect("AUTH-001 finding present");
    assert_eq!(result["level"], "error", "Critical maps to SARIF error");
}

#[test]
fn sarif_warning_severity_maps_to_warning_level() {
    // MOVE-001 fires when a local is passed as a call argument ≥2 times.
    let dir = TempDir::new().unwrap();
    let path = write_fixture(
        &dir,
        "move.rs",
        // x is passed to two separate call positions → MOVE-001 fires
        "pub fn do_swap(x: i128) { foo(x); bar(x); }\n",
    );
    let out = sdkt()
        .args(["audit", path.to_str().unwrap(), "--format", "sarif"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
    let results = v["runs"][0]["results"].as_array().unwrap();
    let move001 = results.iter().find(|r| r["ruleId"] == "MOVE-001");
    let result = move001.expect("MOVE-001 (warning) finding present");
    assert_eq!(
        result["level"], "warning",
        "Warning severity maps to SARIF warning"
    );
}

#[test]
fn sarif_includes_division_before_multiplication_finding() {
    let dir = TempDir::new().unwrap();
    let path = write_fixture(
        &dir,
        "arithmetic.rs",
        "pub fn quote(amount: i128, bps: i128) -> i128 { amount / 10_000 * bps }\n",
    );
    let out = sdkt()
        .args(["audit", path.to_str().unwrap(), "--format", "sarif"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let doc: serde_json::Value = serde_json::from_slice(&out).unwrap();
    assert_valid_sarif(&doc);
    let results = doc["runs"][0]["results"].as_array().unwrap();
    let finding = results
        .iter()
        .find(|finding| finding["ruleId"] == "MATH-001")
        .expect("MATH-001 should be rendered in SARIF");
    assert_eq!(finding["level"], "warning");
    assert!(finding["message"]["text"]
        .as_str()
        .unwrap()
        .contains("divides before multiplying"));
}

// ── Artifact location (file path) ─────────────────────────────────────────────

#[test]
fn sarif_artifact_uri_contains_source_file_path() {
    let dir = TempDir::new().unwrap();
    let path = write_fixture(&dir, "mycontract.rs", "pub fn mint(to: Address) { }\n");
    let path_str = path.to_str().unwrap();
    let out = sdkt()
        .args(["audit", path_str, "--format", "sarif"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
    let results = v["runs"][0]["results"].as_array().unwrap();
    assert!(!results.is_empty(), "need at least one result to check");

    for result in results {
        let uri = result["locations"][0]["physicalLocation"]["artifactLocation"]["uri"]
            .as_str()
            .expect("uri is a string");
        // The URI must include the path that was passed on the command line.
        assert!(
            uri.contains("mycontract.rs"),
            "artifact URI should contain the source filename; got: {uri}"
        );
    }
}

#[test]
fn sarif_multiple_files_preserve_individual_artifact_uris() {
    let dir = TempDir::new().unwrap();
    let a = write_fixture(&dir, "a.rs", "pub fn mint_token(to: Address) { }\n");
    let b = write_fixture(
        &dir,
        "b.rs",
        "pub fn transfer(from: Address, to: Address, amount: i128) { }\n",
    );

    let out = sdkt()
        .args([
            "audit",
            a.to_str().unwrap(),
            b.to_str().unwrap(),
            "--format",
            "sarif",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
    let results = v["runs"][0]["results"].as_array().unwrap();
    assert!(
        !results.is_empty(),
        "multi-file sarif must include findings"
    );

    let auth001 = results
        .iter()
        .find(|result| result["ruleId"] == "AUTH-001")
        .expect("AUTH-001 result should be present");
    let auth004 = results
        .iter()
        .find(|result| result["ruleId"] == "AUTH-004")
        .expect("AUTH-004 result should be present");

    let auth001_uri = auth001["locations"][0]["physicalLocation"]["artifactLocation"]["uri"]
        .as_str()
        .unwrap();
    let auth004_uri = auth004["locations"][0]["physicalLocation"]["artifactLocation"]["uri"]
        .as_str()
        .unwrap();

    assert!(
        auth001_uri.contains("a.rs"),
        "AUTH-001 should be attributed to a.rs; got: {auth001_uri}"
    );
    assert!(
        auth004_uri.contains("b.rs"),
        "AUTH-004 should be attributed to b.rs; got: {auth004_uri}"
    );
}

// ── Rules section ─────────────────────────────────────────────────────────────

#[test]
fn sarif_rule_ids_appear_in_rules_section() {
    let dir = TempDir::new().unwrap();
    let path = write_fixture(
        &dir,
        "bad.rs",
        "pub fn initialize(admin: Address) { }\npub fn mint(to: Address) { }\n",
    );
    let out = sdkt()
        .args(["audit", path.to_str().unwrap(), "--format", "sarif"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
    let rules = v["runs"][0]["tool"]["driver"]["rules"]
        .as_array()
        .expect("rules array");
    assert!(!rules.is_empty(), "rules section is non-empty");

    // Every ruleId in results must have a matching entry in the rules array.
    let results = v["runs"][0]["results"].as_array().unwrap();
    let rule_ids_in_rules: Vec<&str> = rules.iter().filter_map(|r| r["id"].as_str()).collect();

    for result in results {
        let rid = result["ruleId"].as_str().unwrap();
        assert!(
            rule_ids_in_rules.contains(&rid),
            "ruleId '{rid}' in results must have an entry in rules section"
        );
    }
}

// ── Empty-findings case ───────────────────────────────────────────────────────

#[test]
fn sarif_empty_findings_produces_valid_document_with_zero_results() {
    let dir = TempDir::new().unwrap();
    let path = write_fixture(
        &dir,
        "ok.rs",
        "pub fn balance(who: Address) -> u32 { require_auth(); 0 }\n",
    );
    let out = sdkt()
        .args(["audit", path.to_str().unwrap(), "--format", "sarif"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
    let results = v["runs"][0]["results"].as_array().expect("results array");
    assert!(
        results.is_empty(),
        "clean source produces zero SARIF results"
    );
    // Rules section should also be empty when there are no findings.
    let rules = v["runs"][0]["tool"]["driver"]["rules"].as_array().unwrap();
    assert!(rules.is_empty(), "no rules section for zero findings");
}

// ── JSON-schema validation ────────────────────────────────────────────────────

#[test]
fn sarif_output_validates_against_sarif_2_1_0_schema_with_findings() {
    let dir = TempDir::new().unwrap();
    let path = write_fixture(
        &dir,
        "bad.rs",
        "pub fn initialize(admin: Address) { }\npub fn mint(to: Address) { }\n",
    );
    let out = sdkt()
        .args(["audit", path.to_str().unwrap(), "--format", "sarif"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let doc: serde_json::Value = serde_json::from_slice(&out).expect("valid JSON");
    assert_valid_sarif(&doc);
}

#[test]
fn sarif_output_validates_against_sarif_2_1_0_schema_empty_findings() {
    let dir = TempDir::new().unwrap();
    let path = write_fixture(
        &dir,
        "ok.rs",
        "pub fn balance(who: Address) -> u32 { require_auth(); 0 }\n",
    );
    let out = sdkt()
        .args(["audit", path.to_str().unwrap(), "--format", "sarif"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let doc: serde_json::Value = serde_json::from_slice(&out).expect("valid JSON");
    assert_valid_sarif(&doc);
}

// ── Regression: existing formats unchanged ────────────────────────────────────

#[test]
fn json_format_still_produces_findings_and_summary_fields() {
    let dir = TempDir::new().unwrap();
    let path = write_fixture(&dir, "bad.rs", "pub fn initialize(admin: Address) { }\n");
    let out = sdkt()
        .args(["audit", path.to_str().unwrap(), "--format", "json"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    let v: serde_json::Value = serde_json::from_slice(&out).expect("valid JSON");
    assert!(
        v.get("findings").is_some(),
        "json output must have findings"
    );
    assert!(v.get("summary").is_some(), "json output must have summary");
    // Ensure it does NOT look like SARIF
    assert!(v.get("runs").is_none(), "json output must not be SARIF");
}

#[test]
fn pretty_format_still_produces_text_report() {
    let dir = TempDir::new().unwrap();
    let path = write_fixture(&dir, "bad.rs", "pub fn mint(to: Address) { }\n");
    sdkt()
        .args(["audit", path.to_str().unwrap(), "--format", "pretty"])
        .assert()
        .success()
        .stdout(predicates::str::contains("Static Analysis Report"))
        .stdout(predicates::str::contains("AUTH-001"));
}

#[test]
fn invalid_format_exits_nonzero() {
    let dir = TempDir::new().unwrap();
    let path = write_fixture(
        &dir,
        "ok.rs",
        "pub fn balance(who: Address) -> u32 { require_auth(); 0 }\n",
    );
    sdkt()
        .args(["audit", path.to_str().unwrap(), "--format", "xml"])
        .assert()
        .failure();
}

#[test]
fn list_rules_with_sarif_format_exits_nonzero_with_error() {
    sdkt()
        .args(["audit", "--list-rules", "--format", "sarif"])
        .assert()
        .failure()
        .stderr(predicates::str::contains("--format sarif"));
}

#[test]
fn sarif_uribaseid_present_for_relative_path() {
    // Write a fixture with a relative path (just a filename in the cwd).
    let rel_name = "_sarif_test_relative_fixture.rs";
    let cwd = std::env::current_dir().unwrap();
    let abs = cwd.join(rel_name);
    std::fs::write(&abs, "pub fn mint(to: Address) { }\n").unwrap();

    let out = sdkt()
        .args(["audit", rel_name, "--format", "sarif"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();

    // Best-effort cleanup; ignore errors.
    let _ = std::fs::remove_file(&abs);

    let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
    let results = v["runs"][0]["results"].as_array().unwrap();
    if !results.is_empty() {
        let uri_base =
            &results[0]["locations"][0]["physicalLocation"]["artifactLocation"]["uriBaseId"];
        assert_eq!(
            uri_base, "%SRCROOT%",
            "relative path must have %SRCROOT% uriBaseId"
        );
    }
}