quilt-rs 0.33.0

Rust library for accessing Quilt data packages.
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
//! OAuth 2.1 wire protocol against the connect host: PKCE (RFC 7636),
//! Dynamic Client Registration (RFC 7591), and token requests (RFC 6749).
//!
//! Terminology mapping (RFC → code):
//! - *Authorization Endpoint* (RFC 6749 §3.1) → [`catalog_authorize_url`]
//! - *Token Endpoint* (RFC 6749 §3.2) → [`connect_token_url`]
//! - *Authorization Code* (RFC 6749 §1.3.1) → `OAuthParams::code`
//! - *Code Verifier* (RFC 7636 §4.1) → `PkceChallenge::code_verifier`
//! - *Code Challenge* (RFC 7636 §4.2) → `PkceChallenge::code_challenge`
//! - *State* (RFC 6749 §10.12) — CSRF protection token, generated by [`random_state`]
//! - *Client Registration Endpoint* (RFC 7591 §3) → [`connect_register_url`]
//! - *Redirect URI* (RFC 6749 §3.1.2) → `OAuthParams::redirect_uri`

use std::collections::HashMap;
use std::fmt;

use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use serde::Deserialize;
use serde::Serialize;
use sha2::Digest;
use sha2::Sha256;

use crate::Error;
use crate::Res;
use crate::error::AuthError;
use crate::io::remote::client::HttpClient;
use crate::io::storage::auth::OAuthClient;
use crate::io::storage::auth::Tokens;
use quilt_uri::Host;

/// Parameters for the Token Request (RFC 6749 §4.1.3) with PKCE extension.
pub struct OAuthParams {
    /// Authorization code received from the Authorization Endpoint (RFC 6749 §4.1.2)
    pub code: String,
    /// PKCE code verifier (RFC 7636 §4.1) — sent to the Token Endpoint for verification
    pub code_verifier: String,
    /// Redirect URI (RFC 6749 §3.1.2) — must match the value sent in the Authorization Request
    pub redirect_uri: String,
    /// Client identifier (RFC 6749 §2.2) obtained via DCR.
    ///
    /// The caller is responsible for ensuring this matches the `client_id`
    /// stored in the [`OAuthClient`] for the target host (e.g. by calling
    /// [`super::Auth::get_or_register_client`] and using its `client_id`
    /// directly).
    pub client_id: String,
}

/// PKCE code verifier and challenge pair (RFC 7636).
pub struct PkceChallenge {
    /// Random verifier string — send to token endpoint
    pub code_verifier: String,
    /// S256 hash of verifier — send in the authorize URL
    pub code_challenge: String,
}

/// Generate a PKCE code verifier and its S256 challenge.
///
/// The verifier is 64 random bytes, base64url-encoded (86 characters),
/// well within RFC 7636 §4.1's 43–128 character range.
pub fn pkce_challenge() -> PkceChallenge {
    let mut random_bytes = [0u8; 64];
    getrandom::fill(&mut random_bytes).expect("failed to generate random bytes");

    let code_verifier = URL_SAFE_NO_PAD.encode(random_bytes);
    let code_challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(code_verifier.as_bytes()));

    PkceChallenge {
        code_verifier,
        code_challenge,
    }
}

/// Generate a random `state` parameter for CSRF protection (RFC 6749 §10.12).
pub fn random_state() -> String {
    let mut bytes = [0u8; 16];
    getrandom::fill(&mut bytes).expect("failed to generate random bytes");
    URL_SAFE_NO_PAD.encode(bytes)
}

// --- OAuth endpoint URLs ---
//
// OAuth uses two different hostnames derived from the catalog host:
//
// 1. **Catalog host** (`test.quilt.dev`) — the authorize endpoint lives here
//    because the user's browser session (cookies) is on the catalog.
//
// 2. **Connect host** (`test-connect.quilt.dev`) — the token exchange and
//    client registration (DCR) endpoints live on a separate subdomain.

/// Authorization Endpoint (RFC 6749 §3.1) on the catalog host.
///
/// E.g., `test.quilt.dev` → `https://test.quilt.dev/connect/authorize`
pub fn catalog_authorize_url(host: &Host) -> String {
    format!("https://{host}/connect/authorize")
}

/// Derive the connect server hostname from the catalog host.
///
/// E.g., `test.quilt.dev` → `test-connect.quilt.dev`
///
/// # Assumptions
///
/// The catalog hostname is assumed to have exactly one label before the first
/// dot (e.g. `test` in `test.quilt.dev`). Multi-label prefixes such as
/// `a.b.quilt.dev` are not supported and will produce an incorrect result
/// (`a-connect.b.quilt.dev` instead of a well-defined connect hostname).
pub fn connect_host(host: &Host) -> String {
    let s = host.to_string();
    match s.split_once('.') {
        Some((stack, domain)) => format!("{stack}-connect.{domain}"),
        None => format!("{s}-connect"),
    }
}

/// Token Endpoint (RFC 6749 §3.2) on the connect host.
///
/// E.g., `test.quilt.dev` → `https://test-connect.quilt.dev/auth/token`
pub(super) fn connect_token_url(host: &Host) -> String {
    format!("https://{}/auth/token", connect_host(host))
}

/// Client Registration Endpoint (RFC 7591 §3) on the connect host.
pub(super) fn connect_register_url(host: &Host) -> String {
    format!("https://{}/auth/register", connect_host(host))
}

/// DCR request body (RFC 7591).
#[derive(Serialize)]
struct DcrRequest {
    client_name: String,
    redirect_uris: Vec<String>,
    token_endpoint_auth_method: String,
}

/// DCR response body (subset of fields we need).
#[derive(Deserialize)]
struct DcrResponse {
    client_id: String,
}

/// Register a public OAuth client via Dynamic Client Registration (RFC 7591 §3.1).
pub(super) async fn register_client(
    http_client: &impl HttpClient,
    host: &Host,
    redirect_uri: &str,
) -> Res<OAuthClient> {
    let register_url = connect_register_url(host);

    let request = DcrRequest {
        client_name: "QuiltSync".to_string(),
        redirect_uris: vec![redirect_uri.to_string()],
        token_endpoint_auth_method: "none".to_string(),
    };

    let response: DcrResponse = http_client.post_json(&register_url, &request).await?;

    Ok(OAuthClient {
        client_id: response.client_id,
        redirect_uri: redirect_uri.to_string(),
    })
}

/// Fallback TTL (seconds) when the token endpoint omits `expires_in`.
///
/// RFC 6749 §5.1 marks `expires_in` as RECOMMENDED, not required.
/// We use 1 hour as a conservative default that avoids both excessive
/// refresh loops (too short) and stale-token errors (too long).
pub(super) const DEFAULT_EXPIRES_IN: i64 = 3600;

fn default_expires_in() -> i64 {
    DEFAULT_EXPIRES_IN
}

/// Token response from the Connect OAuth token endpoint.
///
/// Uses `expires_in` (seconds until expiry) per RFC 6749,
/// unlike `RemoteTokens` which uses `expires_at` (Unix timestamp).
///
/// `refresh_token` is `Option` because RFC 6749 §6 allows the server to omit
/// it when rotating tokens; callers are responsible for falling back to the
/// previous refresh token in that case.
///
/// `expires_in` is optional per RFC 6749 §5.1 (RECOMMENDED, not required);
/// defaults to [`DEFAULT_EXPIRES_IN`] when absent.
#[derive(Deserialize, Serialize)]
pub(super) struct OAuthTokenResponse {
    pub(super) access_token: String,
    #[serde(default)]
    pub(super) refresh_token: Option<String>,
    #[serde(default = "default_expires_in")]
    pub(super) expires_in: i64,
}

impl fmt::Debug for OAuthTokenResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OAuthTokenResponse")
            .field("expires_in", &self.expires_in)
            .field("access_token", &"[REDACTED]")
            .field(
                "refresh_token",
                &self.refresh_token.as_ref().map(|_| "[REDACTED]"),
            )
            .finish_non_exhaustive()
    }
}

/// Token Request (RFC 6749 §4.1.3) with PKCE code verifier (RFC 7636 §4.5).
pub(super) async fn exchange_oauth_code(
    http_client: &impl HttpClient,
    host: &Host,
    params: &OAuthParams,
) -> Res<Tokens> {
    let token_url = connect_token_url(host);

    let mut form_data: HashMap<String, String> = HashMap::new();
    form_data.insert("grant_type".to_string(), "authorization_code".to_string());
    form_data.insert("code".to_string(), params.code.clone());
    form_data.insert("code_verifier".to_string(), params.code_verifier.clone());
    form_data.insert("redirect_uri".to_string(), params.redirect_uri.clone());
    form_data.insert("client_id".to_string(), params.client_id.clone());

    let response: OAuthTokenResponse = http_client.post(&token_url, &form_data).await?;
    let expires_at = chrono::Utc::now() + chrono::Duration::seconds(response.expires_in);
    Ok(Tokens {
        access_token: response.access_token,
        refresh_token: response.refresh_token.ok_or_else(|| {
            Error::Auth(
                host.to_owned(),
                AuthError::TokensExchange("server did not return a refresh token".to_string()),
            )
        })?,
        expires_at,
    })
}

/// Refresh Token Request (RFC 6749 §6) — exchange a refresh token for new tokens.
pub(super) async fn refresh_oauth_tokens(
    http_client: &impl HttpClient,
    host: &Host,
    refresh_token: &str,
    client_id: &str,
) -> Res<Tokens> {
    let token_url = connect_token_url(host);

    let mut form_data: HashMap<String, String> = HashMap::new();
    form_data.insert("grant_type".to_string(), "refresh_token".to_string());
    form_data.insert("refresh_token".to_string(), refresh_token.to_string());
    form_data.insert("client_id".to_string(), client_id.to_string());

    let response: OAuthTokenResponse = http_client.post(&token_url, &form_data).await?;
    let expires_at = chrono::Utc::now() + chrono::Duration::seconds(response.expires_in);
    Ok(Tokens {
        access_token: response.access_token,
        // RFC 6749 §6: server MAY omit the refresh token — retain the previous one if so.
        refresh_token: response
            .refresh_token
            .unwrap_or_else(|| refresh_token.to_string()),
        expires_at,
    })
}

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

    use async_trait::async_trait;
    use test_log::test;

    use crate::auth::test_utils::*;

    #[test]
    fn test_connect_host() {
        let host: Host = "test.quilt.dev".parse().unwrap();
        assert_eq!(connect_host(&host), "test-connect.quilt.dev");
    }

    #[test]
    fn test_connect_token_url() {
        let host: Host = "test.quilt.dev".parse().unwrap();
        assert_eq!(
            connect_token_url(&host),
            "https://test-connect.quilt.dev/auth/token"
        );
    }

    #[test(tokio::test)]
    async fn test_exchange_oauth_code() {
        let client = OAuthTestHttpClient::default();
        let params = OAuthParams {
            code: AUTH_CODE.to_string(),
            code_verifier: CODE_VERIFIER.to_string(),
            redirect_uri: REDIRECT_URI.to_string(),
            client_id: CLIENT_ID.to_string(),
        };
        let tokens = exchange_oauth_code(&client, &get_host(), &params)
            .await
            .unwrap();
        assert_eq!(tokens.access_token, ACCESS_TOKEN);
        assert_eq!(tokens.refresh_token, "oauth-refresh-token");
    }

    #[test]
    fn test_pkce_challenge() {
        let pkce = pkce_challenge();

        // Verifier should be 86 characters (64 bytes base64url-encoded without padding)
        assert_eq!(pkce.code_verifier.len(), 86);

        // Challenge should be 43 characters (SHA-256 is 32 bytes, base64url-encoded)
        assert_eq!(pkce.code_challenge.len(), 43);

        // Verify the challenge is the S256 hash of the verifier
        let expected_challenge =
            URL_SAFE_NO_PAD.encode(Sha256::digest(pkce.code_verifier.as_bytes()));
        assert_eq!(pkce.code_challenge, expected_challenge);

        // Two calls should produce different verifiers
        let pkce2 = pkce_challenge();
        assert_ne!(pkce.code_verifier, pkce2.code_verifier);
    }

    // RFC 7636 §4.1: code verifier must use only unreserved chars: ALPHA / DIGIT / "-" / "." / "_" / "~"
    #[test]
    fn test_pkce_verifier_charset_rfc7636() {
        let pkce = pkce_challenge();
        for ch in pkce.code_verifier.chars() {
            assert!(
                ch.is_ascii_alphanumeric() || matches!(ch, '-' | '.' | '_' | '~'),
                "code_verifier contains char '{ch}' not allowed by RFC 7636 §4.1"
            );
        }
    }

    #[test(tokio::test)]
    async fn test_refresh_oauth_tokens() -> Res {
        let tokens = refresh_oauth_tokens(
            &OAuthTestHttpClient::default(),
            &get_host(),
            REFRESH_TOKEN,
            CLIENT_ID,
        )
        .await?;
        assert_eq!(tokens.access_token, "refreshed-access-token");
        assert_eq!(tokens.refresh_token, "new-refresh-token");
        Ok(())
    }

    // RFC 6749 §6: if the server omits `refresh_token` in the refresh response,
    // the client MUST retain the previous refresh token.
    #[test(tokio::test)]
    async fn test_refresh_oauth_tokens_retains_old_when_omitted() -> Res {
        struct NoRefreshTokenClient;

        #[async_trait]
        impl HttpClient for NoRefreshTokenClient {
            async fn get<T: serde::de::DeserializeOwned>(
                &self,
                _: &str,
                _: Option<&str>,
            ) -> Res<T> {
                unimplemented!()
            }
            async fn head(&self, _: &str) -> Res<reqwest::header::HeaderMap> {
                unimplemented!()
            }
            async fn post<T: serde::de::DeserializeOwned>(
                &self,
                _: &str,
                _: &HashMap<String, String>,
            ) -> Res<T> {
                let resp = OAuthTokenResponse {
                    access_token: "new-access-token".to_string(),
                    refresh_token: None, // server omits refresh_token
                    expires_in: DEFAULT_EXPIRES_IN,
                };
                Ok(serde_json::from_value(serde_json::to_value(resp)?)?)
            }
            async fn post_json<
                T: serde::de::DeserializeOwned,
                B: serde::Serialize + Send + Sync,
            >(
                &self,
                _: &str,
                _: &B,
            ) -> Res<T> {
                unimplemented!()
            }
        }

        let tokens =
            refresh_oauth_tokens(&NoRefreshTokenClient, &get_host(), REFRESH_TOKEN, CLIENT_ID)
                .await?;
        assert_eq!(tokens.access_token, "new-access-token");
        // Old refresh token must be retained
        assert_eq!(tokens.refresh_token, REFRESH_TOKEN);
        Ok(())
    }

    // RFC 6749 §4.1.4 + §5.1: initial code exchange MUST return a refresh_token;
    // if the server omits it the client should surface an error (not silently proceed).
    #[test(tokio::test)]
    async fn test_exchange_oauth_code_errors_when_refresh_token_missing() {
        struct NoRefreshTokenClient;

        #[async_trait]
        impl HttpClient for NoRefreshTokenClient {
            async fn get<T: serde::de::DeserializeOwned>(
                &self,
                _: &str,
                _: Option<&str>,
            ) -> Res<T> {
                unimplemented!()
            }
            async fn head(&self, _: &str) -> Res<reqwest::header::HeaderMap> {
                unimplemented!()
            }
            async fn post<T: serde::de::DeserializeOwned>(
                &self,
                _: &str,
                _: &HashMap<String, String>,
            ) -> Res<T> {
                let resp = OAuthTokenResponse {
                    access_token: ACCESS_TOKEN.to_string(),
                    refresh_token: None,
                    expires_in: DEFAULT_EXPIRES_IN,
                };
                Ok(serde_json::from_value(serde_json::to_value(resp)?)?)
            }
            async fn post_json<
                T: serde::de::DeserializeOwned,
                B: serde::Serialize + Send + Sync,
            >(
                &self,
                _: &str,
                _: &B,
            ) -> Res<T> {
                unimplemented!()
            }
        }

        let params = OAuthParams {
            code: AUTH_CODE.to_string(),
            code_verifier: CODE_VERIFIER.to_string(),
            redirect_uri: REDIRECT_URI.to_string(),
            client_id: CLIENT_ID.to_string(),
        };
        let result = exchange_oauth_code(&NoRefreshTokenClient, &get_host(), &params).await;
        assert!(
            matches!(result, Err(Error::Auth(_, AuthError::TokensExchange(_)))),
            "expected TokensExchange error, got: {result:?}"
        );
    }

    // RFC 6749 §5.1: `expires_in` is RECOMMENDED, not required. If omitted,
    // the client should fall back to a safe default rather than failing.
    #[test]
    fn test_oauth_token_response_missing_expires_in() {
        let json = r#"{"access_token":"tok","refresh_token":"ref"}"#;
        let resp: OAuthTokenResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.expires_in, DEFAULT_EXPIRES_IN);
    }

    #[test]
    fn oauth_token_response_debug_redacts_secrets() {
        let response = OAuthTokenResponse {
            access_token: "secret-access".to_string(),
            refresh_token: Some("secret-refresh".to_string()),
            expires_in: 3600,
        };
        let output = format!("{response:?}");
        assert!(output.contains("[REDACTED]"));
        assert!(!output.contains("secret-access"));
        assert!(!output.contains("secret-refresh"));
    }

    #[test]
    fn oauth_token_response_debug_none_refresh_token() {
        let response = OAuthTokenResponse {
            access_token: "secret-access".to_string(),
            refresh_token: None,
            expires_in: 3600,
        };
        let output = format!("{response:?}");
        assert!(output.contains("refresh_token: None"));
        assert!(!output.contains("secret-access"));
    }
}