vta-cli-common 0.74.0

Shared CLI command handlers and rendering helpers for VTA CLIs
//! What to do when a calendar provider, or a way in to it, is not offered (VTI-CAL-132).
//!
//! `vta/calendar/connectors/providers/list/0.2` answers **why** โ€” `reason` for a provider and
//! `notOffered[]` for a way in โ€” and nothing else of the operator's configuration. This module
//! turns each reason into the exact fix: for the **operator** (the Google Cloud or Microsoft
//! Entra steps and the TOML to add), and for the **principal** where the fix is theirs (an
//! app-specific password, a private iCal address, a device code). `pnm calendar connect
//! --help-operator` prints the operator's blocks for whatever this VTA does not offer, ready to
//! copy; the browser plugin mirrors the same texts.
//!
//! The texts are plain (no colour) so they paste cleanly into a ticket or a config file.

use serde_json::Value;

/// The loopback redirect `pnm` and the plugin's tab catcher use (any port; RFC 8252 ยง7.3).
pub const LOOPBACK_REDIRECT: &str = "http://127.0.0.1/callback";

/// The browser extension's redirect, with its id left for the operator to fill in.
pub const EXTENSION_REDIRECT: &str = "https://<extension-id>.chromiumapp.org/connectors";

/// What a provider is called to a person.
fn named(provider: &str) -> &'static str {
    match provider {
        "google" => "Google Calendar",
        "microsoft" => "Microsoft (Outlook.com, Microsoft 365)",
        "caldav" => "CalDAV (iCloud, Fastmail, Nextcloud)",
        "icsBusy" => "Busy time from a private iCal address",
        _ => "This provider",
    }
}

const GOOGLE_PROJECT: &str = "\
In the Google Cloud console (https://console.cloud.google.com):
  1. Create or pick a project; APIs & Services -> Library -> enable the Google Calendar API.
  2. APIs & Services -> OAuth consent screen: External; add the scopes
       https://www.googleapis.com/auth/calendar.app.created
       https://www.googleapis.com/auth/calendar.freebusy
     then publish it, or add each user as a test user.";

const GOOGLE_DESKTOP: &str = "\
  3. APIs & Services -> Credentials -> Create credentials -> OAuth client ID ->
     Application type: Desktop app (for pnm, which listens on a loopback port).
  4. Add it to the VTA's config and restart the VTA:

[[calendar.connectors.google.clients]]
client_id = \"<id>.apps.googleusercontent.com\"
client_secret = \"<secret>\"
redirect_uris = [\"http://127.0.0.1/callback\"]";

const GOOGLE_WEB: &str = "\
  3. APIs & Services -> Credentials -> Create credentials -> OAuth client ID ->
     Application type: Web application; Authorised redirect URI:
       https://<extension-id>.chromiumapp.org/connectors
     (the browser extension's id, as its Chrome Web Store item shows it).
  4. Add it to the VTA's config and restart the VTA:

[[calendar.connectors.google.clients]]
client_id = \"<id>.apps.googleusercontent.com\"
client_secret = \"<secret>\"
redirect_uris = [\"https://<extension-id>.chromiumapp.org/connectors\"]";

const ENTRA_APP: &str = "\
In Microsoft Entra ID (https://entra.microsoft.com) -> App registrations -> New registration:
  1. Supported account types: accounts in any organizational directory and personal
     Microsoft accounts (tenant \"common\").
  2. API permissions -> Add -> Microsoft Graph -> Delegated: Calendars.ReadWrite and
     offline_access.";

const ENTRA_LOOPBACK: &str = "\
  Authentication -> Add a platform -> Mobile and desktop applications -> custom redirect URI
       http://127.0.0.1/callback
  (Microsoft matches a loopback address on any port).";

// Not "Single-page application": Entra lets an SPA-platform code be redeemed only by a
// cross-origin browser request (AADSTS9002327), and the VTA redeems it server-side. Not "Web":
// that needs a client secret. A public client with PKCE is what this design is.
const ENTRA_EXTENSION: &str = "\
  Authentication -> Mobile and desktop applications -> Add a custom redirect URI
       https://<extension-id>.chromiumapp.org/connectors
  (the browser extension's id, as its Chrome Web Store item shows it; a public client:
  no secret, PKCE).";

const ENTRA_DEVICE: &str = "\
  Authentication -> Advanced settings -> Allow public client flows: Yes -> Save.";

const MICROSOFT_TOML: &str = "\
[[calendar.connectors.microsoft.clients]]
client_id = \"<application (client) id>\"
tenant = \"common\"
redirect_uris = [\"http://127.0.0.1/callback\", \"https://<extension-id>.chromiumapp.org/connectors\"]
device_code = true";

/// The operator's fix for `reason`, for `provider` โ€” and, for `redirectNotRegistered`, the kind
/// of redirect address no client admits. `None` where the fix is not the operator's
/// (`deviceCodeUnsupported`: Google signs in through a browser, and nothing is configured).
#[must_use]
pub fn operator_fix(provider: &str, reason: &str, redirect_kind: Option<&str>) -> Option<String> {
    let name = named(provider);
    Some(match (reason, provider, redirect_kind) {
        ("noClient", "google", _) => format!(
            "{name} is not offered: no OAuth client is configured for it, and this VTA's \
             software ships none.\n{GOOGLE_PROJECT}\n{GOOGLE_DESKTOP}"
        ),
        ("noClient", "microsoft", _) => format!(
            "{name} is not offered: no OAuth client is configured for it, and this VTA's \
             software ships none.\n{ENTRA_APP}\n  3. {}\n  4. {}\n  5. Add it to the VTA's \
             config and restart the VTA:\n\n{MICROSOFT_TOML}",
            ENTRA_LOOPBACK.trim_start(),
            ENTRA_DEVICE.trim_start(),
        ),
        ("builtinOff", _, _) => format!(
            "{name} is not offered: this VTA's software ships a client for it, but the operator \
             turned built-in clients off and configured none of its own.\nEither turn them back \
             on in the VTA's config and restart the VTA:\n\n[calendar.connectors]\n\
             builtin_clients = true\n\nor configure the operator's own client:\n\n{}",
            operator_fix(provider, "noClient", None).unwrap_or_default()
        ),
        ("redirectNotRegistered", "google", Some("extension")) => format!(
            "No Google client admits the browser extension's redirect, so the extension cannot \
             sign in to Google through this VTA.\n{GOOGLE_PROJECT}\n{GOOGLE_WEB}"
        ),
        ("redirectNotRegistered", "google", _) => format!(
            "No Google client admits a loopback redirect, so pnm cannot sign in to Google \
             through a browser on this machine.\n{GOOGLE_PROJECT}\n{GOOGLE_DESKTOP}"
        ),
        ("redirectNotRegistered", "microsoft", Some("extension")) => format!(
            "No Microsoft client admits the browser extension's redirect.\nIn Microsoft Entra ID \
             -> App registrations -> the VTA's app:\n{ENTRA_EXTENSION}\nthen add \
             \"https://<extension-id>.chromiumapp.org/connectors\" to that client's \
             redirect_uris in the VTA's config and restart the VTA:\n\n{MICROSOFT_TOML}"
        ),
        ("redirectNotRegistered", "microsoft", _) => format!(
            "No Microsoft client admits a loopback redirect, so pnm cannot sign in to Microsoft \
             through a browser on this machine.\nIn Microsoft Entra ID -> App registrations -> \
             the VTA's app:\n{ENTRA_LOOPBACK}\nthen add \"http://127.0.0.1/callback\" to that \
             client's redirect_uris in the VTA's config and restart the VTA:\n\n{MICROSOFT_TOML}"
        ),
        ("deviceCodeDisabled", _, _) => format!(
            "No Microsoft client is enabled for signing in with a code.\nIn Microsoft Entra ID -> \
             App registrations -> the VTA's app:\n{ENTRA_DEVICE}\nthen set device_code = true on \
             that client in the VTA's config and restart the VTA:\n\n{MICROSOFT_TOML}"
        ),
        ("disabledByOperator", "caldav", _) => format!(
            "{name} is turned off on this VTA. To offer it, set in the VTA's config and restart \
             the VTA:\n\n[calendar.connectors]\ncaldav = true"
        ),
        ("disabledByOperator", "icsBusy", _) => format!(
            "{name} is turned off on this VTA. To offer it, set in the VTA's config and restart \
             the VTA:\n\n[calendar.connectors]\nics_busy = true"
        ),
        ("unreachable", _, _) => format!(
            "The VTA cannot reach {name}. Allow its egress to {}.",
            match provider {
                "google" => "oauth2.googleapis.com and www.googleapis.com",
                "microsoft" => "login.microsoftonline.com and graph.microsoft.com",
                _ => "the server's host",
            }
        ),
        _ => return None,
    })
}

/// What the principal can do about `reason`, where it is theirs to act on.
#[must_use]
pub fn user_fix(provider: &str, reason: &str) -> Option<String> {
    Some(match (reason, provider) {
        ("deviceCodeUnsupported", _) => "Google has no sign-in with a code for calendars: sign \
             in through a browser instead.\n    pnm calendar connect --provider google \
             --flow authorization-code"
            .to_string(),
        ("deviceCodeDisabled", "microsoft") => "Sign in through a browser on this machine \
             instead.\n    pnm calendar connect --provider microsoft --flow authorization-code"
            .to_string(),
        ("redirectNotRegistered", "microsoft") => "Or sign in with a code, which needs no \
             redirect, on any device.\n    pnm calendar connect --provider microsoft --flow \
             device-code"
            .to_string(),
        _ => return None,
    })
}

/// How to make an app-specific password, for a CalDAV account.
pub const USER_APP_PASSWORD: &str = "\
iCloud needs an app-specific password, never your Apple ID password: sign in at
https://account.apple.com -> Sign-In and Security -> App-Specific Passwords -> +.
Fastmail: Settings -> Privacy & Security -> Integrations -> New app password (CalDAV).
Nextcloud: Settings -> Security -> Devices & sessions -> Create new app password.";

/// Where a calendar's private address in iCal format is found.
pub const USER_PRIVATE_ICAL: &str = "\
Google: calendar.google.com -> Settings -> your calendar -> Integrate calendar ->
  \"Secret address in iCal format\".
Outlook: Settings -> Calendar -> Shared calendars -> Publish a calendar -> Can view all
  details -> Publish -> the ICS link.
iCloud: Calendar -> the calendar's share button -> Public Calendar -> copy the webcal:// link.
The address reads the whole calendar: keep it secret. The VTA keeps only busy times.";

/// What a device code asks of the principal.
pub const USER_DEVICE_CODE: &str = "\
Open the address shown (https://microsoft.com/devicelogin) on any device, sign in, and
enter the code shown. Enter it only at Microsoft's own address, and only because your own
terminal is showing it to you: whoever enters it grants their account to this VTA. If your
organisation forbids signing in with a code, sign in through a browser instead:
    pnm calendar connect --provider microsoft --flow authorization-code";

/// The help for one `VtaCalendarConnectorProviderOffer`: a block per reason it gives, the
/// operator's fix and โ€” where there is one โ€” the principal's.
#[must_use]
pub fn offer_help(offer: &Value) -> Vec<String> {
    let provider = offer["provider"].as_str().unwrap_or_default();
    let mut out = Vec::new();
    if offer["available"] == false {
        let reason = offer["reason"]
            .as_str()
            .or_else(|| offer["unavailableBecause"].as_str())
            .map(|r| if r == "notConfigured" { "noClient" } else { r })
            .unwrap_or("noClient");
        if let Some(f) = operator_fix(provider, reason, None) {
            out.push(f);
        }
    }
    for n in offer["notOffered"].as_array().into_iter().flatten() {
        let reason = n["reason"].as_str().unwrap_or_default();
        let kind = n["redirectKind"].as_str();
        let mut block = operator_fix(provider, reason, kind).unwrap_or_default();
        if let Some(u) = user_fix(provider, reason) {
            if !block.is_empty() {
                block.push_str("\n\n");
            }
            block.push_str(&u);
        }
        if !block.is_empty() {
            out.push(block);
        }
    }
    out
}

/// Every operator block for what `offers` (a `providers/list` answer) says is not offered.
#[must_use]
pub fn operator_help(offers: &Value) -> Vec<(String, String)> {
    offers["providers"]
        .as_array()
        .into_iter()
        .flatten()
        .flat_map(|o| {
            let p = o["provider"].as_str().unwrap_or_default().to_string();
            offer_help(o).into_iter().map(move |b| (p.clone(), b))
        })
        .collect()
}

/// The whole operator guide, for when the VTA's offers cannot be read: every provider's setup.
#[must_use]
pub fn operator_guide() -> String {
    [
        operator_fix("google", "noClient", None).unwrap_or_default(),
        operator_fix("google", "redirectNotRegistered", Some("extension")).unwrap_or_default(),
        operator_fix("microsoft", "noClient", None).unwrap_or_default(),
        operator_fix("caldav", "disabledByOperator", None).unwrap_or_default(),
        operator_fix("icsBusy", "disabledByOperator", None).unwrap_or_default(),
    ]
    .join("\n\n----\n\n")
}

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

    #[test]
    fn vti_cal_132_each_reason_names_its_fix() {
        let g = operator_fix("google", "noClient", None).unwrap();
        assert!(g.contains("Desktop app"), "{g}");
        assert!(g.contains("[[calendar.connectors.google.clients]]"));
        assert!(g.contains(LOOPBACK_REDIRECT));
        assert!(g.contains("calendar.app.created") && g.contains("calendar.freebusy"));

        let m = operator_fix("microsoft", "noClient", None).unwrap();
        for want in [
            "Entra",
            "Mobile and desktop applications",
            "Calendars.ReadWrite",
            "Allow public client flows",
            "[[calendar.connectors.microsoft.clients]]",
            "device_code = true",
            LOOPBACK_REDIRECT,
            EXTENSION_REDIRECT,
        ] {
            assert!(m.contains(want), "{want}: {m}");
        }

        let off = operator_fix("microsoft", "builtinOff", None).unwrap();
        assert!(off.contains("builtin_clients = true"), "{off}");

        let ext = operator_fix("google", "redirectNotRegistered", Some("extension")).unwrap();
        assert!(ext.contains("Web application") && ext.contains(EXTENSION_REDIRECT));
        let mext = operator_fix("microsoft", "redirectNotRegistered", Some("extension")).unwrap();
        assert!(
            mext.contains("Mobile and desktop applications -> Add a custom redirect URI")
                && mext.contains(EXTENSION_REDIRECT),
            "{mext}"
        );
        assert!(
            !mext.contains("Single-page") && !mext.contains("Web application"),
            "{mext}"
        );
        assert!(
            user_fix("microsoft", "redirectNotRegistered")
                .unwrap()
                .contains("--flow device-code")
        );
        let lb = operator_fix("microsoft", "redirectNotRegistered", Some("loopback")).unwrap();
        assert!(lb.contains("Mobile and desktop applications"), "{lb}");

        let dev = operator_fix("microsoft", "deviceCodeDisabled", None).unwrap();
        assert!(
            dev.contains("Allow public client flows: Yes") && dev.contains("device_code = true")
        );

        assert!(
            operator_fix("caldav", "disabledByOperator", None)
                .unwrap()
                .contains("caldav = true")
        );
        assert!(
            operator_fix("icsBusy", "disabledByOperator", None)
                .unwrap()
                .contains("ics_busy = true")
        );
        assert!(operator_fix("google", "deviceCodeUnsupported", None).is_none());
        assert!(
            user_fix("google", "deviceCodeUnsupported")
                .unwrap()
                .contains("--flow authorization-code")
        );
    }

    #[test]
    fn vti_cal_132_an_offer_reads_as_its_blocks() {
        let google = json!({ "provider": "google", "available": true, "flows": [],
            "notOffered": [
                { "flow": "authorizationCode", "redirectKind": "extension", "reason": "redirectNotRegistered" },
                { "flow": "deviceCode", "reason": "deviceCodeUnsupported" }] });
        let blocks = offer_help(&google);
        assert_eq!(blocks.len(), 2);
        assert!(blocks[0].contains("Web application"));
        assert!(blocks[1].contains("no sign-in with a code"));

        // A 0.1 answer: `unavailableBecause` alone.
        let ms = json!({ "provider": "microsoft", "available": false,
                         "unavailableBecause": "notConfigured", "flows": [] });
        assert!(offer_help(&ms)[0].contains("Entra"));

        let all = operator_help(&json!({ "providers": [google, ms] }));
        assert_eq!(all.len(), 3);
        assert!(operator_guide().contains("ics_busy = true"));
    }
}