apiplant-server 0.1.0

apiplant HTTP server: CRUD routing, function endpoints and TLS on ntex
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
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
//! Built-in authentication endpoints, mounted under `<base>/auth`.
//!
//! These operate on the `user` and `api_key` resources — which are just ordinary
//! resources — but understand the `[auth]` section on the user model
//! (configurable identity/password field names).
//!
//! Each endpoint is extensible through the `user` model's ordinary `[hooks]`
//! section, which carries these events alongside the CRUD ones:
//!
//! ```toml
//! [hooks]
//! after_create = "index_user"    # the table's own lifecycle
//! before_login = "check_lockout" # and the endpoints in front of it
//! after_login  = "record_attempt"
//! ```
//!
//! They follow the same protocol as [resource hooks](crate::hooks) — a returned
//! `{"error": …}` aborts, a returned `{"data": …}` replaces — over these events:
//!
//! | Event | Receives | A `data` replacement |
//! |-------|----------|----------------------|
//! | `before_register` | the submitted body, password already hashed | replaces what is inserted |
//! | `after_register` | the created row | replaces the response's `user` |
//! | `before_login` | the identity being claimed, never the password | replaces the credentials looked up |
//! | `after_login` | the attempt's outcome — see [`login`] | is merged into the response beside `token` |
//! | `before_api_key` | the submitted body | replaces the key's stored fields |
//! | `after_api_key` | the created row | is merged into the response beside `api_key` |
//!
//! Registration additionally fires the `user` resource's own `before_create` /
//! `after_create`, since it *is* a create; the register hooks run outside those
//! and are the place for logic that should not fire on `POST <base>/user`.

use apiplant_core::schema::AuthSpec;
use apiplant_core::{AuthEvent, HookEvent};
use ntex::web::types::{Json, State};
use ntex::web::{HttpRequest, HttpResponse};
use serde_json::{json, Value};
use uuid::Uuid;

use crate::crud::parse_query;
use crate::hooks::{self, HookRequest};
use crate::response::{db_error, error};
use crate::state::AppState;

fn auth_spec(state: &AppState) -> AuthSpec {
    state
        .app
        .resources
        .get("user")
        .and_then(|r| r.auth.clone())
        .unwrap_or_default()
}

fn quote(ident: &str) -> String {
    // auth field names come from the developer's own model; still refuse
    // anything that isn't a plain identifier.
    if ident.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') && !ident.is_empty() {
        format!("\"{ident}\"")
    } else {
        "\"__invalid__\"".to_string()
    }
}

/// `POST <base>/auth/register` — create a user and return a session token.
///
/// Registration is a `create` on the `user` resource, so the `user` model's
/// `before_create` / `after_create` [hooks](crate::hooks) fire here exactly as
/// they do on `POST <base>/user` — the same function serves both doors into the
/// same table. Two differences follow from what registration is:
///
/// * the plaintext `password` is swapped for the hashed `password_field`
///   *before* `before_create` runs, so a hook never sees the secret;
/// * the caller is anonymous, so `after_create` identifies the new account
///   through the hook context's `record_id` (and the row it receives) rather
///   than through `principal_id`. A replacement it returns replaces the `user`
///   object in the response, leaving the issued `token` alone.
pub async fn register(
    req: HttpRequest,
    state: State<AppState>,
    body: Json<serde_json::Map<String, Value>>,
) -> HttpResponse {
    if !state.app.config.auth.allow_registration {
        return error(403, "registration is disabled");
    }
    let user_r = match state.app.resources.get("user") {
        Some(r) => r,
        None => return error(500, "no user resource"),
    };
    let spec = auth_spec(&state);

    let mut data = body.into_inner();
    let password = match data
        .remove("password")
        .and_then(|v| v.as_str().map(String::from))
    {
        Some(p) => p,
        None => return error(400, "`password` is required"),
    };
    let hash = match state.auth.hash_password(&password) {
        Ok(h) => h,
        Err(_) => return error(500, "failed to hash password"),
    };
    data.insert(spec.password_field.clone(), Value::String(hash));

    // Nobody is authenticated yet: whoever is registering has no principal and
    // no organisation, so the hook context carries the request alone.
    let hook_req = HookRequest::new(&req, &parse_query(req.query_string()), None, None);

    // `before_register` runs outside `before_create`, so a model can reject a
    // signup without also rejecting an administrative `POST <base>/user`.
    match hooks::run_auth(
        &state,
        user_r,
        AuthEvent::BeforeRegister,
        &hook_req,
        Value::Object(data.clone()),
    )
    .await
    {
        Ok(Some(replacement)) => {
            let hook = user_r
                .auth_hook(AuthEvent::BeforeRegister)
                .unwrap_or_default();
            match hooks::replacement_object(replacement, hook) {
                Ok(map) => data = map,
                Err(resp) => return resp,
            }
        }
        Ok(None) => {}
        Err(resp) => return resp,
    }

    match hooks::run(
        &state,
        user_r,
        HookEvent::BeforeCreate,
        &hook_req,
        Value::Object(data.clone()),
    )
    .await
    {
        Ok(Some(replacement)) => {
            let hook = user_r.hook(HookEvent::BeforeCreate).unwrap_or_default();
            match hooks::replacement_object(replacement, hook) {
                Ok(map) => data = map,
                Err(resp) => return resp,
            }
        }
        Ok(None) => {}
        Err(resp) => return resp,
    }

    let created = match state.db.create(user_r, &data).await {
        Ok(row) => row,
        Err(e) => return db_error(e),
    };
    let user_id = created
        .get("id")
        .and_then(|v| v.as_str())
        .and_then(|s| Uuid::parse_str(s).ok());
    let Some(user_id) = user_id else {
        return error(500, "created user missing id");
    };

    let hook_req = hook_req.with_record(user_id);
    let user = match hooks::run(
        &state,
        user_r,
        HookEvent::AfterCreate,
        &hook_req,
        created.clone(),
    )
    .await
    {
        Ok(Some(replacement)) => replacement,
        Ok(None) => created,
        Err(resp) => return resp,
    };

    // The account already exists by now, so an `after_register` rejection fails
    // the *response*, not the write — the same bargain `after_create` makes.
    let user = match hooks::run_auth(
        &state,
        user_r,
        AuthEvent::AfterRegister,
        &hook_req,
        user.clone(),
    )
    .await
    {
        Ok(Some(replacement)) => replacement,
        Ok(None) => user,
        Err(resp) => return resp,
    };

    match state.auth.issue_token(user_id) {
        Ok(token) => HttpResponse::Created().json(&json!({ "token": token, "user": user })),
        Err(_) => error(500, "failed to issue token"),
    }
}

/// `POST <base>/auth/login` — verify credentials, return a session token.
///
/// Two hooks fire around the credential check. `before_login` sees the claimed
/// identity (never the password) and can reject the attempt or rewrite the
/// identity that is looked up. `after_login` sees the *outcome* — every attempt
/// reaches it, successful or not, distinguished by `success` and `reason` — so
/// one hook can both widen a successful response and count the failures that a
/// lockout is built on.
pub async fn login(
    req: HttpRequest,
    state: State<AppState>,
    body: Json<serde_json::Map<String, Value>>,
) -> HttpResponse {
    let spec = auth_spec(&state);
    let data = body.into_inner();

    let mut identity = match data.get(&spec.identity_field).and_then(|v| v.as_str()) {
        Some(s) => s.to_string(),
        None => return error(400, format!("`{}` is required", spec.identity_field)),
    };
    let password = match data.get("password").and_then(|v| v.as_str()) {
        Some(s) => s.to_string(),
        None => return error(400, "`password` is required"),
    };

    let Some(user_r) = state.app.resources.get("user") else {
        return error(500, "missing user resource");
    };
    // Nobody is authenticated during a login attempt, by definition.
    let hook_req = HookRequest::new(&req, &parse_query(req.query_string()), None, None);

    // The password never reaches a hook, here or anywhere else: a hook that
    // wants to reject an attempt does it on the identity alone.
    match hooks::run_auth(
        &state,
        user_r,
        AuthEvent::BeforeLogin,
        &hook_req,
        json!({ spec.identity_field.clone(): identity }),
    )
    .await
    {
        Ok(Some(replacement)) => {
            match replacement
                .get(&spec.identity_field)
                .and_then(|v| v.as_str())
            {
                Some(rewritten) => identity = rewritten.to_string(),
                None => {
                    return error(
                        500,
                        format!(
                            "`before_login` replaced the credentials without `{}`",
                            spec.identity_field
                        ),
                    )
                }
            }
        }
        Ok(None) => {}
        Err(resp) => return resp,
    }

    let Some(user_tbl) = table(&state, "user") else {
        return error(500, "missing user resource");
    };
    let sql = format!(
        "SELECT u.id::text AS id, u.{pw}::text AS password_hash \
         FROM {user_tbl} u WHERE u.{ident} = $1 LIMIT 1",
        pw = quote(&spec.password_field),
        ident = quote(&spec.identity_field),
    );
    let rows = match state
        .db
        .raw_json(&sql, &[Value::String(identity.clone())])
        .await
    {
        Ok(v) => v,
        Err(e) => return db_error(e),
    };
    let verified = match rows.as_array().and_then(|a| a.first()) {
        None => {
            // Spend the argon2 time anyway: answering an unknown identity
            // faster than a wrong password is enough to enumerate accounts.
            let _ = state.auth.hash_password(&password);
            None
        }
        Some(row) => {
            let stored = row
                .get("password_hash")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            if state.auth.verify_password(&password, stored) {
                match row
                    .get("id")
                    .and_then(|v| v.as_str())
                    .and_then(|s| Uuid::parse_str(s).ok())
                {
                    Some(id) => Some(id),
                    None => return error(500, "user missing id"),
                }
            } else {
                None
            }
        }
    };

    // The token is issued before the hook runs, so `after_login` can be told
    // what actually happened — and a hook that aborts still costs the caller
    // nothing, because a token nobody receives is a token nobody can use.
    let token = match verified {
        Some(user_id) => match state.auth.issue_token(user_id) {
            Ok(token) => Some(token),
            Err(_) => return error(500, "failed to issue token"),
        },
        None => None,
    };

    let outcome = json!({
        "success": verified.is_some(),
        "user_id": verified.map(|id| id.to_string()),
        "identity": identity,
        // What the caller is never told apart, a hook is: an address nobody
        // holds and a password nobody guessed are different problems.
        "reason": match (verified.is_some(), rows.as_array().is_some_and(|a| a.is_empty())) {
            (true, _) => Value::Null,
            (false, true) => json!("unknown_identity"),
            (false, false) => json!("bad_password"),
        },
    });
    let hook_req = match verified {
        Some(user_id) => hook_req.with_record(user_id),
        None => hook_req,
    };

    // On the way out, `after_login` can widen the response — the user row,
    // their roles, whatever the client needs — but never rewrite the token it
    // is being handed alongside. On a failure there is nothing to widen: only
    // an `{"error": …}` matters, and it is how a lockout answers 429 where the
    // endpoint would have answered 401.
    let mut response = match &token {
        Some(token) => json!({ "token": token }),
        None => Value::Null,
    };
    match hooks::run_auth(&state, user_r, AuthEvent::AfterLogin, &hook_req, outcome).await {
        Ok(Some(replacement)) if token.is_some() => {
            merge_beside(&mut response, replacement, "token")
        }
        Ok(_) => {}
        Err(resp) => return resp,
    }
    match token {
        Some(_) => HttpResponse::Ok().json(&response),
        None => error(401, "invalid credentials"),
    }
}

/// Fold a hook's replacement object into `response`, leaving `reserved` — the
/// secret the endpoint issued — as the endpoint set it.
fn merge_beside(response: &mut Value, replacement: Value, reserved: &str) {
    let (Some(target), Value::Object(fields)) = (response.as_object_mut(), replacement) else {
        return;
    };
    for (key, value) in fields {
        if key != reserved {
            target.insert(key, value);
        }
    }
}

/// `GET <base>/auth/me` — answer whether this credential still means anything.
///
/// A token can verify against the secret and still be worthless: the account it
/// names may have been deleted since it was issued. Both halves are checked
/// here — the signature by [`AppState::resolve_principal`], the account by
/// looking the row up — so a client holding a token has one call to ask whether
/// to keep it. Anything short of a live user is a flat 401.
pub async fn me(req: HttpRequest, state: State<AppState>) -> HttpResponse {
    let Some(principal) = state.resolve_principal(&req).await else {
        return error(401, "authentication required");
    };
    let Some(user_tbl) = table(&state, "user") else {
        return error(500, "missing user resource");
    };
    let sql = format!("SELECT id::text AS id FROM {user_tbl} WHERE id = $1::uuid LIMIT 1");
    let rows = match state
        .db
        .raw_json(&sql, &[Value::String(principal.user_id.to_string())])
        .await
    {
        Ok(v) => v,
        Err(e) => return db_error(e),
    };
    if rows.as_array().is_none_or(|a| a.is_empty()) {
        return error(401, "user no longer exists");
    }
    HttpResponse::Ok().json(&json!({ "user_id": principal.user_id.to_string() }))
}

/// `POST <base>/auth/apikeys` — issue an API key for the authenticated caller.
/// The plaintext key is returned exactly once.
pub async fn create_api_key(
    req: HttpRequest,
    state: State<AppState>,
    body: Json<Value>,
) -> HttpResponse {
    let principal = match state.resolve_principal(&req).await {
        Some(p) => p,
        None => return error(401, "authentication required"),
    };
    let api_key_r = match state.app.resources.get("api_key") {
        Some(r) => r,
        None => return error(500, "no api_key resource"),
    };
    let (plaintext, hash) = state.auth.generate_api_key();

    let mut data = serde_json::Map::new();
    if let Some(name) = body.get("name").and_then(|v| v.as_str()) {
        data.insert("name".into(), Value::String(name.to_string()));
    }
    data.insert("token_hash".into(), Value::String(hash));
    data.insert(
        "owner_id".into(),
        Value::String(principal.user_id.to_string()),
    );

    let active_org = state.active_org(&req, &Some(principal.clone()));
    let hook_req = HookRequest::new(
        &req,
        &parse_query(req.query_string()),
        Some(&principal),
        active_org,
    );

    // A `before_api_key` replacement writes the row, so a model can stamp an
    // expiry or a scope onto every key it issues.
    match hooks::run_auth(
        &state,
        api_key_r,
        AuthEvent::BeforeApiKey,
        &hook_req,
        Value::Object(data.clone()),
    )
    .await
    {
        Ok(Some(replacement)) => {
            let hook = state
                .app
                .resources
                .get("user")
                .and_then(|u| u.auth_hook(AuthEvent::BeforeApiKey))
                .unwrap_or_default();
            match hooks::replacement_object(replacement, hook) {
                Ok(map) => data = map,
                Err(resp) => return resp,
            }
        }
        Ok(None) => {}
        Err(resp) => return resp,
    }

    let row = match state.db.create(api_key_r, &data).await {
        Ok(row) => row,
        Err(e) => return db_error(e),
    };

    let mut response = json!({
        "api_key": plaintext,
        "id": row.get("id").cloned().unwrap_or(Value::Null),
        "note": "store this key now; it will not be shown again",
    });
    let hook_req = match row.get("id").and_then(|v| v.as_str()) {
        Some(id) => match Uuid::parse_str(id) {
            Ok(id) => hook_req.with_record(id),
            Err(_) => hook_req,
        },
        None => hook_req,
    };
    match hooks::run_auth(
        &state,
        api_key_r,
        AuthEvent::AfterApiKey,
        &hook_req,
        row.clone(),
    )
    .await
    {
        Ok(Some(replacement)) => merge_beside(&mut response, replacement, "api_key"),
        Ok(None) => {}
        Err(resp) => return resp,
    }
    HttpResponse::Created().json(&response)
}

fn table(state: &AppState, name: &str) -> Option<String> {
    state
        .app
        .resources
        .get(name)
        .map(|r| format!("\"{}\"", r.table_name()))
}