opensession-api 0.2.34

Shared API types, crypto, and SQL builders for opensession.io
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
//! Generic OAuth2 provider support.
//!
//! Config-driven: no provider-specific code branches. Any OAuth2 provider
//! (GitHub, GitLab, Gitea, OIDC-compatible) can be added via configuration.
//!
//! This module contains only types, URL builders, and JSON parsing.
//! No HTTP calls or DB access — those live in the backend adapters.

use serde::{Deserialize, Serialize};

use crate::ServiceError;

// ── Provider Configuration ──────────────────────────────────────────────────

/// OAuth2 provider configuration. Loaded from environment variables or config file.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OAuthProviderConfig {
    /// Unique provider identifier: "github", "gitlab-corp", "gitea-internal"
    pub id: String,
    /// UI display name: "GitHub", "GitLab (Corp)"
    pub display_name: String,

    // OAuth2 endpoints
    pub authorize_url: String,
    pub token_url: String,
    pub userinfo_url: String,
    /// Optional separate email endpoint (GitHub-specific: /user/emails)
    pub email_url: Option<String>,

    pub client_id: String,
    #[serde(skip_serializing)]
    pub client_secret: String,
    pub scopes: String,

    /// JSON field mapping from userinfo response to internal fields
    pub field_map: OAuthFieldMap,

    /// Skip TLS verification for self-hosted instances (dev only)
    #[serde(default)]
    pub tls_skip_verify: bool,

    /// External URL for browser redirects (may differ from token_url for Docker setups)
    pub external_authorize_url: Option<String>,
}

/// Maps provider-specific JSON field names to our internal fields.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OAuthFieldMap {
    /// Field containing the user's unique ID: "id" (GitHub/GitLab) or "sub" (OIDC)
    pub id: String,
    /// Field containing the username: "login" (GitHub) or "username" (GitLab)
    pub username: String,
    /// Field containing the email: "email"
    pub email: String,
    /// Field containing the avatar URL: "avatar_url" or "picture"
    pub avatar: String,
}

/// Normalized user info extracted from any OAuth provider's userinfo response.
#[derive(Debug, Clone)]
pub struct OAuthUserInfo {
    /// Provider config id (e.g. "github")
    pub provider_id: String,
    /// Provider-side user ID (as string)
    pub provider_user_id: String,
    pub username: String,
    pub email: Option<String>,
    pub avatar_url: Option<String>,
}

/// Normalize OAuth config values loaded from env/secrets.
///
/// Some secret managers preserve trailing newlines/spaces when values are set via
/// shell pipes. We trim and reject empty results so providers don't get enabled
/// with unusable credentials.
pub fn normalize_oauth_config_value(raw: &str) -> Option<String> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        None
    } else {
        let maybe_unquoted = if trimmed.len() >= 2
            && ((trimmed.starts_with('"') && trimmed.ends_with('"'))
                || (trimmed.starts_with('\'') && trimmed.ends_with('\'')))
        {
            &trimmed[1..trimmed.len() - 1]
        } else {
            trimmed
        };
        let normalized = maybe_unquoted.trim();
        if normalized.is_empty() {
            None
        } else {
            Some(normalized.to_string())
        }
    }
}

// ── URL Builders (pure functions, no HTTP) ──────────────────────────────────

/// Build the OAuth authorize URL that the user's browser should be redirected to.
pub fn build_authorize_url(
    config: &OAuthProviderConfig,
    redirect_uri: &str,
    state: &str,
) -> String {
    let base = config
        .external_authorize_url
        .as_deref()
        .unwrap_or(&config.authorize_url);

    format!(
        "{}?client_id={}&redirect_uri={}&state={}&scope={}&response_type=code",
        base,
        urlencoding(&config.client_id),
        urlencoding(redirect_uri),
        urlencoding(state),
        urlencoding(&config.scopes),
    )
}

/// Build the JSON body for the token exchange request.
pub fn build_token_request_body(
    config: &OAuthProviderConfig,
    code: &str,
    redirect_uri: &str,
) -> serde_json::Value {
    serde_json::json!({
        "client_id": config.client_id,
        "client_secret": config.client_secret,
        "code": code,
        "grant_type": "authorization_code",
        "redirect_uri": redirect_uri,
    })
}

/// Build OAuth2 token request as application/x-www-form-urlencoded pairs.
///
/// OAuth2 token exchange endpoints are required to support urlencoded form input.
pub fn build_token_request_form(
    config: &OAuthProviderConfig,
    code: &str,
    redirect_uri: &str,
) -> Vec<(String, String)> {
    vec![
        ("client_id".into(), config.client_id.clone()),
        ("client_secret".into(), config.client_secret.clone()),
        ("code".into(), code.to_string()),
        ("grant_type".into(), "authorization_code".into()),
        ("redirect_uri".into(), redirect_uri.to_string()),
    ]
}

/// Build OAuth2 token request as x-www-form-urlencoded string.
pub fn build_token_request_form_encoded(
    config: &OAuthProviderConfig,
    code: &str,
    redirect_uri: &str,
) -> String {
    build_token_request_form(config, code, redirect_uri)
        .into_iter()
        .map(|(k, v)| format!("{}={}", urlencoding(&k), urlencoding(&v)))
        .collect::<Vec<_>>()
        .join("&")
}

/// Parse access_token from OAuth token response.
///
/// Supports both JSON (`{\"access_token\":\"...\"}`) and query-string style
/// (`access_token=...&scope=...`) payloads.
pub fn parse_access_token_response(raw: &str) -> Result<String, ServiceError> {
    let body = raw.trim();
    if body.is_empty() {
        return Err(ServiceError::Internal(
            "OAuth token exchange failed: empty response body".into(),
        ));
    }

    if let Ok(json) = serde_json::from_str::<serde_json::Value>(body) {
        if let Some(token) = json
            .get("access_token")
            .and_then(|v| v.as_str())
            .map(str::trim)
            .filter(|s| !s.is_empty())
        {
            return Ok(token.to_string());
        }

        let err = json.get("error").and_then(|v| v.as_str());
        let err_desc = json
            .get("error_description")
            .and_then(|v| v.as_str())
            .or_else(|| json.get("error_message").and_then(|v| v.as_str()));

        let detail = match (err, err_desc) {
            (Some(e), Some(d)) if !d.is_empty() => format!("{e}: {d}"),
            (Some(e), _) => e.to_string(),
            (_, Some(d)) if !d.is_empty() => d.to_string(),
            _ => "no access_token field in JSON response".to_string(),
        };

        return Err(ServiceError::Internal(format!(
            "OAuth token exchange failed: {detail}"
        )));
    }

    let mut access_token: Option<String> = None;
    let mut error: Option<String> = None;
    let mut error_description: Option<String> = None;

    for pair in body.split('&') {
        let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
        let key = decode_form_component(k);
        let value = decode_form_component(v);
        match key.as_str() {
            "access_token" if !value.trim().is_empty() => access_token = Some(value),
            "error" if !value.trim().is_empty() => error = Some(value),
            "error_description" if !value.trim().is_empty() => error_description = Some(value),
            _ => {}
        }
    }

    if let Some(token) = access_token {
        return Ok(token);
    }

    let detail = match (error, error_description) {
        (Some(e), Some(d)) => format!("{e}: {d}"),
        (Some(e), None) => e,
        (None, Some(d)) => d,
        (None, None) => "no access_token field in response".to_string(),
    };

    Err(ServiceError::Internal(format!(
        "OAuth token exchange failed: {detail}"
    )))
}

/// Extract normalized user info from a provider's userinfo JSON response.
///
/// `email_json` is an optional array of email objects (GitHub `/user/emails` format)
/// used when the primary userinfo endpoint doesn't include the email.
pub fn extract_user_info(
    config: &OAuthProviderConfig,
    userinfo_json: &serde_json::Value,
    email_json: Option<&[serde_json::Value]>,
) -> Result<OAuthUserInfo, ServiceError> {
    // Extract provider user ID — may be number or string depending on provider
    let provider_user_id = match &userinfo_json[&config.field_map.id] {
        serde_json::Value::Number(n) => n.to_string(),
        serde_json::Value::String(s) => s.clone(),
        _ => {
            return Err(ServiceError::Internal(format!(
                "OAuth userinfo missing '{}' field",
                config.field_map.id
            )))
        }
    };

    let username = userinfo_json[&config.field_map.username]
        .as_str()
        .unwrap_or("unknown")
        .to_string();

    // Email: try userinfo first, then email_json (GitHub format: [{email, primary, verified}])
    let email = userinfo_json[&config.field_map.email]
        .as_str()
        .map(|s| s.to_string())
        .or_else(|| {
            email_json.and_then(|emails| {
                emails
                    .iter()
                    .find(|e| e["primary"].as_bool() == Some(true))
                    .and_then(|e| e["email"].as_str())
                    .map(|s| s.to_string())
            })
        });

    let avatar_url = userinfo_json[&config.field_map.avatar]
        .as_str()
        .map(|s| s.to_string());

    Ok(OAuthUserInfo {
        provider_id: config.id.clone(),
        provider_user_id,
        username,
        email,
        avatar_url,
    })
}

// ── Provider Presets ────────────────────────────────────────────────────────

/// Create a GitHub OAuth2 provider config. Only needs client credentials.
pub fn github_preset(client_id: String, client_secret: String) -> OAuthProviderConfig {
    OAuthProviderConfig {
        id: "github".into(),
        display_name: "GitHub".into(),
        authorize_url: "https://github.com/login/oauth/authorize".into(),
        token_url: "https://github.com/login/oauth/access_token".into(),
        userinfo_url: "https://api.github.com/user".into(),
        email_url: Some("https://api.github.com/user/emails".into()),
        client_id,
        client_secret,
        scopes: "read:user,user:email".into(),
        field_map: OAuthFieldMap {
            id: "id".into(),
            username: "login".into(),
            email: "email".into(),
            avatar: "avatar_url".into(),
        },
        tls_skip_verify: false,
        external_authorize_url: None,
    }
}

/// Create a GitLab OAuth2 provider config for a given instance URL.
///
/// `instance_url` is the server-accessible URL (e.g. `http://gitlab:80` in Docker).
/// `external_url` is the browser-accessible URL (e.g. `http://localhost:8929`).
/// If `external_url` is None, `instance_url` is used for browser redirects too.
pub fn gitlab_preset(
    instance_url: String,
    external_url: Option<String>,
    client_id: String,
    client_secret: String,
) -> OAuthProviderConfig {
    let base = instance_url.trim_end_matches('/');
    let ext_base = external_url
        .as_deref()
        .map(|u| u.trim_end_matches('/').to_string());

    OAuthProviderConfig {
        id: "gitlab".into(),
        display_name: "GitLab".into(),
        authorize_url: format!("{base}/oauth/authorize"),
        token_url: format!("{base}/oauth/token"),
        userinfo_url: format!("{base}/api/v4/user"),
        email_url: None, // GitLab includes email in /api/v4/user
        client_id,
        client_secret,
        scopes: "read_user".into(),
        field_map: OAuthFieldMap {
            id: "id".into(),
            username: "username".into(),
            email: "email".into(),
            avatar: "avatar_url".into(),
        },
        tls_skip_verify: false,
        external_authorize_url: ext_base.map(|b| format!("{b}/oauth/authorize")),
    }
}

// ── API Response Types ──────────────────────────────────────────────────────

/// Available auth providers (returned by GET /api/auth/providers).
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[cfg_attr(feature = "ts", ts(export))]
pub struct AuthProvidersResponse {
    pub email_password: bool,
    pub oauth: Vec<OAuthProviderInfo>,
}

/// Public info about an OAuth provider.
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[cfg_attr(feature = "ts", ts(export))]
pub struct OAuthProviderInfo {
    pub id: String,
    pub display_name: String,
}

/// A linked OAuth provider shown in user settings.
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[cfg_attr(feature = "ts", ts(export))]
pub struct LinkedProvider {
    pub provider: String,
    pub provider_username: String,
    pub display_name: String,
}

// ── Helpers ─────────────────────────────────────────────────────────────────

fn urlencoding(s: &str) -> String {
    // Minimal URL-encoding for OAuth parameters
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(b as char);
            }
            _ => {
                out.push('%');
                out.push(char::from(b"0123456789ABCDEF"[(b >> 4) as usize]));
                out.push(char::from(b"0123456789ABCDEF"[(b & 0x0f) as usize]));
            }
        }
    }
    out
}

fn decode_form_component(s: &str) -> String {
    let bytes = s.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0usize;
    while i < bytes.len() {
        match bytes[i] {
            b'+' => {
                out.push(b' ');
                i += 1;
            }
            b'%' if i + 2 < bytes.len() => {
                let hi = hex_value(bytes[i + 1]);
                let lo = hex_value(bytes[i + 2]);
                if let (Some(h), Some(l)) = (hi, lo) {
                    out.push((h << 4) | l);
                    i += 3;
                } else {
                    out.push(bytes[i]);
                    i += 1;
                }
            }
            b => {
                out.push(b);
                i += 1;
            }
        }
    }
    String::from_utf8_lossy(&out).to_string()
}

fn hex_value(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(10 + b - b'a'),
        b'A'..=b'F' => Some(10 + b - b'A'),
        _ => None,
    }
}

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

    use super::{
        build_authorize_url, build_token_request_body, build_token_request_form,
        build_token_request_form_encoded, extract_user_info, github_preset, gitlab_preset,
        normalize_oauth_config_value, parse_access_token_response,
    };

    #[test]
    fn parse_access_token_json_ok() {
        let raw = r#"{"access_token":"gho_123","scope":"read:user","token_type":"bearer"}"#;
        let token = parse_access_token_response(raw).expect("token parse");
        assert_eq!(token, "gho_123");
    }

    #[test]
    fn parse_access_token_form_ok() {
        let raw = "access_token=gho_abc&scope=read%3Auser&token_type=bearer";
        let token = parse_access_token_response(raw).expect("token parse");
        assert_eq!(token, "gho_abc");
    }

    #[test]
    fn parse_access_token_json_error_has_reason() {
        let raw = r#"{"error":"bad_verification_code","error_description":"The code passed is incorrect or expired."}"#;
        let err = parse_access_token_response(raw).expect_err("must fail");
        assert!(err.message().contains("bad_verification_code"));
    }

    #[test]
    fn parse_access_token_empty_body_is_error() {
        let err = parse_access_token_response("   ").expect_err("must fail");
        assert!(err.message().contains("empty response body"));
    }

    #[test]
    fn build_authorize_url_prefers_external_and_encodes_values() {
        let mut provider = github_preset("cid".into(), "secret".into());
        provider.external_authorize_url = Some("https://external.example/oauth/authorize".into());
        provider.scopes = "read:user user:email".into();
        let built = build_authorize_url(
            &provider,
            "https://app.local/auth/callback?mode=web",
            "state value",
        );
        assert!(built.starts_with("https://external.example/oauth/authorize?"));
        assert!(built.contains("client_id=cid"));
        assert!(
            built.contains("redirect_uri=https%3A%2F%2Fapp.local%2Fauth%2Fcallback%3Fmode%3Dweb")
        );
        assert!(built.contains("state=state%20value"));
        assert!(built.contains("scope=read%3Auser%20user%3Aemail"));
    }

    #[test]
    fn build_token_request_body_contains_required_fields() {
        let provider = github_preset("cid".into(), "secret".into());
        let body = build_token_request_body(&provider, "code-1", "https://app/callback");
        assert_eq!(body["client_id"], "cid");
        assert_eq!(body["client_secret"], "secret");
        assert_eq!(body["code"], "code-1");
        assert_eq!(body["grant_type"], "authorization_code");
        assert_eq!(body["redirect_uri"], "https://app/callback");
    }

    #[test]
    fn build_token_request_form_contains_required_fields() {
        let provider = github_preset("cid".into(), "secret".into());
        let form = build_token_request_form(&provider, "code-1", "https://app/callback");
        assert_eq!(
            form,
            vec![
                ("client_id".into(), "cid".into()),
                ("client_secret".into(), "secret".into()),
                ("code".into(), "code-1".into()),
                ("grant_type".into(), "authorization_code".into()),
                ("redirect_uri".into(), "https://app/callback".into()),
            ]
        );
    }

    #[test]
    fn build_form_encoded_contains_required_fields() {
        let provider = github_preset("cid".into(), "secret".into());
        let encoded = build_token_request_form_encoded(&provider, "code-1", "https://app/callback");
        assert!(encoded.contains("client_id=cid"));
        assert!(encoded.contains("client_secret=secret"));
        assert!(encoded.contains("grant_type=authorization_code"));
        assert!(encoded.contains("code=code-1"));
    }

    #[test]
    fn extract_user_info_prefers_primary_email() {
        let provider = github_preset("cid".into(), "secret".into());
        let userinfo = json!({
            "id": 42,
            "login": "alice",
            "avatar_url": "https://avatar.example/alice.png",
            "email": null
        });
        let emails = vec![
            json!({"email":"secondary@example.com","primary":false}),
            json!({"email":"primary@example.com","primary":true}),
        ];

        let info =
            extract_user_info(&provider, &userinfo, Some(&emails)).expect("userinfo should parse");
        assert_eq!(info.provider_id, "github");
        assert_eq!(info.provider_user_id, "42");
        assert_eq!(info.username, "alice");
        assert_eq!(info.email.as_deref(), Some("primary@example.com"));
        assert_eq!(
            info.avatar_url.as_deref(),
            Some("https://avatar.example/alice.png")
        );
    }

    #[test]
    fn extract_user_info_requires_id_field() {
        let provider = github_preset("cid".into(), "secret".into());
        let userinfo = json!({
            "login": "alice"
        });
        let err = extract_user_info(&provider, &userinfo, None).expect_err("must fail");
        assert!(err.message().contains("missing 'id' field"));
    }

    #[test]
    fn normalize_oauth_config_value_trims_and_rejects_empty() {
        assert_eq!(
            normalize_oauth_config_value("  value-with-spaces\t\n"),
            Some("value-with-spaces".to_string())
        );
        assert_eq!(normalize_oauth_config_value("   \n\t  "), None);
    }

    #[test]
    fn normalize_oauth_config_value_strips_wrapping_quotes() {
        assert_eq!(
            normalize_oauth_config_value(" \"quoted-value\" "),
            Some("quoted-value".to_string())
        );
        assert_eq!(
            normalize_oauth_config_value(" 'another' "),
            Some("another".to_string())
        );
        assert_eq!(normalize_oauth_config_value("  \"   \" "), None);
    }

    #[test]
    fn github_preset_populates_expected_defaults() {
        let provider = github_preset("cid".into(), "secret".into());
        assert_eq!(provider.id, "github");
        assert_eq!(provider.display_name, "GitHub");
        assert_eq!(
            provider.email_url.as_deref(),
            Some("https://api.github.com/user/emails")
        );
        assert_eq!(provider.scopes, "read:user,user:email");
    }

    #[test]
    fn gitlab_preset_trims_urls_and_sets_external_authorize_url() {
        let provider = gitlab_preset(
            "https://gitlab.internal/".into(),
            Some("https://gitlab.example.com/".into()),
            "cid".into(),
            "secret".into(),
        );
        assert_eq!(provider.id, "gitlab");
        assert_eq!(
            provider.authorize_url,
            "https://gitlab.internal/oauth/authorize"
        );
        assert_eq!(provider.token_url, "https://gitlab.internal/oauth/token");
        assert_eq!(provider.userinfo_url, "https://gitlab.internal/api/v4/user");
        assert_eq!(
            provider.external_authorize_url.as_deref(),
            Some("https://gitlab.example.com/oauth/authorize")
        );
    }
}