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
//! ⛔ Warning ⛔: This crate is in a very early state and there are still many features I plan to add. In all honesty I don't think you should use it until this message is gone :).
//!
//! # Mini Rust Auth
//!  
//! Some people say that you should never implement you own auth and they are here I am doing it maybe wrong.
//! This was developed for a personal project and I delivery it with no grantee of it working.
//!
//! ## Goal
//!
//! This crate builds out a easy to work with API for auth.
//! It manages the creation, deletion, and verification of users.
//! It also manages the creation, deletion, and validation of sessions.
//!
//! ## Project overview
//!
//! The `rust_auth::auth` module provides a api that can be used in any project.
//! It also provides `rust_auth::wrappers` which provides wrappers around the functions in `rust_auth::auth` that can be used with actix_web as endpoints.
//!
//! The binary built delivers a actix_web based api.
//!
//! ## **Security notes**
//!
//! This is based on 'Argon2' as of now. All commination should be done over tls. If you want yo use this feel free but be aware that I am no security expert.
pub mod auth;
pub mod session;
pub mod wrappers;

#[cfg(test)]
mod session_test {
    use crate::auth;
    use crate::auth::AddUserReturn;
    use crate::session;
    use crate::session::generate_session;
    use actix_web::{http::header::ContentType, test, App, HttpMessage};

    /// Connects to database pool
    async fn connect_to_pool() -> sqlx::Pool<sqlx::Postgres> {
        match auth::connect_to_db_get_pool().await {
            Ok(pool) => pool,
            Err(_) => panic!("could not connect to db"),
        }
    }

    async fn complete_migrations(pool: &sqlx::Pool<sqlx::Postgres>) -> () {
        let sqlx_migrator = sqlx::migrate!();
        let _migration_undo = match sqlx_migrator.undo(pool, 0).await {
            Ok(_) => true,
            Err(err) => return assert!(false, "migrator failed with err: {}", err.to_string()),
        };

        let _migration_run = match sqlx_migrator.run(pool).await {
            Ok(_) => true,
            Err(_) => return assert!(false, "migrator failed run"),
        };
    }

    use super::*;

    #[actix_web::test]
    async fn test_gen_and_valid_session_based() {
        let postgres_pool = match auth::connect_to_db_get_pool().await {
            Ok(pool) => pool,
            Err(_err) => panic!("cound not connect to db"),
        };

        complete_migrations(&postgres_pool).await;

        let creds = auth::Credentials {
            user_name: "test_user_session_based".to_string().to_owned(),
            password: "mypass".to_string().to_owned(),
            realm: "user".to_string().to_owned(),
        };

        let _user_added = match auth::add_user(&creds, &postgres_pool).await {
            AddUserReturn::Good() => (),
            _ => panic!("Add user failed"),
        };

        let app = test::init_service(
            App::new()
                .app_data(actix_web::web::Data::new(postgres_pool.clone()))
                .wrap(actix_session::SessionMiddleware::new(
                    actix_session::storage::CookieSessionStore::default(),
                    actix_web::cookie::Key::from(
                        "wfjro2f2ofj293fj23f2dfljw;fljf2lkfskjdf;slkdfjsd;lkfjsd;lfksjflkdjj23fkj3".as_bytes(),
                    ),
                ))
                .route(
                    "/generate_session",
                    actix_web::web::get().to(session::generate_session_web_resp),
                )
                .route(
                    "/validate_session",
                    actix_web::web::get().to(session::validate_session_web_resp),
                ),
        )
        .await;

        let gen_sesh_req = test::TestRequest::get()
            .uri("/generate_session")
            .set_json(&creds)
            // .insert_header(ContentType::plaintext())
            .to_request();
        let resp = test::call_service(&app, gen_sesh_req).await;
        
        let cookies = match resp.response().cookies().next() {
            Some(cookie) => cookie,
            None => panic!("Cookie was not set")
        };
        let validate_session_request = test::TestRequest::get()
            .uri("/validate_session")
            .cookie(cookies)
            .to_request();
        let resp = test::call_service(&app, validate_session_request).await;
        println!("{:?}", &resp.status());
        println!("{:?}", &resp.response().body());
        assert!(resp.status().is_success());
    }
}

#[cfg(test)]
mod auth_tests {
    use crate::auth;

    /// Connects to database pool
    async fn connect_to_pool() -> sqlx::Pool<sqlx::Postgres> {
        match auth::connect_to_db_get_pool().await {
            Ok(pool) => pool,
            Err(_) => panic!("could not connect to db"),
        }
    }

    /// Will erase and reset the current db for testing
    async fn complete_migrations(pool: &sqlx::Pool<sqlx::Postgres>) -> () {
        let sqlx_migrator = sqlx::migrate!();
        let _migration_undo = match sqlx_migrator.undo(pool, 0).await {
            Ok(_) => true,
            Err(err) => return assert!(false, "migrator failed with err: {}", err.to_string()),
        };

        let _migration_run = match sqlx_migrator.run(pool).await {
            Ok(_) => true,
            Err(_) => return assert!(false, "migrator failed run"),
        };
    }

    /// Tests that we are able to generate a session
    #[actix_web::test]
    async fn get_session() {
        let pool = connect_to_pool().await;
        complete_migrations(&pool).await;

        let creds = auth::Credentials {
            user_name: "test_user".to_string().to_owned(),
            password: "my_pass".to_string().to_owned(),
            realm: "user".to_string().to_owned(),
        };

        let _add_user_result = match auth::add_user(&creds, &pool).await {
            auth::AddUserReturn::Good() => (),
            _ => (), // Pass bc other tests may have inserted user
        };

        match auth::generate_session(&creds, &pool, auth::SESSION_VALID_FOR_SECONDS).await {
            Ok(session) => {
                assert!(session.user_name == creds.user_name && session.session_token != "")
            }
            Err(err) => panic!("the test for get session failed with: {:?}", err),
        }
    }

    /// Checks that after a session is created it can be properly validated
    #[actix_web::test]
    async fn verify_session() {
        let pool = connect_to_pool().await;
        complete_migrations(&pool).await;

        let creds = auth::Credentials {
            user_name: "test_user_verify_session".to_string().to_owned(),
            password: "mypass".to_string().to_owned(),
            realm: "user".to_string().to_owned(),
        };

        let _add_user_result = match auth::add_user(&creds, &pool).await {
            auth::AddUserReturn::Good() => (),
            _ => panic!("Add user failed"),
        };

        let session = match auth::generate_session(&creds, &pool, auth::SESSION_VALID_FOR_SECONDS).await {
            Ok(session) => session,
            Err(err) => {
                return assert!(
                    false,
                    "Generate session got error:{:?}\non user:{:?}",
                    err, creds
                )
            }
        };

        match auth::validate_session(&session, &pool).await {
            auth::SessionValidated::ValidSession() => assert!(true, "Session validated"),
            auth::SessionValidated::InvalidSession() => {
                assert!(false, "Session wrongly invalidated")
            }
        }
    }

    #[actix_web::test]
    async fn verify_session_invalid_token_end() {
        let pool = connect_to_pool().await;
        complete_migrations(&pool).await;

        let creds = auth::Credentials {
            user_name: "test_user".to_string().to_owned(),
            password: "my_pass".to_string().to_owned(),
            realm: "user".to_string().to_owned(),
        };

        let _add_user_result = match auth::add_user(&creds, &pool).await {
            auth::AddUserReturn::Good() => (),
            _ => (),
        };

        let mut session = match auth::generate_session(&creds, &pool, auth::SESSION_VALID_FOR_SECONDS).await {
            Ok(session) => session,
            Err(err) => return assert!(false, "{:?}", err),
        };

        // Alter session token such that it no longer matches what is in the db
        let replace_last_char_with = match session.session_token.pop() {
            Some(c) => {
                if c == 'a' {
                    'b'
                } else {
                    'a'
                }
            }
            None => 'a',
        };

        session.session_token.push(replace_last_char_with);
        match auth::validate_session(&session, &pool).await {
            auth::SessionValidated::ValidSession() => assert!(false, "Session validated wrongly"),
            auth::SessionValidated::InvalidSession() => {
                assert!(true, "Session correctly invalidated")
            }
        }
    }

    #[actix_web::test]
    async fn verify_session_invalid_user_name() {
        let pool = connect_to_pool().await;
        complete_migrations(&pool).await;

        let creds = auth::Credentials {
            user_name: "test_user".to_string().to_owned(),
            password: "my_pass".to_string().to_owned(),
            realm: "user".to_string().to_owned(),
        };

        let _add_user_result = match auth::add_user(&creds, &pool).await {
            auth::AddUserReturn::Good() => (),
            _ => (),
        };

        let mut session = match auth::generate_session(&creds, &pool, auth::SESSION_VALID_FOR_SECONDS).await {
            Ok(session) => session,
            Err(err) => return assert!(false, "{:?}", err),
        };

        // Alter session token such that it no longer matches what is in the db
        session.user_name = "".to_string();
        match auth::validate_session(&session, &pool).await {
            auth::SessionValidated::ValidSession() => assert!(false, "Session validated wrongly"),
            auth::SessionValidated::InvalidSession() => {
                assert!(true, "Session correctly invalidated")
            }
        }
    }

    #[actix_web::test]
    async fn invalidate_session_test() {
        let pool = connect_to_pool().await;
        complete_migrations(&pool).await;

        let creds = auth::Credentials {
            user_name: "test_user".to_string().to_owned(),
            password: "my_pass".to_string().to_owned(),
            realm: "user".to_string().to_owned(),
        };

        let _add_user_result = match auth::add_user(&creds, &pool).await {
            auth::AddUserReturn::Good() => (),
            _ => (),
        };

        let session = match auth::generate_session(&creds, &pool, auth::SESSION_VALID_FOR_SECONDS).await {
            Ok(session) => session,
            Err(err) => return assert!(false, "{:?}", err),
        };

        match auth::invalidate_session(&session, &pool).await {
            auth::SessionInvalided::SucessfullyInvalidated() => {
                match auth::validate_session(&session, &pool).await {
                    auth::SessionValidated::ValidSession() => {
                        panic!("Session was reported invalidated but was still returning as valid")
                    }
                    auth::SessionValidated::InvalidSession() => {
                        assert!(true, "Session invalidated correctly")
                    }
                }
            }

            _ => assert!(false, "Session invalidated error"),
        }
    }
}