vta-cli-common 0.71.0

Shared CLI command handlers and rendering helpers for VTA CLIs
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
//! `pnm calendar connectors …` — calendars at Google, Microsoft or a CalDAV server
//! (iCloud, Fastmail, Nextcloud) the VTA writes your events into and reads busy time from
//! (`vta/calendar/connectors/*/0.1`, VTI-CAL-100 – 118).
//!
//! The connection lives in the VTA, never here: for an OAuth provider this command opens a
//! one-shot listener on a loopback port (RFC 8252 §7.3), prints the provider's address to
//! open in a browser, and relays the code the provider redirects back with to the VTA — the
//! VTA alone redeems it, with a PKCE verifier only it holds (VTI-CAL-101, 102). A CalDAV
//! password is sealed in this process to a single-use wrapping key from the VTA and never
//! sent in the clear (VTI-CAL-106).

use std::io::{IsTerminal, Read};

use serde_json::{Value, json};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use vta_sdk::error::VtaError;
use vta_sdk::prelude::*;
use vta_sdk::trust_tasks as tt;

use crate::render::{BOLD, CYAN, DIM, GREEN, RESET, YELLOW, is_json_output, print_json};

type CmdResult = Result<(), Box<dyn std::error::Error>>;

/// How long the loopback listener waits for the provider's redirect: the VTA's
/// authorization request lasts 10 minutes (VTI-CAL-101).
const LISTEN_SECONDS: u64 = 600;

fn local_code(e: &VtaError) -> Option<&str> {
    e.rejection_code()
        .map(|c| c.rsplit_once(':').map_or(c, |(_, l)| l))
}

/// The command that fixes a refusal, when the operator's intent maps to one.
fn fix_for(code: &str, id: Option<&str>) -> Option<String> {
    let id = id.unwrap_or("<connector-id>");
    Some(match code {
        "providerUnavailable" => "This VTA's operator has not registered an OAuth client for \
             that provider ([calendar.connectors] in the VTA's config; docs/02-vta/calendar.md). \
             A CalDAV server needs none:\n    pnm calendar connectors create --provider caldav \
             --endpoint https://caldav.icloud.com/ --username <apple-id> --context <id>"
            .to_string(),
        "limitReached" => "Remove a connector you no longer use first:\n    \
             pnm calendar connectors list\n    pnm calendar connectors remove <connector-id>"
            .to_string(),
        "redirectInvalid" => "The redirect address must be one the operator registered, or a \
             loopback address; omit --redirect-uri to let this command listen on one."
            .to_string(),
        "authorizationExpired" | "stateMismatch" => format!(
            "Ask the provider again:\n    pnm calendar connectors update {id} --reauthorize"
        ),
        "credentialRejected" => format!(
            "The server refused the password. Make a new app-specific password and:\n    \
             pnm calendar connectors update {id} --password"
        ),
        "removing" => "The connector is being removed; nothing more can change on it.".to_string(),
        "notFound" => {
            "List the connectors you may see:\n    pnm calendar connectors list".to_string()
        }
        _ => return None,
    })
}

async fn call(
    client: &VtaClient,
    uri: &str,
    payload: Value,
    id: Option<&str>,
) -> Result<Value, Box<dyn std::error::Error>> {
    match client.dispatch_trust_task(uri, payload, 30).await {
        Ok(v) => Ok(v),
        Err(e) => match local_code(&e).and_then(|c| fix_for(c, id)) {
            Some(fix) => Err(format!("{e}\n  {fix}").into()),
            None => Err(Box::new(e)),
        },
    }
}

/// What `create` was asked.
#[derive(Debug, Default)]
pub struct ConnectorCreate {
    pub context: String,
    pub provider: String,
    pub label: String,
    /// `busy`, `titles` or `off`, for `context`.
    pub write: String,
    /// Read busy time back.
    pub busy: bool,
    /// Contexts the busy time read counts in; default the connector's own.
    pub busy_contexts: Vec<String>,
    /// Calendars at the provider to read busy time from; default the primary (or all).
    pub busy_calendars: Vec<String>,
    /// An OAuth redirect the client handles itself; default a loopback listener here.
    pub redirect_uri: Option<String>,
    /// CalDAV.
    pub endpoint: Option<String>,
    pub username: Option<String>,
}

/// What `update` was asked.
#[derive(Debug, Default)]
pub struct ConnectorUpdate {
    pub label: Option<String>,
    /// `busy`, `titles` or `off`, for the connector's own context.
    pub write: Option<String>,
    pub busy: Option<bool>,
    pub busy_contexts: Vec<String>,
    pub reauthorize: bool,
    pub redirect_uri: Option<String>,
    /// A new app-specific password for a CalDAV connector, for this server and account
    /// (the VTA never answers them, VTI-CAL-106, so they are given again).
    pub password_for: Option<(String, String)>,
}

fn busy_choice(on: bool, contexts: &[String], calendars: &[String]) -> Value {
    let mut b = json!({ "enabled": on });
    if !contexts.is_empty() {
        b["contextIds"] = json!(contexts);
    }
    if !calendars.is_empty() {
        b["calendars"] = json!(calendars);
    }
    b
}

/// Read a password without echo (or from stdin when piped), and seal it to a fresh wrapping
/// key from the VTA, naming the server and account inside the seal.
async fn sealed_password(
    client: &VtaClient,
    endpoint: &str,
    username: &str,
) -> Result<String, Box<dyn std::error::Error>> {
    let password = zeroize::Zeroizing::new(if std::io::stdin().is_terminal() {
        dialoguer::Password::new()
            .with_prompt(format!("App-specific password for {username}"))
            .interact()?
    } else {
        let mut s = String::new();
        std::io::stdin().read_to_string(&mut s)?;
        s.trim_end_matches(['\r', '\n']).to_string()
    });
    if password.is_empty() {
        return Err("no password was given".into());
    }
    let wrapping = client.get_wrapping_key().await?;
    Ok(vta_sdk::sealed_transfer::seal_calendar_credential(
        &wrapping.wrapping_key,
        endpoint,
        username,
        &password,
    )
    .await?)
}

/// A one-shot loopback listener for the provider's redirect (RFC 8252 §7.3).
struct Loopback {
    listener: tokio::net::TcpListener,
    redirect_uri: String,
}

impl Loopback {
    async fn bind() -> Result<Self, Box<dyn std::error::Error>> {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
        let port = listener.local_addr()?.port();
        Ok(Self {
            listener,
            redirect_uri: format!("http://127.0.0.1:{port}/callback"),
        })
    }

    /// Wait for the redirect carrying `state`; answer the browser and return the query.
    /// Requests that are not it (a favicon, a stale tab) are answered 404 and ignored.
    async fn wait(self, state: &str) -> Result<Vec<(String, String)>, Box<dyn std::error::Error>> {
        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(LISTEN_SECONDS);
        loop {
            let (mut sock, _) = tokio::time::timeout_at(deadline, self.listener.accept())
                .await
                .map_err(|_| "no redirect came back from the provider within 10 minutes")??;
            let mut buf = vec![0u8; 8192];
            let n = tokio::time::timeout(std::time::Duration::from_secs(10), sock.read(&mut buf))
                .await
                .unwrap_or(Ok(0))
                .unwrap_or(0);
            let head = String::from_utf8_lossy(&buf[..n]);
            let target = head
                .lines()
                .next()
                .and_then(|l| l.strip_prefix("GET "))
                .and_then(|l| l.split(' ').next())
                .unwrap_or("");
            let query = target
                .strip_prefix("/callback?")
                .map(|q| {
                    q.split('&')
                        .filter_map(|kv| kv.split_once('='))
                        .map(|(k, v)| (k.to_string(), percent_decode(v)))
                        .collect::<Vec<_>>()
                })
                .unwrap_or_default();
            if !query.iter().any(|(k, v)| k == "state" && v == state) {
                let _ = sock
                    .write_all(
                        b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
                    )
                    .await;
                continue;
            }
            let page = "<!doctype html><meta charset=utf-8><title>VTA</title>\
                        <p>Done. You can close this tab and return to the terminal.";
            let _ = sock
                .write_all(
                    format!(
                        "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\n\
                         Content-Length: {}\r\nConnection: close\r\n\r\n{page}",
                        page.len()
                    )
                    .as_bytes(),
                )
                .await;
            return Ok(query);
        }
    }
}

fn percent_decode(s: &str) -> String {
    let s = s.replace('+', " ");
    let bytes = s.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%'
            && i + 2 < bytes.len()
            && let Some(b) = std::str::from_utf8(&bytes[i + 1..i + 3])
                .ok()
                .and_then(|h| u8::from_str_radix(h, 16).ok())
        {
            out.push(b);
            i += 3;
        } else {
            out.push(bytes[i]);
            i += 1;
        }
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// Print where to grant access, wait on the loopback listener, and relay what came back.
async fn grant(
    client: &VtaClient,
    id: &str,
    provider: &str,
    authorization: &Value,
    listener: Option<Loopback>,
) -> Result<Value, Box<dyn std::error::Error>> {
    let url = authorization["url"].as_str().unwrap_or("?");
    let state = authorization["state"]
        .as_str()
        .unwrap_or_default()
        .to_string();
    println!("Open this address in your browser and grant access:");
    println!();
    println!("  {url}");
    println!();
    if provider == "microsoft" {
        println!(
            "{YELLOW}Microsoft grants more than the VTA keeps:{RESET} its narrowest calendar \
             permission (Calendars.ReadWrite) lets the VTA read and change every calendar in the \
             account. The VTA writes only to a calendar it creates and reads only start, end \
             and free/busy status (VTI-CAL-105)."
        );
        println!();
    }
    let Some(listener) = listener else {
        println!(
            "{DIM}When the provider redirects back, relay the code with:{RESET}\n    \
             pnm calendar connectors complete {id} --state {state} --code <code>"
        );
        return Ok(Value::Null);
    };
    println!("{DIM}Waiting for the provider to redirect back (10 minutes)…{RESET}");
    let query = listener.wait(&state).await?;
    let get = |k: &str| query.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
    let mut req = json!({ "connectorId": id, "state": state });
    match (get("code"), get("error")) {
        (Some(code), _) => req["code"] = json!(code),
        (None, Some(err)) => req["providerError"] = json!(err),
        (None, None) => {
            return Err("the provider redirected back with neither a code nor an error".into());
        }
    }
    call(
        client,
        tt::TASK_VTA_CALENDAR_CONNECTORS_AUTHORIZE_COMPLETE_0_1,
        req,
        Some(id),
    )
    .await
}

fn print_connector(c: &Value) {
    let fault = c["lastFault"]["code"]
        .as_str()
        .map(|f| format!(" · last fault {f}"))
        .unwrap_or_default();
    println!(
        "  {CYAN}{}{RESET}  {BOLD}{}{RESET}  {DIM}{} · {} · context {} · {} pending{}{RESET}",
        c["connectorId"].as_str().unwrap_or("?"),
        c["label"].as_str().unwrap_or(""),
        c["provider"].as_str().unwrap_or("?"),
        c["state"].as_str().unwrap_or("?"),
        c["contextId"].as_str().unwrap_or("?"),
        c["pendingWrites"].as_u64().unwrap_or(0),
        fault,
    );
    for cov in c["coverage"].as_array().into_iter().flatten() {
        println!(
            "      {DIM}writes {} for {}{RESET}",
            cov["write"].as_str().unwrap_or("?"),
            cov["contextId"].as_str().unwrap_or("?")
        );
    }
    if c["busy"]["enabled"].as_bool() == Some(true) {
        println!(
            "      {DIM}reads busy time{}{RESET}",
            c["lastReadAt"]
                .as_str()
                .map(|t| format!(", last {t}"))
                .unwrap_or_default()
        );
    }
}

fn done(resp: &Value) -> CmdResult {
    if is_json_output() {
        return Ok(print_json(resp)?);
    }
    if let Some(c) = resp.get("connector") {
        print_connector(c);
    }
    Ok(())
}

/// `connectors create` → `vta/calendar/connectors/create/0.1`, then — for an OAuth provider —
/// the grant through a loopback listener and `authorize/complete`.
pub async fn cmd_connectors_create(client: &VtaClient, opts: &ConnectorCreate) -> CmdResult {
    let mut req = json!({
        "contextId": opts.context,
        "provider": opts.provider,
        "label": opts.label,
        "coverage": [{ "contextId": opts.context, "write": opts.write }],
        "busy": busy_choice(opts.busy, &opts.busy_contexts, &opts.busy_calendars),
    });
    let mut listener = None;
    if opts.provider == "caldav" {
        let (Some(endpoint), Some(username)) = (&opts.endpoint, &opts.username) else {
            return Err("a CalDAV connector needs --endpoint and --username".into());
        };
        let sealed = sealed_password(client, endpoint, username).await?;
        req["caldav"] =
            json!({ "endpoint": endpoint, "username": username, "sealedPassword": sealed });
    } else if let Some(r) = &opts.redirect_uri {
        req["redirectUri"] = json!(r);
    } else {
        let l = Loopback::bind().await?;
        req["redirectUri"] = json!(l.redirect_uri);
        listener = Some(l);
    }
    let resp = call(
        client,
        tt::TASK_VTA_CALENDAR_CONNECTORS_CREATE_0_1,
        req,
        None,
    )
    .await?;
    let id = resp["connector"]["connectorId"]
        .as_str()
        .unwrap_or_default()
        .to_string();
    let Some(authorization) = resp.get("authorization") else {
        if !is_json_output() {
            println!("{GREEN}\u{2713}{RESET} Connected.");
        }
        return done(&resp);
    };
    if is_json_output() && listener.is_none() {
        return Ok(print_json(&resp)?);
    }
    let completed = grant(client, &id, &opts.provider, authorization, listener).await?;
    if completed.is_null() {
        return Ok(());
    }
    if !is_json_output() {
        println!("{GREEN}\u{2713}{RESET} Connected.");
    }
    done(&completed)
}

/// `connectors complete` → `vta/calendar/connectors/authorize/complete/0.1`, for a client that
/// caught the redirect itself.
pub async fn cmd_connectors_complete(
    client: &VtaClient,
    id: &str,
    state: &str,
    code: Option<&str>,
    error: Option<&str>,
) -> CmdResult {
    let mut req = json!({ "connectorId": id, "state": state });
    match (code, error) {
        (Some(c), _) => req["code"] = json!(c),
        (None, Some(e)) => req["providerError"] = json!(e),
        (None, None) => {
            return Err("give --code, or --error with what the provider answered".into());
        }
    }
    let resp = call(
        client,
        tt::TASK_VTA_CALENDAR_CONNECTORS_AUTHORIZE_COMPLETE_0_1,
        req,
        Some(id),
    )
    .await?;
    done(&resp)
}

/// `connectors list` → `vta/calendar/connectors/list/0.1`.
pub async fn cmd_connectors_list(client: &VtaClient, context: Option<&str>) -> CmdResult {
    let mut req = json!({});
    if let Some(c) = context {
        req["contextId"] = json!(c);
    }
    let resp = call(client, tt::TASK_VTA_CALENDAR_CONNECTORS_LIST_0_1, req, None).await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    let items = resp["connectors"].as_array().cloned().unwrap_or_default();
    if items.is_empty() {
        println!(
            "No connectors. `pnm calendar connectors create --provider google --context <id>` \
             makes one."
        );
    }
    for c in &items {
        print_connector(c);
    }
    Ok(())
}

/// `connectors show` → `vta/calendar/connectors/show/0.1`.
pub async fn cmd_connectors_show(client: &VtaClient, id: &str) -> CmdResult {
    let resp = call(
        client,
        tt::TASK_VTA_CALENDAR_CONNECTORS_SHOW_0_1,
        json!({ "connectorId": id }),
        Some(id),
    )
    .await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    done(&resp)
}

/// `connectors update` → `vta/calendar/connectors/update/0.1` (and, with `--reauthorize`, the
/// grant again).
pub async fn cmd_connectors_update(
    client: &VtaClient,
    id: &str,
    opts: &ConnectorUpdate,
) -> CmdResult {
    let current = call(
        client,
        tt::TASK_VTA_CALENDAR_CONNECTORS_SHOW_0_1,
        json!({ "connectorId": id }),
        Some(id),
    )
    .await?;
    let c = &current["connector"];
    let provider = c["provider"].as_str().unwrap_or_default().to_string();
    let mut req = json!({ "connectorId": id });
    if let Some(l) = &opts.label {
        req["label"] = json!(l);
    }
    if let Some(w) = &opts.write {
        req["coverage"] = json!([{ "contextId": c["contextId"], "write": w }]);
    }
    if let Some(on) = opts.busy {
        req["busy"] = busy_choice(on, &opts.busy_contexts, &[]);
    }
    let mut listener = None;
    if opts.reauthorize {
        if let Some(r) = &opts.redirect_uri {
            req["reauthorize"] = json!({ "redirectUri": r });
        } else {
            let l = Loopback::bind().await?;
            req["reauthorize"] = json!({ "redirectUri": l.redirect_uri });
            listener = Some(l);
        }
    }
    if let Some((endpoint, username)) = &opts.password_for {
        req["caldavPassword"] = json!(sealed_password(client, endpoint, username).await?);
    }
    let resp = call(
        client,
        tt::TASK_VTA_CALENDAR_CONNECTORS_UPDATE_0_1,
        req,
        Some(id),
    )
    .await?;
    match resp.get("authorization") {
        Some(a) => {
            let completed = grant(client, id, &provider, a, listener).await?;
            if completed.is_null() {
                return Ok(());
            }
            done(&completed)
        }
        None => done(&resp),
    }
}

/// `connectors remove` → `vta/calendar/connectors/remove/0.1`.
pub async fn cmd_connectors_remove(client: &VtaClient, id: &str, keep_calendar: bool) -> CmdResult {
    let resp = call(
        client,
        tt::TASK_VTA_CALENDAR_CONNECTORS_REMOVE_0_1,
        json!({ "connectorId": id, "keepCalendar": keep_calendar }),
        Some(id),
    )
    .await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    println!(
        "{GREEN}\u{2713}{RESET} Removing. The VTA {}, revokes its grant and forgets the \
         connector; `pnm calendar connectors list` shows it until then.",
        if keep_calendar {
            "leaves its calendar at the provider"
        } else {
            "deletes its calendar at the provider"
        }
    );
    Ok(())
}

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

    #[test]
    fn a_redirect_query_is_percent_decoded() {
        assert_eq!(percent_decode("4%2F0Aean%2Bx"), "4/0Aean+x");
        assert_eq!(percent_decode("access_denied"), "access_denied");
        assert_eq!(percent_decode("a+b%"), "a b%");
    }

    #[tokio::test]
    async fn the_loopback_listener_answers_only_its_own_state() {
        let l = Loopback::bind().await.unwrap();
        let addr = l.redirect_uri.trim_end_matches("/callback").to_string();
        let host = addr.trim_start_matches("http://").to_string();
        let waiter = tokio::spawn(async move { l.wait("S1").await.unwrap() });
        for target in [
            "/favicon.ico",
            "/callback?state=OTHER&code=x",
            "/callback?state=S1&code=4%2Fabc",
        ] {
            let mut s = tokio::net::TcpStream::connect(&host).await.unwrap();
            s.write_all(format!("GET {target} HTTP/1.1\r\nHost: x\r\n\r\n").as_bytes())
                .await
                .unwrap();
            let mut out = String::new();
            let _ = s.read_to_string(&mut out).await;
        }
        let q = waiter.await.unwrap();
        assert!(q.contains(&("code".to_string(), "4/abc".to_string())));
    }
}