sunbeam-g2v 0.5.2

Sunbeam Service Framework - A ConnectRPC-based framework for building microservices
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
//! Authentication and authorization middleware.
//!
//! Provides multitenancy-aware authn/authz for Sunbeam services:
//!
//! - `auth_middleware` resolves the caller to a [`TenantId`] using a bearer
//!   token (introspection), a session cookie, or a session token header.
//! - [`PermissionLayer`] enforces ReBAC permission checks against the configured
//!   authorization backend.
//! - [`AuthorizationClient`] talks to that backend over HTTP.

#[cfg(feature = "auth")]
pub mod authorization;
#[cfg(feature = "auth")]
pub mod cookie_signer;
#[cfg(feature = "auth")]
pub mod error;
#[cfg(feature = "auth")]
pub mod introspection;
#[cfg(feature = "auth")]
pub mod permission;
#[cfg(feature = "auth")]
pub mod session;
#[cfg(feature = "auth")]
pub mod session_token;

#[cfg(feature = "auth")]
pub use authorization::{AuthorizationClient, AuthorizationConfig};
#[cfg(feature = "auth")]
pub use cookie_signer::{CookieError, CookieSigner};
#[cfg(feature = "auth")]
pub use introspection::{
    CachedIntrospectionSessionClient, IntrospectionConfig, IntrospectionSessionClient,
};
#[cfg(feature = "auth")]
pub use permission::{ObjectExtractor, PermissionLayer, PermissionService};
#[cfg(feature = "auth")]
pub use session::{SessionClient, SessionStore};
#[cfg(feature = "auth")]
pub use session_token::{SessionClaims, SessionTokenError, SessionTokenSigner};

use axum::{
    body::Body,
    extract::Request,
    http::StatusCode,
    middleware::Next,
    response::{IntoResponse, Response},
};
use std::sync::Arc;

pub use error::AuthError;

/// Header carrying a session token.
pub const SESSION_TOKEN_HEADER: &str = "x-session-token";
/// Default session cookie name.
pub const SESSION_COOKIE_NAME: &str = "__Host-sso_session";

/// Resolved tenant for the request.
#[derive(Debug, Clone)]
pub struct TenantId(pub String);

/// Slim identity context for use in handlers.
#[derive(Debug, Clone, Default)]
pub struct AuthContext {
    /// Resolved tenant id.
    pub tenant_id: Option<String>,
    /// Authenticated subject (identity id or client id).
    pub subject: Option<String>,
    /// Actor scopes, if present in the token.
    pub scopes: Vec<String>,
    /// SHA-256 hash of the raw token, for audit logging.
    pub token_hash: Option<String>,
    /// Authentication Method Reference values (e.g. `password`, `totp`).
    pub authentication_methods: Vec<String>,
}

impl AuthContext {
    /// Create an unauthenticated context.
    pub fn unauthenticated() -> Self {
        Self::default()
    }

    /// Create an authenticated context for the given tenant and subject.
    pub fn authenticated(tenant_id: impl Into<String>, subject: impl Into<String>) -> Self {
        Self {
            tenant_id: Some(tenant_id.into()),
            subject: Some(subject.into()),
            scopes: Vec::new(),
            token_hash: None,
            authentication_methods: Vec::new(),
        }
    }

    /// Set scopes.
    pub fn with_scopes(mut self, scopes: Vec<String>) -> Self {
        self.scopes = scopes;
        self
    }

    /// Set the token hash.
    pub fn with_token_hash(mut self, hash: impl Into<String>) -> Self {
        self.token_hash = Some(hash.into());
        self
    }

    /// Set authentication methods.
    pub fn with_authentication_methods(mut self, methods: Vec<String>) -> Self {
        self.authentication_methods = methods;
        self
    }

    /// Returns true when a subject has been resolved.
    pub fn is_authenticated(&self) -> bool {
        self.subject.is_some()
    }

    /// Require a scope from this context.
    ///
    /// Returns `ServiceError::PermissionDenied` if the scope is missing.
    pub fn require_scope(&self, scope: &str) -> Result<(), crate::error::ServiceError> {
        if !self.scopes.iter().any(|s| s == scope) {
            return Err(crate::error::ServiceError::PermissionDenied(format!(
                "missing required scope: {scope}"
            )));
        }
        Ok(())
    }

    /// Require an Authentication Method Reference from this context.
    ///
    /// Returns `ServiceError::PermissionDenied` if the method is missing.
    /// Intended for RPC handlers that need stepped-up assurance (e.g. admin
    /// operations requiring a second factor).
    pub fn require_amr(&self, method: &str) -> Result<(), crate::error::ServiceError> {
        if !self.authentication_methods.iter().any(|m| m == method) {
            return Err(crate::error::ServiceError::PermissionDenied(format!(
                "missing required authentication method: {method}"
            )));
        }
        Ok(())
    }
}

/// Shared state required by [`auth_middleware`].
#[derive(Clone)]
pub struct AuthMiddlewareState {
    /// Validates sessions (via sso-gateway introspection).
    pub sessions: Arc<dyn SessionClient>,
    /// Signs and verifies session cookies.
    pub session_signer: Option<Arc<SessionTokenSigner>>,
    /// Checks server-side session revocation.
    pub session_store: Option<Arc<dyn SessionStore>>,
}

impl std::fmt::Debug for AuthMiddlewareState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AuthMiddlewareState")
            .field("sessions", &"<dyn SessionClient>")
            .field("session_signer", &self.session_signer.is_some())
            .field("session_store", &self.session_store.is_some())
            .finish()
    }
}

impl AuthMiddlewareState {
    /// Create state with the required session client.
    pub fn new(sessions: Arc<dyn SessionClient>) -> Self {
        Self {
            sessions,
            session_signer: None,
            session_store: None,
        }
    }

    /// Attach a session token signer for cookie-based authentication.
    pub fn with_session_signer(mut self, signer: SessionTokenSigner) -> Self {
        self.session_signer = Some(Arc::new(signer));
        self
    }

    /// Attach a session store for revocation checking.
    pub fn with_session_store(mut self, store: Arc<dyn SessionStore>) -> Self {
        self.session_store = Some(store);
        self
    }
}

/// Axum middleware that resolves authentication and inserts a [`TenantId`] and
/// [`AuthContext`] into request extensions.
///
/// Public OAuth2/OIDC discovery paths are not validated here; handlers for those
/// routes perform their own tenant validation.
pub async fn auth_middleware(
    axum::extract::State(state): axum::extract::State<AuthMiddlewareState>,
    mut request: Request,
    next: Next,
) -> Response {
    let path = request.uri().path();
    if is_public_path(path) {
        return next.run(request).await;
    }

    // 1. Bearer token authentication (introspection flows).
    if let Some(token) = bearer_token(request.headers()) {
        match authenticate_session(
            state.sessions.as_ref(),
            None,
            Some(&token),
        )
        .await
        {
            Ok((tenant_id, identity_id)) => {
                let auth_ctx = AuthContext::authenticated(&tenant_id, &identity_id)
                    .with_token_hash(hash_token(&token));
                request.extensions_mut().insert(TenantId(tenant_id));
                request.extensions_mut().insert(auth_ctx);
            }
            Err(resp) => return resp,
        }
        return next.run(request).await;
    }

    // 2. Session cookie authentication (signed opaque tokens).
    if let Some(cookie) = session_cookie(request.headers(), SESSION_COOKIE_NAME)
        && let Some(signer) = &state.session_signer
    {
        match authenticate_session_cookie(
            signer.as_ref(),
            state.session_store.as_deref(),
            &cookie,
        )
        .await
        {
            Ok((tenant_id, subject)) => {
                let auth_ctx = AuthContext::authenticated(&tenant_id, &subject);
                request.extensions_mut().insert(TenantId(tenant_id));
                request.extensions_mut().insert(auth_ctx);
            }
            Err(resp) => return resp,
        }
        return next.run(request).await;
    }

    // 3. Session token header (API flows).
    if let Some(token) = header_value(&request, SESSION_TOKEN_HEADER) {
        match authenticate_session(
            state.sessions.as_ref(),
            None,
            Some(&token),
        )
        .await
        {
            Ok((tenant_id, identity_id)) => {
                let auth_ctx = AuthContext::authenticated(&tenant_id, &identity_id);
                request.extensions_mut().insert(TenantId(tenant_id));
                request.extensions_mut().insert(auth_ctx);
            }
            Err(resp) => return resp,
        }
        return next.run(request).await;
    }

    // 4. Session cookie header (browser flows).
    if let Some(cookie) = header_value(&request, "cookie") {
        match authenticate_session(
            state.sessions.as_ref(),
            Some(&cookie),
            None,
        )
        .await
        {
            Ok((tenant_id, identity_id)) => {
                let auth_ctx = AuthContext::authenticated(&tenant_id, &identity_id);
                request.extensions_mut().insert(TenantId(tenant_id));
                request.extensions_mut().insert(auth_ctx);
            }
            Err(resp) => return resp,
        }
        return next.run(request).await;
    }

    // 5. Bare tenant header is not a valid authentication method.
    // Without a bearer token, session cookie, or session token, the request is unauthenticated.
    auth_error(
        StatusCode::UNAUTHORIZED,
        "missing authorization header or session cookie",
    )
}

fn is_public_path(path: &str) -> bool {
    path.starts_with("/.well-known/")
        || path.starts_with("/oauth2/")
        || path.starts_with("/health/")
}

fn header_value(request: &Request, name: &str) -> Option<String> {
    request
        .headers()
        .get(name)
        .and_then(|v| v.to_str().ok())
        .map(str::to_string)
}

/// Extract a bearer token from the `Authorization` header.
///
/// The `Bearer` prefix is matched case-insensitively and empty tokens are
/// rejected.
pub fn bearer_token(headers: &axum::http::HeaderMap) -> Option<String> {
    headers
        .get(axum::http::header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| {
            let (scheme, token) = v.split_once(' ')?;
            if !scheme.eq_ignore_ascii_case("Bearer") || token.is_empty() {
                return None;
            }
            Some(token.to_string())
        })
}

/// Extract a named cookie value from the `Cookie` header.
pub fn session_cookie(headers: &axum::http::HeaderMap, name: &str) -> Option<String> {
    headers
        .get(axum::http::header::COOKIE)
        .and_then(|v| v.to_str().ok())
        .and_then(|cookies| {
            cookies.split(';').find_map(|cookie| {
                let (cookie_name, value) = cookie.trim().split_once('=')?;
                if cookie_name == name {
                    Some(value.to_string())
                } else {
                    None
                }
            })
        })
}

/// Hash a secret token for cache keys and audit logging.
pub fn hash_token(token: &str) -> String {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(token.as_bytes());
    hex::encode(hasher.finalize())
}

#[allow(clippy::result_large_err)]
async fn authenticate_session(
    client: &dyn SessionClient,
    cookie: Option<&str>,
    token: Option<&str>,
) -> Result<(String, String), Response> {
    let session = client
        .to_session(cookie, token)
        .await
        .map_err(|_| auth_error(StatusCode::UNAUTHORIZED, "invalid or expired session"))?;

    // sso-gateway introspection injects tenant_id directly into the response.
    if let Some(tenant_id) = session.get("tenant_id").and_then(|v| v.as_str()) {
        let subject = session
            .get("sub")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        return Ok((tenant_id.to_string(), subject));
    }

    // Fall back to identity-based session extraction.
    let upstream_identity_id = session["identity"]["id"].as_str().unwrap_or("").to_string();

    if upstream_identity_id.is_empty() {
        return Err(auth_error(
            StatusCode::UNAUTHORIZED,
            "session missing identity",
        ));
    }

    Ok((upstream_identity_id.clone(), upstream_identity_id))
}

#[allow(clippy::result_large_err)]
async fn authenticate_session_cookie(
    signer: &SessionTokenSigner,
    store: Option<&dyn SessionStore>,
    cookie: &str,
) -> Result<(String, String), Response> {
    let claims = signer.verify(cookie).map_err(|err| {
        tracing::debug!(%err, "session cookie verification failed");
        auth_error(StatusCode::UNAUTHORIZED, "invalid or expired session cookie")
    })?;

    if let Some(store) = store {
        let active = store.is_active(&claims.sid).await.map_err(|err| {
            tracing::warn!(%err, "session store lookup failed");
            auth_error(StatusCode::INTERNAL_SERVER_ERROR, "session store error")
        })?;
        if !active {
            return Err(auth_error(
                StatusCode::UNAUTHORIZED,
                "session has been revoked",
            ));
        }
    }

    Ok((claims.tenant_id, claims.sub))
}

fn auth_error(status: StatusCode, message: &'static str) -> Response {
    let body = Body::from(format!("{{\"error\":\"{message}\"}}"));
    (
        status,
        [(axum::http::header::CONTENT_TYPE, "application/json")],
        body,
    )
        .into_response()
}

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

    #[test]
    fn is_public_path_matches_public_prefixes() {
        assert!(is_public_path("/.well-known/openid-configuration"));
        assert!(is_public_path("/oauth2/auth"));
        assert!(is_public_path("/health/live"));
        assert!(!is_public_path("/api/v1/things"));
    }

    #[test]
    fn bearer_token_extracts_token() {
        let mut headers = axum::http::HeaderMap::new();
        headers.insert(
            axum::http::header::AUTHORIZATION,
            axum::http::HeaderValue::from_static("Bearer secret-token"),
        );
        assert_eq!(bearer_token(&headers), Some("secret-token".to_string()));
    }

    #[test]
    fn bearer_token_is_case_insensitive() {
        let mut headers = axum::http::HeaderMap::new();
        headers.insert(
            axum::http::header::AUTHORIZATION,
            axum::http::HeaderValue::from_static("bearer secret-token"),
        );
        assert_eq!(bearer_token(&headers), Some("secret-token".to_string()));
    }

    #[test]
    fn bearer_token_rejects_empty_token() {
        let mut headers = axum::http::HeaderMap::new();
        headers.insert(
            axum::http::header::AUTHORIZATION,
            axum::http::HeaderValue::from_static("Bearer "),
        );
        assert_eq!(bearer_token(&headers), None);
    }

    #[test]
    fn bearer_token_rejects_non_bearer() {
        let mut headers = axum::http::HeaderMap::new();
        headers.insert(
            axum::http::header::AUTHORIZATION,
            axum::http::HeaderValue::from_static("Basic dXNlcjpwYXNz"),
        );
        assert_eq!(bearer_token(&headers), None);
    }

    #[test]
    fn session_cookie_extracts_named_cookie() {
        let mut headers = axum::http::HeaderMap::new();
        headers.insert(
            axum::http::header::COOKIE,
            axum::http::HeaderValue::from_static("other=1; __Host-sso_session=abc123; another=2"),
        );
        assert_eq!(
            session_cookie(&headers, SESSION_COOKIE_NAME),
            Some("abc123".to_string())
        );
    }

    #[test]
    fn session_cookie_returns_none_when_missing() {
        let mut headers = axum::http::HeaderMap::new();
        headers.insert(
            axum::http::header::COOKIE,
            axum::http::HeaderValue::from_static("other=1"),
        );
        assert_eq!(session_cookie(&headers, SESSION_COOKIE_NAME), None);
    }

    #[test]
    fn hash_token_is_deterministic_and_hex() {
        let h1 = hash_token("my-secret-token");
        let h2 = hash_token("my-secret-token");
        assert_eq!(h1, h2);
        assert_eq!(h1.len(), 64);
        assert!(h1.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn hash_token_differs_for_different_tokens() {
        let h1 = hash_token("token-one");
        let h2 = hash_token("token-two");
        assert_ne!(h1, h2);
    }

    #[test]
    fn auth_context_require_scope_enforces() {
        let ctx = AuthContext::authenticated("tenant-1", "sub-1")
            .with_scopes(vec!["tenant:read".into()]);
        assert!(ctx.require_scope("tenant:read").is_ok());
        let err = ctx.require_scope("tenant:write").unwrap_err();
        assert!(matches!(err, crate::error::ServiceError::PermissionDenied(_)));
    }

    #[test]
    fn auth_context_require_amr_enforces() {
        let ctx = AuthContext::authenticated("tenant-1", "sub-1")
            .with_authentication_methods(vec!["password".into(), "totp".into()]);
        assert!(ctx.require_amr("password").is_ok());
        assert!(ctx.require_amr("totp").is_ok());
        let err = ctx.require_amr("webauthn").unwrap_err();
        assert!(matches!(err, crate::error::ServiceError::PermissionDenied(_)));
    }
}