offline-cli 0.4.0

The Offline Protocol developer CLI
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
//! `offline keys`: list, create, revoke and rotate application API keys.

use anyhow::{anyhow, bail, Context, Result};
use clap::{Args, Subcommand};
use serde_json::json;

use crate::api::types::ApiKeyRecord;
use crate::commands::provision::{client_from_config, developer_session, resolve_app_id};
use crate::config::CliConfig;
use crate::output;

#[derive(Subcommand)]
pub enum KeysCommand {
    /// List API keys for an application
    List(ListArgs),
    /// Create a new application API key
    Create(CreateArgs),
    /// Revoke an API key: requests made with it are refused from then on
    Revoke(RevokeArgs),
    /// Replace an API key: create a new one with the same name, product and
    /// permissions, then revoke the old one
    Rotate(RotateArgs),
}

#[derive(Args)]
pub struct ListArgs {
    #[arg(long)]
    pub app_id: Option<String>,
    #[arg(long)]
    pub json: bool,
}

#[derive(Args)]
pub struct CreateArgs {
    pub alias: String,
    #[arg(long, default_value = "all")]
    pub product: String,
    #[arg(long, default_value = "full_access")]
    pub permissions: String,
    #[arg(long)]
    pub app_id: Option<String>,
    #[arg(long)]
    pub json: bool,
    /// Store the new key as the active CLI credential
    #[arg(long)]
    pub set_default: bool,
}

#[derive(Args)]
pub struct RevokeArgs {
    /// The key's id (from `offline keys list`) or its exact name
    pub key: String,
    #[arg(long)]
    pub app_id: Option<String>,
    /// Revoke without asking for confirmation (required when not run in a terminal)
    #[arg(long, short = 'y')]
    pub yes: bool,
    #[arg(long)]
    pub json: bool,
}

#[derive(Args)]
pub struct RotateArgs {
    /// The key's id (from `offline keys list`) or its exact name
    pub key: String,
    #[arg(long)]
    pub app_id: Option<String>,
    /// Rotate without asking for confirmation (required when not run in a terminal)
    #[arg(long, short = 'y')]
    pub yes: bool,
    #[arg(long)]
    pub json: bool,
    /// Store the new key as the active CLI credential. This happens anyway
    /// when the old key was the one this machine uses.
    #[arg(long)]
    pub set_default: bool,
}

pub async fn run(command: KeysCommand) -> Result<()> {
    match command {
        KeysCommand::List(list) => list_keys(list).await,
        KeysCommand::Create(create) => create_key(create).await,
        KeysCommand::Revoke(revoke) => revoke_key(revoke).await,
        KeysCommand::Rotate(rotate) => rotate_key(rotate).await,
    }
}

async fn list_keys(args: ListArgs) -> Result<()> {
    let mut config = CliConfig::load()?;
    let token = developer_session(&mut config, "keys").await?;
    let app_id = resolve_app_id(&config, args.app_id.as_deref())?;
    let client = client_from_config(&config).await?;
    let keys = client.list_api_keys(&token, &app_id).await?;

    if args.json {
        output::json(&json!({ "appId": app_id, "keys": keys }))?;
        return Ok(());
    }

    output::heading(&format!("api keys for {app_id}"));
    if keys.is_empty() {
        output::note("no keys — run `offline keys create \"CLI default\"`");
        return Ok(());
    }
    for key in &keys {
        let name = key.name.as_deref().unwrap_or("(unnamed)");
        let product = key.product.as_deref().unwrap_or("?");
        let status = key.status.as_deref().unwrap_or("?");
        let preview = key.key_preview.as_deref().unwrap_or("");
        let id = key.id.as_deref().unwrap_or("?");
        let this_machine = if is_stored_key(&config, &app_id, key) {
            "  (used by this CLI)"
        } else {
            ""
        };
        println!("  {name} {preview}  product={product}  status={status}  id={id}{this_machine}");
    }
    output::note("revoke with `offline keys revoke <id or name>`, replace with `offline keys rotate <id or name>`");
    Ok(())
}

async fn create_key(args: CreateArgs) -> Result<()> {
    let mut config = CliConfig::load()?;
    let token = developer_session(&mut config, "keys").await?;
    let app_id = resolve_app_id(&config, args.app_id.as_deref())?;
    let client = client_from_config(&config).await?;
    let product = match args.product.as_str() {
        "all" | "offline_id" | "mesh_sdk" | "proof_of_location" => args.product.clone(),
        other => bail!(
            "unsupported product `{other}` — use all, offline_id, mesh_sdk, or proof_of_location"
        ),
    };
    let key = client
        .create_api_key(&token, &app_id, &args.alias, &product, &args.permissions)
        .await?;

    let api_key = secret_of(&key)?;

    if args.set_default {
        store_as_default(&mut config, &app_id, &api_key)?;
    }

    if args.json {
        output::json(&json!({
            "appId": app_id,
            "key": key,
            "setDefault": args.set_default,
        }))?;
        return Ok(());
    }

    output::success(&format!(
        "created API key `{}` for application `{app_id}`",
        args.alias
    ));
    output::warn("Copy this key now — it will not be shown again:");
    println!("  {api_key}");
    if !args.set_default {
        output::note("Run with --set-default to store it as the active CLI credential");
    }
    Ok(())
}

async fn revoke_key(args: RevokeArgs) -> Result<()> {
    let mut config = CliConfig::load()?;
    let token = developer_session(&mut config, "keys").await?;
    let app_id = resolve_app_id(&config, args.app_id.as_deref())?;
    let client = client_from_config(&config).await?;
    let keys = client.list_api_keys(&token, &app_id).await?;
    let key = find_key(&keys, &args.key)?;
    let key_id = key
        .id
        .clone()
        .ok_or_else(|| anyhow!("the server listed this key without an id"))?;
    let label = describe(key);
    let was_stored = is_stored_key(&config, &app_id, key);

    let mut prompt =
        format!("Revoke {label} on `{app_id}`? Apps and servers using it stop working.");
    if was_stored {
        prompt.push_str(" This CLI uses this key too.");
    }
    confirm(&prompt, args.yes)?;

    client.revoke_api_key(&token, &app_id, &key_id).await?;
    if was_stored {
        forget_stored_key(&mut config, &app_id)?;
    }

    if args.json {
        output::json(&json!({
            "appId": app_id,
            "revoked": { "id": key_id, "name": key.name },
            "removedFromCliConfig": was_stored,
        }))?;
        return Ok(());
    }

    output::success(&format!("revoked {label} on `{app_id}`"));
    if was_stored {
        output::warn("This CLI was using that key, so it was removed from your local config.");
        output::note(
            "Run `offline setup` or `offline keys create <name> --set-default` to get a new one",
        );
    }
    Ok(())
}

async fn rotate_key(args: RotateArgs) -> Result<()> {
    let mut config = CliConfig::load()?;
    let token = developer_session(&mut config, "keys").await?;
    let app_id = resolve_app_id(&config, args.app_id.as_deref())?;
    let client = client_from_config(&config).await?;
    let keys = client.list_api_keys(&token, &app_id).await?;
    let old = find_key(&keys, &args.key)?;
    let old_id = old
        .id
        .clone()
        .ok_or_else(|| anyhow!("the server listed this key without an id"))?;
    let label = describe(old);
    let name = old
        .name
        .clone()
        .unwrap_or_else(|| "rotated key".to_string());
    let product = old.product.clone().unwrap_or_else(|| "all".to_string());
    let permissions = old
        .permissions
        .clone()
        .unwrap_or_else(|| "full_access".to_string());
    let was_stored = is_stored_key(&config, &app_id, old);

    confirm(
        &format!(
            "Rotate {label} on `{app_id}`? A new key replaces it and the old one is revoked right away."
        ),
        args.yes,
    )?;

    let new_key = client
        .create_api_key(&token, &app_id, &name, &product, &permissions)
        .await
        .context("creating the replacement key; the old key was not changed")?;
    let secret = secret_of(&new_key)?;

    let store = args.set_default || was_stored;
    if store {
        store_as_default(&mut config, &app_id, &secret)?;
    }

    if let Err(err) = client.revoke_api_key(&token, &app_id, &old_id).await {
        // The new key exists and is the only copy the user will see, so show
        // it before failing.
        if !args.json {
            output::warn(
                "Created the new key, but revoking the old one failed. Copy the new key now:",
            );
            println!("  {secret}");
        }
        return Err(err.context(format!(
            "the old key {label} is still active; revoke it with `offline keys revoke {old_id}`"
        )));
    }

    if args.json {
        output::json(&json!({
            "appId": app_id,
            "revoked": { "id": old_id, "name": old.name },
            "key": new_key,
            "setDefault": store,
        }))?;
        return Ok(());
    }

    output::success(&format!(
        "rotated {label} on `{app_id}`: the old key is revoked"
    ));
    output::warn("Copy the new key now — it will not be shown again:");
    println!("  {secret}");
    if store {
        output::note("Stored as the active CLI credential");
    }
    Ok(())
}

/// Find a key by id, or by exact name when no id matches. A name shared by
/// several keys is refused, with their ids, so the wrong key is never revoked.
fn find_key<'a>(keys: &'a [ApiKeyRecord], wanted: &str) -> Result<&'a ApiKeyRecord> {
    let wanted = wanted.trim();
    if let Some(key) = keys.iter().find(|k| k.id.as_deref() == Some(wanted)) {
        return Ok(key);
    }
    let by_name: Vec<&ApiKeyRecord> = keys
        .iter()
        .filter(|k| k.name.as_deref() == Some(wanted))
        .collect();
    match by_name.as_slice() {
        [key] => Ok(key),
        [] => bail!("no API key with id or name `{wanted}` — run `offline keys list` to see them"),
        many => {
            let ids: Vec<&str> = many.iter().filter_map(|k| k.id.as_deref()).collect();
            bail!(
                "{} keys are named `{wanted}`; pass one of their ids instead: {}",
                many.len(),
                ids.join(", ")
            )
        }
    }
}

fn describe(key: &ApiKeyRecord) -> String {
    let name = key.name.as_deref().unwrap_or("(unnamed)");
    match key.key_preview.as_deref() {
        Some(preview) if !preview.is_empty() => format!("key `{name}` ({preview})"),
        _ => format!("key `{name}`"),
    }
}

/// Whether `key` is the one this machine stores for the application, judged by
/// the last four characters the server lists (it never returns the secret).
fn is_stored_key(config: &CliConfig, app_id: &str, key: &ApiKeyRecord) -> bool {
    let Some(preview) = key.key_preview.as_deref() else {
        return false;
    };
    let last4: String = preview.chars().filter(|c| *c != '\u{2026}').collect();
    if last4.len() != 4 {
        return false;
    }
    config
        .app_keys
        .get(app_id)
        .or(if config.app_id.as_deref() == Some(app_id) {
            config.api_key.as_ref()
        } else {
            None
        })
        .is_some_and(|secret| secret.ends_with(&last4))
}

fn secret_of(key: &ApiKeyRecord) -> Result<String> {
    key.key
        .clone()
        .filter(|k| !k.is_empty())
        .ok_or_else(|| anyhow!("create API key response missing key value"))
}

fn store_as_default(config: &mut CliConfig, app_id: &str, api_key: &str) -> Result<()> {
    config
        .app_keys
        .insert(app_id.to_string(), api_key.to_string());
    config.api_key = Some(api_key.to_string());
    config.app_id = Some(app_id.to_string());
    config.save()
}

fn forget_stored_key(config: &mut CliConfig, app_id: &str) -> Result<()> {
    let removed = config.app_keys.remove(app_id);
    if config.app_id.as_deref() == Some(app_id) && (removed.is_none() || config.api_key == removed)
    {
        config.api_key = None;
    }
    config.save()
}

fn confirm(prompt: &str, yes: bool) -> Result<()> {
    use std::io::IsTerminal;
    if yes {
        return Ok(());
    }
    if !std::io::stdin().is_terminal() {
        bail!("refusing to change keys without confirmation; pass --yes to run non-interactively");
    }
    let go = dialoguer::Confirm::new()
        .with_prompt(prompt)
        .default(false)
        .interact()
        .context("reading confirmation")?;
    if !go {
        bail!("cancelled; no key was changed");
    }
    Ok(())
}

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

    fn key(id: &str, name: &str, preview: &str) -> ApiKeyRecord {
        ApiKeyRecord {
            key: None,
            name: Some(name.into()),
            id: Some(id.into()),
            application_id: Some("app_1".into()),
            product: Some("all".into()),
            permissions: Some("full_access".into()),
            status: Some("active".into()),
            key_preview: Some(preview.into()),
            created_at: None,
        }
    }

    #[test]
    fn find_key_prefers_id_then_unique_name() {
        let keys = vec![
            key("id-1", "server", "\u{2026}aaaa"),
            key("id-2", "ci", "\u{2026}bbbb"),
        ];
        assert_eq!(find_key(&keys, "id-2").unwrap().id.as_deref(), Some("id-2"));
        assert_eq!(
            find_key(&keys, "server").unwrap().id.as_deref(),
            Some("id-1")
        );
        assert!(find_key(&keys, "missing").is_err());
    }

    #[test]
    fn find_key_refuses_ambiguous_names() {
        let keys = vec![
            key("id-1", "dup", "\u{2026}aaaa"),
            key("id-2", "dup", "\u{2026}bbbb"),
        ];
        let err = find_key(&keys, "dup").unwrap_err().to_string();
        assert!(err.contains("id-1") && err.contains("id-2"), "{err}");
    }

    #[test]
    fn stored_key_matches_on_last_four() {
        let mut config = CliConfig::default();
        config
            .app_keys
            .insert("app_1".into(), "op_secret_abcd".into());
        assert!(is_stored_key(
            &config,
            "app_1",
            &key("id-1", "k", "\u{2026}abcd")
        ));
        assert!(!is_stored_key(
            &config,
            "app_1",
            &key("id-1", "k", "\u{2026}wxyz")
        ));
        assert!(!is_stored_key(
            &config,
            "app_2",
            &key("id-1", "k", "\u{2026}abcd")
        ));
    }

    #[test]
    fn stored_key_falls_back_to_active_credential() {
        let config = CliConfig {
            api_key: Some("op_secret_abcd".into()),
            app_id: Some("app_1".into()),
            ..CliConfig::default()
        };
        assert!(is_stored_key(
            &config,
            "app_1",
            &key("id-1", "k", "\u{2026}abcd")
        ));
    }
}