pipedash-core 0.9.0

Framework-agnostic core library for Pipedash
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
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
pub(crate) mod loopback;

use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use chrono::{
    DateTime,
    Duration,
    Utc,
};
use pipedash_plugin_api::{
    from_status,
    map_send_error,
    redact_url,
    truncate_chars,
    SignInClient,
    SignInRefreshRejection,
    SignInToken,
};
use reqwest::Url;
use serde::Deserialize;
use serde_json::{
    Map,
    Value,
};
use sha2::{
    Digest,
    Sha256,
};

use crate::domain::{
    DomainError,
    DomainResult,
    SignInCredential,
    SIGN_IN_EXPIRED,
};
use crate::infrastructure::providers::PluginAdapter;

const OFFLINE_ACCESS: &str = "offline_access";
const ACCOUNT_CLAIMS: [&str; 4] = ["email", "preferred_username", "name", "sub"];
const EXPIRED_GRANT_ERRORS: [&str; 3] = ["invalid_grant", "invalid_client", "unauthorized_client"];
const BODY_PREVIEW_CHARS: usize = 300;

#[derive(Debug, Clone)]
pub(crate) struct Endpoints {
    pub authorization: Url,
    pub token: Url,
    pub scopes_supported: Option<Vec<String>>,
}

#[derive(Deserialize)]
struct Discovery {
    authorization_endpoint: Url,
    token_endpoint: Url,
    #[serde(default)]
    scopes_supported: Option<Vec<String>>,
}

pub(crate) struct Authorization {
    pub url: Url,
    pub state: String,
    pub verifier: String,
}

#[derive(Debug, Default)]
pub(crate) struct Callback {
    pub code: Option<String>,
    pub state: Option<String>,
    pub error: Option<String>,
    pub error_description: Option<String>,
}

impl Callback {
    pub(crate) fn from_url(url: &Url) -> Self {
        let mut callback = Self::default();
        for (key, value) in url.query_pairs() {
            let slot = match key.as_ref() {
                "code" => &mut callback.code,
                "state" => &mut callback.state,
                "error" => &mut callback.error,
                "error_description" => &mut callback.error_description,
                _ => continue,
            };
            *slot = Some(value.into_owned());
        }
        callback
    }
}

#[derive(Deserialize)]
struct TokenResponse {
    access_token: String,
    #[serde(default)]
    id_token: Option<String>,
    #[serde(default)]
    refresh_token: Option<String>,
    #[serde(default)]
    expires_in: Option<i64>,
}

#[derive(Deserialize)]
struct OAuthError {
    error: String,
    #[serde(default)]
    error_description: Option<String>,
}

#[derive(Clone, Copy)]
enum Grant {
    Exchange,
    Refresh,
}

pub(crate) fn random_id<const N: usize>() -> String {
    URL_SAFE_NO_PAD.encode(rand::random::<[u8; N]>())
}

fn parse_url(raw: &str) -> DomainResult<Url> {
    Url::parse(raw)
        .map_err(|e| DomainError::InvalidConfig(format!("Invalid sign-in URL {raw}: {e}")))
}

fn send_error(err: reqwest::Error, url: &Url) -> DomainError {
    PluginAdapter::map_error(map_send_error(err, url))
}

fn web_endpoint(url: Url) -> DomainResult<Url> {
    if matches!(url.scheme(), "http" | "https") {
        Ok(url)
    } else {
        Err(DomainError::InvalidConfig(format!(
            "The sign-in server returned an address that isn't a web page: {}",
            redact_url(&url)
        )))
    }
}

pub(crate) async fn discover(http: &reqwest::Client, issuer: &str) -> DomainResult<Endpoints> {
    let url = parse_url(&format!(
        "{}/.well-known/openid-configuration",
        issuer.trim_end_matches('/')
    ))?;
    let response = http
        .get(url.clone())
        .send()
        .await
        .map_err(|e| send_error(e, &url))?;
    let status = response.status();
    if !status.is_success() {
        return Err(DomainError::InvalidConfig(format!(
            "Couldn't read the sign-in settings from {} ({status})",
            redact_url(&url)
        )));
    }
    let discovery: Discovery = response.json().await.map_err(|e| {
        DomainError::ApiError(format!(
            "The sign-in server at {} returned invalid settings: {}",
            redact_url(&url),
            e.without_url()
        ))
    })?;
    Ok(Endpoints {
        authorization: web_endpoint(discovery.authorization_endpoint)?,
        token: web_endpoint(discovery.token_endpoint)?,
        scopes_supported: discovery.scopes_supported,
    })
}

pub(crate) fn authorize(client: &SignInClient, endpoints: &Endpoints) -> Authorization {
    let verifier = random_id::<32>();
    let state = random_id::<32>();
    let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()));

    let mut scopes = client.scopes.clone();
    let offline_supported = endpoints
        .scopes_supported
        .as_ref()
        .is_none_or(|supported| supported.iter().any(|scope| scope == OFFLINE_ACCESS));
    if offline_supported && !scopes.iter().any(|scope| scope == OFFLINE_ACCESS) {
        scopes.push(OFFLINE_ACCESS.to_string());
    }

    let mut url = endpoints.authorization.clone();
    url.query_pairs_mut()
        .append_pair("response_type", "code")
        .append_pair("client_id", &client.client_id)
        .append_pair("redirect_uri", &client.redirect_uri)
        .append_pair("scope", &scopes.join(" "))
        .append_pair("state", &state)
        .append_pair("code_challenge", &challenge)
        .append_pair("code_challenge_method", "S256")
        .extend_pairs(
            client
                .authorize_params
                .iter()
                .map(|(key, value)| (key.as_str(), value.as_str())),
        );

    Authorization {
        url,
        state,
        verifier,
    }
}

pub(crate) async fn exchange(
    http: &reqwest::Client, token_endpoint: &Url, client: &SignInClient, code: &str, verifier: &str,
) -> DomainResult<SignInCredential> {
    let form = [
        ("grant_type", "authorization_code"),
        ("code", code),
        ("redirect_uri", client.redirect_uri.as_str()),
        ("client_id", client.client_id.as_str()),
        ("code_verifier", verifier),
    ];
    let response = request_token(http, token_endpoint, &form, Grant::Exchange, &[]).await?;
    credential(
        response,
        client.token,
        token_endpoint,
        &client.client_id,
        None,
    )
}

pub(crate) async fn refresh(
    http: &reqwest::Client, current: &SignInCredential, rejections: &[SignInRefreshRejection],
) -> DomainResult<SignInCredential> {
    let refresh_token = current
        .refresh_token
        .as_deref()
        .ok_or_else(|| DomainError::ProviderAuthenticationFailed(SIGN_IN_EXPIRED.into()))?;
    let token_endpoint = parse_url(&current.token_endpoint)?;
    let form = [
        ("grant_type", "refresh_token"),
        ("refresh_token", refresh_token),
        ("client_id", current.client_id.as_str()),
    ];
    let response = request_token(http, &token_endpoint, &form, Grant::Refresh, rejections).await?;
    credential(
        response,
        current.kind,
        &token_endpoint,
        &current.client_id,
        Some(current),
    )
}

async fn request_token(
    http: &reqwest::Client, endpoint: &Url, form: &[(&str, &str)], grant: Grant,
    rejections: &[SignInRefreshRejection],
) -> DomainResult<TokenResponse> {
    let response = http
        .post(endpoint.clone())
        .form(form)
        .send()
        .await
        .map_err(|e| send_error(e, endpoint))?;
    let status = response.status();
    let body = response.text().await.map_err(|e| send_error(e, endpoint))?;

    if status.is_success() {
        return serde_json::from_str(&body).map_err(|e| {
            DomainError::ApiError(format!(
                "The sign-in server returned an invalid token response: {e}"
            ))
        });
    }

    if let Ok(error) = serde_json::from_str::<OAuthError>(&body) {
        match grant {
            Grant::Refresh
                if EXPIRED_GRANT_ERRORS.contains(&error.error.as_str())
                    || rejections.iter().any(|rejection| {
                        rejection.status == status.as_u16()
                            && rejection.error == error.error
                            && Some(rejection.description) == error.error_description.as_deref()
                    }) =>
            {
                return Err(DomainError::ProviderAuthenticationFailed(
                    SIGN_IN_EXPIRED.into(),
                ));
            }
            Grant::Exchange => {
                return Err(DomainError::ProviderAuthenticationFailed(
                    error.error_description.unwrap_or(error.error),
                ));
            }
            Grant::Refresh => {}
        }
    }

    let message = format!(
        "{} from {}: {}",
        status.as_u16(),
        redact_url(endpoint),
        truncate_chars(body.trim(), BODY_PREVIEW_CHARS)
    );
    Err(PluginAdapter::map_error(from_status(
        status.as_u16(),
        message,
        None,
    )))
}

fn credential(
    response: TokenResponse, kind: SignInToken, token_endpoint: &Url, client_id: &str,
    previous: Option<&SignInCredential>,
) -> DomainResult<SignInCredential> {
    let token = match kind {
        SignInToken::IdToken => response.id_token.clone().ok_or_else(|| {
            DomainError::ProviderAuthenticationFailed(
                "The sign-in server didn't return an ID token".into(),
            )
        })?,
        SignInToken::AccessToken => response.access_token,
    };
    let expires_at = jwt_claims(&token)
        .and_then(|claims| claims.get("exp")?.as_i64())
        .and_then(|exp| DateTime::from_timestamp(exp, 0))
        .or_else(|| {
            response
                .expires_in
                .map(|seconds| Utc::now() + Duration::seconds(seconds))
        });
    let account = response
        .id_token
        .as_deref()
        .and_then(jwt_claims)
        .and_then(|claims| account_of(&claims))
        .or_else(|| previous.and_then(|p| p.account.clone()));
    let refresh_token = response
        .refresh_token
        .or_else(|| previous.and_then(|p| p.refresh_token.clone()));

    Ok(SignInCredential {
        token,
        refresh_token,
        expires_at,
        token_endpoint: token_endpoint.to_string(),
        client_id: client_id.to_string(),
        kind,
        account,
    })
}

fn jwt_claims(token: &str) -> Option<Map<String, Value>> {
    let payload = token.split('.').nth(1)?;
    let bytes = URL_SAFE_NO_PAD.decode(payload.trim_end_matches('=')).ok()?;
    serde_json::from_slice(&bytes).ok()
}

fn account_of(claims: &Map<String, Value>) -> Option<String> {
    ACCOUNT_CLAIMS.iter().find_map(|key| {
        claims
            .get(*key)?
            .as_str()
            .filter(|value| !value.is_empty())
            .map(str::to_string)
    })
}

#[cfg(test)]
pub(crate) mod test_idp {
    use std::sync::{
        Arc,
        Mutex,
    };

    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
    use base64::Engine as _;
    use serde_json::{
        json,
        Value,
    };
    use tokio::io::{
        AsyncReadExt,
        AsyncWriteExt,
    };

    pub(crate) fn jwt(claims: Value) -> String {
        format!(
            "{}.{}.sig",
            URL_SAFE_NO_PAD.encode(br#"{"alg":"none"}"#),
            URL_SAFE_NO_PAD.encode(claims.to_string())
        )
    }

    #[derive(Clone)]
    pub(crate) struct Idp {
        pub base_url: String,
        pub forms: Arc<Mutex<Vec<String>>>,
        reply: Arc<Mutex<(u16, String)>>,
    }

    impl Idp {
        pub(crate) async fn start() -> Self {
            let _ = rustls::crypto::ring::default_provider().install_default();
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
            let base_url = format!("http://{}", listener.local_addr().unwrap());
            let idp = Self {
                base_url: base_url.clone(),
                forms: Arc::default(),
                reply: Arc::new(Mutex::new((200, "{}".into()))),
            };
            let server = idp.clone();
            tokio::spawn(async move {
                while let Ok((mut stream, _)) = listener.accept().await {
                    let server = server.clone();
                    tokio::spawn(async move {
                        let (target, body) = read_request(&mut stream).await;
                        let (status, reply) =
                            if target.ends_with("/.well-known/openid-configuration") {
                                (
                                200,
                                json!({
                                    "authorization_endpoint": format!("{}/auth", server.base_url),
                                    "token_endpoint": format!("{}/token", server.base_url),
                                    "scopes_supported": ["openid", "email", "offline_access"],
                                })
                                .to_string(),
                            )
                            } else {
                                server.forms.lock().unwrap().push(body);
                                server.reply.lock().unwrap().clone()
                            };
                        let response = format!(
                            "HTTP/1.1 {status} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}",
                            reply.len()
                        );
                        let _ = stream.write_all(response.as_bytes()).await;
                    });
                }
            });
            idp
        }

        pub(crate) fn token_endpoint(&self) -> String {
            format!("{}/token", self.base_url)
        }

        pub(crate) fn reply(&self, status: u16, body: Value) {
            *self.reply.lock().unwrap() = (status, body.to_string());
        }
    }

    async fn read_request(stream: &mut tokio::net::TcpStream) -> (String, String) {
        let mut data = Vec::new();
        let mut buffer = [0; 4096];
        loop {
            if let Some(end) = data.windows(4).position(|w| w == b"\r\n\r\n") {
                let head = String::from_utf8_lossy(&data[..end]).to_string();
                let length = head
                    .lines()
                    .find_map(|line| {
                        let (name, value) = line.split_once(':')?;
                        name.eq_ignore_ascii_case("content-length")
                            .then(|| value.trim().parse::<usize>().ok())?
                    })
                    .unwrap_or(0);
                if data.len() >= end + 4 + length {
                    let target = head.split_whitespace().nth(1).unwrap_or("/").to_string();
                    let body = String::from_utf8_lossy(&data[end + 4..end + 4 + length]);
                    return (target, body.to_string());
                }
            }
            match stream.read(&mut buffer).await {
                Ok(0) | Err(_) => return (String::new(), String::new()),
                Ok(n) => data.extend_from_slice(&buffer[..n]),
            }
        }
    }
}

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

    use super::test_idp::{
        jwt,
        Idp,
    };
    use super::*;

    fn client(token: SignInToken) -> SignInClient {
        SignInClient {
            label: "Dex".into(),
            issuer: "https://idp.example.com".into(),
            client_id: "argo-cd-cli".into(),
            scopes: vec!["openid".into(), "email".into()],
            redirect_uri: "http://localhost:8085/auth/callback".into(),
            authorize_params: vec![("connector_id".into(), "github".into())],
            token,
        }
    }

    fn endpoints(scopes_supported: Option<Vec<String>>) -> Endpoints {
        Endpoints {
            authorization: Url::parse("https://idp.example.com/auth").unwrap(),
            token: Url::parse("https://idp.example.com/token").unwrap(),
            scopes_supported,
        }
    }

    fn query(url: &Url) -> Vec<(String, String)> {
        url.query_pairs()
            .map(|(k, v)| (k.into_owned(), v.into_owned()))
            .collect()
    }

    #[test]
    fn authorize_uses_pkce_s256_and_requests_offline_access_once() {
        let authorization = authorize(&client(SignInToken::IdToken), &endpoints(None));
        let pairs = query(&authorization.url);
        let get = |key: &str| {
            pairs
                .iter()
                .find(|(k, _)| k == key)
                .map(|(_, v)| v.clone())
                .unwrap()
        };

        assert_eq!(get("response_type"), "code");
        assert_eq!(get("scope"), "openid email offline_access");
        assert_eq!(get("state"), authorization.state);
        assert_eq!(get("code_challenge_method"), "S256");
        assert_eq!(
            get("code_challenge"),
            URL_SAFE_NO_PAD.encode(Sha256::digest(authorization.verifier.as_bytes()))
        );
        assert_eq!(
            pairs.last().unwrap(),
            &("connector_id".into(), "github".into())
        );

        let mut with_offline = client(SignInToken::IdToken);
        with_offline.scopes.push(OFFLINE_ACCESS.into());
        let again = authorize(&with_offline, &endpoints(None));
        assert_eq!(
            query(&again.url)
                .iter()
                .find(|(k, _)| k == "scope")
                .unwrap()
                .1,
            "openid email offline_access"
        );
        let unsupported = authorize(
            &client(SignInToken::IdToken),
            &endpoints(Some(vec!["openid".into()])),
        );
        assert!(!unsupported.url.as_str().contains(OFFLINE_ACCESS));
    }

    #[tokio::test]
    async fn exchange_posts_verifier_and_reads_id_token() {
        let idp = Idp::start().await;
        let id_token = jwt(json!({"exp": 1_900_000_000, "email": "dev@example.com", "sub": "1"}));
        idp.reply(
            200,
            json!({"access_token": "opaque", "id_token": id_token, "refresh_token": "r1", "expires_in": 60}),
        );
        let endpoint = Url::parse(&idp.token_endpoint()).unwrap();

        let credential = exchange(
            &reqwest::Client::new(),
            &endpoint,
            &client(SignInToken::IdToken),
            "the-code",
            "the-verifier",
        )
        .await
        .unwrap();

        assert_eq!(credential.token, id_token);
        assert_eq!(credential.refresh_token.as_deref(), Some("r1"));
        assert_eq!(credential.account.as_deref(), Some("dev@example.com"));
        assert_eq!(
            credential.expires_at,
            DateTime::from_timestamp(1_900_000_000, 0)
        );
        let form = idp.forms.lock().unwrap()[0].clone();
        assert!(form.contains("grant_type=authorization_code"));
        assert!(form.contains("code=the-code"));
        assert!(form.contains("code_verifier=the-verifier"));
        assert!(form.contains("redirect_uri=http%3A%2F%2Flocalhost%3A8085%2Fauth%2Fcallback"));
    }

    #[tokio::test]
    async fn exchange_reports_the_identity_provider_error() {
        let idp = Idp::start().await;
        idp.reply(
            400,
            json!({"error": "invalid_request", "error_description": "Bad code"}),
        );
        let endpoint = Url::parse(&idp.token_endpoint()).unwrap();

        let error = exchange(
            &reqwest::Client::new(),
            &endpoint,
            &client(SignInToken::IdToken),
            "c",
            "v",
        )
        .await
        .unwrap_err();

        assert!(matches!(error, DomainError::ProviderAuthenticationFailed(m) if m == "Bad code"));
    }

    fn stored(idp: &Idp) -> SignInCredential {
        SignInCredential {
            token: "old".into(),
            refresh_token: Some("r1".into()),
            expires_at: None,
            token_endpoint: idp.token_endpoint(),
            client_id: "cli".into(),
            kind: SignInToken::AccessToken,
            account: Some("dev@example.com".into()),
        }
    }

    #[tokio::test]
    async fn refresh_keeps_previous_refresh_token_and_account() {
        let idp = Idp::start().await;
        idp.reply(200, json!({"access_token": "new", "expires_in": 3600}));

        let renewed = refresh(&reqwest::Client::new(), &stored(&idp), &[])
            .await
            .unwrap();

        assert_eq!(renewed.token, "new");
        assert_eq!(renewed.refresh_token.as_deref(), Some("r1"));
        assert_eq!(renewed.account.as_deref(), Some("dev@example.com"));
        assert!(renewed.expires_at.unwrap() > Utc::now() + Duration::minutes(59));
        let form = idp.forms.lock().unwrap()[0].clone();
        assert!(form.contains("grant_type=refresh_token"));
        assert!(form.contains("refresh_token=r1"));
    }

    #[tokio::test]
    async fn refresh_with_revoked_grant_asks_to_sign_in_again() {
        let idp = Idp::start().await;
        idp.reply(400, json!({"error": "invalid_grant"}));

        let error = refresh(&reqwest::Client::new(), &stored(&idp), &[])
            .await
            .unwrap_err();

        assert!(
            matches!(error, DomainError::ProviderAuthenticationFailed(m) if m == SIGN_IN_EXPIRED)
        );
    }

    #[tokio::test]
    async fn refresh_server_error_stays_transient() {
        let idp = Idp::start().await;
        idp.reply(503, json!({"error": "temporarily_unavailable"}));

        let error = refresh(&reqwest::Client::new(), &stored(&idp), &[])
            .await
            .unwrap_err();

        assert!(matches!(error, DomainError::ServiceUnavailable { .. }));
    }

    #[test]
    fn sign_in_endpoints_must_be_web_addresses() {
        for allowed in [
            "https://idp.example.com/auth",
            "http://localhost:5556/dex/auth",
        ] {
            assert!(web_endpoint(Url::parse(allowed).unwrap()).is_ok());
        }
        for rejected in [
            "javascript:alert(1)",
            "file:///etc/passwd",
            "pipedash://open",
        ] {
            assert!(matches!(
                web_endpoint(Url::parse(rejected).unwrap()),
                Err(DomainError::InvalidConfig(_))
            ));
        }
    }

    #[test]
    fn callback_reads_query_pairs() {
        let callback = Callback::from_url(
            &Url::parse("http://localhost:8085/auth/callback?code=c&state=s&extra=1").unwrap(),
        );
        assert_eq!(callback.code.as_deref(), Some("c"));
        assert_eq!(callback.state.as_deref(), Some("s"));
        assert_eq!(callback.error, None);
    }
}