shimpz-cli 0.1.9

Fast local tooling for Shimpz Assistants
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
//! Browser-based CLI authorization and token lifecycle.

use std::{
    process::Command,
    thread,
    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};

use serde::{Deserialize, Serialize, de::DeserializeOwned};
use ureq::{Agent, Body, http::Response};
use zeroize::Zeroizing;

use crate::{
    credentials::{self, Credentials},
    output,
};

const ORIGIN: &str = "https://developers.shimpz.com";
const AUTHORIZE_URL: &str = "https://developers.shimpz.com/api/oauth/device/authorization";
const DEVICE_TOKEN_URL: &str = "https://developers.shimpz.com/api/oauth/device/token";
const REFRESH_TOKEN_URL: &str = "https://developers.shimpz.com/api/oauth/token/refresh";
const SESSION_URL: &str = "https://developers.shimpz.com/api/v1/auth/session";
const POLL_INTERVAL: Duration = Duration::from_secs(5);
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
const MAX_RESPONSE_BYTES: u64 = 32 * 1024;
const IDENTITY_SCOPE: &str = "identity:read";
const AVAILABLE_SCOPES: [&str; 4] = [
    "identity:read",
    "teams:read",
    "assistant:publish",
    "assistant:install",
];

pub(crate) fn login() -> Result<String, String> {
    let credential_lock = credentials::lock()?;
    let api = Api::new();
    if let Some(mut stored) = credentials::load(&credential_lock)? {
        if let Some(session) = ensure_session(&api, &credential_lock, &mut stored)? {
            return Ok(format!("Already authenticated as {}.", session.account_id));
        }
        api.revoke(stored.refresh_token())?;
        credentials::clear(&credential_lock)?;
    }
    interactive_login(&api, &credential_lock, &[IDENTITY_SCOPE])?;
    Ok("Authentication complete. You can close the browser tab.".into())
}

pub(crate) fn ensure_authenticated(required_scope: &str) -> Result<Credentials, String> {
    if !AVAILABLE_SCOPES.contains(&required_scope) {
        return Err("CLI requested an unknown permission".into());
    }
    let credential_lock = credentials::lock()?;
    let api = Api::new();
    let mut requested_scopes = cumulative_scopes(&[], required_scope);
    if let Some(mut stored) = credentials::load(&credential_lock)? {
        requested_scopes = cumulative_scopes(stored.scopes(), required_scope);
        if ensure_session(&api, &credential_lock, &mut stored)?
            .is_some_and(|session| session.has_scope(required_scope))
        {
            return Ok(stored);
        }
        api.revoke(stored.refresh_token())?;
        credentials::clear(&credential_lock)?;
    }
    let mut stored = interactive_login(&api, &credential_lock, &requested_scopes)?;
    output::success("Authentication complete. You can close the browser tab.");
    let authorized = ensure_session(&api, &credential_lock, &mut stored)?
        .is_some_and(|session| session.has_scope(required_scope));
    if !authorized {
        api.revoke(stored.refresh_token())?;
        credentials::clear(&credential_lock)?;
        return Err("CLI authorization lacks the required permission".into());
    }
    Ok(stored)
}

fn interactive_login(
    api: &Api,
    credential_lock: &credentials::CredentialLock,
    scopes: &[&str],
) -> Result<Credentials, String> {
    let authorization = api.authorize(scopes)?;
    output::info("Authorize Shimpz in your browser.");
    output::detail("URL", &authorization.verification_url);
    output::detail("Code", &authorization.user_code);
    if open_browser(&authorization.verification_url) {
        output::info("Your default browser was opened automatically.");
    } else {
        output::warning("The browser could not be opened. Open the URL above.");
    }
    output::progress("Waiting for browser authorization...");
    let tokens = api.wait_for_tokens(&authorization)?;
    credentials::store(credential_lock, &tokens)?;
    Ok(tokens)
}

fn cumulative_scopes(existing: &[String], required: &str) -> Vec<&'static str> {
    AVAILABLE_SCOPES
        .into_iter()
        .filter(|scope| {
            *scope == IDENTITY_SCOPE
                || *scope == required
                || existing.iter().any(|current| current == scope)
        })
        .collect()
}

pub(crate) fn status() -> Result<String, String> {
    let credential_lock = credentials::lock()?;
    let Some(mut stored) = credentials::load(&credential_lock)? else {
        return Ok("Not authenticated. Run `shimpz auth`.".into());
    };
    let api = Api::new();
    let Some(session) = ensure_session(&api, &credential_lock, &mut stored)? else {
        return Ok("Authentication needs renewal. Run `shimpz auth`.".into());
    };
    Ok(format!(
        "Authenticated as {}.\nScopes: {}",
        session.account_id,
        session.scopes.join(", ")
    ))
}

pub(crate) fn logout() -> Result<String, String> {
    let credential_lock = credentials::lock()?;
    let Some(stored) = credentials::load(&credential_lock)? else {
        return Ok("Already logged out.".into());
    };
    Api::new().revoke(stored.refresh_token())?;
    credentials::clear(&credential_lock)?;
    Ok("Logged out and revoked the CLI session.".into())
}

struct Api {
    agent: Agent,
}

impl Api {
    fn new() -> Self {
        let config = Agent::config_builder()
            .timeout_global(Some(REQUEST_TIMEOUT))
            .max_redirects(0)
            .http_status_as_error(false)
            .build();
        Self {
            agent: config.into(),
        }
    }

    fn authorize(&self, scopes: &[&str]) -> Result<DeviceAuthorization, String> {
        let mut response = self
            .agent
            .post(AUTHORIZE_URL)
            .header("Accept", "application/json")
            .send_json(AuthorizationRequest { scopes })
            .map_err(|_| unavailable())?;
        if response.status().as_u16() != 200 {
            return Err(status_error(&mut response, "authorization could not start"));
        }
        let authorization: DeviceAuthorization = read_json(&mut response)?;
        authorization.validate()?;
        Ok(authorization)
    }

    fn wait_for_tokens(&self, authorization: &DeviceAuthorization) -> Result<Credentials, String> {
        let deadline = Instant::now()
            .checked_add(Duration::from_secs(authorization.expires_in))
            .ok_or_else(unavailable)?;
        while Instant::now() < deadline {
            let mut response = self
                .agent
                .post(DEVICE_TOKEN_URL)
                .header("Accept", "application/json")
                .send_json(DeviceTokenRequest {
                    device_code: authorization.device_code.expose(),
                })
                .map_err(|_| unavailable())?;
            match response.status().as_u16() {
                200 => return token_credentials(&mut response),
                400 | 429 => thread::sleep(POLL_INTERVAL),
                _ => {
                    return Err(status_error(
                        &mut response,
                        "browser authorization could not finish",
                    ));
                }
            }
        }
        Err("browser authorization expired; run `shimpz auth` again".into())
    }

    fn session(&self, access_token: &str) -> Result<Option<AuthSession>, String> {
        let authorization = Zeroizing::new(format!("Bearer {access_token}"));
        let mut response = self
            .agent
            .get(SESSION_URL)
            .header("Accept", "application/json")
            .header("Authorization", authorization.as_str())
            .call()
            .map_err(|_| unavailable())?;
        match response.status().as_u16() {
            200 => {
                let session: AuthSession = read_json(&mut response)?;
                session.validate()?;
                Ok(Some(session))
            }
            401 | 403 => Ok(None),
            _ => Err(status_error(
                &mut response,
                "CLI authentication could not be validated",
            )),
        }
    }

    fn refresh(&self, refresh_token: &str) -> Result<Option<Credentials>, String> {
        let request = RefreshTokenRequest { refresh_token };
        let mut response = self
            .agent
            .post(REFRESH_TOKEN_URL)
            .header("Accept", "application/json")
            .send_json(request)
            .map_err(|_| unavailable())?;
        match response.status().as_u16() {
            200 => token_credentials(&mut response).map(Some),
            400 | 403 => Ok(None),
            _ => Err(status_error(
                &mut response,
                "CLI credentials could not be refreshed",
            )),
        }
    }

    fn revoke(&self, refresh_token: &str) -> Result<(), String> {
        let authorization = Zeroizing::new(format!("Bearer {refresh_token}"));
        let mut response = self
            .agent
            .delete(SESSION_URL)
            .header("Accept", "application/json")
            .header("Authorization", authorization.as_str())
            .call()
            .map_err(|_| unavailable())?;
        match response.status().as_u16() {
            204 | 401 => Ok(()),
            _ => Err(status_error(
                &mut response,
                "CLI session could not be revoked",
            )),
        }
    }
}

fn ensure_session(
    api: &Api,
    credential_lock: &credentials::CredentialLock,
    credentials: &mut Credentials,
) -> Result<Option<AuthSession>, String> {
    if let Some(session) = api.session(credentials.access_token())? {
        return Ok(Some(session));
    }
    let Some(replacement) = api.refresh(credentials.refresh_token())? else {
        return Ok(None);
    };
    credentials::store(credential_lock, &replacement)?;
    *credentials = replacement;
    api.session(credentials.access_token())
}

fn token_credentials(response: &mut Response<Body>) -> Result<Credentials, String> {
    let tokens: TokenResponse = read_json(response)?;
    tokens.into_credentials()
}

fn read_json<T: DeserializeOwned>(response: &mut Response<Body>) -> Result<T, String> {
    if response
        .headers()
        .get("Content-Type")
        .and_then(|value| value.to_str().ok())
        != Some("application/json")
    {
        return Err("Developers returned an invalid response".into());
    }
    response
        .body_mut()
        .with_config()
        .limit(MAX_RESPONSE_BYTES)
        .read_json()
        .map_err(|_| "Developers returned an invalid response".into())
}

fn status_error(response: &mut Response<Body>, fallback: &'static str) -> String {
    read_json::<ErrorEnvelope>(response)
        .ok()
        .filter(|envelope| envelope.error.valid())
        .map_or_else(|| fallback.into(), |envelope| envelope.error.message)
}

fn valid_error_code(value: &str) -> bool {
    !value.is_empty()
        && value.len() <= 64
        && value
            .bytes()
            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
}

fn unavailable() -> String {
    "Developers is unavailable; try again shortly".into()
}

fn now_unix() -> Result<u64, String> {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_secs())
        .map_err(|_| unavailable())
}

fn open_browser(url: &str) -> bool {
    #[cfg(target_os = "windows")]
    let mut command = Command::new("cmd");
    #[cfg(target_os = "windows")]
    command.args(["/C", "start", "", url]);

    #[cfg(target_os = "macos")]
    let mut command = Command::new("open");
    #[cfg(target_os = "macos")]
    command.arg(url);

    #[cfg(all(unix, not(target_os = "macos")))]
    let mut command = Command::new("xdg-open");
    #[cfg(all(unix, not(target_os = "macos")))]
    command.arg(url);

    #[cfg(any(unix, target_os = "windows"))]
    return command.spawn().is_ok();

    #[cfg(not(any(unix, target_os = "windows")))]
    false
}

#[derive(Serialize)]
struct AuthorizationRequest<'a> {
    scopes: &'a [&'a str],
}

#[derive(Serialize)]
struct DeviceTokenRequest<'a> {
    device_code: &'a str,
}

#[derive(Serialize)]
struct RefreshTokenRequest<'a> {
    refresh_token: &'a str,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct DeviceAuthorization {
    flow_handle: String,
    device_code: SecretInput,
    user_code: String,
    verification_url: String,
    expires_in: u64,
}

impl DeviceAuthorization {
    fn validate(&self) -> Result<(), String> {
        let expected_url = format!("{ORIGIN}/cli/auth?flow={}", self.flow_handle);
        if !valid_handle(&self.flow_handle)
            || !valid_user_code(&self.user_code)
            || self.verification_url != expected_url
            || self.expires_in != 600
            || !valid_token(self.device_code.expose())
        {
            return Err("Developers returned an invalid authorization response".into());
        }
        Ok(())
    }
}

#[derive(Deserialize)]
#[serde(transparent)]
struct SecretInput(String);

impl SecretInput {
    fn expose(&self) -> &str {
        &self.0
    }

    fn into_string(mut self) -> String {
        std::mem::take(&mut self.0)
    }
}

impl Drop for SecretInput {
    fn drop(&mut self) {
        use zeroize::Zeroize as _;

        self.0.zeroize();
    }
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct TokenResponse {
    access_token: SecretInput,
    refresh_token: SecretInput,
    token_type: String,
    expires_in: u64,
    refresh_expires_in: u64,
    scopes: Vec<String>,
}

impl TokenResponse {
    fn into_credentials(self) -> Result<Credentials, String> {
        if self.token_type != "Bearer"
            || self.expires_in != 900
            || !(1..=2_592_000).contains(&self.refresh_expires_in)
        {
            return Err("Developers returned an invalid token response".into());
        }
        let now = now_unix()?;
        Credentials::new(
            self.access_token.into_string(),
            self.refresh_token.into_string(),
            now.checked_add(self.expires_in).ok_or_else(unavailable)?,
            now.checked_add(self.refresh_expires_in)
                .ok_or_else(unavailable)?,
            self.scopes,
        )
        .map_err(|_| "Developers returned an invalid token response".into())
    }
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct AuthSession {
    authenticated: bool,
    account_id: String,
    scopes: Vec<String>,
}

impl AuthSession {
    fn validate(&self) -> Result<(), String> {
        if !self.authenticated
            || self.account_id.len() != 32
            || !self
                .account_id
                .bytes()
                .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
            || self.scopes.is_empty()
            || self.scopes.len() > AVAILABLE_SCOPES.len()
            || self
                .scopes
                .iter()
                .any(|scope| !AVAILABLE_SCOPES.contains(&scope.as_str()))
        {
            return Err("Developers returned an invalid session response".into());
        }
        Ok(())
    }

    fn has_scope(&self, scope: &str) -> bool {
        self.scopes.iter().any(|value| value == scope)
    }
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ErrorEnvelope {
    error: ApiError,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ApiError {
    code: String,
    message: String,
    request_id: String,
}

impl ApiError {
    fn valid(&self) -> bool {
        valid_error_code(&self.code)
            && !self.message.is_empty()
            && self.message.len() <= 200
            && self
                .message
                .bytes()
                .all(|byte| byte.is_ascii() && !byte.is_ascii_control())
            && self.request_id.len() == 32
            && self
                .request_id
                .bytes()
                .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
    }
}

fn valid_handle(value: &str) -> bool {
    value.len() == 22 && base64url(value)
}

fn valid_token(value: &str) -> bool {
    value.len() == 43 && base64url(value)
}

fn base64url(value: &str) -> bool {
    value
        .bytes()
        .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
}

fn valid_user_code(value: &str) -> bool {
    value.len() == 9
        && value.bytes().enumerate().all(|(index, byte)| {
            if index == 4 {
                byte == b'-'
            } else {
                b"BCDFGHJKLMNPQRSTVWXZ".contains(&byte)
            }
        })
}

#[cfg(test)]
mod tests {
    use super::{
        AuthSession, DeviceAuthorization, SecretInput, TokenResponse, cumulative_scopes,
        valid_error_code, valid_user_code,
    };

    #[test]
    fn validates_only_the_production_browser_url() {
        let valid = DeviceAuthorization {
            flow_handle: "a".repeat(22),
            device_code: SecretInput("b".repeat(43)),
            user_code: "BCDF-GHJK".into(),
            verification_url: format!(
                "https://developers.shimpz.com/cli/auth?flow={}",
                "a".repeat(22)
            ),
            expires_in: 600,
        };

        assert!(valid.validate().is_ok());
    }

    #[test]
    fn requests_only_identity_and_cumulative_command_scopes() {
        assert_eq!(cumulative_scopes(&[], "identity:read"), ["identity:read"]);
        assert_eq!(
            cumulative_scopes(&[], "assistant:publish"),
            ["identity:read", "assistant:publish"]
        );
        assert_eq!(
            cumulative_scopes(
                &["identity:read".into(), "assistant:publish".into()],
                "assistant:install"
            ),
            ["identity:read", "assistant:publish", "assistant:install"]
        );
    }

    #[test]
    fn rejects_malformed_protocol_values() {
        assert!(valid_user_code("BCDF-GHJK"));
        assert!(!valid_user_code("ABCD-EFGH"));
        assert!(valid_error_code("step_up_required"));
        assert!(!valid_error_code("Step Up"));
        let invalid_session = AuthSession {
            authenticated: true,
            account_id: "A".repeat(32),
            scopes: vec!["identity:read".into()],
        };
        assert!(invalid_session.validate().is_err());
        let session = AuthSession {
            authenticated: true,
            account_id: "a".repeat(32),
            scopes: vec!["identity:read".into(), "assistant:publish".into()],
        };
        assert!(session.has_scope("assistant:publish"));
        assert!(!session.has_scope("assistant:install"));
    }

    #[test]
    fn rejects_inconsistent_token_lifetimes() {
        let response = TokenResponse {
            access_token: SecretInput("a".repeat(43)),
            refresh_token: SecretInput("b".repeat(43)),
            token_type: "Bearer".into(),
            expires_in: 899,
            refresh_expires_in: 2_592_000,
            scopes: vec!["identity:read".into()],
        };

        assert!(response.into_credentials().is_err());
    }
}