airs-cli 0.3.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
//! Command planning (all usage validation, before any tenant read) and dispatch.

pub mod doctor;
pub mod profiles;
pub mod scan;
pub mod tenant;
pub mod tenant_import;
pub mod tenant_write;
pub mod topics;

use crate::cli::{Cli, ProfilesCommand, RuntimeCommand, TenantCommand, TopCommand, TopicsCommand};
use crate::debug::{DebugLog, DebugPolicy};
use crate::error::{
    self, CliError, InterruptContext, Operation, Phase, Plane, SdkContext, SecretSet,
};
use crate::output::{self, Format, Output};
use crate::pagination::{self, GetParams, ListParams};
use crate::tenant::{self as registry, Environment, TenantContext};
use std::time::Duration;

/// Per-invocation state shared by every command.
pub struct Invocation {
    pub output: Output,
    /// Shared by every SDK client; cancelled by SIGINT/SIGTERM.
    pub session: scm::Session,
    pub env: Environment,
    /// The validated `--tenant` value.
    pub tenant_flag: Option<String>,
    /// Secrets seen this invocation (shared with the OAuth provider, which adds every
    /// lease); server text carrying one is never printed.
    pub secrets: SecretSet,
    /// The `--debug` API log, when this run writes one (DESIGN §2.9); every client's
    /// transport records into it.
    pub debug: Option<DebugLog>,
    /// Which streams are terminals (the prompt and confirmation gates, §3.10).
    pub terminals: crate::input::Terminals,
    /// Whether a tenant write passed its commit point (an interruption then reports
    /// `the change was saved`, §3.9).
    pub committed: bool,
}

impl Invocation {
    pub fn new(output: Output, tenant_flag: Option<String>) -> Self {
        Self {
            output,
            session: scm::Session::new(),
            env: Environment::capture(),
            tenant_flag,
            secrets: SecretSet::default(),
            debug: None,
            terminals: crate::input::Terminals::detect(),
            committed: false,
        }
    }

    /// Open the debug log (after planning, before the tenant is read) and print its
    /// notice. A failure is an operational error and no request is sent.
    pub fn open_debug_log(&mut self) -> Result<(), CliError> {
        let dir =
            crate::debug::directory(self.env.xdg_state_home.as_deref(), self.env.home.as_deref())?;
        let log = DebugLog::open(
            &dir,
            self.secrets.clone(),
            crate::render::style::stderr_color(),
        )?;
        self.output.status(&format!(
            "Debug: API log → {}",
            output::terminal_safe(&log.path().display().to_string())
        ));
        self.debug = Some(log);
        Ok(())
    }

    /// Load the selected tenant (store, selection, tenant file, TSG pin) and register
    /// its secrets for output scrubbing.
    pub fn load_tenant(&mut self) -> Result<TenantContext, CliError> {
        let context = registry::load_selected(&self.env, self.tenant_flag.as_deref())?;
        self.secrets.register_config(&context.config);
        Ok(context)
    }

    /// Prepare a management read (milestone 2): load the tenant, settle the output
    /// format (`format` is the explicit `--output`; otherwise the tenant's
    /// `defaultOutput`, else `pretty`), check the management credentials, build the
    /// clients and fetch the OAuth token under `options` (from [`walk_options`];
    /// `None`: the SDK's own token budget).
    pub async fn connect_management(
        &mut self,
        format: Option<Format>,
        options: Option<&scm::RequestOptions>,
    ) -> Result<(scm::airs::management::ManagementClient, Format), CliError> {
        let context = self.load_tenant()?;
        let format = output::resolve_tenant_default(format, context.config.default_output());
        crate::tenant::config::require_management(&context.config, Some(context.name()))?;
        let clients = crate::clients::ManagementClients::build(
            &context.config,
            &self.session,
            &self.secrets,
            self.debug.as_ref(),
        )?;
        let budget = if options.is_some() {
            crate::clients::WALK_BUDGET
        } else {
            crate::clients::TOKEN_BUDGET
        };
        clients.authenticate(options, budget).await?;
        Ok((clients.management, format))
    }

    /// Map an SDK error from a management API call made under `budget`.
    pub fn management_error(&self, error: &scm::Error, budget: Duration) -> CliError {
        error::from_sdk(
            error,
            &SdkContext {
                plane: Plane::Management,
                phase: Phase::Api,
                operation: Operation::Read,
                timeout: budget,
                secrets: &self.secrets,
            },
        )
    }
}

/// One shared deadline for a whole walk, including its token request (DESIGN §5).
pub fn walk_options() -> Result<scm::RequestOptions, CliError> {
    scm::RequestOptions::with_timeout(crate::clients::WALK_BUDGET).map_err(|_| {
        CliError::operational("AISEC_SDK_ERROR:The request options could not be configured")
    })
}

/// A fully validated invocation.
pub enum Plan {
    /// A command group without a subcommand: its help on stderr, exit 2.
    GroupHelp(&'static [&'static str]),
    TenantList(Format),
    TenantPath(Option<String>),
    TenantRead(Option<String>, Format),
    TenantGet {
        name: String,
        key: &'static str,
        format: Format,
    },
    Doctor(Format),
    Scan(scan::ScanInput, Format),
    ProfilesList(ListParams, Option<Format>),
    ProfilesGet(GetParams, Option<Format>),
    TopicsList(ListParams, Option<Format>),
    TopicsGet(GetParams, Option<Format>),
    /// `tenant create|set|unset|switch|delete` (§3.11).
    TenantWrite(tenant_write::WritePlan),
    /// `tenant import` (§3.12).
    TenantImport(tenant_import::ImportPlan),
}

impl Plan {
    /// What an interrupted run reports when no SDK call said otherwise. Exhaustive on
    /// purpose: a new command (a write, M4) must decide what an interruption means.
    pub fn interrupt_context(&self) -> InterruptContext {
        match self {
            Self::Scan(..) => InterruptContext::ScanOutcomeUnknown,
            // `the change was saved` once the commit point passed (lib::execute).
            Self::TenantWrite(_) | Self::TenantImport(_) => {
                InterruptContext::NoConfigurationChanged
            }
            Self::GroupHelp(_)
            | Self::TenantList(_)
            | Self::TenantPath(_)
            | Self::TenantRead(..)
            | Self::TenantGet { .. }
            | Self::Doctor(_)
            | Self::ProfilesList(..)
            | Self::ProfilesGet(..)
            | Self::TopicsList(..)
            | Self::TopicsGet(..) => InterruptContext::NoDataWritten,
        }
    }

    /// Whether `--debug` opens a log for this command (DESIGN §2.9, D63): only the
    /// commands that can send requests. Exhaustive on purpose: a new command decides.
    pub fn debug_policy(&self) -> DebugPolicy {
        match self {
            Self::Doctor(_)
            | Self::Scan(..)
            | Self::ProfilesList(..)
            | Self::ProfilesGet(..)
            | Self::TopicsList(..)
            | Self::TopicsGet(..) => DebugPolicy::Log,
            Self::GroupHelp(_)
            | Self::TenantList(_)
            | Self::TenantPath(_)
            | Self::TenantRead(..)
            | Self::TenantGet { .. }
            | Self::TenantWrite(_)
            | Self::TenantImport(_) => DebugPolicy::None,
        }
    }
}

/// Validate every flag and value. Never reads the registry or the network. Every
/// command validates `--output` (DESIGN §2.4); management reads settle a missing one
/// from the tenant later.
pub fn plan(cli: &Cli) -> Result<Plan, CliError> {
    let explicit = cli.global.output.as_deref();
    // `tenant import` renders its report: `--output` is resolved first, then any
    // `--tenant` is refused, then its own checks run (§3.11, §3.12).
    if let Some(TopCommand::Tenant(crate::cli::TenantGroup {
        command: Some(TenantCommand::Import(args)),
    })) = &cli.command
    {
        let format = output::resolve(explicit)?;
        if cli.global.tenant.is_some() {
            return Err(CliError::usage(
                "--tenant cannot be used with 'tenant import'; name the tenant as an argument",
            ));
        }
        return Ok(Plan::TenantImport(tenant_import::plan(args, format)?));
    }
    // The write commands name their tenant positionally: `--output` is validated first,
    // then any `--tenant` is refused, then the command's own checks run (§3.11).
    if let Some(TopCommand::Tenant(crate::cli::TenantGroup {
        command: Some(command),
    })) = &cli.command
        && let Some(subcommand) = tenant_write::write_command_name(command)
    {
        output::validate_explicit(explicit)?;
        if cli.global.tenant.is_some() {
            return Err(CliError::usage(format!(
                "--tenant cannot be used with 'tenant {subcommand}'; name the tenant as an argument"
            )));
        }
        return Ok(Plan::TenantWrite(tenant_write::plan(command)?));
    }
    registry::validate_tenant_flag(cli.global.tenant.as_deref())?;
    let Some(command) = &cli.command else {
        return Ok(Plan::GroupHelp(&[]));
    };
    Ok(match command {
        TopCommand::Tenant(group) => match &group.command {
            None => Plan::GroupHelp(&["tenant"]),
            Some(
                TenantCommand::Create(_)
                | TenantCommand::Set(_)
                | TenantCommand::Unset { .. }
                | TenantCommand::Switch { .. }
                | TenantCommand::Delete { .. }
                | TenantCommand::Import(_),
            ) => unreachable!("write commands are planned above"),
            Some(TenantCommand::List) => Plan::TenantList(output::resolve(explicit)?),
            // The path is printed in every format; an invalid name is still rejected.
            Some(TenantCommand::Path { name }) => {
                output::validate_explicit(explicit)?;
                Plan::TenantPath(name.clone())
            }
            Some(TenantCommand::Read { name }) => {
                Plan::TenantRead(name.clone(), output::resolve(explicit)?)
            }
            Some(TenantCommand::Get { name, key }) => {
                // The key is validated before the format (D34 order).
                let key = crate::tenant::config::schema_key(key).ok_or_else(|| {
                    CliError::usage(format!(
                        "Unknown configuration key. Supported keys: {}",
                        crate::tenant::config::KEYS.join(", ")
                    ))
                })?;
                Plan::TenantGet {
                    name: name.clone(),
                    key,
                    format: output::resolve(explicit)?,
                }
            }
        },
        TopCommand::Doctor => Plan::Doctor(output::resolve(explicit)?),
        TopCommand::Runtime(group) => match &group.command {
            None => Plan::GroupHelp(&["runtime"]),
            Some(RuntimeCommand::Scan(args)) => {
                let format = output::resolve(explicit)?;
                Plan::Scan(scan::validate_input(args)?, format)
            }
            Some(RuntimeCommand::Profiles(profiles)) => match &profiles.command {
                None => Plan::GroupHelp(&["runtime", "profiles"]),
                Some(ProfilesCommand::List(args)) => {
                    let format = output::validate_explicit(explicit)?;
                    Plan::ProfilesList(
                        pagination::parse_list(&args.paging, args.all_versions)?,
                        format,
                    )
                }
                Some(ProfilesCommand::Get(args)) => {
                    let format = output::validate_explicit(explicit)?;
                    Plan::ProfilesGet(pagination::parse_get(&args.lookup)?, format)
                }
            },
            Some(RuntimeCommand::Topics(topics)) => match &topics.command {
                None => Plan::GroupHelp(&["runtime", "topics"]),
                Some(TopicsCommand::List(args)) => {
                    let format = output::validate_explicit(explicit)?;
                    Plan::TopicsList(
                        pagination::parse_list(&args.paging, args.all_versions)?,
                        format,
                    )
                }
                Some(TopicsCommand::Get(args)) => {
                    let format = output::validate_explicit(explicit)?;
                    Plan::TopicsGet(pagination::parse_get(&args.lookup)?, format)
                }
            },
        },
    })
}

/// Run a validated plan (everything except `GroupHelp`, which `lib` renders).
pub async fn dispatch(invocation: &mut Invocation, plan: Plan) -> Result<(), CliError> {
    match plan {
        Plan::GroupHelp(_) => Ok(()),
        Plan::TenantList(format) => tenant::list(invocation, format),
        Plan::TenantPath(name) => tenant::path(invocation, name.as_deref()),
        Plan::TenantRead(name, format) => tenant::read(invocation, name.as_deref(), format),
        Plan::TenantGet { name, key, format } => tenant::get(invocation, &name, key, format),
        Plan::Doctor(format) => doctor::run(invocation, format).await,
        Plan::Scan(input, format) => scan::run(invocation, &input, format).await,
        Plan::ProfilesList(params, format) => profiles::list(invocation, &params, format).await,
        Plan::ProfilesGet(params, format) => profiles::get(invocation, &params, format).await,
        Plan::TopicsList(params, format) => topics::list(invocation, &params, format).await,
        Plan::TopicsGet(params, format) => topics::get(invocation, &params, format).await,
        Plan::TenantWrite(write) => tenant_write::run(invocation, write),
        Plan::TenantImport(import) => tenant_import::run(invocation, import),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::FromArgMatches;

    fn plan_of(args: &[&str]) -> Result<Plan, CliError> {
        let matches = crate::cli::command().try_get_matches_from(args).unwrap();
        plan(&Cli::from_arg_matches(&matches).unwrap())
    }

    fn usage(args: &[&str]) -> String {
        match plan_of(args) {
            Err(CliError::Usage(message)) => message,
            Err(other) => panic!("expected usage error, got {other:?}"),
            Ok(_) => panic!("expected usage error"),
        }
    }

    #[test]
    fn usage_errors_need_no_tenant() {
        assert_eq!(
            usage(&[
                "airs-cli-rs",
                "runtime",
                "profiles",
                "list",
                "--output",
                "xml"
            ]),
            "Invalid output format 'xml'. Expected: pretty, table, json"
        );
        assert_eq!(
            usage(&["airs-cli-rs", "doctor", "--output", "yaml"]),
            "Invalid output format 'yaml'. Expected: pretty, table, json"
        );
        assert_eq!(
            usage(&["airs-cli-rs", "tenant", "path", "--output", "csv"]),
            "Invalid output format 'csv'. Expected: pretty, table, json"
        );
        assert_eq!(
            usage(&["airs-cli-rs", "runtime", "topics", "list", "--limit", "0"]),
            "--limit must be a positive integer"
        );
        assert_eq!(
            usage(&[
                "airs-cli-rs",
                "runtime",
                "profiles",
                "get",
                "x",
                "--revision",
                "abc"
            ]),
            "--revision must be a non-negative integer"
        );
        assert!(
            usage(&["airs-cli-rs", "tenant", "get", "dev", "nope"]).starts_with(
                "Unknown configuration key. Supported keys: airsApiKey, airsApiToken,"
            )
        );
        assert!(
            usage(&["airs-cli-rs", "--tenant", "-x", "doctor"]).starts_with("Tenant name must be")
        );
        assert_eq!(
            usage(&["airs-cli-rs", "runtime", "scan", "--profile", "p", ""]),
            "AISEC_USER_REQUEST_PAYLOAD_ERROR:At least one of prompt, response, codePrompt, codeResponse, or toolEvent must be provided"
        );
    }

    #[test]
    fn unknown_key_wins_over_output_and_path_ignores_a_valid_output() {
        assert!(
            usage(&[
                "airs-cli-rs",
                "tenant",
                "get",
                "dev",
                "nope",
                "--output",
                "xml"
            ])
            .starts_with("Unknown configuration key")
        );
        assert!(matches!(
            plan_of(&["airs-cli-rs", "tenant", "path", "--output", "table"]),
            Ok(Plan::TenantPath(None))
        ));
    }

    #[test]
    fn write_commands_validate_output_then_refuse_tenant() {
        assert_eq!(
            usage(&[
                "airs-cli-rs",
                "--tenant",
                "-x",
                "tenant",
                "switch",
                "dev",
                "--output",
                "xml"
            ]),
            "Invalid output format 'xml'. Expected: pretty, table, json"
        );
        for (sub, args) in [
            ("create", &["create", "dev"][..]),
            ("set", &["set", "dev", "defaultOutput", "json"]),
            ("unset", &["unset", "dev", "defaultOutput"]),
            ("switch", &["switch", "dev"]),
            ("delete", &["rm", "dev"]),
        ] {
            let mut full = vec!["airs-cli-rs", "--tenant", "-x", "tenant"];
            full.extend_from_slice(args);
            assert_eq!(
                usage(&full),
                format!(
                    "--tenant cannot be used with 'tenant {sub}'; name the tenant as an argument"
                )
            );
        }
        assert_eq!(
            usage(&["airs-cli-rs", "--tenant", "dev", "tenant", "create", "_bad"]),
            "--tenant cannot be used with 'tenant create'; name the tenant as an argument",
            "before the name check"
        );
        assert_eq!(
            usage(&[
                "airs-cli-rs",
                "tenant",
                "create",
                "_bad",
                "--output",
                "table"
            ]),
            "Tenant name must be 1–64 letters, digits, hyphens or underscores and start with a letter/digit"
        );
        assert!(matches!(
            plan_of(&["airs-cli-rs", "tenant", "switch", "dev", "--output", "json"]),
            Ok(Plan::TenantWrite(tenant_write::WritePlan::Switch { .. }))
        ));
        assert_eq!(
            plan_of(&["airs-cli-rs", "tenant", "switch", "dev"])
                .ok()
                .unwrap()
                .interrupt_context(),
            InterruptContext::NoConfigurationChanged
        );
    }

    #[test]
    fn groups_without_subcommands_render_help() {
        for (args, path) in [
            (&["airs-cli-rs"][..], &[][..]),
            (&["airs-cli-rs", "--quiet"], &[]),
            (&["airs-cli-rs", "runtime"], &["runtime"]),
            (
                &["airs-cli-rs", "runtime", "topics"],
                &["runtime", "topics"],
            ),
            (&["airs-cli-rs", "tenant"], &["tenant"]),
        ] {
            match plan_of(args) {
                Ok(Plan::GroupHelp(found)) => assert_eq!(found, path),
                _ => panic!("expected group help for {args:?}"),
            }
        }
    }

    #[test]
    fn debug_policy_logs_only_commands_that_send_requests() {
        let policy = |args: &[&str]| plan_of(args).ok().unwrap().debug_policy();
        for args in [
            &["airs-cli-rs", "doctor"][..],
            &["airs-cli-rs", "runtime", "scan", "--profile", "p", "hi"],
            &["airs-cli-rs", "runtime", "profiles", "list"],
            &["airs-cli-rs", "runtime", "profiles", "get", "x"],
            &["airs-cli-rs", "runtime", "topics", "ls"],
            &["airs-cli-rs", "runtime", "topics", "get", "x"],
        ] {
            assert_eq!(policy(args), DebugPolicy::Log, "{args:?}");
        }
        for args in [
            &["airs-cli-rs", "tenant", "list"][..],
            &["airs-cli-rs", "tenant", "switch", "dev"],
            &["airs-cli-rs", "tenant", "delete", "dev"],
            &["airs-cli-rs", "tenant", "create", "dev"],
            &["airs-cli-rs", "tenant", "path"],
            &["airs-cli-rs", "tenant", "read"],
            &["airs-cli-rs", "tenant", "get", "dev", "mgmtTsgId"],
            &["airs-cli-rs", "runtime"],
        ] {
            assert_eq!(policy(args), DebugPolicy::None, "{args:?}");
        }
    }

    #[test]
    fn valid_plans() {
        assert!(matches!(
            plan_of(&[
                "airs-cli-rs",
                "runtime",
                "profiles",
                "ls",
                "--output",
                "json",
                "--all"
            ]),
            Ok(Plan::ProfilesList(
                ListParams { all: true, .. },
                Some(Format::Json)
            ))
        ));
        assert!(matches!(
            plan_of(&["airs-cli-rs", "tenant", "get", "dev", "mgmtTsgId"]),
            Ok(Plan::TenantGet {
                key: "mgmtTsgId",
                format: Format::Pretty,
                ..
            })
        ));
        assert!(matches!(
            plan_of(&["airs-cli-rs", "--output", "json", "doctor"]),
            Ok(Plan::Doctor(Format::Json))
        ));
        assert!(matches!(
            plan_of(&["airs-cli-rs", "tenant", "list"]),
            Ok(Plan::TenantList(Format::Pretty))
        ));
        assert!(matches!(
            plan_of(&["airs-cli-rs", "runtime", "topics", "get", "x"]),
            Ok(Plan::TopicsGet(_, None))
        ));
        assert!(matches!(
            plan_of(&[
                "airs-cli-rs",
                "runtime",
                "scan",
                "--profile",
                "p",
                "hi",
                "--output",
                "table"
            ]),
            Ok(Plan::Scan(_, Format::Table))
        ));
    }
}