airs-cli 0.8.0

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
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
//! Endpoint admission and SDK client construction (DESIGN §5).
//!
//! Every configured URL is admitted with `Endpoint::loopback` (https anywhere, http
//! only for loopback hosts). Credentials come only from the tenant file and are
//! checked locally before any request, so configuration mistakes cost zero requests.
//!
//! A client with a plain-http (loopback) endpoint uses [`DirectTransport`], which never
//! goes through a proxy: http is admitted only because the traffic stays on the host,
//! and a proxy would carry the cleartext credentials off it.

use crate::debug::{DebugLog, DebugTransport};
use crate::error::{self, CliError, Operation, Phase, Plane, SdkContext, SecretSet};
use crate::tenant::config::{TenantConfig, js_trim};
use futures_util::StreamExt;
use futures_util::future::BoxFuture;
use scm::airs::management::ManagementClient;
use scm::airs::scan::Scanner;
use scm::auth::{AuthContext, Authentication, OAuthProvider, TokenLease, TokenProvider};
use scm::config::DestinationPolicy;
use scm::transport::{ReqwestTransport, Transport, TransportRequest, TransportResponse};
use scm::{Client, Endpoint, ErrorKind, Limits, OriginPolicy, RequestOptions, Secret, Session};
use std::sync::Arc;
use std::sync::atomic::{AtomicU16, Ordering};
use std::time::Duration;

pub const DEFAULT_TOKEN_ENDPOINT: &str =
    "https://auth.apps.paloaltonetworks.com/oauth2/access_token";
pub const DEFAULT_MGMT_ENDPOINT: &str = "https://api.apps.paloaltonetworks.com/aisec";
pub const DEFAULT_SCAN_ENDPOINT: &str = "https://service.api.aisecurity.paloaltonetworks.com";
/// The red team planes' defaults (the SDK constants, TS `SDK:91-93`; DESIGN §15.3).
pub const DEFAULT_RED_TEAM_DATA_ENDPOINT: &str =
    "https://api.apps.paloaltonetworks.com/ai-red-teaming/data-plane";
pub const DEFAULT_RED_TEAM_MGMT_ENDPOINT: &str =
    "https://api.apps.paloaltonetworks.com/ai-red-teaming/mgmt-plane";
pub const DEFAULT_RED_TEAM_BROKER_ENDPOINT: &str =
    "https://api.apps.paloaltonetworks.com/ai-red-teaming/data-plane/network-broker";

/// The SDK default budget for one request without explicit `RequestOptions`.
pub const SINGLE_REQUEST_BUDGET: Duration = Duration::from_secs(60);
/// The SDK's fixed budget for an OAuth refresh when no options are passed.
pub const TOKEN_BUDGET: Duration = Duration::from_secs(30);
/// Full walks (`--all`, lookups, latest-topic listings).
pub const WALK_BUDGET: Duration = Duration::from_secs(300);
/// The whole of one doctor probe (token + request).
pub const PROBE_BUDGET: Duration = Duration::from_secs(5);

/// TS SDK default attempt count for 502/503/504 on management reads.
const MANAGEMENT_RETRIES: u32 = 5;
/// The TypeScript SDK's scanner credential limit (UTF-16 code units).
const MAX_SCANNER_CREDENTIAL: usize = 2048;

/// A client could not be configured; `key` names the tenant setting at fault.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SetupError {
    pub key: Option<&'static str>,
    pub error: CliError,
}

impl SetupError {
    fn config(key: &'static str, message: impl Into<String>) -> Self {
        Self {
            key: Some(key),
            error: CliError::operational(message),
        }
    }
    fn sdk(message: &str) -> Self {
        Self {
            key: None,
            error: CliError::operational(message),
        }
    }
    /// The failure message (for doctor details).
    pub fn message(&self) -> String {
        self.error.message()
    }
}

impl From<SetupError> for CliError {
    fn from(value: SetupError) -> Self {
        value.error
    }
}

/// The admission failure for `key` (the value is never echoed).
fn invalid_endpoint(key: &'static str) -> SetupError {
    SetupError::config(
        key,
        format!(
            "Invalid {key}: endpoints must use https (http is allowed only for loopback hosts) and must not contain credentials, a query or a fragment"
        ),
    )
}

/// Admit a configured URL (or the default when unset).
pub fn admit(
    key: &'static str,
    configured: Option<&str>,
    default: &str,
) -> Result<Endpoint, SetupError> {
    Endpoint::loopback(configured.unwrap_or(default)).map_err(|_| invalid_endpoint(key))
}

/// The status of the last HTTP response a client received (0 until one arrives).
///
/// A walk or probe that ends at its deadline while the SDK waits to retry a 429/5xx
/// surfaces as `Deadline`, and a deadline that drops a page fetch loses the answer's
/// status; doctor reads this to report what the endpoint actually said (§9).
#[derive(Clone, Debug, Default)]
pub struct LastStatus(Arc<AtomicU16>);

impl LastStatus {
    pub fn get(&self) -> Option<u16> {
        match self.0.load(Ordering::SeqCst) {
            0 => None,
            status => Some(status),
        }
    }
}

/// Records each response status in a [`LastStatus`]; otherwise the inner transport.
struct ObservedTransport {
    inner: Arc<dyn Transport>,
    last: LastStatus,
}

impl Transport for ObservedTransport {
    fn send<'a>(
        &'a self,
        request: TransportRequest,
    ) -> BoxFuture<'a, scm::Result<TransportResponse>> {
        Box::pin(async move {
            let response = self.inner.send(request).await?;
            self.last
                .0
                .store(response.status().as_u16(), Ordering::SeqCst);
            Ok(response)
        })
    }
}

/// The SDK's `ReqwestTransport` (which honours proxy settings), or [`DirectTransport`]
/// when any of the client's endpoints is plain http; wrapped by the debug transport
/// (a pass-through without `debug`, DESIGN §2.9) and observed by `last`.
fn transport(
    endpoints: &[&Endpoint],
    last: &LastStatus,
    debug: Option<&DebugLog>,
) -> Result<Arc<dyn Transport>, SetupError> {
    let failed = || SetupError::sdk("AISEC_SDK_ERROR:The HTTP transport could not be initialised");
    let inner: Arc<dyn Transport> = if endpoints
        .iter()
        .any(|endpoint| endpoint.url().scheme() == "http")
    {
        Arc::new(DirectTransport::new().ok_or_else(failed)?)
    } else {
        Arc::new(ReqwestTransport::new().map_err(|_| failed())?)
    };
    Ok(Arc::new(ObservedTransport {
        inner: DebugTransport::wrap(inner, debug),
        last: last.clone(),
    }))
}

/// The SDK's own user agent (`PAN-AIRS/<scm-sdk version>-rust-sdk`).
const SDK_USER_AGENT: &str = scm::constants::USER_AGENT;

/// `ReqwestTransport` with the SDK's hardening (no redirects, no retries, bounded
/// headers, gzip only) that never uses a proxy: environment and system proxies are
/// ignored. Used only for admitted plain-http (loopback) endpoints.
struct DirectTransport {
    client: reqwest::Client,
}

impl DirectTransport {
    fn new() -> Option<Self> {
        reqwest::Client::builder()
            .no_proxy()
            .redirect(reqwest::redirect::Policy::none())
            .retry(reqwest::retry::never())
            .connect_timeout(Duration::from_secs(10))
            .pool_max_idle_per_host(32)
            .pool_idle_timeout(Duration::from_secs(90))
            .http1_max_headers(128)
            .http2_max_header_list_size(16 * 1024)
            .no_brotli()
            .no_deflate()
            .no_zstd()
            .gzip(true)
            .referer(false)
            .user_agent(SDK_USER_AGENT)
            .build()
            .ok()
            .map(|client| Self { client })
    }
}

impl Transport for DirectTransport {
    fn send<'a>(
        &'a self,
        request: TransportRequest,
    ) -> BoxFuture<'a, scm::Result<TransportResponse>> {
        Box::pin(async move {
            let response = self
                .client
                .request(request.method().clone(), request.url().clone())
                .headers(request.headers().clone())
                .body(request.body().clone())
                .send()
                .await
                .map_err(|_| scm::Error::new(ErrorKind::Transport))?;
            let status = response.status();
            let headers = response.headers().clone();
            let stream = response
                .bytes_stream()
                .map(|chunk| chunk.map_err(|_| scm::Error::new(ErrorKind::Transport)));
            Ok(TransportResponse::new(status, headers, Box::pin(stream)))
        })
    }
}

/// The OAuth provider, recording every lease it hands out in the invocation's
/// [`SecretSet`]. The SDK fetches leases on its own (a 401/403 refresh-and-replay, an
/// expiry during a walk); each one is registered before any error is mapped, so a
/// server that echoes the bearer in a request ID or error code never gets it printed.
pub struct RecordingProvider {
    inner: Arc<OAuthProvider>,
    secrets: SecretSet,
    /// The invocation's API log: token records are held until the lease is registered.
    debug: Option<DebugLog>,
}

impl RecordingProvider {
    /// Fetch or reuse a lease under `options` (the SDK's 30 s refresh budget without).
    pub async fn get_token(&self, options: Option<&RequestOptions>) -> scm::Result<TokenLease> {
        let options = match options {
            Some(options) => options.clone(),
            None => RequestOptions::with_timeout(TOKEN_BUDGET)?,
        };
        self.token(&options).await
    }
}

impl TokenProvider for RecordingProvider {
    fn token<'a>(&'a self, options: &'a RequestOptions) -> BoxFuture<'a, scm::Result<TokenLease>> {
        Box::pin(async move {
            // The token response's record waits until its lease is in the set, so a
            // token echoed in that response's own headers is masked (DESIGN §2.9).
            // Dropping this future drops the hold, which withholds the headers.
            let hold = self.debug.as_ref().map(DebugLog::hold_tokens);
            let result = self.inner.token(options).await;
            if let Ok(lease) = &result {
                self.secrets.add(lease.secret().expose());
            }
            if let Some(hold) = hold {
                hold.release();
            }
            result
        })
    }
    fn context(&self) -> &AuthContext {
        self.inner.context()
    }
    fn invalidate(&self, generation: u64) -> bool {
        self.inner.invalidate(generation)
    }
}

/// The management client and the application-owned OAuth provider behind it.
pub struct ManagementClients {
    pub provider: Arc<RecordingProvider>,
    pub management: ManagementClient,
    /// The last response status either of them received.
    pub last_status: LastStatus,
}

impl ManagementClients {
    /// Build from the effective config. Credentials must already be checked present.
    /// Every OAuth lease is registered in `secrets` (shared with the invocation); every
    /// attempt of the client and its provider is recorded in `debug`.
    pub fn build(
        config: &TenantConfig,
        session: &Session,
        secrets: &SecretSet,
        debug: Option<&DebugLog>,
    ) -> Result<Self, SetupError> {
        let api = admit(
            "mgmtEndpoint",
            config.effective_str("mgmtEndpoint"),
            DEFAULT_MGMT_ENDPOINT,
        )?;
        let issuer = admit(
            "mgmtTokenEndpoint",
            config.effective_str("mgmtTokenEndpoint"),
            DEFAULT_TOKEN_ENDPOINT,
        )?;
        let last_status = LastStatus::default();
        let OAuthParts {
            provider,
            transport,
            policy,
        } = oauth_parts(
            config,
            &issuer,
            std::slice::from_ref(&api),
            session,
            secrets,
            debug,
            &last_status,
        )?;
        let mut limits = Limits::default();
        limits.max_retries = MANAGEMENT_RETRIES;
        let client = Client::builder(api)
            .transport(transport)
            .destination_policy(policy)
            .authentication(Authentication::oauth(
                provider.clone() as Arc<dyn TokenProvider>,
                false,
            ))
            .session(session.clone())
            .limits(limits)
            .build()
            .map_err(|_| {
                SetupError::sdk("AISEC_SDK_ERROR:The management client could not be configured")
            })?;
        let management = ManagementClient::new(client).map_err(|_| {
            SetupError::sdk("AISEC_SDK_ERROR:The management client could not be configured")
        })?;
        Ok(Self {
            provider,
            management,
            last_status,
        })
    }

    /// Fetch the OAuth token explicitly so token failures are reported as such.
    /// `budget` is the duration `options` was created with (30 s without options).
    pub async fn authenticate(
        &self,
        options: Option<&RequestOptions>,
        budget: Duration,
    ) -> Result<(), CliError> {
        match self.provider.get_token(options).await {
            Ok(_) => Ok(()),
            Err(failure) => Err(error::from_sdk(
                &failure,
                &SdkContext {
                    plane: Plane::Management,
                    phase: Phase::Token,
                    operation: Operation::Read,
                    timeout: budget,
                    secrets: &self.provider.secrets,
                },
            )),
        }
    }
}

/// The OAuth identity of a management-plane client: the lease-recording provider, the
/// transport (direct when any endpoint is plain http) and one destination policy
/// admitting `apis` and the issuer.
struct OAuthParts {
    provider: Arc<RecordingProvider>,
    transport: Arc<dyn Transport>,
    policy: Arc<dyn DestinationPolicy>,
}

/// Validate `mgmtTsgId`, `mgmtClientId` and `mgmtClientSecret` (§5 messages) and build
/// the [`OAuthParts`] for `apis` (the API bases the client may reach).
fn oauth_parts(
    config: &TenantConfig,
    issuer: &Endpoint,
    apis: &[Endpoint],
    session: &Session,
    secrets: &SecretSet,
    debug: Option<&DebugLog>,
    last_status: &LastStatus,
) -> Result<OAuthParts, SetupError> {
    let tsg = config.effective_str("mgmtTsgId").unwrap_or_default();
    if tsg.is_empty() || tsg.len() > 32 || !tsg.bytes().all(|b| b.is_ascii_digit()) {
        return Err(SetupError::config(
            "mgmtTsgId",
            "Invalid mgmtTsgId: the Rust SDK requires 1-32 ASCII digits",
        ));
    }
    let client_id = config.effective_str("mgmtClientId").unwrap_or_default();
    let context = AuthContext::new(issuer.clone(), client_id, 0, tsg).map_err(|_| {
        SetupError::config(
            "mgmtClientId",
            "Invalid mgmtClientId: the Rust SDK requires at most 1024 bytes without control characters",
        )
    })?;
    let invalid_secret = || {
        SetupError::config(
            "mgmtClientSecret",
            "Invalid mgmtClientSecret: the Rust SDK requires at most 16 KiB without control characters",
        )
    };
    let secret = Secret::new(config.effective_str("mgmtClientSecret").unwrap_or_default())
        .map_err(|_| invalid_secret())?;
    let mut endpoints: Vec<&Endpoint> = apis.iter().collect();
    endpoints.push(issuer);
    let transport = transport(&endpoints, last_status, debug)?;
    let mut admitted: Vec<Endpoint> = apis.to_vec();
    admitted.push(issuer.clone());
    let policy: Arc<dyn DestinationPolicy> = Arc::new(OriginPolicy::new(admitted));
    let provider = Arc::new(RecordingProvider {
        inner: Arc::new(
            OAuthProvider::new(
                context,
                secret,
                transport.clone(),
                policy.clone(),
                session.clone(),
            )
            .map_err(|_| invalid_secret())?,
        ),
        secrets: secrets.clone(),
        debug: debug.cloned(),
    });
    Ok(OAuthParts {
        provider,
        transport,
        policy,
    })
}

/// The red team client (the management OAuth identity across the data, management and
/// network broker planes, DESIGN §15.3) and the provider behind it.
pub struct RedTeamClients {
    pub provider: Arc<RecordingProvider>,
    pub red_team: scm::airs::red_team::RedTeamClient,
}

impl RedTeamClients {
    /// Build from the effective config (credentials already checked present): the three
    /// red team endpoints and the issuer admitted into one policy, `max_retries = 5`.
    pub fn build(
        config: &TenantConfig,
        session: &Session,
        secrets: &SecretSet,
        debug: Option<&DebugLog>,
    ) -> Result<Self, SetupError> {
        let data = admit(
            "redTeamDataEndpoint",
            config.effective_str("redTeamDataEndpoint"),
            DEFAULT_RED_TEAM_DATA_ENDPOINT,
        )?;
        let management = admit(
            "redTeamMgmtEndpoint",
            config.effective_str("redTeamMgmtEndpoint"),
            DEFAULT_RED_TEAM_MGMT_ENDPOINT,
        )?;
        let broker = admit(
            "redTeamNetworkBrokerEndpoint",
            config.effective_str("redTeamNetworkBrokerEndpoint"),
            DEFAULT_RED_TEAM_BROKER_ENDPOINT,
        )?;
        let issuer = admit(
            "mgmtTokenEndpoint",
            config.effective_str("mgmtTokenEndpoint"),
            DEFAULT_TOKEN_ENDPOINT,
        )?;
        let OAuthParts {
            provider,
            transport,
            policy,
        } = oauth_parts(
            config,
            &issuer,
            &[data.clone(), management.clone(), broker.clone()],
            session,
            secrets,
            debug,
            &LastStatus::default(),
        )?;
        let failed =
            || SetupError::sdk("AISEC_SDK_ERROR:The red team client could not be configured");
        let mut limits = Limits::default();
        limits.max_retries = MANAGEMENT_RETRIES;
        let client = Client::builder(data)
            .transport(transport)
            .destination_policy(policy)
            .authentication(Authentication::oauth(
                provider.clone() as Arc<dyn TokenProvider>,
                false,
            ))
            .session(session.clone())
            .limits(limits)
            .build()
            .map_err(|_| failed())?;
        let red_team = scm::airs::red_team::RedTeamClient::new(client, management, broker)
            .map_err(|_| failed())?;
        Ok(Self { provider, red_team })
    }

    /// Fetch the OAuth token explicitly so token failures are reported as such
    /// (`budget`: the duration `options` was created with, 30 s without options).
    pub async fn authenticate(
        &self,
        options: Option<&RequestOptions>,
        budget: Duration,
    ) -> Result<(), CliError> {
        match self.provider.get_token(options).await {
            Ok(_) => Ok(()),
            Err(failure) => Err(error::from_sdk(
                &failure,
                &SdkContext {
                    plane: Plane::Management,
                    phase: Phase::Token,
                    operation: Operation::Read,
                    timeout: budget,
                    secrets: &self.provider.secrets,
                },
            )),
        }
    }
}

/// The response bound of the DLP client (G13, DESIGN §16.3): a keyword-bearing
/// dictionary page can exceed the SDK's default 8 MiB (validation then allows 400,000
/// nodes).
pub const DLP_MAX_RESPONSE_BYTES: usize = 32 * 1024 * 1024;

/// The DLP client (the management OAuth identity on the tenant's `dlpEndpoint`, DESIGN
/// §16.3) and the provider behind it.
pub struct DlpClients {
    pub provider: Arc<RecordingProvider>,
    pub dlp: scm::dlp::DlpClient,
}

impl DlpClients {
    /// Build from the effective config (credentials already checked present): the
    /// tenant's `dlpEndpoint` (else the SDK default) and the issuer admitted into one
    /// policy, `max_retries = 5` for the replay-safe reads, a 32 MiB response bound and
    /// the default 8 MiB request bound. `mgmtEndpoint` is not used.
    pub fn build(
        config: &TenantConfig,
        session: &Session,
        secrets: &SecretSet,
        debug: Option<&DebugLog>,
    ) -> Result<Self, SetupError> {
        let base = admit(
            "dlpEndpoint",
            config.effective_str("dlpEndpoint"),
            scm::constants::DEFAULT_DLP_ENDPOINT,
        )?;
        let issuer = admit(
            "mgmtTokenEndpoint",
            config.effective_str("mgmtTokenEndpoint"),
            DEFAULT_TOKEN_ENDPOINT,
        )?;
        let OAuthParts {
            provider,
            transport,
            policy,
        } = oauth_parts(
            config,
            &issuer,
            std::slice::from_ref(&base),
            session,
            secrets,
            debug,
            &LastStatus::default(),
        )?;
        let failed = || SetupError::sdk("AISEC_SDK_ERROR:The DLP client could not be configured");
        let mut limits = Limits::default();
        limits.max_retries = MANAGEMENT_RETRIES;
        limits.max_response_bytes = DLP_MAX_RESPONSE_BYTES;
        let client = Client::builder(base)
            .transport(transport)
            .destination_policy(policy)
            .authentication(Authentication::oauth(
                provider.clone() as Arc<dyn TokenProvider>,
                false,
            ))
            .session(session.clone())
            .limits(limits)
            .build()
            .map_err(|_| failed())?;
        let dlp = scm::dlp::DlpClient::new(client).map_err(|_| failed())?;
        Ok(Self { provider, dlp })
    }

    /// Fetch the OAuth token explicitly so token failures are reported as such
    /// (`budget`: the duration `options` was created with, 30 s without options).
    pub async fn authenticate(
        &self,
        options: Option<&RequestOptions>,
        budget: Duration,
    ) -> Result<(), CliError> {
        match self.provider.get_token(options).await {
            Ok(_) => Ok(()),
            Err(failure) => Err(error::from_sdk(
                &failure,
                &SdkContext {
                    plane: Plane::Management,
                    phase: Phase::Token,
                    operation: Operation::Read,
                    timeout: budget,
                    secrets: &self.provider.secrets,
                },
            )),
        }
    }
}

/// The model-security client (the management OAuth identity on the tenant's
/// `modelSecDataEndpoint` and `modelSecMgmtEndpoint`, DESIGN §17.3) and the provider
/// behind it.
pub struct ModelSecurityClients {
    pub provider: Arc<RecordingProvider>,
    pub model_security: scm::airs::model_security::ModelSecurityClient,
}

impl ModelSecurityClients {
    /// Build from the effective config (credentials already checked present): the data
    /// and management bases (else the SDK defaults) and the issuer admitted into one
    /// policy, `max_retries = 5` for the replay-safe reads, the default 8 MiB response
    /// bound. `mgmtEndpoint` is not used; no TSG header is sent (TS parity).
    pub fn build(
        config: &TenantConfig,
        session: &Session,
        secrets: &SecretSet,
        debug: Option<&DebugLog>,
    ) -> Result<Self, SetupError> {
        let data = admit(
            "modelSecDataEndpoint",
            config.effective_str("modelSecDataEndpoint"),
            scm::constants::DEFAULT_MODEL_SEC_DATA_ENDPOINT,
        )?;
        let management = admit(
            "modelSecMgmtEndpoint",
            config.effective_str("modelSecMgmtEndpoint"),
            scm::constants::DEFAULT_MODEL_SEC_MGMT_ENDPOINT,
        )?;
        let issuer = admit(
            "mgmtTokenEndpoint",
            config.effective_str("mgmtTokenEndpoint"),
            DEFAULT_TOKEN_ENDPOINT,
        )?;
        let OAuthParts {
            provider,
            transport,
            policy,
        } = oauth_parts(
            config,
            &issuer,
            &[data.clone(), management.clone()],
            session,
            secrets,
            debug,
            &LastStatus::default(),
        )?;
        let failed =
            || SetupError::sdk("AISEC_SDK_ERROR:The model security client could not be configured");
        let mut limits = Limits::default();
        limits.max_retries = MANAGEMENT_RETRIES;
        let client = Client::builder(data.clone())
            .transport(transport)
            .destination_policy(policy)
            .authentication(Authentication::oauth(
                provider.clone() as Arc<dyn TokenProvider>,
                false,
            ))
            .session(session.clone())
            .limits(limits)
            .build()
            .map_err(|_| failed())?;
        let model_security =
            scm::airs::model_security::ModelSecurityClient::new(client, data, management)
                .map_err(|_| failed())?;
        Ok(Self {
            provider,
            model_security,
        })
    }

    /// Fetch the OAuth token explicitly so token failures are reported as such
    /// (`budget`: the duration `options` was created with, 30 s without options).
    pub async fn authenticate(
        &self,
        options: Option<&RequestOptions>,
        budget: Duration,
    ) -> Result<(), CliError> {
        match self.provider.get_token(options).await {
            Ok(_) => Ok(()),
            Err(failure) => Err(error::from_sdk(
                &failure,
                &SdkContext {
                    plane: Plane::Management,
                    phase: Phase::Token,
                    operation: Operation::Read,
                    timeout: budget,
                    secrets: &self.provider.secrets,
                },
            )),
        }
    }
}

/// A trimmed scanner credential, checked against the TypeScript and SDK limits.
fn scanner_credential(
    config: &TenantConfig,
    key: &'static str,
    label: &str,
) -> Result<Option<Secret>, SetupError> {
    let Some(value) = config
        .effective_str(key)
        .map(js_trim)
        .filter(|v| !v.is_empty())
    else {
        return Ok(None);
    };
    if value.encode_utf16().nth(MAX_SCANNER_CREDENTIAL).is_some() {
        return Err(SetupError::config(
            key,
            format!(
                "AISEC_USER_REQUEST_PAYLOAD_ERROR:{label} exceeds max length of {MAX_SCANNER_CREDENTIAL}"
            ),
        ));
    }
    if !value.bytes().all(|byte| byte.is_ascii_graphic()) {
        return Err(SetupError::config(
            key,
            format!("Invalid {key}: the Rust SDK requires printable ASCII without spaces"),
        ));
    }
    Secret::new(value)
        .map(Some)
        .map_err(|_| SetupError::config(key, format!("Invalid {key}")))
}

/// Build the scanner through `scm::configuration::init` (TS `init()` semantics); every
/// attempt is recorded in `debug`.
pub fn build_scanner(
    config: &TenantConfig,
    session: &Session,
    debug: Option<&DebugLog>,
) -> Result<Scanner, SetupError> {
    build_observed_scanner(config, session, debug).map(|(scanner, _)| scanner)
}

/// [`build_scanner`], plus the status of the last response it receives.
pub fn build_observed_scanner(
    config: &TenantConfig,
    session: &Session,
    debug: Option<&DebugLog>,
) -> Result<(Scanner, LastStatus), SetupError> {
    let endpoint = admit(
        "airsApiEndpoint",
        config.effective_str("airsApiEndpoint"),
        DEFAULT_SCAN_ENDPOINT,
    )?;
    let api_key = scanner_credential(config, "airsApiKey", "apiKey")?;
    let api_token = scanner_credential(config, "airsApiToken", "apiToken")?;
    let mut options = scm::configuration::InitOptions::default();
    options.api_key = api_key;
    options.api_token = api_token;
    options.num_retries = config.num_retries();
    let last_status = LastStatus::default();
    let transport = transport(&[&endpoint], &last_status, debug)?;
    options.api_endpoint = Some(endpoint);
    let configuration =
        scm::configuration::init(options).map_err(|_| invalid_endpoint("airsApiEndpoint"))?;
    let failed = || SetupError::sdk("AISEC_SDK_ERROR:The scanner client could not be configured");
    let client = configuration
        .client_builder()
        .map_err(|_| failed())?
        .transport(transport)
        .session(session.clone())
        .build()
        .map_err(|_| failed())?;
    Ok((Scanner::new(client).map_err(|_| failed())?, last_status))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tenant::config::{ConfigValue, schema_key};

    /// A tenant config from a JSON object of strings and integers (test shorthand).
    fn config(text: &str) -> TenantConfig {
        let serde_json::Value::Object(entries) = serde_json::from_str(text).unwrap() else {
            panic!("object expected");
        };
        TenantConfig::from_values(entries.into_iter().map(|(key, value)| {
            let key = schema_key(&key).unwrap();
            let value = match value {
                serde_json::Value::String(text) => ConfigValue::Text(text),
                serde_json::Value::Number(number) => ConfigValue::Integer(number.as_i64().unwrap()),
                other => panic!("unsupported {other}"),
            };
            (key, value)
        }))
    }

    #[test]
    fn endpoint_admission() {
        for url in [
            "https://example.com/aisec",
            "http://127.0.0.1:8080/aisec",
            "http://127.9.9.9",
            "http://localhost:1",
            "http://[::1]:9/x",
        ] {
            assert!(
                admit("mgmtEndpoint", Some(url), DEFAULT_MGMT_ENDPOINT).is_ok(),
                "{url}"
            );
        }
        for url in [
            "http://example.test",
            "http://0.0.0.0:1",
            "https://user:pw@example.com",
            "https://example.com/?q=1",
            "https://example.com/#f",
            "not a url",
        ] {
            let error = admit("mgmtEndpoint", Some(url), DEFAULT_MGMT_ENDPOINT).unwrap_err();
            assert_eq!(error.key, Some("mgmtEndpoint"));
            assert!(!error.message().contains(url), "the value is never echoed");
            assert!(
                error
                    .message()
                    .starts_with("Invalid mgmtEndpoint: endpoints must use https")
            );
        }
        assert!(admit("x", None, DEFAULT_SCAN_ENDPOINT).is_ok());
    }

    #[test]
    fn management_configuration_errors_are_local() {
        let session = Session::new();
        let secrets = SecretSet::default();
        let bad_tsg = config(r#"{"mgmtClientId":"c","mgmtClientSecret":"s","mgmtTsgId":"abc"}"#);
        let error = ManagementClients::build(&bad_tsg, &session, &secrets, None)
            .err()
            .unwrap();
        assert_eq!(
            error.message(),
            "Invalid mgmtTsgId: the Rust SDK requires 1-32 ASCII digits"
        );
        let bad_endpoint = config(
            r#"{"mgmtClientId":"c","mgmtClientSecret":"s","mgmtTsgId":"1","mgmtTokenEndpoint":"http://example.test/t"}"#,
        );
        let error = ManagementClients::build(&bad_endpoint, &session, &secrets, None)
            .err()
            .unwrap();
        assert_eq!(error.key, Some("mgmtTokenEndpoint"));
        let control = config(r#"{"mgmtClientId":"c\n","mgmtClientSecret":"s","mgmtTsgId":"1"}"#);
        assert_eq!(
            ManagementClients::build(&control, &session, &secrets, None)
                .err()
                .unwrap()
                .key,
            Some("mgmtClientId")
        );
        let good = config(
            r#"{"mgmtClientId":"c","mgmtClientSecret":"s","mgmtTsgId":"1","mgmtEndpoint":"http://127.0.0.1:1/aisec","mgmtTokenEndpoint":"http://127.0.0.1:1/token"}"#,
        );
        assert!(ManagementClients::build(&good, &session, &secrets, None).is_ok());
    }

    #[test]
    fn red_team_clients_admit_the_three_planes_or_their_defaults() {
        let session = Session::new();
        let secrets = SecretSet::default();
        let defaults = config(r#"{"mgmtClientId":"c","mgmtClientSecret":"s","mgmtTsgId":"1"}"#);
        assert!(RedTeamClients::build(&defaults, &session, &secrets, None).is_ok());
        let loopback = config(
            r#"{"mgmtClientId":"c","mgmtClientSecret":"s","mgmtTsgId":"1","redTeamDataEndpoint":"http://127.0.0.1:1/d","redTeamMgmtEndpoint":"http://127.0.0.1:1/m","redTeamNetworkBrokerEndpoint":"http://127.0.0.1:1/b","mgmtTokenEndpoint":"http://127.0.0.1:1/t"}"#,
        );
        assert!(RedTeamClients::build(&loopback, &session, &secrets, None).is_ok());
        for key in [
            "redTeamDataEndpoint",
            "redTeamMgmtEndpoint",
            "redTeamNetworkBrokerEndpoint",
        ] {
            let bad = config(&format!(
                r#"{{"mgmtClientId":"c","mgmtClientSecret":"s","mgmtTsgId":"1","{key}":"http://example.test/x"}}"#
            ));
            let error = RedTeamClients::build(&bad, &session, &secrets, None)
                .err()
                .unwrap();
            assert_eq!(error.key, Some(key));
        }
        let bad_tsg = config(r#"{"mgmtClientId":"c","mgmtClientSecret":"s","mgmtTsgId":"x"}"#);
        assert_eq!(
            RedTeamClients::build(&bad_tsg, &session, &secrets, None)
                .err()
                .unwrap()
                .key,
            Some("mgmtTsgId")
        );
    }

    /// DESIGN §16.3: the DLP base is only the tenant's `dlpEndpoint`, else the SDK
    /// default (TS `client-wiring.spec.ts`); a bad value names the key.
    #[test]
    fn dlp_clients_admit_the_tenant_endpoint_or_the_default() {
        let session = Session::new();
        let secrets = SecretSet::default();
        let defaults = config(r#"{"mgmtClientId":"c","mgmtClientSecret":"s","mgmtTsgId":"1"}"#);
        let clients = DlpClients::build(&defaults, &session, &secrets, None).unwrap();
        assert_eq!(
            clients
                .dlp
                .client()
                .endpoint()
                .url()
                .as_str()
                .trim_end_matches('/'),
            scm::constants::DEFAULT_DLP_ENDPOINT
        );
        let loopback = config(
            r#"{"mgmtClientId":"c","mgmtClientSecret":"s","mgmtTsgId":"1","dlpEndpoint":"http://127.0.0.1:1/dlp/","mgmtEndpoint":"http://example.test/not-used","mgmtTokenEndpoint":"http://127.0.0.1:1/t"}"#,
        );
        let clients = DlpClients::build(&loopback, &session, &secrets, None).unwrap();
        assert!(
            clients
                .dlp
                .client()
                .endpoint()
                .url()
                .as_str()
                .starts_with("http://127.0.0.1:1/dlp")
        );
        let bad = config(
            r#"{"mgmtClientId":"c","mgmtClientSecret":"s","mgmtTsgId":"1","dlpEndpoint":"http://dlp.example.test/x"}"#,
        );
        let error = DlpClients::build(&bad, &session, &secrets, None)
            .err()
            .unwrap();
        assert_eq!(error.key, Some("dlpEndpoint"));
        assert!(!error.message().contains("example.test"));
        let bad_tsg = config(r#"{"mgmtClientId":"c","mgmtClientSecret":"s","mgmtTsgId":"x"}"#);
        assert_eq!(
            DlpClients::build(&bad_tsg, &session, &secrets, None)
                .err()
                .unwrap()
                .key,
            Some("mgmtTsgId")
        );
    }

    /// DESIGN §17.3: the model-security bases are only the tenant's
    /// `modelSecDataEndpoint`/`modelSecMgmtEndpoint`, else the SDK defaults (TS
    /// `client-options.spec.ts`); a bad value names the key, never the value.
    #[test]
    fn model_security_clients_admit_the_tenant_endpoints_or_the_defaults() {
        let session = Session::new();
        let secrets = SecretSet::default();
        let base = |client: &scm::Client| {
            client
                .endpoint()
                .url()
                .as_str()
                .trim_end_matches('/')
                .to_owned()
        };
        let defaults = config(r#"{"mgmtClientId":"c","mgmtClientSecret":"s","mgmtTsgId":"1"}"#);
        let clients = ModelSecurityClients::build(&defaults, &session, &secrets, None).unwrap();
        assert_eq!(
            base(clients.model_security.data_client()),
            scm::constants::DEFAULT_MODEL_SEC_DATA_ENDPOINT
        );
        assert_eq!(
            base(clients.model_security.management_client()),
            scm::constants::DEFAULT_MODEL_SEC_MGMT_ENDPOINT
        );
        let loopback = config(
            r#"{"mgmtClientId":"c","mgmtClientSecret":"s","mgmtTsgId":"1","modelSecDataEndpoint":"http://127.0.0.1:1/aims/data/","modelSecMgmtEndpoint":"http://127.0.0.1:1/aims/mgmt","mgmtEndpoint":"http://example.test/not-used","mgmtTokenEndpoint":"http://127.0.0.1:1/t"}"#,
        );
        let clients = ModelSecurityClients::build(&loopback, &session, &secrets, None).unwrap();
        assert_eq!(
            base(clients.model_security.data_client()),
            "http://127.0.0.1:1/aims/data"
        );
        assert_eq!(
            base(clients.model_security.management_client()),
            "http://127.0.0.1:1/aims/mgmt"
        );
        for key in ["modelSecDataEndpoint", "modelSecMgmtEndpoint"] {
            let bad = config(&format!(
                r#"{{"mgmtClientId":"c","mgmtClientSecret":"s","mgmtTsgId":"1","{key}":"http://ms.example.test/x"}}"#
            ));
            let error = ModelSecurityClients::build(&bad, &session, &secrets, None)
                .err()
                .unwrap();
            assert_eq!(error.key, Some(key));
            assert!(!error.message().contains("example.test"));
        }
    }

    #[test]
    fn scanner_credentials_are_trimmed_and_bounded() {
        let session = Session::new();
        let good = config(r#"{"airsApiKey":"  key-1 \n","airsApiEndpoint":"http://127.0.0.1:1"}"#);
        assert!(build_scanner(&good, &session, None).is_ok());
        let long = format!(r#"{{"airsApiKey":"{}"}}"#, "k".repeat(2049));
        assert_eq!(
            build_scanner(&config(&long), &session, None)
                .err()
                .unwrap()
                .message(),
            "AISEC_USER_REQUEST_PAYLOAD_ERROR:apiKey exceeds max length of 2048"
        );
        let exact = format!(r#"{{"airsApiToken":"{}"}}"#, "k".repeat(2048));
        assert!(build_scanner(&config(&exact), &session, None).is_ok());
        let spaced = config(r#"{"airsApiToken":"a b"}"#);
        assert_eq!(
            build_scanner(&spaced, &session, None).err().unwrap().key,
            Some("airsApiToken")
        );
        let endpoint = config(r#"{"airsApiKey":"k","airsApiEndpoint":"http://example.test"}"#);
        assert_eq!(
            build_scanner(&endpoint, &session, None).err().unwrap().key,
            Some("airsApiEndpoint")
        );
    }
}