servicenow-cli 0.6.3

Fast, safe, human-friendly ServiceNow operations from the terminal
Documentation
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
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use oauth2::basic::BasicClient;
use oauth2::{
    AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken, PkceCodeChallenge, RedirectUrl,
    RefreshToken, Scope, TokenResponse, TokenUrl,
};
use reqwest::header::LOCATION;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;

use crate::api::{ApiError, normalize_instance};
use crate::config::{AuthType, Config, update_stored_credential};
use crate::credentials::StoredCredential;

const CALLBACK_TIMEOUT: Duration = Duration::from_secs(300);
const LOGIN_DISCOVERY_TIMEOUT: Duration = Duration::from_secs(5);
const MAX_LOGIN_REDIRECTS: usize = 6;

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum LoginProvider {
    MicrosoftEntra,
    ExternalSso(Option<String>),
    Undetermined,
}

/// Inspect an authenticated UI route without following a request to an external identity provider.
pub async fn discover_login_provider(instance: &str) -> Result<LoginProvider, ApiError> {
    let site_url = normalize_instance(instance)?;
    let origin = reqwest::Url::parse(&site_url)
        .map_err(|error| ApiError::InvalidInput(format!("invalid instance URL: {error}")))?;
    let mut url = origin
        .join("/nav_to.do?uri=incident_list.do")
        .map_err(|error| ApiError::InvalidInput(format!("invalid login URL: {error}")))?;
    let http = reqwest::Client::builder()
        .redirect(reqwest::redirect::Policy::none())
        .timeout(LOGIN_DISCOVERY_TIMEOUT)
        .build()?;

    for _ in 0..MAX_LOGIN_REDIRECTS {
        let response = http
            .get(url.clone())
            .header(reqwest::header::ACCEPT, "text/html,application/xhtml+xml")
            .send()
            .await?;
        if response.status().is_redirection() {
            let location = response
                .headers()
                .get(LOCATION)
                .ok_or_else(|| ApiError::Other("login redirect omitted its location".into()))?
                .to_str()
                .map_err(|_| ApiError::Other("login redirect was not valid text".into()))?;
            let location_lower = location.to_ascii_lowercase();
            if contains_microsoft_login(&location_lower) {
                return Ok(LoginProvider::MicrosoftEntra);
            }
            let next = url
                .join(location)
                .map_err(|error| ApiError::Other(format!("invalid login redirect: {error}")))?;
            if !same_origin(&origin, &next) {
                return Ok(external_provider(&next));
            }
            if is_sso_route(&next) {
                return Ok(LoginProvider::ExternalSso(None));
            }
            url = next;
            continue;
        }
        if !response.status().is_success() {
            return Err(ApiError::Other(format!(
                "login discovery returned HTTP {}",
                response.status()
            )));
        }
        let body = response.text().await?.to_ascii_lowercase();
        if contains_microsoft_login(&body) {
            return Ok(LoginProvider::MicrosoftEntra);
        }
        if [
            "login_with_sso.do",
            "glide_sso_id",
            "external_login_complete.do",
            "multi_sso",
        ]
        .iter()
        .any(|marker| body.contains(marker))
        {
            return Ok(LoginProvider::ExternalSso(None));
        }
        return Ok(LoginProvider::Undetermined);
    }

    Err(ApiError::Other(
        "login discovery exceeded the redirect limit".into(),
    ))
}

fn is_sso_route(url: &reqwest::Url) -> bool {
    matches!(
        url.path().to_ascii_lowercase().as_str(),
        "/auth_redirect.do" | "/login_with_sso.do" | "/external_login_complete.do"
    )
}

fn same_origin(left: &reqwest::Url, right: &reqwest::Url) -> bool {
    left.scheme() == right.scheme()
        && left.host_str() == right.host_str()
        && left.port_or_known_default() == right.port_or_known_default()
}

fn external_provider(url: &reqwest::Url) -> LoginProvider {
    let host = url.host_str().map(str::to_ascii_lowercase);
    if host.as_deref().is_some_and(is_microsoft_login_host) {
        LoginProvider::MicrosoftEntra
    } else {
        LoginProvider::ExternalSso(host)
    }
}

fn is_microsoft_login_host(host: &str) -> bool {
    matches!(host, "login.microsoft.com" | "login.windows.net")
        || host == "login.microsoftonline.com"
        || host.ends_with(".microsoftonline.com")
}

fn contains_microsoft_login(body: &str) -> bool {
    [
        "login.microsoftonline.com",
        "login.microsoft.com",
        "login.windows.net",
    ]
    .iter()
    .any(|host| body.contains(host))
}

pub async fn oauth_login(
    instance: &str,
    client_id: &str,
    client_secret: Option<String>,
    scope: Option<&str>,
    redirect_uri: &str,
    open_browser: bool,
) -> Result<StoredCredential, ApiError> {
    let site_url = normalize_instance(instance)?;
    let redirect = reqwest::Url::parse(redirect_uri)
        .map_err(|error| ApiError::InvalidInput(format!("invalid OAuth redirect URI: {error}")))?;
    if redirect.scheme() != "http"
        || !matches!(redirect.host_str(), Some("127.0.0.1" | "localhost"))
        || redirect.port().is_none()
    {
        return Err(ApiError::InvalidInput(
            "OAuth redirect URI must use http://127.0.0.1:<port>/path or localhost".into(),
        ));
    }
    let port = redirect.port().expect("validated redirect port");
    let listener = TcpListener::bind(("127.0.0.1", port))
        .await
        .map_err(|error| {
            ApiError::Other(format!(
                "failed to listen for OAuth callback on port {port}: {error}"
            ))
        })?;

    let client = oauth_client(&site_url, client_id, client_secret.as_deref(), redirect_uri)?;
    let (challenge, verifier) = PkceCodeChallenge::new_random_sha256();
    let mut authorization = client
        .authorize_url(CsrfToken::new_random)
        .set_pkce_challenge(challenge);
    if let Some(scope) = scope.filter(|value| !value.trim().is_empty()) {
        for value in scope.split_whitespace() {
            authorization = authorization.add_scope(Scope::new(value.into()));
        }
    }
    let (authorization_url, csrf) = authorization.url();

    eprintln!("Authorize this CLI in your browser:\n\n  {authorization_url}\n");
    if open_browser && let Err(error) = open::that(authorization_url.as_str()) {
        eprintln!("Could not open the browser automatically: {error}");
    }

    let (code, returned_state) = tokio::time::timeout(
        CALLBACK_TIMEOUT,
        receive_callback(listener, redirect.path()),
    )
    .await
    .map_err(|_| ApiError::Auth("OAuth authorization timed out after five minutes".into()))??;
    if returned_state != csrf.secret().as_str() {
        return Err(ApiError::Auth(
            "OAuth state mismatch; authorization was rejected for safety".into(),
        ));
    }

    let http = oauth2::reqwest::ClientBuilder::new()
        .redirect(oauth2::reqwest::redirect::Policy::none())
        .build()
        .map_err(|error| ApiError::Other(format!("failed to build OAuth client: {error}")))?;
    let token = client
        .exchange_code(AuthorizationCode::new(code))
        .set_pkce_verifier(verifier)
        .request_async(&http)
        .await
        .map_err(|error| ApiError::Auth(format!("OAuth token exchange failed: {error}")))?;
    Ok(StoredCredential::OAuth {
        access_token: token.access_token().secret().into(),
        refresh_token: token.refresh_token().map(|value| value.secret().into()),
        expires_at: token.expires_in().map(expires_at),
        client_secret,
    })
}

pub async fn refresh_if_needed(config: &mut Config) -> Result<bool, ApiError> {
    if !matches!(config.auth_type, AuthType::OAuth) || !config.uses_persistent_store() {
        return Ok(false);
    }
    let Some(session) = config.oauth.clone() else {
        return Ok(false);
    };
    if session
        .expires_at
        .is_none_or(|expiry| expiry > epoch_seconds().saturating_add(60))
    {
        return Ok(false);
    }
    let Some(refresh_token) = session.refresh_token else {
        return Err(ApiError::Auth(
            "OAuth token expired and no refresh token is available; run `servicenow auth login`"
                .into(),
        ));
    };
    let client_id = config.client_id.as_deref().ok_or_else(|| {
        ApiError::InvalidInput("OAuth profile is missing client_id; log in again".into())
    })?;
    let redirect_uri = config
        .redirect_uri
        .as_deref()
        .unwrap_or("http://127.0.0.1:8484/callback");
    let site_url = normalize_instance(&config.instance)?;
    let client = oauth_client(
        &site_url,
        client_id,
        session.client_secret.as_deref(),
        redirect_uri,
    )?;
    let http = oauth2::reqwest::ClientBuilder::new()
        .redirect(oauth2::reqwest::redirect::Policy::none())
        .build()
        .map_err(|error| ApiError::Other(format!("failed to build OAuth client: {error}")))?;
    let token = client
        .exchange_refresh_token(&RefreshToken::new(refresh_token.clone()))
        .request_async(&http)
        .await
        .map_err(|error| ApiError::Auth(format!("OAuth refresh failed: {error}")))?;
    let access_token = token.access_token().secret().to_string();
    let new_refresh = token
        .refresh_token()
        .map(|value| value.secret().to_string())
        .or(Some(refresh_token));
    let new_expiry = token.expires_in().map(expires_at);
    update_stored_credential(
        &config.profile,
        StoredCredential::OAuth {
            access_token: access_token.clone(),
            refresh_token: new_refresh.clone(),
            expires_at: new_expiry,
            client_secret: session.client_secret.clone(),
        },
    )?;
    config.secret = access_token;
    config.oauth = Some(crate::config::OAuthSession {
        refresh_token: new_refresh,
        expires_at: new_expiry,
        client_secret: session.client_secret,
    });
    Ok(true)
}

fn oauth_client(
    site_url: &str,
    client_id: &str,
    client_secret: Option<&str>,
    redirect_uri: &str,
) -> Result<
    BasicClient<
        oauth2::EndpointSet,
        oauth2::EndpointNotSet,
        oauth2::EndpointNotSet,
        oauth2::EndpointNotSet,
        oauth2::EndpointSet,
    >,
    ApiError,
> {
    let mut client = BasicClient::new(ClientId::new(client_id.into()))
        .set_auth_uri(
            AuthUrl::new(format!("{site_url}/oauth_auth.do"))
                .map_err(|error| ApiError::InvalidInput(format!("invalid OAuth URL: {error}")))?,
        )
        .set_token_uri(
            TokenUrl::new(format!("{site_url}/oauth_token.do"))
                .map_err(|error| ApiError::InvalidInput(format!("invalid token URL: {error}")))?,
        )
        .set_redirect_uri(RedirectUrl::new(redirect_uri.into()).map_err(|error| {
            ApiError::InvalidInput(format!("invalid OAuth redirect URI: {error}"))
        })?);
    if let Some(secret) = client_secret.filter(|value| !value.is_empty()) {
        client = client.set_client_secret(ClientSecret::new(secret.into()));
    }
    Ok(client)
}

async fn receive_callback(
    listener: TcpListener,
    expected_path: &str,
) -> Result<(String, String), ApiError> {
    let (mut stream, _) = listener
        .accept()
        .await
        .map_err(|error| ApiError::Other(format!("OAuth callback failed: {error}")))?;
    let mut buffer = vec![0_u8; 16 * 1024];
    let count = stream
        .read(&mut buffer)
        .await
        .map_err(|error| ApiError::Other(format!("failed to read OAuth callback: {error}")))?;
    let request = String::from_utf8_lossy(&buffer[..count]);
    let target = request
        .lines()
        .next()
        .and_then(|line| line.split_whitespace().nth(1))
        .ok_or_else(|| ApiError::Auth("invalid OAuth callback request".into()))?;
    let callback = reqwest::Url::parse(&format!("http://127.0.0.1{target}"))
        .map_err(|error| ApiError::Auth(format!("invalid OAuth callback: {error}")))?;
    if callback.path() != expected_path {
        return Err(ApiError::Auth("OAuth callback path did not match".into()));
    }
    let params: std::collections::HashMap<_, _> = callback.query_pairs().into_owned().collect();
    let result = if let Some(error) = params.get("error") {
        Err(ApiError::Auth(format!(
            "OAuth authorization was denied: {}",
            params.get("error_description").unwrap_or(error)
        )))
    } else {
        let code = params
            .get("code")
            .cloned()
            .ok_or_else(|| ApiError::Auth("OAuth callback omitted code".into()))?;
        let state = params
            .get("state")
            .cloned()
            .ok_or_else(|| ApiError::Auth("OAuth callback omitted state".into()))?;
        Ok((code, state))
    };
    let (status, message) = if result.is_ok() {
        ("200 OK", "Authorization complete. You can close this tab.")
    } else {
        (
            "400 Bad Request",
            "Authorization failed. Return to your terminal.",
        )
    };
    let body = format!(
        "<!doctype html><meta charset=utf-8><title>ServiceNow CLI</title><style>body{{font:18px system-ui;max-width:42rem;margin:15vh auto;padding:2rem;color:#172b4d}}strong{{color:#2e844a}}</style><strong>{message}</strong>"
    );
    let response = format!(
        "HTTP/1.1 {status}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
        body.len()
    );
    let _ = stream.write_all(response.as_bytes()).await;
    result
}

fn expires_at(duration: Duration) -> u64 {
    epoch_seconds().saturating_add(duration.as_secs())
}

fn epoch_seconds() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

#[cfg(test)]
mod tests {
    use super::*;
    use wiremock::matchers::{method, path, query_param};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[tokio::test]
    async fn detects_microsoft_entra_redirect_without_following_it() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/nav_to.do"))
            .and(query_param("uri", "incident_list.do"))
            .respond_with(ResponseTemplate::new(302).insert_header(
                "location",
                "https://login.microsoftonline.com/example/oauth2/v2.0/authorize",
            ))
            .expect(1)
            .mount(&server)
            .await;

        assert_eq!(
            discover_login_provider(&server.uri()).await.unwrap(),
            LoginProvider::MicrosoftEntra
        );
    }

    #[tokio::test]
    async fn follows_only_same_origin_login_redirects() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/nav_to.do"))
            .and(query_param("uri", "incident_list.do"))
            .respond_with(ResponseTemplate::new(302).insert_header("location", "/sso/start"))
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/sso/start"))
            .respond_with(
                ResponseTemplate::new(302)
                    .insert_header("location", "https://id.example.com/sign-in"),
            )
            .expect(1)
            .mount(&server)
            .await;

        assert_eq!(
            discover_login_provider(&server.uri()).await.unwrap(),
            LoginProvider::ExternalSso(Some("id.example.com".into()))
        );
    }

    #[tokio::test]
    async fn detects_sso_markers_in_the_login_page() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/nav_to.do"))
            .and(query_param("uri", "incident_list.do"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string(r#"<a href="login_with_sso.do">Use SSO</a>"#),
            )
            .mount(&server)
            .await;

        assert_eq!(
            discover_login_provider(&server.uri()).await.unwrap(),
            LoginProvider::ExternalSso(None)
        );
    }

    #[tokio::test]
    async fn detects_microsoft_entra_inside_a_same_origin_auth_redirect() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/nav_to.do"))
            .and(query_param("uri", "incident_list.do"))
            .respond_with(ResponseTemplate::new(302).insert_header(
                "location",
                "/auth_redirect.do?sysparm_stack=no&sysparm_url=https%3A%2F%2Flogin.microsoftonline.com%2Ftenant-guid%2Fsaml2%3FSAMLRequest%3Dexample",
            ))
            .expect(1)
            .mount(&server)
            .await;

        assert_eq!(
            discover_login_provider(&server.uri()).await.unwrap(),
            LoginProvider::MicrosoftEntra
        );
    }

    #[tokio::test]
    async fn local_login_form_does_not_prove_basic_authentication() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/nav_to.do"))
            .and(query_param("uri", "incident_list.do"))
            .respond_with(ResponseTemplate::new(302).insert_header("location", "/login.do"))
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/login.do"))
            .respond_with(ResponseTemplate::new(200).set_body_string("<form>Password</form>"))
            .expect(1)
            .mount(&server)
            .await;

        assert_eq!(
            discover_login_provider(&server.uri()).await.unwrap(),
            LoginProvider::Undetermined
        );
    }

    #[tokio::test]
    async fn rejects_non_loopback_oauth_redirects() {
        let error = oauth_login(
            "dev12345",
            "client",
            None,
            None,
            "https://example.com/callback",
            false,
        )
        .await
        .unwrap_err();
        assert!(matches!(error, ApiError::InvalidInput(_)));
    }
}