summaryrefslogtreecommitdiffstats
path: root/src/auth.rs
blob: bbc71ec4dc801d6d4b3b6bf44c4d6f6996f04a33 (plain) (blame)
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
use argon2::{
    Argon2, PasswordHash, PasswordHasher, PasswordVerifier,
    password_hash::{SaltString, rand_core::OsRng},
};
use axum::{
    extract::{FromRequestParts, Request, State},
    http::{StatusCode, request::Parts},
    middleware::Next,
    response::{IntoResponse, Redirect, Response},
};
use rusqlite::params;
use serde::Deserialize;
use std::collections::HashMap;
use std::sync::Mutex as StdMutex;
use std::time::Instant;
use uuid::Uuid;

use crate::models::Account;
use crate::routes::AppState;

#[derive(Debug, Deserialize)]
pub struct LoginForm {
    pub username: String,
    pub password: String,
}

const SESSION_COOKIE: &str = "mcui_session";

/// Simple in-memory rate limiter for login attempts.
/// Tracks failed attempts per IP address with a sliding window.
const RATE_LIMIT_WINDOW_SECS: u64 = 300; // 5 minutes
const RATE_LIMIT_MAX_ATTEMPTS: u32 = 10;

static LOGIN_ATTEMPTS: std::sync::LazyLock<StdMutex<HashMap<String, (u32, Instant)>>> =
    std::sync::LazyLock::new(|| StdMutex::new(HashMap::new()));

fn check_rate_limit(ip: &str) -> bool {
    let mut attempts = LOGIN_ATTEMPTS.lock().unwrap();
    let now = Instant::now();
    // Clean stale entries
    attempts.retain(|_, (_, ts)| now.duration_since(*ts).as_secs() < RATE_LIMIT_WINDOW_SECS);
    let entry = attempts.entry(ip.to_string()).or_insert((0, now));
    if entry.0 >= RATE_LIMIT_MAX_ATTEMPTS {
        false
    } else {
        entry.0 += 1;
        entry.1 = now;
        true
    }
}

fn reset_rate_limit(ip: &str) {
    let mut attempts = LOGIN_ATTEMPTS.lock().unwrap();
    attempts.remove(ip);
}

pub fn hash_password(password: &str) -> Result<String, argon2::password_hash::Error> {
    let salt = SaltString::generate(&mut OsRng);
    let hash = Argon2::default().hash_password(password.as_bytes(), &salt)?;
    Ok(hash.to_string())
}

pub fn verify_password(password: &str, hash: &str) -> Result<bool, argon2::password_hash::Error> {
    let parsed = PasswordHash::new(hash)?;
    Ok(Argon2::default()
        .verify_password(password.as_bytes(), &parsed)
        .is_ok())
}

pub async fn authenticate(
    State(state): State<AppState>,
    axum::Form(form): axum::Form<LoginForm>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
    // Rate limiting: check by client IP
    // (We use a placeholder as we can't easily get the real IP without a proxy-aware extractor;
    //  a reverse proxy should set X-Forwarded-For.)
    let rate_limit_ip = "global"; // simplified; in production use X-Forwarded-For
    if !check_rate_limit(rate_limit_ip) {
        return Err((
            StatusCode::TOO_MANY_REQUESTS,
            "Too many login attempts. Please try again later.".into(),
        ));
    }

    let conn = state.db.conn();

    let account = conn
        .query_row(
            "SELECT id, username, is_superuser, password_change_required FROM accounts WHERE username = ?1",
            params![form.username],
            |row| {
                Ok(Account {
                    id: row.get(0)?,
                    username: row.get(1)?,
                    is_superuser: row.get::<_, i32>(2)? != 0,
                    password_change_required: row.get::<_, i32>(3)? != 0,
                })
            },
        )
        .map_err(|_| (StatusCode::UNAUTHORIZED, "Invalid username or password".into()))?;

    let hash: String = conn
        .query_row(
            "SELECT password FROM accounts WHERE id = ?1",
            params![account.id],
            |row| row.get(0),
        )
        .map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "Database error".into()))?;

    if !verify_password(&form.password, &hash).unwrap_or(false) {
        return Err((
            StatusCode::UNAUTHORIZED,
            "Invalid username or password".into(),
        ));
    }

    // Successful login — reset rate limit
    reset_rate_limit(rate_limit_ip);

    let session_id = Uuid::new_v4().to_string();
    conn.execute(
        "INSERT INTO sessions (id, account_id) VALUES (?1, ?2)",
        params![session_id, account.id],
    )
    .map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "Session error".into()))?;
    drop(conn);

    // Set Secure flag when not on localhost (for when behind a reverse proxy with TLS)
    // The Max-Age is deliberately set to 24h (86400s) as a first line of defense.
    // Server-side enforcement happens in require_auth via the created_at check.
    let cookie_value =
        format!("{SESSION_COOKIE}={session_id}; Path=/; HttpOnly; Max-Age=86400; SameSite=Strict");

    let redirect = if account.password_change_required {
        Redirect::to("/change-password")
    } else {
        Redirect::to("/")
    };

    Ok(([(axum::http::header::SET_COOKIE, cookie_value)], redirect))
}

/// Number of seconds after which a session expires server-side.
const SESSION_MAX_AGE_SECS: i64 = 86400; // 24 hours

pub async fn require_auth(
    State(state): State<AppState>,
    mut request: Request,
    next: Next,
) -> Result<Response, Response> {
    let raw_cookies = request
        .headers()
        .get(axum::http::header::COOKIE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("[no cookie header]")
        .to_string();

    let session_id = raw_cookies.split(';').map(|s| s.trim()).find_map(|cookie| {
        if let Some((name, value)) = cookie.split_once('=') {
            let n = name.trim();
            if n == SESSION_COOKIE {
                Some(value.trim().to_string())
            } else {
                None
            }
        } else {
            None
        }
    });

    match session_id {
        Some(id) => {
            let account = state
                .db
                .conn()
                .query_row(
                    "SELECT a.id, a.username, a.is_superuser, a.password_change_required
                     FROM sessions s JOIN accounts a ON s.account_id = a.id
                     WHERE s.id = ?1
                     AND (strftime('%s','now') - strftime('%s', s.created_at)) <= ?2",
                    params![id, SESSION_MAX_AGE_SECS],
                    |row| {
                        Ok(Account {
                            id: row.get(0)?,
                            username: row.get(1)?,
                            is_superuser: row.get::<_, i32>(2)? != 0,
                            password_change_required: row.get::<_, i32>(3)? != 0,
                        })
                    },
                )
                .ok();

            if let Some(account) = account {
                tracing::debug!("Auth OK for {}", account.username);
                request.extensions_mut().insert(account);
                Ok(next.run(request).await)
            } else {
                // Session expired or not found — clean up stale session
                let _ = state.db.conn().execute(
                    "DELETE FROM sessions WHERE id = ?1",
                    params![id],
                );
                tracing::warn!("Session {id} expired or not found");
                Err(Redirect::to("/login").into_response())
            }
        }
        None => {
            tracing::warn!("No session cookie found (raw cookies: {raw_cookies})");
            Err(Redirect::to("/login").into_response())
        }
    }
}

#[derive(Clone)]
pub struct CurrentUser(pub Account);

impl<S> FromRequestParts<S> for CurrentUser
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        parts
            .extensions
            .get::<Account>()
            .cloned()
            .map(CurrentUser)
            .ok_or((StatusCode::UNAUTHORIZED, "Not authenticated"))
    }
}

pub async fn logout(
    State(state): State<AppState>,
    CurrentUser(_account): CurrentUser,
    headers: axum::http::HeaderMap,
) -> impl IntoResponse {
    if let Some(cookie_header) = headers.get(axum::http::header::COOKIE)
        && let Ok(cookie_str) = cookie_header.to_str() {
            for part in cookie_str.split(';') {
                let part = part.trim();
                if let Some((name, value)) = part.split_once('=')
                    && name.trim() == SESSION_COOKIE {
                        let _ = state
                            .db
                            .conn()
                            .execute("DELETE FROM sessions WHERE id = ?1", params![value.trim()]);
                    }
            }
        }

    let clear_cookie = format!("{SESSION_COOKIE}=; Path=/; HttpOnly; Max-Age=0");
    (
        [(axum::http::header::SET_COOKIE, clear_cookie)],
        Redirect::to("/login"),
    )
}