Skip to main content

che_rest/auth/
mod.rs

1pub mod access;
2pub mod models;
3pub mod views;
4
5use std::{any::Any, sync::Arc};
6
7use axum::{
8    body::Body,
9    extract::State,
10    http::{HeaderValue, Method, Request, header},
11    middleware::Next,
12    response::{IntoResponse, Response},
13};
14#[cfg(all(test, feature = "sqlite"))]
15use che_orm::ProjectState;
16use che_orm::{Migration, Model};
17
18mod migration_access;
19mod migration_initial;
20use sha2::{Digest, Sha256};
21use time::OffsetDateTime;
22
23use crate::{
24    AppModule, AppState, Filter, FilterSetSpec, ModuleContext, Permission, ViewAction, ViewSet,
25};
26
27pub use models::{
28    AccessEvent, AuthSession, AuthToken, Group, GroupMembership, GroupModelPermission, User,
29    UserModelPermission, hash_password, verify_password,
30};
31
32#[derive(che_orm::ModelSerializer)]
33#[serializer(model = User)]
34pub struct AdminUserSerializer {
35    #[serializer(read_only)]
36    pub id: i64,
37    #[serializer(read_only)]
38    pub username: String,
39}
40
41#[derive(Clone, Copy, Default)]
42pub struct AdminUserViewSet;
43
44#[derive(Clone, Copy, Default)]
45pub struct AdminUserFilterSet;
46
47static ADMIN_USER_FILTERS: &[Filter<User>] = &[Filter::contains(User::USERNAME)];
48
49impl FilterSetSpec for AdminUserFilterSet {
50    type Model = User;
51
52    fn filters(&self) -> &'static [Filter<Self::Model>] {
53        ADMIN_USER_FILTERS
54    }
55}
56
57impl ViewSet for AdminUserViewSet {
58    type Model = User;
59    type Serializer = AdminUserSerializer;
60    type ListSerializer = Self::Serializer;
61    type QuerySet = che_orm::DatabaseQuery<User>;
62    type FilterSet = AdminUserFilterSet;
63    type Permission = ReadOnlyAdminUser;
64
65    fn get_queryset(&self) -> Self::QuerySet {
66        che_orm::DatabaseQuery::new(User::query())
67    }
68
69    fn path(&self) -> &'static str {
70        "/auth/users"
71    }
72}
73
74#[derive(Debug, Clone, serde::Serialize)]
75pub struct CurrentUser {
76    pub id: i64,
77    pub username: String,
78    pub is_staff: bool,
79    pub is_admin: bool,
80    pub is_superuser: bool,
81}
82
83#[derive(Clone)]
84pub struct CurrentPrincipal {
85    auth_user: CurrentUser,
86    app_user: Option<Arc<dyn Any + Send + Sync>>,
87}
88
89impl CurrentPrincipal {
90    pub fn auth_user(&self) -> &CurrentUser {
91        &self.auth_user
92    }
93
94    pub fn app<T: Send + Sync + 'static>(&self) -> Option<&T> {
95        self.app_user
96            .as_deref()
97            .and_then(|user| user.downcast_ref::<T>())
98    }
99}
100
101#[derive(Debug, Clone, Copy, Default)]
102pub struct IsAuthenticated;
103
104impl<M: che_orm::Model> Permission<M> for IsAuthenticated {
105    fn object_scoped(&self) -> bool {
106        false
107    }
108    async fn check_request(
109        &self,
110        _state: crate::rest::permissions::PermissionContext<'_>,
111        current: Option<&CurrentPrincipal>,
112        _action: ViewAction,
113    ) -> crate::AppResult<()> {
114        current.map(|_| ()).ok_or(crate::AppError::Unauthorized(
115            "authentication credentials were not provided".into(),
116        ))
117    }
118}
119
120#[derive(Debug, Clone, Copy, Default)]
121pub struct IsAdminUser;
122
123impl<M: che_orm::Model> Permission<M> for IsAdminUser {
124    fn object_scoped(&self) -> bool {
125        false
126    }
127    async fn check_request(
128        &self,
129        _state: crate::rest::permissions::PermissionContext<'_>,
130        current: Option<&CurrentPrincipal>,
131        _action: ViewAction,
132    ) -> crate::AppResult<()> {
133        if current.is_some_and(|current| {
134            let user = current.auth_user();
135            user.is_admin || user.is_superuser
136        }) {
137            Ok(())
138        } else {
139            Err(crate::AppError::Forbidden(
140                "admin permissions are required".into(),
141            ))
142        }
143    }
144}
145
146#[derive(Debug, Clone, Copy, Default)]
147pub struct ReadOnlyAdminUser;
148
149impl<M: che_orm::Model> Permission<M> for ReadOnlyAdminUser {
150    fn object_scoped(&self) -> bool {
151        false
152    }
153    async fn check_request(
154        &self,
155        state: crate::rest::permissions::PermissionContext<'_>,
156        current: Option<&CurrentPrincipal>,
157        action: ViewAction,
158    ) -> crate::AppResult<()> {
159        <IsAdminUser as Permission<M>>::check_request(&IsAdminUser, state, current, action).await?;
160        if matches!(action, ViewAction::List | ViewAction::Retrieve) {
161            Ok(())
162        } else {
163            Err(crate::AppError::Forbidden(
164                "user relation endpoint is read-only".into(),
165            ))
166        }
167    }
168}
169
170#[derive(Debug, Clone)]
171pub struct CurrentSession {
172    pub id: i64,
173    pub user_id: i64,
174    pub csrf_hash: String,
175    pub revision: i64,
176    pub created_at: OffsetDateTime,
177    pub expires_at: OffsetDateTime,
178}
179
180#[derive(Clone, Copy)]
181pub struct AuthModule;
182
183pub fn module() -> AuthModule {
184    AuthModule
185}
186
187/// Declarative initial migration shipped with the authentication application.
188/// A project consumes this registry through [`crate::Management`], rather
189/// than copying the migration source into its own migrations directory.
190pub fn migrations() -> Vec<Migration> {
191    vec![
192        migration_initial::migration(),
193        migration_access::migration(),
194    ]
195}
196
197impl AppModule for AuthModule {
198    fn name(&self) -> &'static str {
199        "auth"
200    }
201
202    fn schema(&self) -> che_orm::SchemaSet {
203        che_orm::SchemaSet::new()
204            .model::<User>()
205            .model::<AuthToken>()
206            .model::<AuthSession>()
207            .model::<Group>()
208            .model::<GroupMembership>()
209            .model::<UserModelPermission>()
210            .model::<GroupModelPermission>()
211            .model::<AccessEvent>()
212    }
213
214    fn migrations(&self) -> Vec<Migration> {
215        migrations()
216    }
217
218    fn init(&self, context: &mut ModuleContext) {
219        context.route_at_root(views::routes());
220        context.route(views::api_routes());
221        context.viewset_with(AdminUserViewSet);
222    }
223
224    fn middleware(&self, router: axum::Router, _state: &AppState) -> axum::Router {
225        router.layer(axum::middleware::from_fn_with_state(
226            _state.clone(),
227            auth_middleware,
228        ))
229    }
230
231    fn openapi(&self, state: &AppState) -> serde_json::Value {
232        serde_json::json!({
233            "paths": {
234                "/api-token-auth/": {"post": {"servers": [{"url": "/"}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/LoginRequest"}}}}, "responses": {"200": {"description": "Token issued"}, "401": {"$ref": "#/components/responses/Unauthorized"}}}},
235                "/api-session-auth/login/": {"post": {"servers": [{"url": "/"}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/LoginRequest"}}}}, "responses": {"200": {"description": "Session cookie issued"}, "401": {"$ref": "#/components/responses/Unauthorized"}}}},
236                "/api-session-auth/logout/": {"post": {"servers": [{"url": "/"}], "responses": {"204": {"description": "Logged out"}}}},
237                "/api-session-auth/me/": {"get": {"servers": [{"url": "/"}], "security": [{"SessionCookie": []}], "responses": {"200": {"description": "Current session"}, "401": {"$ref": "#/components/responses/Unauthorized"}}}}
238            },
239            "components": {
240                "schemas": {
241                    "LoginRequest": {"type": "object", "required": ["username", "password"], "properties": {"username": {"type": "string"}, "password": {"type": "string", "format": "password"}}}
242                },
243                "responses": {
244                    "Unauthorized": {"description": "Unauthorized", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}
245                },
246                "securitySchemes": {
247                    "TokenAuth": {"type": "apiKey", "in": "header", "name": "Authorization", "description": "Use the format: Token <key>"},
248                    "SessionCookie": {"type": "apiKey", "in": "cookie", "name": state.config.auth.session.cookie_name},
249                    "CsrfToken": {"type": "apiKey", "in": "header", "name": "X-CSRF-Token"}
250                }
251            }
252        })
253    }
254}
255
256pub async fn auth_middleware(
257    State(state): State<AppState>,
258    mut request: Request<Body>,
259    next: Next,
260) -> Response {
261    if let Some(token) = request
262        .headers()
263        .get(header::AUTHORIZATION)
264        .and_then(|value| value.to_str().ok())
265        .and_then(|value| value.strip_prefix("Token "))
266        .map(str::trim)
267        .filter(|value| !value.is_empty())
268    {
269        let Ok(Some(auth_token)) = state
270            .database()
271            .query::<AuthToken>()
272            .filter(AuthToken::KEY_HASH.eq(token_hash(token)))
273            .first()
274            .await
275        else {
276            return crate::AppError::Unauthorized("invalid token".into()).into_response();
277        };
278        let Ok(Some(user)) = state.database().get::<User>(auth_token.user_id).await else {
279            return crate::AppError::Unauthorized("invalid token".into()).into_response();
280        };
281        if !user.is_active {
282            return crate::AppError::Unauthorized("inactive user".into()).into_response();
283        }
284        let principal = match current_principal(&state, &user).await {
285            Ok(principal) => principal,
286            Err(error) => return error.into_response(),
287        };
288        request.extensions_mut().insert(principal);
289        return next.run(request).await;
290    }
291
292    let Some(session_key) = cookie(&request, &state.config.auth.session.cookie_name) else {
293        return next.run(request).await;
294    };
295    let Some((session, user)) = load_session(&state, &session_key).await else {
296        return next.run(request).await;
297    };
298    let csrf_token = cookie(&request, &state.config.auth.session.csrf_cookie_name)
299        .filter(|token| token_hash(token) == session.csrf_hash);
300    if unsafe_method(request.method()) && !csrf_valid(&request, &session) {
301        return crate::AppError::Forbidden("CSRF validation failed".into()).into_response();
302    }
303    let principal = match current_principal(&state, &user).await {
304        Ok(principal) => principal,
305        Err(error) => return error.into_response(),
306    };
307    request.extensions_mut().insert(principal);
308    request.extensions_mut().insert(session.clone());
309    let mut response = next.run(request).await;
310    renew_session(
311        &state,
312        &session,
313        &session_key,
314        csrf_token.as_deref(),
315        &mut response,
316    )
317    .await;
318    response
319}
320
321fn current_user(user: &User) -> CurrentUser {
322    CurrentUser {
323        id: user.id,
324        username: user.username.clone(),
325        is_staff: user.is_staff,
326        is_admin: user.is_admin,
327        is_superuser: user.is_superuser,
328    }
329}
330
331async fn current_principal(state: &AppState, user: &User) -> crate::AppResult<CurrentPrincipal> {
332    Ok(CurrentPrincipal {
333        auth_user: current_user(user),
334        app_user: state.resolve_current_user(user).await?,
335    })
336}
337
338async fn load_session(state: &AppState, key: &str) -> Option<(CurrentSession, User)> {
339    let session = state
340        .database()
341        .query::<AuthSession>()
342        .filter(AuthSession::KEY_HASH.eq(token_hash(key)))
343        .first()
344        .await
345        .ok()??;
346    if session.expires_at <= OffsetDateTime::now_utc() {
347        return None;
348    }
349    let user = state.database().get::<User>(session.user_id).await.ok()??;
350    if !user.is_active {
351        return None;
352    }
353    Some((
354        CurrentSession {
355            id: session.id,
356            user_id: session.user_id,
357            csrf_hash: session.csrf_hash,
358            revision: session.revision,
359            created_at: session.created_at,
360            expires_at: session.expires_at,
361        },
362        user,
363    ))
364}
365
366async fn renew_session(
367    state: &AppState,
368    session: &CurrentSession,
369    session_key: &str,
370    csrf_token: Option<&str>,
371    response: &mut Response,
372) {
373    let now = OffsetDateTime::now_utc();
374    let Some(csrf_token) = csrf_token else {
375        return;
376    };
377    let Some(expires_at) = renewed_expiry(state, session, now) else {
378        return;
379    };
380    let Ok(Some(_)) = state
381        .database()
382        .update::<AuthSession>(session.id)
383        .set(AuthSession::EXPIRES_AT, expires_at)
384        .execute()
385        .await
386    else {
387        return;
388    };
389
390    let max_age = (expires_at - now).whole_seconds();
391    append_cookie(
392        response,
393        cookie_header(
394            state,
395            &state.config.auth.session.cookie_name,
396            session_key,
397            max_age,
398            true,
399        ),
400    );
401    append_cookie(
402        response,
403        cookie_header(
404            state,
405            &state.config.auth.session.csrf_cookie_name,
406            csrf_token,
407            max_age,
408            false,
409        ),
410    );
411}
412
413fn renewed_expiry(
414    state: &AppState,
415    session: &CurrentSession,
416    now: OffsetDateTime,
417) -> Option<OffsetDateTime> {
418    let config = &state.config.auth.session;
419    if config.ttl_seconds <= 0
420        || config.renewal_window_seconds <= 0
421        || config.absolute_ttl_seconds <= 0
422        || session.expires_at > now + time::Duration::seconds(config.renewal_window_seconds)
423    {
424        return None;
425    }
426
427    let absolute_expiry = session.created_at + time::Duration::seconds(config.absolute_ttl_seconds);
428    let expires_at = (now + time::Duration::seconds(config.ttl_seconds)).min(absolute_expiry);
429    (expires_at > session.expires_at).then_some(expires_at)
430}
431
432fn append_cookie(response: &mut Response, value: String) {
433    if let Ok(value) = HeaderValue::from_str(&value) {
434        response.headers_mut().append(header::SET_COOKIE, value);
435    }
436}
437
438fn cookie(request: &Request<Body>, name: &str) -> Option<String> {
439    request
440        .headers()
441        .get(header::COOKIE)?
442        .to_str()
443        .ok()?
444        .split(';')
445        .map(str::trim)
446        .find_map(|item| item.strip_prefix(&format!("{name}=")).map(str::to_owned))
447}
448
449fn unsafe_method(method: &Method) -> bool {
450    matches!(
451        method,
452        &Method::POST | &Method::PUT | &Method::PATCH | &Method::DELETE
453    )
454}
455
456fn csrf_valid(request: &Request<Body>, session: &CurrentSession) -> bool {
457    request
458        .headers()
459        .get("X-CSRF-Token")
460        .and_then(|value| value.to_str().ok())
461        .is_some_and(|value| token_hash(value) == session.csrf_hash)
462}
463
464fn cookie_header(
465    state: &AppState,
466    name: &str,
467    value: &str,
468    max_age: i64,
469    http_only: bool,
470) -> String {
471    let mut result = format!(
472        "{name}={value}; Path=/; Max-Age={max_age}; SameSite={}",
473        state.config.auth.session.same_site
474    );
475    if http_only {
476        result.push_str("; HttpOnly");
477    }
478    if state.config.auth.session.secure {
479        result.push_str("; Secure");
480    }
481    result
482}
483
484pub fn generate_token() -> String {
485    let mut bytes = [0_u8; 32];
486    rand::RngCore::fill_bytes(&mut rand::thread_rng(), &mut bytes);
487    hex::encode(bytes)
488}
489
490pub fn token_hash(token: &str) -> String {
491    hex::encode(Sha256::digest(token.as_bytes()))
492}
493
494#[cfg(all(test, feature = "sqlite"))]
495mod tests {
496    use std::sync::{
497        Arc,
498        atomic::{AtomicUsize, Ordering},
499    };
500
501    use super::*;
502    use axum::{
503        Extension, Json, Router,
504        body::{Body, to_bytes},
505        http::{Request, StatusCode, header},
506        routing::get,
507    };
508    use serde_json::json;
509    use tower::ServiceExt;
510
511    use crate::{AllowAny, AppModule, CurrentUserResolverFuture, ModuleContext, Server, ViewSet};
512
513    #[test]
514    fn library_migrations_replay_the_auth_schema() {
515        assert_eq!(migrations()[0].checksum, "v1:cf9bef2cfd081db4");
516        let graph = che_orm::MigrationGraph::new(migrations()).unwrap();
517        let actual = graph.replay(Default::default()).unwrap();
518        let expected = ProjectState::from_app_schema("auth", &AuthModule.schema());
519        assert_eq!(actual.models(), expected.models());
520    }
521
522    #[derive(Debug, Clone, PartialEq, Eq)]
523    struct ApplicationUser {
524        user_id: i64,
525        organization_id: i64,
526    }
527
528    struct TestModule;
529
530    #[derive(Clone, Copy, Default)]
531    struct ApplicationUserPermission;
532
533    impl Permission<User> for ApplicationUserPermission {
534        async fn check_request(
535            &self,
536            _state: crate::rest::permissions::PermissionContext<'_>,
537            current: Option<&CurrentPrincipal>,
538            _action: ViewAction,
539        ) -> crate::AppResult<()> {
540            current
541                .and_then(|current| current.app::<ApplicationUser>())
542                .ok_or_else(|| crate::AppError::Unauthorized("profile required".into()))?;
543            Ok(())
544        }
545    }
546
547    #[derive(Clone, Copy, Default)]
548    struct ApplicationUserViewSet;
549
550    impl ViewSet for ApplicationUserViewSet {
551        type Model = User;
552        type Serializer = AdminUserSerializer;
553        type ListSerializer = Self::Serializer;
554        type QuerySet = che_orm::DatabaseQuery<User>;
555        type FilterSet = AdminUserFilterSet;
556        type Permission = AllowAny;
557
558        fn path(&self) -> &'static str {
559            "/profiles"
560        }
561
562        fn get_queryset(&self) -> Self::QuerySet {
563            che_orm::DatabaseQuery::new(User::query())
564        }
565
566        fn prepare_create(
567            &self,
568            _state: &AppState,
569            current: Option<&CurrentPrincipal>,
570            write: che_orm::ValidatedWrite<Self::Model>,
571        ) -> crate::AppResult<che_orm::ValidatedWrite<Self::Model>> {
572            current
573                .and_then(|current| current.app::<ApplicationUser>())
574                .ok_or_else(|| crate::AppError::Unauthorized("profile required".into()))?;
575            Ok(write)
576        }
577    }
578
579    impl AppModule for TestModule {
580        fn name(&self) -> &'static str {
581            "test"
582        }
583
584        fn schema(&self) -> che_orm::SchemaSet {
585            che_orm::SchemaSet::new()
586        }
587
588        fn init(&self, context: &mut ModuleContext) {
589            context.route_at_root(
590                Router::new()
591                    .route("/protected", get(protected))
592                    .route("/public", get(|| async { StatusCode::OK })),
593            );
594        }
595    }
596
597    async fn protected(current: Option<Extension<CurrentPrincipal>>) -> Json<serde_json::Value> {
598        let current = current.map(|current| current.0);
599        Json(json!({
600            "authenticated": current.is_some(),
601            "id": current.as_ref().map(|current| current.auth_user().id),
602            "has_profile": current
603                .as_ref()
604                .is_some_and(|current| current.app::<ApplicationUser>().is_some()),
605        }))
606    }
607
608    fn profile_resolver(
609        calls: Arc<AtomicUsize>,
610    ) -> impl for<'a> Fn(&'a AppState, &'a User) -> CurrentUserResolverFuture<'a, ApplicationUser>
611    + Send
612    + Sync
613    + 'static {
614        move |_state, user| {
615            let calls = calls.clone();
616            let user_id = user.id;
617            Box::pin(async move {
618                calls.fetch_add(1, Ordering::SeqCst);
619                Ok(Some(ApplicationUser {
620                    user_id,
621                    organization_id: 7,
622                }))
623            })
624        }
625    }
626
627    fn no_profile_resolver<'a>(
628        _state: &'a AppState,
629        _user: &'a User,
630    ) -> CurrentUserResolverFuture<'a, ApplicationUser> {
631        Box::pin(async { Ok(None) })
632    }
633
634    async fn auth_app(state: AppState) -> axum::Router {
635        Server::new(state)
636            .install(crate::InstalledApps::new().add(module()).add(TestModule))
637            .build()
638            .await
639            .unwrap()
640    }
641
642    async fn setup_auth(state: &AppState) -> User {
643        state.database().create_table::<User>().await.unwrap();
644        state.database().create_table::<AuthToken>().await.unwrap();
645        state
646            .database()
647            .create_table::<AuthSession>()
648            .await
649            .unwrap();
650        state
651            .database()
652            .create::<User>()
653            .set(User::USERNAME, "user")
654            .set(User::PASSWORD_HASH, "unused")
655            .set(User::IS_ACTIVE, true)
656            .set(User::IS_ADMIN, true)
657            .execute()
658            .await
659            .unwrap()
660    }
661
662    async fn response_json(response: axum::response::Response) -> serde_json::Value {
663        serde_json::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap()).unwrap()
664    }
665
666    #[test]
667    fn password_hash_round_trip_and_token_hash_are_stable() {
668        let hash = hash_password("secret").unwrap();
669        assert!(verify_password("secret", &hash));
670        assert!(!verify_password("wrong", &hash));
671        assert_eq!(token_hash("token"), token_hash("token"));
672        assert_ne!(token_hash("token"), token_hash("other"));
673    }
674
675    #[test]
676    fn csrf_requires_matching_token_header() {
677        let token = "csrf-token";
678        let session = CurrentSession {
679            id: 1,
680            user_id: 2,
681            csrf_hash: token_hash(token),
682            revision: 0,
683            created_at: OffsetDateTime::now_utc(),
684            expires_at: OffsetDateTime::now_utc(),
685        };
686        let request = Request::builder()
687            .header("X-CSRF-Token", token)
688            .body(Body::empty())
689            .unwrap();
690        assert!(csrf_valid(&request, &session));
691
692        let request = Request::builder()
693            .header("X-CSRF-Token", "wrong-token")
694            .body(Body::empty())
695            .unwrap();
696        assert!(!csrf_valid(&request, &session));
697    }
698
699    #[tokio::test]
700    async fn session_is_renewed_only_in_the_renewal_window() {
701        let state = AppState::from_database(che_orm::Database::connect(":memory:").await.unwrap());
702        let now = OffsetDateTime::now_utc();
703        let session = CurrentSession {
704            id: 1,
705            user_id: 2,
706            csrf_hash: String::new(),
707            revision: 0,
708            created_at: now - time::Duration::days(5),
709            expires_at: now + time::Duration::hours(1),
710        };
711        let renewed = renewed_expiry(&state, &session, now).unwrap();
712        assert!(renewed > now + time::Duration::days(6));
713
714        let session = CurrentSession {
715            expires_at: now + time::Duration::days(2),
716            ..session
717        };
718        assert!(renewed_expiry(&state, &session, now).is_none());
719    }
720
721    #[tokio::test]
722    async fn session_renewal_does_not_exceed_absolute_ttl() {
723        let state = AppState::from_database(che_orm::Database::connect(":memory:").await.unwrap());
724        let now = OffsetDateTime::now_utc();
725        let created_at = now - time::Duration::days(29);
726        let session = CurrentSession {
727            id: 1,
728            user_id: 2,
729            csrf_hash: String::new(),
730            revision: 0,
731            created_at,
732            expires_at: now + time::Duration::hours(1),
733        };
734        assert_eq!(
735            renewed_expiry(&state, &session, now),
736            Some(created_at + time::Duration::days(30))
737        );
738    }
739
740    #[test]
741    fn cookie_parser_handles_multiple_cookies() {
742        let request = Request::builder()
743            .header(header::COOKIE, "other=value; che_rest_session=session-key")
744            .body(Body::empty())
745            .unwrap();
746        assert_eq!(
747            cookie(&request, "che_rest_session"),
748            Some("session-key".into())
749        );
750        assert_eq!(cookie(&request, "missing"), None);
751    }
752
753    #[tokio::test]
754    async fn admin_permission_requires_admin_or_superuser() {
755        let state = AppState::from_database(che_orm::Database::connect(":memory:").await.unwrap());
756        let regular = CurrentUser {
757            id: 1,
758            username: "regular".into(),
759            is_staff: false,
760            is_admin: false,
761            is_superuser: false,
762        };
763        let regular = CurrentPrincipal {
764            auth_user: regular,
765            app_user: None,
766        };
767        assert!(
768            <IsAdminUser as Permission<User>>::check_request(
769                &IsAdminUser,
770                (&state).into(),
771                Some(&regular),
772                ViewAction::List,
773            )
774            .await
775            .is_err()
776        );
777
778        let admin = CurrentPrincipal {
779            auth_user: CurrentUser {
780                is_admin: true,
781                ..regular.auth_user.clone()
782            },
783            app_user: None,
784        };
785        assert!(
786            <IsAdminUser as Permission<User>>::check_request(
787                &IsAdminUser,
788                (&state).into(),
789                Some(&admin),
790                ViewAction::List,
791            )
792            .await
793            .is_ok()
794        );
795    }
796
797    #[tokio::test]
798    async fn resolver_builds_principal_with_framework_and_application_users() {
799        let calls = Arc::new(AtomicUsize::new(0));
800        let state = AppState::from_database(che_orm::Database::connect_in_memory().await.unwrap())
801            .with_current_user_resolver(profile_resolver(calls.clone()));
802        let user = User {
803            id: 42,
804            username: "user".into(),
805            password_hash: String::new(),
806            is_active: true,
807            is_staff: false,
808            is_admin: true,
809            is_superuser: false,
810        };
811
812        let principal = current_principal(&state, &user).await.unwrap();
813
814        assert_eq!(calls.load(Ordering::SeqCst), 1);
815        assert_eq!(principal.auth_user().id, 42);
816        assert!(principal.auth_user().is_admin);
817        assert_eq!(
818            principal.app::<ApplicationUser>().unwrap().organization_id,
819            7
820        );
821        assert!(principal.app::<String>().is_none());
822    }
823
824    #[tokio::test]
825    async fn resolver_returning_none_keeps_framework_authentication() {
826        let state = AppState::from_database(che_orm::Database::connect_in_memory().await.unwrap())
827            .with_current_user_resolver(no_profile_resolver);
828        let user = User {
829            id: 42,
830            username: "user".into(),
831            password_hash: String::new(),
832            is_active: true,
833            is_staff: false,
834            is_admin: false,
835            is_superuser: false,
836        };
837
838        let principal = current_principal(&state, &user).await.unwrap();
839
840        assert_eq!(principal.auth_user().id, user.id);
841        assert!(principal.app::<ApplicationUser>().is_none());
842        assert!(
843            <IsAuthenticated as Permission<User>>::check_request(
844                &IsAuthenticated,
845                (&state).into(),
846                Some(&principal),
847                ViewAction::List,
848            )
849            .await
850            .is_ok()
851        );
852    }
853
854    #[tokio::test]
855    async fn admin_user_creation_is_mounted_under_api_prefix() {
856        let state = AppState::from_database(che_orm::Database::connect_in_memory().await.unwrap());
857        setup_auth(&state).await;
858        let app = auth_app(state).await;
859        let request = Request::builder()
860            .method(Method::POST)
861            .uri("/api/auth/users/create/")
862            .header(header::CONTENT_TYPE, "application/json")
863            .body(Body::from(r#"{"username":"new-user","password":"secret"}"#))
864            .unwrap();
865
866        let response = app.oneshot(request).await.unwrap();
867
868        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
869    }
870
871    #[tokio::test]
872    async fn custom_permissions_and_viewset_hooks_can_access_application_user() {
873        let state = AppState::from_database(che_orm::Database::connect_in_memory().await.unwrap())
874            .with_current_user_resolver(profile_resolver(Arc::new(AtomicUsize::new(0))));
875        let principal = current_principal(
876            &state,
877            &User {
878                id: 1,
879                username: "user".into(),
880                password_hash: String::new(),
881                is_active: true,
882                is_staff: false,
883                is_admin: false,
884                is_superuser: false,
885            },
886        )
887        .await
888        .unwrap();
889        let write = <AdminUserSerializer as che_orm::ModelWriteSerializer>::is_valid(
890            json!({}),
891            che_orm::WriteMode::Create,
892        )
893        .unwrap();
894
895        <ApplicationUserPermission as Permission<User>>::check_request(
896            &ApplicationUserPermission,
897            (&state).into(),
898            Some(&principal),
899            ViewAction::Create,
900        )
901        .await
902        .unwrap();
903        ApplicationUserViewSet
904            .prepare_create(&state, Some(&principal), write)
905            .unwrap();
906    }
907
908    #[tokio::test]
909    async fn token_and_session_authentication_resolve_application_user() {
910        let calls = Arc::new(AtomicUsize::new(0));
911        let state = AppState::from_database(che_orm::Database::connect_in_memory().await.unwrap())
912            .with_current_user_resolver(profile_resolver(calls.clone()));
913        let user = setup_auth(&state).await;
914        let token = "token";
915        state
916            .database()
917            .create::<AuthToken>()
918            .set(AuthToken::USER_ID, user.id)
919            .set(AuthToken::KEY_HASH, token_hash(token))
920            .execute()
921            .await
922            .unwrap();
923        let session_key = "session";
924        state
925            .database()
926            .create::<AuthSession>()
927            .set(AuthSession::USER_ID, user.id)
928            .set(AuthSession::KEY_HASH, token_hash(session_key))
929            .set(AuthSession::CSRF_HASH, token_hash("csrf"))
930            .set(AuthSession::DATA, "{}")
931            .set(AuthSession::REVISION, 0_i64)
932            .set(
933                AuthSession::EXPIRES_AT,
934                OffsetDateTime::now_utc() + time::Duration::hours(1),
935            )
936            .execute()
937            .await
938            .unwrap();
939        let app = auth_app(state.clone()).await;
940
941        let token_response = app
942            .clone()
943            .oneshot(
944                Request::builder()
945                    .uri("/protected")
946                    .header(header::AUTHORIZATION, "Token token")
947                    .body(Body::empty())
948                    .unwrap(),
949            )
950            .await
951            .unwrap();
952        assert_eq!(token_response.status(), StatusCode::OK);
953        assert_eq!(response_json(token_response).await["has_profile"], true);
954
955        let session_response = app
956            .oneshot(
957                Request::builder()
958                    .uri("/protected")
959                    .header(header::COOKIE, "che_rest_session=session")
960                    .body(Body::empty())
961                    .unwrap(),
962            )
963            .await
964            .unwrap();
965        assert_eq!(session_response.status(), StatusCode::OK);
966        assert_eq!(response_json(session_response).await["id"], user.id);
967        assert_eq!(calls.load(Ordering::SeqCst), 2);
968    }
969
970    #[tokio::test]
971    async fn authentication_succeeds_without_a_profile_or_resolver() {
972        let state = AppState::from_database(che_orm::Database::connect_in_memory().await.unwrap());
973        let user = setup_auth(&state).await;
974        state
975            .database()
976            .create::<AuthToken>()
977            .set(AuthToken::USER_ID, user.id)
978            .set(AuthToken::KEY_HASH, token_hash("token"))
979            .execute()
980            .await
981            .unwrap();
982        let app = auth_app(state).await;
983
984        let public = app
985            .clone()
986            .oneshot(
987                Request::builder()
988                    .uri("/public")
989                    .body(Body::empty())
990                    .unwrap(),
991            )
992            .await
993            .unwrap();
994        assert_eq!(public.status(), StatusCode::OK);
995        let protected = app
996            .oneshot(
997                Request::builder()
998                    .uri("/protected")
999                    .header(header::AUTHORIZATION, "Token token")
1000                    .body(Body::empty())
1001                    .unwrap(),
1002            )
1003            .await
1004            .unwrap();
1005        let payload = response_json(protected).await;
1006        assert_eq!(payload["authenticated"], true);
1007        assert_eq!(payload["has_profile"], false);
1008    }
1009}
1010
1011#[cfg(all(test, feature = "sqlite"))]
1012mod access_tests;