3.7 KiB · text History bbb2a48
//! DSN keys, and the `dsn` shortcut.

use anyhow::{Result, anyhow};
use serde_json::json;

use crate::api::models::Key;
use crate::cli::KeysCommand;
use crate::commands::Ctx;
use crate::output::{Table, Tone, ago, field, paint};

pub fn run(ctx: &Ctx, command: Option<&KeysCommand>) -> Result<()> {
    let org = ctx.org()?;
    let project = ctx.project(None)?;

    match command {
        None | Some(KeysCommand::List) => {
            let keys = ctx.api.keys(&org, &project)?;
            if ctx.emitted(&keys.raw)? {
                return Ok(());
            }
            let mut table = Table::new(["ID", "NAME", "STATE", "RATE LIMIT", "CREATED", "DSN"]);
            for k in keys.iter() {
                table.row([
                    k.id.clone(),
                    k.name.clone().unwrap_or_default(),
                    state(k),
                    k.rate_limit
                        .as_ref()
                        .map_or_else(|| "-".to_string(), |r| format!("{}/{}s", r.count, r.window)),
                    ago(k.date_created.as_deref()),
                    k.dsn.public.clone(),
                ]);
            }
            table.print_or("No keys.");
            Ok(())
        }
        Some(KeysCommand::Create { name }) => {
            let key = ctx.api.create_key(&org, &project, name.as_deref())?;
            if ctx.emitted(&key.raw)? {
                return Ok(());
            }
            println!("{} key {}", paint("Created", Tone::Good), key.id);
            field("dsn", &key.dsn.public);
            Ok(())
        }
        Some(KeysCommand::Revoke { id, disable }) => {
            if *disable {
                let key = ctx
                    .api
                    .update_key(&org, &project, id, json!({ "isActive": false }))?;
                if ctx.emitted(&key.raw)? {
                    return Ok(());
                }
                println!("{} key {}", paint("Disabled", Tone::Good), key.id);
            } else {
                ctx.api.delete_key(&org, &project, id)?;
                if ctx.json {
                    return crate::output::print_json(&json!({ "deleted": id }));
                }
                println!("{} key {id}", paint("Revoked", Tone::Good));
            }
            Ok(())
        }
    }
}

/// The project's first active key's DSN, alone on a line, for
/// `SENTRY_DSN=$(vgl dsn)`.
pub fn dsn(ctx: &Ctx) -> Result<()> {
    let org = ctx.org()?;
    let project = ctx.project(None)?;
    let keys = ctx.api.keys(&org, &project)?;
    let index = first_active(&keys.data).ok_or_else(|| {
        anyhow!("{org}/{project} has no active DSN key; make one with `vgl keys create`")
    })?;

    if ctx.json {
        let raw = keys.raw.get(index).cloned().unwrap_or_default();
        return crate::output::print_json(&raw);
    }
    println!("{}", keys.data[index].dsn.public);
    Ok(())
}

fn first_active(keys: &[Key]) -> Option<usize> {
    keys.iter().position(|k| k.is_active)
}

fn state(k: &Key) -> String {
    if k.is_active {
        paint("active", Tone::Good)
    } else {
        paint("disabled", Tone::Muted)
    }
}

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

    fn key(id: &str, active: bool) -> Key {
        serde_json::from_value(json!({
            "id": id,
            "name": "Default",
            "isActive": active,
            "rateLimit": null,
            "dsn": {"public": format!("https://{id}@vigil.example.com/1")},
            "dateCreated": "2026-12-01T00:00:00Z"
        }))
        .unwrap()
    }

    #[test]
    fn the_dsn_is_the_first_active_keys() {
        let keys = vec![key("aaa", false), key("bbb", true), key("ccc", true)];
        assert_eq!(first_active(&keys), Some(1));
        assert_eq!(first_active(&[key("aaa", false)]), None);
    }
}