astrid 0.10.1

Command-line interface for Astrid secure agent runtime
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
//! `astrid caps` — capability inspection and management.
//!
//! Maps directly onto Layer 6 admin IPC topics
//! `astrid.v1.admin.caps.grant` / `astrid.v1.admin.caps.revoke` and
//! reads agent grants/revokes from `astrid.v1.admin.agent.list`.
//!
//! `astrid caps show <name>` (or no-arg, defaulting to the active
//! context) renders a table of effective capabilities by source.
//! Group inheritance is not yet exposed by Layer 6 (no group-membership
//! reverse index); the CLI surfaces direct grants and revokes only and
//! marks group caps as "(via group: <name>)" without listing the
//! capabilities the group confers. This is documented as a Phase 4
//! follow-up.

use std::process::ExitCode;

use anyhow::{Context, Result};
use astrid_core::PrincipalId;
use astrid_core::kernel_api::{AdminRequestKind, AdminResponseBody, AgentSummary};
use clap::{Args, Subcommand};
use colored::Colorize;
use serde::Serialize;

use crate::admin_client::into_result;
use crate::context;
use crate::theme::Theme;
use crate::value_formatter::{ValueFormat, emit_structured};

#[derive(Subcommand, Debug, Clone)]
pub(crate) enum CapsCommand {
    /// Show effective capabilities for an agent.
    Show(ShowArgs),
    /// Grant a capability to an agent.
    Grant(GrantArgs),
    /// Revoke a capability from an agent.
    Revoke(RevokeArgs),
    /// Test whether an agent holds a specific capability.
    Check(CheckArgs),
    /// Manage signed capability tokens (pre-grant tool access without
    /// per-use approval).
    #[command(subcommand)]
    Token(TokenCommand),
}

#[derive(Subcommand, Debug, Clone)]
pub(crate) enum TokenCommand {
    /// Mint a capability token pre-granting an agent access to a resource.
    Mint(TokenMintArgs),
    /// Revoke a capability token by its id.
    Revoke(TokenRevokeArgs),
    /// List the capability tokens minted for an agent.
    List(TokenListArgs),
}

#[derive(Args, Debug, Clone)]
pub(crate) struct TokenMintArgs {
    /// Agent (principal) the token is minted for. Only this principal can
    /// consume it.
    pub principal: String,
    /// Resource pattern to grant, e.g. `mcp://server:tool`.
    pub resource: String,
    /// Permission to grant. Defaults to `invoke` (the natural default for
    /// `mcp://` tool grants). One of: read, write, execute, delete, invoke,
    /// list, create.
    #[arg(long)]
    pub permission: Option<String>,
    /// Token lifetime (e.g. `30m`, `24h`, or bare seconds). Omit for a
    /// permanent token (valid until revoked).
    #[arg(long)]
    pub ttl: Option<String>,
}

#[derive(Args, Debug, Clone)]
pub(crate) struct TokenRevokeArgs {
    /// The token id (the `token_id` printed by `caps token mint`/`list`).
    pub token_id: String,
}

#[derive(Args, Debug, Clone)]
pub(crate) struct TokenListArgs {
    /// Agent (principal) whose tokens are listed.
    pub principal: String,
}

#[derive(Args, Debug, Clone)]
pub(crate) struct ShowArgs {
    /// Agent name (defaults to the active context).
    pub name: Option<String>,
    /// Output format.
    #[arg(long, default_value = "pretty")]
    pub format: String,
}

#[derive(Args, Debug, Clone)]
pub(crate) struct GrantArgs {
    /// Agent name.
    pub name: String,
    /// Capability pattern. Colon-delimited segments of
    /// `[a-zA-Z0-9_-]+` or bare `*` (no dots — capability identifiers
    /// are role labels, not resource URIs). Examples:
    /// `self:capsule:install`, `network:egress:openai`,
    /// `system:shutdown`, `*` (with --unsafe-admin).
    pub capability: String,
    /// Grant to a group instead of an individual (deferred — group
    /// modify IPC is followup work).
    #[arg(short, long, hide = true)]
    pub group: bool,
    /// Required when `capability` is the universal `*` pattern.
    /// Granting `*` to an individual agent confers admin-level
    /// authority; the kernel refuses without this acknowledgement.
    /// Mirrors the same flag on `group create --caps "*"`.
    #[arg(long)]
    pub unsafe_admin: bool,
}

#[derive(Args, Debug, Clone)]
pub(crate) struct RevokeArgs {
    /// Agent name.
    pub name: String,
    /// Capability pattern to revoke. Same grammar as `caps grant` —
    /// colon-delimited `[a-zA-Z0-9_-]+` segments or bare `*`.
    pub capability: String,
    /// Revoke from a group (deferred).
    #[arg(short, long, hide = true)]
    pub group: bool,
}

#[derive(Args, Debug, Clone)]
pub(crate) struct CheckArgs {
    /// Agent name.
    pub name: String,
    /// Capability pattern to check. Same grammar as `caps grant` —
    /// colon-delimited `[a-zA-Z0-9_-]+` segments or bare `*`.
    pub capability: String,
}

/// Top-level dispatcher for `astrid caps`.
pub(crate) async fn run(cmd: CapsCommand) -> Result<ExitCode> {
    match cmd {
        CapsCommand::Show(args) => run_show(args).await,
        CapsCommand::Grant(args) => run_grant(args).await,
        CapsCommand::Revoke(args) => run_revoke(args).await,
        CapsCommand::Check(args) => run_check(args).await,
        CapsCommand::Token(cmd) => match cmd {
            TokenCommand::Mint(args) => run_token_mint(args).await,
            TokenCommand::Revoke(args) => run_token_revoke(args).await,
            TokenCommand::List(args) => run_token_list(args).await,
        },
    }
}

/// Caps record emitted by `--format json|yaml|toml`.
#[derive(Debug, Clone, Serialize)]
pub(crate) struct CapsRecord {
    /// Principal identifier.
    pub principal: String,
    /// Group memberships (capabilities inherited from these are not
    /// expanded in this view — see module docs).
    pub groups: Vec<String>,
    /// Direct capability grants beyond group inheritance.
    pub grants: Vec<String>,
    /// Capabilities explicitly revoked (highest precedence).
    pub revokes: Vec<String>,
}

impl From<AgentSummary> for CapsRecord {
    fn from(s: AgentSummary) -> Self {
        Self {
            principal: s.principal.to_string(),
            groups: s.groups,
            grants: s.grants,
            revokes: s.revokes,
        }
    }
}

async fn fetch_summary(target: &PrincipalId) -> Result<AgentSummary> {
    let mut client = crate::admin_client::connect_as_active_agent().await?;
    let body = client.request(AdminRequestKind::AgentList).await?;
    let body = into_result(body)?;
    let agents = match body {
        AdminResponseBody::AgentList(list) => list,
        other => anyhow::bail!("unexpected response from kernel: {other:?}"),
    };
    agents
        .into_iter()
        .find(|a| a.principal == *target)
        .with_context(|| format!("agent '{target}' not found"))
}

async fn run_show(args: ShowArgs) -> Result<ExitCode> {
    let target = context::resolve_agent(args.name.as_deref())?;
    let format = ValueFormat::parse(&args.format);
    let summary = fetch_summary(&target).await?;

    if !format.is_pretty() {
        let record: CapsRecord = summary.into();
        emit_structured(&record, format)?;
        return Ok(ExitCode::SUCCESS);
    }

    print_caps_pretty(&summary);
    Ok(ExitCode::SUCCESS)
}

fn print_caps_pretty(agent: &AgentSummary) {
    // Pad raw strings *before* applying ANSI escape codes — the
    // `{:<N}` formatter counts every byte (including escape codes)
    // toward width, so colouring a value inside the format spec
    // visually shrinks its column by the ANSI overhead and misaligns
    // every subsequent column.
    println!(
        "  {}  {}  STATUS",
        format!("{:<60}", "CAPABILITY").bold(),
        format!("{:<24}", "SOURCE").bold()
    );
    for g in &agent.groups {
        println!(
            "  {:<60}  {}  {}",
            format!("(group: {g})"),
            format!("{:<24}", "group").dimmed(),
            "inherited".green()
        );
    }
    // Layer 5 precedence is revoke > grant. A grant `cap` is shadowed
    // if ANY revoke pattern matches it under the same segment-glob
    // rules the kernel uses for enforcement
    // (`capability_matches(revoke, cap)`). Exact string equality would
    // miss pattern revokes (e.g. `sys:*` shadowing `sys:status`),
    // misleading an operator into thinking a cap is live when it
    // isn't.
    for cap in &agent.grants {
        let status = if agent
            .revokes
            .iter()
            .any(|r| astrid_core::capability_grammar::capability_matches(r, cap))
        {
            "shadowed by revoke".dimmed().to_string()
        } else {
            "active".green().to_string()
        };
        println!(
            "  {:<60}  {}  {status}",
            cap,
            format!("{:<24}", "individual grant").dimmed(),
        );
    }
    for cap in &agent.revokes {
        println!(
            "  {:<60}  {}  {}",
            cap,
            format!("{:<24}", "individual revoke").dimmed(),
            "revoked".yellow()
        );
    }
    if agent.groups.is_empty() && agent.grants.is_empty() && agent.revokes.is_empty() {
        println!("  {}", Theme::info("(no direct grants or revokes)"));
    }
}

/// Client-side mirror of the kernel's universal-grant rail.
///
/// The bare `"*"` pattern grants admin-equivalent reach to a single
/// agent — a one-step bypass of the group-creation safety rail
/// (`group create --caps "*"` already requires `--unsafe-admin`).
/// Mirroring the check at the CLI saves a round-trip and surfaces the
/// reason inline. Multi-segment wildcards (`network:egress:*`,
/// `self:capsule:*`) are scoped and unaffected.
fn validate_grant_pattern(pattern: &str, unsafe_admin: bool) -> Result<(), &'static str> {
    if pattern == "*" && !unsafe_admin {
        return Err(
            "refusing to grant universal `*` without --unsafe-admin: this confers admin-equivalent reach on a single agent. Re-run with --unsafe-admin if intentional.",
        );
    }
    Ok(())
}

async fn run_grant(args: GrantArgs) -> Result<ExitCode> {
    if args.group {
        eprintln!(
            "astrid: --group on `caps grant` requires an `admin.group.modify --add-caps` IPC topic that has not shipped yet."
        );
        eprintln!(
            "  Use `astrid group modify --add-caps` once available, or grant per-agent for now."
        );
        return Ok(ExitCode::from(2));
    }
    // Client-side mirror of the kernel's universal-grant rail. The
    // kernel is authoritative — the same check fires there even if a
    // client speaks the wire format directly — but rejecting the
    // request locally saves an IPC round-trip and lets the operator
    // see the explanatory error without scrolling daemon logs.
    if let Err(msg) = validate_grant_pattern(&args.capability, args.unsafe_admin) {
        eprintln!("{}", Theme::error(msg));
        return Ok(ExitCode::from(2));
    }
    let principal = PrincipalId::new(&args.name).context("invalid agent name")?;
    let mut client = crate::admin_client::connect_as_active_agent().await?;
    let body = client
        .request(AdminRequestKind::CapsGrant {
            principal,
            capabilities: vec![args.capability.clone()],
            unsafe_admin: args.unsafe_admin,
        })
        .await?;
    let _ = into_result(body)?;
    println!(
        "{}",
        Theme::success(&format!(
            "Granted '{}' to agent '{}'",
            args.capability, args.name
        ))
    );
    Ok(ExitCode::SUCCESS)
}

async fn run_revoke(args: RevokeArgs) -> Result<ExitCode> {
    if args.group {
        eprintln!(
            "astrid: --group on `caps revoke` requires an `admin.group.modify --remove-caps` IPC topic that has not shipped yet."
        );
        return Ok(ExitCode::from(2));
    }
    let principal = PrincipalId::new(&args.name).context("invalid agent name")?;
    let mut client = crate::admin_client::connect_as_active_agent().await?;
    let body = client
        .request(AdminRequestKind::CapsRevoke {
            principal,
            capabilities: vec![args.capability.clone()],
        })
        .await?;
    let _ = into_result(body)?;
    println!(
        "{}",
        Theme::success(&format!(
            "Revoked '{}' from agent '{}'",
            args.capability, args.name
        ))
    );
    Ok(ExitCode::SUCCESS)
}

async fn run_check(args: CheckArgs) -> Result<ExitCode> {
    // Mirrors the Layer 5 enforcement preamble's resolution order:
    // explicit revokes (highest precedence) → direct grants → group-
    // inherited patterns. Pattern matching uses
    // `astrid_core::capability_grammar::capability_matches` — the
    // same function the kernel runs — so the CLI answer matches what
    // the kernel would decide at request time (modulo races against
    // an admin write between the two admin RPCs we issue below).
    use astrid_core::capability_grammar::capability_matches;

    let principal = PrincipalId::new(&args.name).context("invalid agent name")?;
    let mut client = crate::admin_client::connect_as_active_agent().await?;

    let summary_body = client.request(AdminRequestKind::AgentList).await?;
    let summary_body = into_result(summary_body)?;
    let agents = match summary_body {
        AdminResponseBody::AgentList(list) => list,
        other => anyhow::bail!("unexpected response from kernel: {other:?}"),
    };
    let Some(agent) = agents.iter().find(|a| a.principal == principal) else {
        eprintln!(
            "{}",
            Theme::error(&format!("agent '{principal}' not found"))
        );
        return Ok(ExitCode::from(1));
    };

    // Revoke wins over everything.
    if let Some(pattern) = agent
        .revokes
        .iter()
        .find(|p| capability_matches(p, &args.capability))
    {
        println!(
            "{}: {} {} '{}' (revoke pattern: {pattern})",
            "denied".red().bold(),
            args.capability,
            "is revoked from".dimmed(),
            args.name
        );
        return Ok(ExitCode::from(1));
    }

    // Direct grant beats group inheritance — easier diagnostic.
    if let Some(pattern) = agent
        .grants
        .iter()
        .find(|p| capability_matches(p, &args.capability))
    {
        println!(
            "{}: '{}' {} (grant pattern: {pattern})",
            "allowed".green().bold(),
            args.name,
            "holds a direct grant".dimmed()
        );
        return Ok(ExitCode::SUCCESS);
    }

    // Group inheritance: fetch the full group catalogue and resolve.
    if !agent.groups.is_empty() {
        let groups_body = client.request(AdminRequestKind::GroupList).await?;
        let groups_body = into_result(groups_body)?;
        let groups = match groups_body {
            AdminResponseBody::GroupList(list) => list,
            other => anyhow::bail!("unexpected response from kernel: {other:?}"),
        };

        for group_name in &agent.groups {
            let Some(group) = groups.iter().find(|g| &g.name == group_name) else {
                continue;
            };
            if let Some(pattern) = group
                .capabilities
                .iter()
                .find(|p| capability_matches(p, &args.capability))
            {
                println!(
                    "{}: '{}' {} '{}' (pattern: {pattern})",
                    "allowed".green().bold(),
                    args.name,
                    "inherits from group".dimmed(),
                    group_name
                );
                return Ok(ExitCode::SUCCESS);
            }
        }
    }

    println!(
        "{}: '{}' {} {}",
        "denied".red().bold(),
        args.name,
        "has no grant matching".dimmed(),
        args.capability
    );
    Ok(ExitCode::from(1))
}

/// Extract the JSON body from a `Success` admin response, erroring on any
/// other variant (errors are already lifted by [`into_result`]).
fn success_value(body: AdminResponseBody) -> Result<serde_json::Value> {
    match body {
        AdminResponseBody::Success(v) => Ok(v),
        other => anyhow::bail!("unexpected response from kernel: {other:?}"),
    }
}

async fn run_token_mint(args: TokenMintArgs) -> Result<ExitCode> {
    let principal = PrincipalId::new(&args.principal).context("invalid agent name")?;
    // Reuse the shared duration parser (same one `agent create --timeout`
    // uses) so `--ttl 30m` / `24h` / bare seconds all work; the kernel takes
    // whole seconds.
    let ttl_secs = match args.ttl.as_deref() {
        Some(s) => Some(
            crate::commands::quota::parse_duration(s)
                .context("invalid --ttl")?
                .as_secs(),
        ),
        None => None,
    };

    let mut client = crate::admin_client::connect_as_active_agent().await?;
    let body = client
        .request(AdminRequestKind::CapsTokenMint {
            principal,
            resource: args.resource.clone(),
            permission: args.permission.clone(),
            ttl_secs,
        })
        .await?;
    let value = success_value(into_result(body)?)?;

    let token_id = value
        .get("token_id")
        .and_then(|v| v.as_str())
        .unwrap_or("?");
    let resource = value
        .get("resource")
        .and_then(|v| v.as_str())
        .unwrap_or(&args.resource);
    let permission = value
        .get("permission")
        .and_then(|v| v.as_str())
        .unwrap_or("invoke");
    let expiry = value
        .get("expires_at")
        .and_then(|v| v.as_str())
        .map_or_else(|| "never".to_string(), ToString::to_string);

    println!(
        "{}",
        Theme::success(&format!(
            "Minted token {token_id} for agent '{}'",
            args.principal
        ))
    );
    println!("  resource:   {resource}");
    println!("  permission: {permission}");
    println!("  expires:    {expiry}");
    Ok(ExitCode::SUCCESS)
}

async fn run_token_revoke(args: TokenRevokeArgs) -> Result<ExitCode> {
    let mut client = crate::admin_client::connect_as_active_agent().await?;
    let body = client
        .request(AdminRequestKind::CapsTokenRevoke {
            token_id: args.token_id.clone(),
        })
        .await?;
    let _ = success_value(into_result(body)?)?;
    println!(
        "{}",
        Theme::success(&format!("Revoked token {}", args.token_id))
    );
    Ok(ExitCode::SUCCESS)
}

async fn run_token_list(args: TokenListArgs) -> Result<ExitCode> {
    let principal = PrincipalId::new(&args.principal).context("invalid agent name")?;
    let mut client = crate::admin_client::connect_as_active_agent().await?;
    let body = client
        .request(AdminRequestKind::CapsTokenList { principal })
        .await?;
    let value = success_value(into_result(body)?)?;

    let tokens = value
        .get("tokens")
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();
    if tokens.is_empty() {
        let principal = &args.principal;
        println!("{}", Theme::info(&format!("(no tokens for '{principal}')")));
        return Ok(ExitCode::SUCCESS);
    }

    println!(
        "  {}  {}  {}  {}",
        format!("{:<38}", "TOKEN ID").bold(),
        format!("{:<32}", "RESOURCE").bold(),
        format!("{:<10}", "SCOPE").bold(),
        "EXPIRES".bold()
    );
    for t in &tokens {
        let id = t.get("token_id").and_then(|v| v.as_str()).unwrap_or("?");
        let resource = t.get("resource").and_then(|v| v.as_str()).unwrap_or("?");
        let scope = t.get("scope").and_then(|v| v.as_str()).unwrap_or("?");
        let perms = t
            .get("permissions")
            .and_then(|v| v.as_array())
            .map(|a| {
                a.iter()
                    .filter_map(|p| p.as_str())
                    .collect::<Vec<_>>()
                    .join(",")
            })
            .unwrap_or_default();
        let expires = t
            .get("expires_at")
            .and_then(|v| v.as_str())
            .unwrap_or("never");
        // Pad raw strings before printing (consistent with `print_caps_pretty`).
        let id = format!("{id:<38}");
        let resource = format!("{resource:<32}");
        let scope = format!("{scope:<10}");
        println!("  {id}  {resource}  {scope}  {expires}  [{perms}]");
    }
    Ok(ExitCode::SUCCESS)
}

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

    #[test]
    fn validate_grant_pattern_rejects_bare_star_without_unsafe_admin() {
        let err = validate_grant_pattern("*", false).expect_err("bare `*` must be rejected");
        assert!(err.contains("--unsafe-admin"), "msg={err}");
    }

    #[test]
    fn validate_grant_pattern_accepts_bare_star_with_unsafe_admin() {
        validate_grant_pattern("*", true).expect("bare `*` with --unsafe-admin must pass");
    }

    #[test]
    fn validate_grant_pattern_accepts_scoped_wildcards() {
        // Multi-segment wildcards are inherently scoped — the rail only
        // triggers on the universal pattern.
        validate_grant_pattern("network:egress:*", false).expect("scoped wildcard");
        validate_grant_pattern("self:capsule:*", false).expect("scoped wildcard");
        validate_grant_pattern("agent:disable", false).expect("concrete cap");
    }

    #[test]
    fn record_round_trips_to_json() {
        let summary = AgentSummary {
            principal: PrincipalId::new("alice").unwrap(),
            enabled: true,
            groups: vec!["agent".into()],
            grants: vec!["self:capsule:install".into()],
            revokes: vec!["network:egress:evil.com".into()],
        };
        let rec: CapsRecord = summary.into();
        let json = serde_json::to_string(&rec).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed["principal"], "alice");
        assert_eq!(parsed["grants"][0], "self:capsule:install");
        assert_eq!(parsed["revokes"][0], "network:egress:evil.com");
    }
}