ironflow-auth 2.2.2

Authentication library for ironflow — JWT, password hashing, extractors
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
//! Axum extractors for authenticated callers.
//!
//! Provides three extractors:
//!
//! - [`AuthenticatedUser`] -- JWT only (cookie or `Authorization: Bearer` header)
//! - [`ApiKeyAuth`] -- API key only (`irfl_...` prefix)
//! - [`Authenticated`] -- Dual auth: API key OR JWT

use std::sync::Arc;

use axum::Json;
use axum::extract::{FromRef, FromRequestParts};
use axum::http::StatusCode;
use axum::http::request::Parts;
use axum::response::{IntoResponse, Response};
use axum_extra::extract::cookie::CookieJar;
use chrono::Utc;
use ironflow_store::api_key_store::ApiKeyStore;
use ironflow_store::entities::ApiKeyScope;
use ironflow_store::user_store::UserStore;
use serde_json::json;
use uuid::Uuid;

use crate::cookies::AUTH_COOKIE_NAME;
use crate::jwt::{AccessToken, JwtConfig};
use crate::password;

// ---------------------------------------------------------------------------
// AuthenticatedUser (JWT only)
// ---------------------------------------------------------------------------

/// An authenticated user extracted from a JWT.
///
/// Use as an Axum handler parameter to enforce JWT authentication.
/// Requires `Arc<JwtConfig>` to be extractable from state via `FromRef`.
///
/// # Examples
///
/// ```no_run
/// use ironflow_auth::extractor::AuthenticatedUser;
///
/// async fn protected(user: AuthenticatedUser) -> String {
///     format!("Hello, {}!", user.username)
/// }
/// ```
#[derive(Debug, Clone)]
pub struct AuthenticatedUser {
    /// The user's unique identifier.
    pub user_id: Uuid,
    /// The user's username.
    pub username: String,
    /// Whether the user is an administrator.
    pub is_admin: bool,
}

impl<S> FromRequestParts<S> for AuthenticatedUser
where
    S: Send + Sync,
    Arc<JwtConfig>: FromRef<S>,
{
    type Rejection = AuthRejection;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        let jwt_config = Arc::<JwtConfig>::from_ref(state);

        let jar = CookieJar::from_headers(&parts.headers);
        let token = jar
            .get(AUTH_COOKIE_NAME)
            .map(|c| c.value().to_string())
            .or_else(|| {
                parts
                    .headers
                    .get("authorization")
                    .and_then(|v| v.to_str().ok())
                    .and_then(|v| v.strip_prefix("Bearer "))
                    .map(|t| t.to_string())
            });

        let token = token.ok_or(AuthRejection {
            status: StatusCode::UNAUTHORIZED,
            code: "MISSING_TOKEN",
            message: "No authentication token provided",
        })?;

        let claims = AccessToken::decode(&token, &jwt_config).map_err(|_| AuthRejection {
            status: StatusCode::UNAUTHORIZED,
            code: "INVALID_TOKEN",
            message: "Invalid or expired authentication token",
        })?;

        Ok(AuthenticatedUser {
            user_id: claims.user_id,
            username: claims.username,
            is_admin: claims.is_admin,
        })
    }
}

/// Rejection type when JWT authentication fails.
pub struct AuthRejection {
    status: StatusCode,
    code: &'static str,
    message: &'static str,
}

impl IntoResponse for AuthRejection {
    fn into_response(self) -> Response {
        let body = json!({
            "error": {
                "code": self.code,
                "message": self.message,
            }
        });
        (self.status, Json(body)).into_response()
    }
}

// ---------------------------------------------------------------------------
// ApiKeyAuth (API key only)
// ---------------------------------------------------------------------------

/// API key prefix used to distinguish API keys from JWT tokens.
pub const API_KEY_PREFIX: &str = "irfl_";

/// An authenticated caller via API key.
///
/// Use as an Axum handler parameter to enforce API key authentication.
///
/// # Examples
///
/// ```no_run
/// use ironflow_auth::extractor::ApiKeyAuth;
///
/// async fn protected(key: ApiKeyAuth) -> String {
///     format!("Key {} (user {})", key.key_name, key.user_id)
/// }
/// ```
#[derive(Debug, Clone)]
pub struct ApiKeyAuth {
    /// The API key ID.
    pub key_id: Uuid,
    /// The owner user ID.
    pub user_id: Uuid,
    /// The API key name.
    pub key_name: String,
    /// Scopes granted to this key.
    pub scopes: Vec<ApiKeyScope>,
    /// Whether the key owner is an admin (checked at request time).
    pub owner_is_admin: bool,
}

impl ApiKeyAuth {
    /// Check if the API key has a specific scope.
    pub fn has_scope(&self, required: &ApiKeyScope) -> bool {
        ApiKeyScope::has_permission(&self.scopes, required)
    }
}

/// Rejection type when API key authentication fails.
pub struct ApiKeyRejection {
    status: StatusCode,
    code: &'static str,
    message: &'static str,
}

impl IntoResponse for ApiKeyRejection {
    fn into_response(self) -> Response {
        let body = json!({
            "error": {
                "code": self.code,
                "message": self.message,
            }
        });
        (self.status, Json(body)).into_response()
    }
}

impl<S> FromRequestParts<S> for ApiKeyAuth
where
    S: Send + Sync,
    Arc<dyn ApiKeyStore>: FromRef<S>,
    Arc<dyn UserStore>: FromRef<S>,
{
    type Rejection = ApiKeyRejection;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        let api_key_store = Arc::<dyn ApiKeyStore>::from_ref(state);
        let user_store = Arc::<dyn UserStore>::from_ref(state);

        let token = parts
            .headers
            .get("authorization")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.strip_prefix("Bearer "))
            .ok_or(ApiKeyRejection {
                status: StatusCode::UNAUTHORIZED,
                code: "MISSING_TOKEN",
                message: "No authentication token provided",
            })?;

        if !token.starts_with(API_KEY_PREFIX) {
            return Err(ApiKeyRejection {
                status: StatusCode::UNAUTHORIZED,
                code: "INVALID_TOKEN",
                message: "Expected API key (irfl_...) in Authorization header",
            });
        }

        let suffix_len = (token.len() - API_KEY_PREFIX.len()).min(8);
        let prefix = &token[..API_KEY_PREFIX.len() + suffix_len];

        let api_key = api_key_store
            .find_api_key_by_prefix(prefix)
            .await
            .map_err(|_| ApiKeyRejection {
                status: StatusCode::INTERNAL_SERVER_ERROR,
                code: "INTERNAL_ERROR",
                message: "Failed to look up API key",
            })?
            .ok_or(ApiKeyRejection {
                status: StatusCode::UNAUTHORIZED,
                code: "INVALID_TOKEN",
                message: "Invalid API key",
            })?;

        if !api_key.is_active {
            return Err(ApiKeyRejection {
                status: StatusCode::UNAUTHORIZED,
                code: "KEY_DISABLED",
                message: "API key is disabled",
            });
        }

        if let Some(expires_at) = api_key.expires_at
            && expires_at < Utc::now()
        {
            return Err(ApiKeyRejection {
                status: StatusCode::UNAUTHORIZED,
                code: "KEY_EXPIRED",
                message: "API key has expired",
            });
        }

        let valid = password::verify(token, &api_key.key_hash).map_err(|_| ApiKeyRejection {
            status: StatusCode::INTERNAL_SERVER_ERROR,
            code: "INTERNAL_ERROR",
            message: "Failed to verify API key",
        })?;

        if !valid {
            return Err(ApiKeyRejection {
                status: StatusCode::UNAUTHORIZED,
                code: "INVALID_TOKEN",
                message: "Invalid API key",
            });
        }

        let _ = api_key_store.touch_api_key(api_key.id).await;

        let owner = user_store
            .find_user_by_id(api_key.user_id)
            .await
            .map_err(|_| ApiKeyRejection {
                status: StatusCode::INTERNAL_SERVER_ERROR,
                code: "INTERNAL_ERROR",
                message: "Failed to look up API key owner",
            })?;
        let owner_is_admin = owner.map(|u| u.is_admin).unwrap_or(false);

        Ok(ApiKeyAuth {
            key_id: api_key.id,
            user_id: api_key.user_id,
            key_name: api_key.name,
            scopes: api_key.scopes,
            owner_is_admin,
        })
    }
}

// ---------------------------------------------------------------------------
// Authenticated (dual: API key OR JWT)
// ---------------------------------------------------------------------------

/// An authenticated caller, either via API key or JWT.
///
/// If the `Authorization: Bearer` token starts with `irfl_`, API key auth is used.
/// Otherwise, JWT auth is attempted (cookie first, then header).
///
/// # Examples
///
/// ```no_run
/// use ironflow_auth::extractor::Authenticated;
///
/// async fn protected(auth: Authenticated) -> String {
///     format!("User {}", auth.user_id)
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Authenticated {
    /// The authenticated user's ID.
    pub user_id: Uuid,
    /// The authentication method used.
    pub method: AuthMethod,
}

/// How the caller was authenticated.
#[derive(Debug, Clone)]
pub enum AuthMethod {
    /// Authenticated via JWT (cookie or Bearer header).
    Jwt {
        /// The user's username.
        username: String,
        /// Whether the user is an admin.
        is_admin: bool,
    },
    /// Authenticated via API key.
    ApiKey {
        /// The API key ID.
        key_id: Uuid,
        /// The API key name.
        key_name: String,
        /// Scopes granted to this key.
        scopes: Vec<ApiKeyScope>,
        /// Whether the key owner is an admin (checked at request time).
        owner_is_admin: bool,
    },
}

impl Authenticated {
    /// Whether the authenticated caller has admin privileges.
    ///
    /// For JWT users, checks the `is_admin` claim.
    /// For API key users, checks the owner's current admin status
    /// (fetched at request time, so demotions take effect immediately).
    pub fn is_admin(&self) -> bool {
        match &self.method {
            AuthMethod::Jwt { is_admin, .. } => *is_admin,
            AuthMethod::ApiKey { owner_is_admin, .. } => *owner_is_admin,
        }
    }
}

impl<S> FromRequestParts<S> for Authenticated
where
    S: Send + Sync,
    Arc<JwtConfig>: FromRef<S>,
    Arc<dyn ApiKeyStore>: FromRef<S>,
    Arc<dyn UserStore>: FromRef<S>,
{
    type Rejection = AuthRejection;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        let jar = CookieJar::from_headers(&parts.headers);
        let cookie_token = jar.get(AUTH_COOKIE_NAME).map(|c| c.value().to_string());

        let header_token = parts
            .headers
            .get("authorization")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.strip_prefix("Bearer "))
            .map(|t| t.to_string());

        // If the Bearer token is an API key, use API key auth
        if let Some(ref token) = header_token
            && token.starts_with(API_KEY_PREFIX)
        {
            let api_key_auth =
                ApiKeyAuth::from_request_parts(parts, state)
                    .await
                    .map_err(|_| AuthRejection {
                        status: StatusCode::UNAUTHORIZED,
                        code: "INVALID_TOKEN",
                        message: "Invalid or expired authentication token",
                    })?;
            return Ok(Authenticated {
                user_id: api_key_auth.user_id,
                method: AuthMethod::ApiKey {
                    key_id: api_key_auth.key_id,
                    key_name: api_key_auth.key_name,
                    scopes: api_key_auth.scopes,
                    owner_is_admin: api_key_auth.owner_is_admin,
                },
            });
        }

        // Otherwise, try JWT (cookie first, then header)
        let token = cookie_token.or(header_token).ok_or(AuthRejection {
            status: StatusCode::UNAUTHORIZED,
            code: "MISSING_TOKEN",
            message: "No authentication token provided",
        })?;

        let jwt_config = Arc::<JwtConfig>::from_ref(state);
        let claims = AccessToken::decode(&token, &jwt_config).map_err(|_| AuthRejection {
            status: StatusCode::UNAUTHORIZED,
            code: "INVALID_TOKEN",
            message: "Invalid or expired authentication token",
        })?;

        Ok(Authenticated {
            user_id: claims.user_id,
            method: AuthMethod::Jwt {
                username: claims.username,
                is_admin: claims.is_admin,
            },
        })
    }
}