airs-cli 0.4.1

Native Rust CLI for Prisma AIRS (executable airs-cli-rs until 1.0), built on the scm-sdk crate
Documentation
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
//! CLI failures, their stderr rendering and exit codes, and the secret-safe mapping
//! from SDK errors to messages (DESIGN ยง6).
//!
//! The SDK retains no server text; this module adds none either. Server-derived
//! metadata (request ID, service code) is dropped when it carries a configured secret.

use scm::{ErrorKind, ProblemDetails, RemoteOutcome};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;

pub const EXIT_OK: i32 = 0;
pub const EXIT_OPERATIONAL: i32 = 1;
pub const EXIT_USAGE: i32 = 2;
pub const EXIT_SIGINT: i32 = 130;
pub const EXIT_SIGTERM: i32 = 143;

/// A failed invocation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CliError {
    /// Exit 2: invalid flags, values or local request input.
    Usage(String),
    /// Exit 1: tenant, credential, network or service failure.
    Operational(Failure),
    /// Exit 130/143: a signal cancelled the invocation.
    Interrupted(InterruptContext),
    /// The command already reported the failure on its own streams.
    Reported(i32),
}

/// An operational failure: the message, an optional `HTTP <status>` line and extra lines.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Failure {
    pub message: String,
    pub status: Option<u16>,
    pub details: Vec<String>,
}

/// What an interrupted invocation tells the user about remote side effects.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InterruptContext {
    NoDataWritten,
    ScanNotSubmitted,
    ScanOutcomeUnknown,
    /// The signal arrived while stdout was being written.
    OutputIncomplete,
    /// A tenant write command stopped before its commit point (DESIGN ยง2.5, ยง3.9).
    NoConfigurationChanged,
    /// A tenant write command passed its commit point before the signal was acted on.
    ChangeSaved,
    /// A runtime write command stopped before any write was sent (DESIGN ยง13.2).
    NothingChanged,
    /// A runtime write was sent and then cancelled: it may have been applied.
    ChangeMayBeApplied,
    /// `topics revert` updated the profile; its topic delete was not sent (ยง13.2).
    ProfileUpdatedTopicKept,
    /// `topics revert` updated the profile; its topic delete was sent and cancelled.
    ProfileUpdatedTopicUnknown,
    /// `topics eval` stopped: `sent` of `total` scans were dispatched (ยง13.10).
    EvalStopped {
        sent: usize,
        total: usize,
    },
    /// `profiles cleanup` stopped in its deletion loop (ยง13.15).
    CleanupStopped {
        deleted: usize,
        failed: usize,
        unknown: usize,
        not_attempted: usize,
    },
}

impl InterruptContext {
    pub fn text(self) -> std::borrow::Cow<'static, str> {
        let text = match self {
            Self::NoDataWritten => "no data was written",
            Self::ScanNotSubmitted => "no scan was submitted",
            Self::ScanOutcomeUnknown => {
                "the scan request may already have reached AIRS (outcome unknown)"
            }
            Self::OutputIncomplete => "the output was not completely written",
            Self::NoConfigurationChanged => "no configuration was changed",
            Self::ChangeSaved => "the change was saved",
            Self::NothingChanged => "nothing was changed",
            Self::ChangeMayBeApplied => {
                "the change may already have been applied (outcome unknown)"
            }
            Self::ProfileUpdatedTopicKept => "the profile was updated; the topic was not deleted",
            Self::ProfileUpdatedTopicUnknown => {
                "the profile was updated; the topic may already have been deleted (outcome unknown)"
            }
            Self::EvalStopped { sent, total } => {
                return std::borrow::Cow::Owned(format!(
                    "{sent} of {total} scans were sent; no metrics were computed"
                ));
            }
            Self::CleanupStopped {
                deleted,
                failed,
                unknown,
                not_attempted,
            } => {
                let mut text = format!("{deleted} deleted");
                if failed > 0 {
                    text.push_str(&format!(", {failed} failed"));
                }
                if unknown > 0 {
                    text.push_str(&format!(", {unknown} outcome unknown"));
                }
                text.push_str(&format!(", {not_attempted} not attempted"));
                return std::borrow::Cow::Owned(text);
            }
        };
        std::borrow::Cow::Borrowed(text)
    }
}

impl CliError {
    pub fn usage(message: impl Into<String>) -> Self {
        Self::Usage(message.into())
    }
    pub fn operational(message: impl Into<String>) -> Self {
        Self::Operational(Failure {
            message: message.into(),
            ..Failure::default()
        })
    }

    /// The process exit code; `signal_code` is 130/143 when a signal arrived.
    pub fn exit_code(&self, signal_code: Option<i32>) -> i32 {
        match self {
            Self::Usage(_) => EXIT_USAGE,
            Self::Operational(_) => EXIT_OPERATIONAL,
            Self::Interrupted(_) => signal_code.unwrap_or(EXIT_SIGINT),
            Self::Reported(code) => *code,
        }
    }

    /// The message alone: the operational message, or the rendered text of any other
    /// failure without its surrounding blank lines (doctor details, setup errors).
    pub fn message(&self) -> String {
        match self {
            Self::Operational(failure) => failure.message.clone(),
            other => other.render().trim().to_owned(),
        }
    }

    /// The exact uncoloured stderr bytes for this failure (empty when already
    /// reported).
    pub fn render(&self) -> String {
        self.render_colored(false)
    }

    /// The exact stderr bytes for this failure, in TypeScript's colours when `color`
    /// (DESIGN ยง2.8), for a run without `--debug` (the `Re-run with --debug` hint
    /// follows an `HTTP <status>` line).
    pub fn render_colored(&self, color: bool) -> String {
        self.render_styled(color, true)
    }

    /// The exact stderr bytes for this failure. `debug_hint`: print the TS
    /// `Re-run with --debug โ€ฆ` line after an `HTTP <status>` line (DESIGN ยง2.2; off under
    /// `--debug`, D69). Control characters in messages are replaced (DESIGN ยง2.2), so no
    /// server- or file-derived text can drive the terminal.
    pub fn render_styled(&self, color: bool, debug_hint: bool) -> String {
        use crate::output::terminal_safe;
        use crate::render::style::{Style, paint};
        let red = |text: &str| paint(Style::Red, text, color);
        match self {
            // chalk.red(`\n  โœ— ${message}\n`) + console.error's newline.
            Self::Usage(message) => {
                format!("{}\n", red(&format!("\n  โœ— {}\n", terminal_safe(message))))
            }
            Self::Operational(failure) => {
                let mut text = format!(
                    "{}\n",
                    red(&format!("\n  โœ— Error: {}", terminal_safe(&failure.message)))
                );
                if let Some(status) = failure.status {
                    text.push_str(&format!("{}\n", red(&format!("    HTTP {status}"))));
                    if debug_hint {
                        text.push_str(&format!("{}\n", paint(Style::Dim, DEBUG_HINT, color)));
                    }
                }
                for line in &failure.details {
                    text.push_str(&format!(
                        "{}\n",
                        red(&format!("    {}", terminal_safe(line)))
                    ));
                }
                text.push('\n');
                text
            }
            Self::Interrupted(context) => format!(
                "{}\n\n",
                red(&format!("\n  โœ— Error: Interrupted; {}", context.text()))
            ),
            Self::Reported(_) => String::new(),
        }
    }
}

/// The TS hint after an `HTTP <status>` line (`src/cli/renderer/common.ts:21`).
pub const DEBUG_HINT: &str = "    Re-run with --debug to capture redacted API diagnostics.";

/// Configured secrets, used to drop server-derived metadata that would reveal one.
///
/// Clones share one set: the OAuth provider wrapper ([`crate::clients`]) keeps a clone
/// and registers every token lease the SDK obtains, including the leases of a silent
/// 401/403 refresh-and-replay, so every later error mapping sees them.
#[derive(Clone, Default)]
pub struct SecretSet {
    forms: Arc<Mutex<Vec<String>>>,
}

impl SecretSet {
    fn forms(&self) -> MutexGuard<'_, Vec<String>> {
        self.forms.lock().unwrap_or_else(PoisonError::into_inner)
    }

    fn push(&self, candidate: String) {
        let mut forms = self.forms();
        if !forms.contains(&candidate) {
            forms.push(candidate);
        }
    }

    /// Register a secret in its raw, trimmed, form-encoded and base64 forms.
    pub fn add(&self, value: &str) {
        for candidate in [value, crate::tenant::config::js_trim(value)] {
            if candidate.is_empty() {
                continue;
            }
            let encoded: String =
                url::form_urlencoded::byte_serialize(candidate.as_bytes()).collect();
            for form in [
                candidate.to_owned(),
                encoded,
                base64(candidate.as_bytes(), STANDARD_ALPHABET),
                base64(candidate.as_bytes(), URL_SAFE_ALPHABET),
            ] {
                self.push(form);
            }
        }
    }

    /// Register the OAuth client pair as the HTTP Basic credential carries it:
    /// `base64(id:secret)` with raw and RFC 6749 form-encoded halves (DESIGN ยง6, D29),
    /// in the standard and URL-safe alphabets, plus their raw `id:secret` text.
    pub fn add_basic_credentials(&self, client_id: &str, client_secret: &str) {
        let form = |text: &str| -> String {
            url::form_urlencoded::byte_serialize(text.as_bytes()).collect()
        };
        for (id, secret) in [
            (client_id, client_secret),
            (
                crate::tenant::config::js_trim(client_id),
                crate::tenant::config::js_trim(client_secret),
            ),
        ] {
            if secret.is_empty() {
                continue;
            }
            for pair in [
                format!("{id}:{secret}"),
                format!("{}:{}", form(id), form(secret)),
            ] {
                for candidate in [
                    base64(pair.as_bytes(), STANDARD_ALPHABET),
                    base64(pair.as_bytes(), URL_SAFE_ALPHABET),
                    pair,
                ] {
                    self.push(candidate);
                }
            }
        }
    }

    /// Register every secret a tenant config carries: each secret-named key's value
    /// and the HTTP Basic client pair. Commands and doctor share this one rule.
    pub fn register_config(&self, config: &crate::tenant::config::TenantConfig) {
        for secret in config.secret_values() {
            self.add(secret);
        }
        if let (Some(id), Some(secret)) = (
            config.effective_str("mgmtClientId"),
            config.effective_str("mgmtClientSecret"),
        ) {
            self.add_basic_credentials(id, secret);
        }
    }

    /// Whether `text` contains a secret (or is a sizeable fragment of one).
    pub fn taints(&self, text: &str) -> bool {
        self.forms()
            .iter()
            .any(|form| text.contains(form.as_str()) || (text.len() >= 4 && form.contains(text)))
    }

    /// Whether `text` contains any registered form, ignoring ASCII case (the debug
    /// log's line check). No fragment rule, so ordinary words inside a long line never
    /// trigger it. Case is ignored because header names arrive lowercased: a secret a
    /// server echoes as a header name is written case-folded (DESIGN ยง2.9).
    pub fn appears_in_ignoring_case(&self, text: &str) -> bool {
        let text = text.to_ascii_lowercase();
        self.forms()
            .iter()
            .any(|form| text.contains(form.to_ascii_lowercase().as_str()))
    }

    /// `text`, or [`WITHHELD`] when it carries a secret (server-provided strings the
    /// CLI prints, DESIGN ยง6 and ยง8).
    pub fn scrub<'a>(&self, text: &'a str) -> &'a str {
        if self.taints(text) { WITHHELD } else { text }
    }
}

/// What a server-provided string that carried a secret is printed as.
pub const WITHHELD: &str = "[withheld]";

const STANDARD_ALPHABET: &[u8; 64] =
    b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const URL_SAFE_ALPHABET: &[u8; 64] =
    b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";

/// Unpadded base64 (a padded encoding always contains the unpadded one).
fn base64(bytes: &[u8], alphabet: &[u8; 64]) -> String {
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for chunk in bytes.chunks(3) {
        let b = [
            chunk[0],
            chunk.get(1).copied().unwrap_or(0),
            chunk.get(2).copied().unwrap_or(0),
        ];
        let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
        let symbols = chunk.len() + 1;
        for index in 0..symbols {
            let shift = 18 - 6 * index;
            out.push(char::from(alphabet[((n >> shift) & 0x3f) as usize]));
        }
    }
    out
}

/// Which client produced the error.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Plane {
    Management,
    Scanner,
}

/// Whether the failing call was the explicit OAuth token request or an API call.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Phase {
    Token,
    Api,
}

/// Reads are side-effect free; a scan submission or a management write may have been
/// processed remotely.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Operation {
    Read,
    ScanSubmit,
    /// A management POST, PUT or DELETE (DESIGN ยง13.2).
    Write,
}

/// Everything the mapping needs besides the error itself.
#[derive(Clone, Copy)]
pub struct SdkContext<'a> {
    pub plane: Plane,
    pub phase: Phase,
    pub operation: Operation,
    /// The total budget the call ran under, for the timeout message.
    pub timeout: Duration,
    pub secrets: &'a SecretSet,
}

/// The safe facts of an SDK error that the CLI messages are derived from.
#[derive(Clone)]
pub struct ErrorFacts {
    pub kind: ErrorKind,
    pub status: Option<u16>,
    pub error_type: Option<&'static str>,
    pub problem: Option<ProblemDetails>,
    pub service_code: Option<String>,
    pub request_id: Option<String>,
    pub remote_outcome: RemoteOutcome,
}

impl ErrorFacts {
    pub fn of(error: &scm::Error) -> Self {
        Self {
            kind: error.kind(),
            status: error.status(),
            error_type: error.error_type().map(scm::ErrorType::as_str),
            problem: error.problem().cloned(),
            service_code: error.service_code().map(str::to_owned),
            request_id: error.request_id().map(str::to_owned),
            remote_outcome: error.remote_outcome(),
        }
    }

    /// An HTTP error status, including a body that exceeded the client limit.
    pub fn http_status(&self) -> Option<u16> {
        match self.kind {
            ErrorKind::Http => self.status,
            ErrorKind::Limit => self.status.filter(|status| *status >= 400),
            _ => None,
        }
    }
}

/// Map an SDK error to the CLI failure (DESIGN ยง6).
pub fn from_sdk(error: &scm::Error, context: &SdkContext<'_>) -> CliError {
    describe(&ErrorFacts::of(error), context)
}

/// The `โœ— Error:` message for an SDK error, without status or detail lines.
pub fn sdk_message(error: &scm::Error, context: &SdkContext<'_>) -> String {
    facts_message(&ErrorFacts::of(error), context)
}

/// [`sdk_message`] for already extracted (possibly adjusted) facts.
pub fn facts_message(facts: &ErrorFacts, context: &SdkContext<'_>) -> String {
    match describe(facts, context) {
        CliError::Operational(failure) => failure.message,
        CliError::Interrupted(interrupt) => format!("Interrupted; {}", interrupt.text()),
        CliError::Usage(message) => message,
        CliError::Reported(_) => String::new(),
    }
}

pub fn describe(facts: &ErrorFacts, context: &SdkContext<'_>) -> CliError {
    if facts.kind == ErrorKind::Cancelled {
        return CliError::Interrupted(match context.operation {
            Operation::Read => InterruptContext::NoDataWritten,
            Operation::ScanSubmit if facts.remote_outcome == RemoteOutcome::NotSent => {
                InterruptContext::ScanNotSubmitted
            }
            Operation::ScanSubmit => InterruptContext::ScanOutcomeUnknown,
            Operation::Write if facts.remote_outcome == RemoteOutcome::NotSent => {
                InterruptContext::NothingChanged
            }
            Operation::Write => InterruptContext::ChangeMayBeApplied,
        });
    }
    let mut failure = Failure::default();
    let management = context.plane == Plane::Management;
    if let Some(status) = facts.http_status() {
        failure.message = api_error_message(facts, status, context.secrets);
        failure.status = Some(status);
        if let Some(id) = facts
            .request_id
            .as_deref()
            .filter(|id| !context.secrets.taints(id))
        {
            failure.details.push(format!("Request ID: {id}"));
        }
    } else {
        failure.message = match facts.kind {
            ErrorKind::Authentication => match facts.status {
                Some(status) => {
                    failure.status = Some(status);
                    format!("AISEC_OAUTH_ERROR:Token request failed with status {status}")
                }
                None => OAUTH_SCHEMA.to_owned(),
            },
            ErrorKind::Decode if management && context.phase == Phase::Token => {
                OAUTH_SCHEMA.to_owned()
            }
            ErrorKind::Transport | ErrorKind::Io
                if management && context.phase == Phase::Token =>
            {
                "AISEC_OAUTH_ERROR:Token request failed: network error".to_owned()
            }
            ErrorKind::Transport | ErrorKind::Io => {
                "AISEC_CLIENT_SIDE_ERROR:Network request failed (connection refused, reset or unreachable)"
                    .to_owned()
            }
            ErrorKind::Deadline => format!(
                "AISEC_SDK_ERROR:Request timed out after {}s",
                context.timeout.as_secs()
            ),
            ErrorKind::Decode => {
                "AISEC_RESPONSE_VALIDATION:Response did not match the expected schema".to_owned()
            }
            ErrorKind::Limit => "AISEC_SDK_ERROR:Response exceeded a client safety limit".to_owned(),
            ErrorKind::Pagination => "AISEC_SDK_ERROR:Pagination stopped: the service returned a repeated cursor or an empty intermediate page".to_owned(),
            ErrorKind::Destination if facts.status.is_some_and(|s| (300..400).contains(&s)) => {
                failure.status = facts.status;
                "AISEC_CLIENT_SIDE_ERROR:Redirect responses are not followed".to_owned()
            }
            kind => format!(
                "{}:{} error",
                facts.error_type.unwrap_or("AISEC_SDK_ERROR"),
                kind_name(kind)
            ),
        };
    }
    if context.operation == Operation::ScanSubmit
        && facts.remote_outcome == RemoteOutcome::Unknown
        && !facts.status.is_some_and(|s| (400..500).contains(&s))
    {
        failure
            .details
            .push("Outcome unknown: the scan may have been received and processed by AIRS.".into());
    }
    CliError::Operational(failure)
}

const OAUTH_SCHEMA: &str = "AISEC_OAUTH_ERROR:Token response did not match the OAuth schema";

/// `<type>:API error <status>[; <title>; <detail>; <prop>: <reason>][ (errorCode: <code>)]`
fn api_error_message(facts: &ErrorFacts, status: u16, secrets: &SecretSet) -> String {
    let error_type = if status >= 500 {
        "AISEC_SERVER_SIDE_ERROR"
    } else {
        "AISEC_CLIENT_SIDE_ERROR"
    };
    let mut parts = vec![format!("API error {status}")];
    if let Some(problem) = &facts.problem {
        for text in [problem.title(), problem.detail()].into_iter().flatten() {
            if !parts.iter().skip(1).any(|part| part == text) {
                parts.push(text.to_owned());
            }
        }
        for field in problem.errors().unwrap_or_default() {
            parts.push(format!("{}: {}", field.property(), field.reason()));
        }
    }
    let mut message = format!("{error_type}:{}", parts.join("; "));
    if let Some(code) = facts
        .service_code
        .as_deref()
        .filter(|code| !secrets.taints(code))
    {
        message.push_str(&format!(" (errorCode: {code})"));
    }
    message
}

pub fn kind_name(kind: ErrorKind) -> &'static str {
    match kind {
        ErrorKind::Configuration => "Configuration",
        ErrorKind::Validation => "Validation",
        ErrorKind::Destination => "Destination",
        ErrorKind::Authentication => "Authentication",
        ErrorKind::Io => "Io",
        ErrorKind::Transport => "Transport",
        ErrorKind::Http => "Http",
        ErrorKind::Decode => "Decode",
        ErrorKind::Limit => "Limit",
        ErrorKind::Deadline => "Deadline",
        ErrorKind::Cancelled => "Cancelled",
        ErrorKind::Protocol => "Protocol",
        ErrorKind::Pagination => "Pagination",
        _ => "Unknown",
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn facts(kind: ErrorKind, status: Option<u16>) -> ErrorFacts {
        let error_type = match (kind, status) {
            (ErrorKind::Http, Some(s)) if s >= 500 => Some("AISEC_SERVER_SIDE_ERROR"),
            (ErrorKind::Http, _) => Some("AISEC_CLIENT_SIDE_ERROR"),
            _ => scm::Error::new(kind)
                .error_type()
                .map(scm::ErrorType::as_str),
        };
        ErrorFacts {
            kind,
            status,
            error_type,
            problem: None,
            service_code: None,
            request_id: None,
            remote_outcome: RemoteOutcome::NotSent,
        }
    }

    fn context<'a>(secrets: &'a SecretSet, plane: Plane, phase: Phase) -> SdkContext<'a> {
        SdkContext {
            plane,
            phase,
            operation: Operation::Read,
            timeout: Duration::from_secs(60),
            secrets,
        }
    }

    fn failure(error: CliError) -> Failure {
        match error {
            CliError::Operational(failure) => failure,
            other => panic!("expected operational, got {other:?}"),
        }
    }

    #[test]
    fn renders_exact_stream_bytes() {
        assert_eq!(CliError::usage("bad").render(), "\n  โœ— bad\n\n");
        assert_eq!(
            CliError::operational("boom").render(),
            "\n  โœ— Error: boom\n\n"
        );
        let error = CliError::Operational(Failure {
            message: "m".into(),
            status: Some(404),
            details: vec!["Request ID: r-1".into()],
        });
        assert_eq!(
            error.render(),
            "\n  โœ— Error: m\n    HTTP 404\n    Re-run with --debug to capture redacted API diagnostics.\n    Request ID: r-1\n\n"
        );
        // Under --debug the hint is omitted (D69).
        assert_eq!(
            error.render_styled(false, false),
            "\n  โœ— Error: m\n    HTTP 404\n    Request ID: r-1\n\n"
        );
        assert_eq!(
            CliError::operational("no status").render_styled(false, true),
            "\n  โœ— Error: no status\n\n",
            "the hint follows the HTTP line only"
        );
        assert_eq!(
            CliError::Interrupted(InterruptContext::NoDataWritten).render(),
            "\n  โœ— Error: Interrupted; no data was written\n\n"
        );
        assert_eq!(CliError::Reported(1).render(), "");
    }

    #[test]
    fn coloured_blocks_follow_chalk() {
        assert_eq!(
            CliError::usage("bad").render_colored(true),
            "\u{1b}[31m\u{1b}[39m\n\u{1b}[31m  โœ— bad\u{1b}[39m\n\u{1b}[31m\u{1b}[39m\n"
        );
        let error = CliError::Operational(Failure {
            message: "AISEC_CLIENT_SIDE_ERROR:API error 404".into(),
            status: Some(404),
            details: vec!["Request ID: r-1".into()],
        });
        assert_eq!(
            error.render_colored(true),
            "\u{1b}[31m\u{1b}[39m\n\u{1b}[31m  โœ— Error: AISEC_CLIENT_SIDE_ERROR:API error 404\u{1b}[39m\n\u{1b}[31m    HTTP 404\u{1b}[39m\n\u{1b}[2m    Re-run with --debug to capture redacted API diagnostics.\u{1b}[22m\n\u{1b}[31m    Request ID: r-1\u{1b}[39m\n\n"
        );
        assert_eq!(error.render_colored(false), error.render());
        assert_eq!(
            CliError::Interrupted(InterruptContext::NoDataWritten).render_colored(true),
            "\u{1b}[31m\u{1b}[39m\n\u{1b}[31m  โœ— Error: Interrupted; no data was written\u{1b}[39m\n\n"
        );
    }

    #[test]
    fn exit_codes() {
        assert_eq!(CliError::usage("x").exit_code(None), 2);
        assert_eq!(CliError::operational("x").exit_code(Some(130)), 1);
        let interrupted = CliError::Interrupted(InterruptContext::NoDataWritten);
        assert_eq!(interrupted.exit_code(Some(143)), 143);
        assert_eq!(interrupted.exit_code(None), 130);
        assert_eq!(CliError::Reported(1).exit_code(None), 1);
    }

    #[test]
    fn http_errors_with_problem_code_and_request_id() {
        let secrets = SecretSet::default();
        let mut f = facts(ErrorKind::Http, Some(400));
        f.problem = ProblemDetails::from_value(&json!({
            "title": "Bad Request",
            "detail": "secret text",
            "errors": [{"property": "name", "reason": "is required"}]
        }));
        f.service_code = Some("E400".into());
        f.request_id = Some("req-1".into());
        let failure = failure(describe(
            &f,
            &context(&secrets, Plane::Management, Phase::Api),
        ));
        assert_eq!(
            failure.message,
            "AISEC_CLIENT_SIDE_ERROR:API error 400; Bad Request; [withheld]; name: is required (errorCode: E400)"
        );
        assert_eq!(failure.status, Some(400));
        assert_eq!(failure.details, ["Request ID: req-1"]);

        let failure = failure_of(ErrorKind::Http, Some(503), Plane::Scanner, Phase::Api);
        assert_eq!(failure.message, "AISEC_SERVER_SIDE_ERROR:API error 503");
        let failure = failure_of(ErrorKind::Limit, Some(401), Plane::Scanner, Phase::Api);
        assert_eq!(failure.message, "AISEC_CLIENT_SIDE_ERROR:API error 401");
        assert_eq!(failure.status, Some(401));
    }

    fn failure_of(kind: ErrorKind, status: Option<u16>, plane: Plane, phase: Phase) -> Failure {
        let secrets = SecretSet::default();
        failure(describe(
            &facts(kind, status),
            &context(&secrets, plane, phase),
        ))
    }

    #[test]
    fn duplicate_problem_title_and_detail_are_shown_once() {
        let secrets = SecretSet::default();
        let mut f = facts(ErrorKind::Http, Some(404));
        f.problem =
            ProblemDetails::from_value(&json!({"title": "Not Found", "detail": "Not Found"}));
        let failure = failure(describe(&f, &context(&secrets, Plane::Scanner, Phase::Api)));
        assert_eq!(
            failure.message,
            "AISEC_CLIENT_SIDE_ERROR:API error 404; Not Found"
        );
    }

    #[test]
    fn tainted_metadata_is_dropped() {
        let secrets = SecretSet::default();
        secrets.add("FAKE-SECRET-100");
        let mut f = facts(ErrorKind::Http, Some(401));
        f.service_code = Some("FAKE-SECRET-100".into());
        f.request_id = Some("RkFLRS1TRUNSRVQtMTAw".into());
        let failure = failure(describe(
            &f,
            &context(&secrets, Plane::Management, Phase::Api),
        ));
        assert_eq!(failure.message, "AISEC_CLIENT_SIDE_ERROR:API error 401");
        assert!(failure.details.is_empty());
    }

    #[test]
    fn secret_forms() {
        let secrets = SecretSet::default();
        secrets.add(" a b/c+ ");
        assert!(secrets.taints("x a b/c+ y"));
        assert!(secrets.taints("a+b%2Fc%2B"));
        assert!(secrets.taints(&base64(b"a b/c+", STANDARD_ALPHABET)));
        assert!(!secrets.taints("unrelated"));
        assert_eq!(
            base64(b"FAKE-SECRET-100", STANDARD_ALPHABET),
            "RkFLRS1TRUNSRVQtMTAw"
        );
        assert_eq!(base64(b"ab", STANDARD_ALPHABET), "YWI");
        assert_eq!(base64(b"\xfb\xff", URL_SAFE_ALPHABET), "-_8");
    }

    /// The debug line check ignores ASCII case: a secret echoed as a (lowercased)
    /// header name still matches.
    #[test]
    fn line_check_ignores_case() {
        let secrets = SecretSet::default();
        secrets.add("FAKE-Secret-100");
        assert!(secrets.appears_in_ignoring_case(r#"{"fake-secret-100":"***"}"#));
        assert!(secrets.appears_in_ignoring_case("x FAKE-SECRET-100 y"));
        assert!(secrets.appears_in_ignoring_case(
            &base64(b"FAKE-Secret-100", STANDARD_ALPHABET).to_lowercase()
        ));
        assert!(!secrets.appears_in_ignoring_case("fake-secret-10"));
    }

    #[test]
    fn basic_credential_forms() {
        let secrets = SecretSet::default();
        secrets.add_basic_credentials("client 100", "FAKE/SECRET 100");
        // base64(id:secret), raw and form-encoded halves (D29).
        assert!(secrets.taints(&format!(
            "x{}y",
            base64(b"client 100:FAKE/SECRET 100", STANDARD_ALPHABET)
        )));
        assert!(secrets.taints(&base64(b"client+100:FAKE%2FSECRET+100", STANDARD_ALPHABET)));
        assert!(secrets.taints(&base64(b"client+100:FAKE%2FSECRET+100", URL_SAFE_ALPHABET)));
        assert!(!secrets.taints("unrelated"));
        // Without a secret there is no credential pair to protect.
        let empty = SecretSet::default();
        empty.add_basic_credentials("client-100", "");
        assert!(!empty.taints(&base64(b"client-100:", STANDARD_ALPHABET)));
    }

    #[test]
    fn oauth_failures_are_distinguished() {
        let f = failure_of(
            ErrorKind::Authentication,
            Some(401),
            Plane::Management,
            Phase::Token,
        );
        assert_eq!(
            f.message,
            "AISEC_OAUTH_ERROR:Token request failed with status 401"
        );
        assert_eq!(f.status, Some(401));
        let f = failure_of(ErrorKind::Transport, None, Plane::Management, Phase::Token);
        assert_eq!(
            f.message,
            "AISEC_OAUTH_ERROR:Token request failed: network error"
        );
        let f = failure_of(ErrorKind::Decode, None, Plane::Management, Phase::Token);
        assert_eq!(f.message, OAUTH_SCHEMA);
        let f = failure_of(
            ErrorKind::Authentication,
            None,
            Plane::Management,
            Phase::Token,
        );
        assert_eq!(f.message, OAUTH_SCHEMA);
        for status in [Some(200), None] {
            let f = failure_of(ErrorKind::Decode, status, Plane::Management, Phase::Api);
            assert_eq!(
                f.message,
                "AISEC_RESPONSE_VALIDATION:Response did not match the expected schema"
            );
        }
    }

    #[test]
    fn local_and_transport_kinds() {
        let f = failure_of(ErrorKind::Transport, None, Plane::Scanner, Phase::Api);
        assert_eq!(
            f.message,
            "AISEC_CLIENT_SIDE_ERROR:Network request failed (connection refused, reset or unreachable)"
        );
        assert_eq!(f.status, None);
        let f = failure_of(ErrorKind::Deadline, None, Plane::Scanner, Phase::Api);
        assert_eq!(f.message, "AISEC_SDK_ERROR:Request timed out after 60s");
        let f = failure_of(ErrorKind::Limit, Some(200), Plane::Scanner, Phase::Api);
        assert_eq!(
            f.message,
            "AISEC_SDK_ERROR:Response exceeded a client safety limit"
        );
        let f = failure_of(ErrorKind::Pagination, None, Plane::Management, Phase::Api);
        assert!(f.message.starts_with("AISEC_SDK_ERROR:Pagination stopped"));
        let f = failure_of(
            ErrorKind::Destination,
            Some(302),
            Plane::Scanner,
            Phase::Api,
        );
        assert_eq!(
            f.message,
            "AISEC_CLIENT_SIDE_ERROR:Redirect responses are not followed"
        );
        assert_eq!(f.status, Some(302));
        let f = failure_of(ErrorKind::Validation, None, Plane::Management, Phase::Api);
        assert_eq!(
            f.message,
            "AISEC_USER_REQUEST_PAYLOAD_ERROR:Validation error"
        );
        let f = failure_of(ErrorKind::Configuration, None, Plane::Scanner, Phase::Api);
        assert_eq!(f.message, "AISEC_MISSING_VARIABLE:Configuration error");
    }

    #[test]
    fn scan_submissions_report_unknown_outcomes() {
        let secrets = SecretSet::default();
        let mut ctx = context(&secrets, Plane::Scanner, Phase::Api);
        ctx.operation = Operation::ScanSubmit;
        let mut f = facts(ErrorKind::Http, Some(503));
        f.remote_outcome = RemoteOutcome::Unknown;
        let failure_503 = failure(describe(&f, &ctx));
        assert_eq!(
            failure_503.details,
            ["Outcome unknown: the scan may have been received and processed by AIRS."]
        );
        let mut f = facts(ErrorKind::Limit, Some(401));
        f.remote_outcome = RemoteOutcome::Unknown;
        assert!(failure(describe(&f, &ctx)).details.is_empty());
        let mut f = facts(ErrorKind::Cancelled, None);
        f.remote_outcome = RemoteOutcome::Unknown;
        assert_eq!(
            describe(&f, &ctx),
            CliError::Interrupted(InterruptContext::ScanOutcomeUnknown)
        );
        f.remote_outcome = RemoteOutcome::NotSent;
        assert_eq!(
            describe(&f, &ctx),
            CliError::Interrupted(InterruptContext::ScanNotSubmitted)
        );
        ctx.operation = Operation::Read;
        assert_eq!(
            describe(&f, &ctx),
            CliError::Interrupted(InterruptContext::NoDataWritten)
        );
    }

    #[test]
    fn facts_from_real_sdk_errors() {
        let facts = ErrorFacts::of(&scm::Error::new(ErrorKind::Transport));
        assert_eq!(facts.kind, ErrorKind::Transport);
        assert_eq!(facts.error_type, Some("AISEC_CLIENT_SIDE_ERROR"));
        assert_eq!(facts.remote_outcome, RemoteOutcome::NotSent);
        let secrets = SecretSet::default();
        let message = sdk_message(
            &scm::Error::new(ErrorKind::Decode),
            &context(&secrets, Plane::Scanner, Phase::Api),
        );
        assert_eq!(
            message,
            "AISEC_RESPONSE_VALIDATION:Response did not match the expected schema"
        );
    }
}