fastauth-core 0.8.0

Core of fastauth: the builder, plugin system, sessions, crypto and routing.
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
use std::collections::HashMap;
use std::sync::Arc;

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ColumnType {
    Id,
    Text,
    Bool,
    Int,
    Timestamp,
    Json,
    Bytes,
}

/// How [`ColumnType::Id`] columns are stored. The configured
/// [`IdStrategy`](crate::config::IdStrategy) decides it, and adapters read it from
/// [`Schema::id_storage`] or [`TableDef::id_storage`] when they create columns and bind ids.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum IdStorage {
    /// The database's native UUID type where it has one (Postgres `uuid`), else text.
    Uuid,
    /// Text on every database.
    #[default]
    Text,
}

/// How a column's name is stored in the database. Code always uses the name a column is
/// declared with (`email_verified`); the adapter stores and queries the stored name.
/// [`Builder::column_naming`](crate::Builder::column_naming) picks it for every table, and
/// [`Builder::rename_column`](crate::Builder::rename_column) overrides it for one column.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ColumnNaming {
    /// As declared: `email_verified`, `user_id`. The default.
    #[default]
    SnakeCase,
    /// `email_verified` is stored as `emailVerified`, `user_id` as `userId`: Better Auth's
    /// naming, so fastauth can share its tables.
    CamelCase,
}

impl ColumnNaming {
    /// The stored name of a column declared as `name`.
    pub fn apply(self, name: &str) -> String {
        match self {
            ColumnNaming::SnakeCase => name.to_owned(),
            ColumnNaming::CamelCase => {
                let mut out = String::with_capacity(name.len());
                let mut upper = false;
                for (i, ch) in name.char_indices() {
                    if ch == '_' && i > 0 && i + 1 < name.len() {
                        upper = true;
                    } else if upper {
                        out.extend(ch.to_uppercase());
                        upper = false;
                    } else {
                        out.push(ch);
                    }
                }
                out
            }
        }
    }
}

/// How the columns of a schema are stored: the naming strategy, per-column renames and
/// byte columns stored as text. Collected by the builder and applied at `.build()`.
#[derive(Clone, Debug, Default)]
pub(crate) struct Storage {
    pub(crate) naming: ColumnNaming,
    /// `(table, column, stored name)`.
    pub(crate) renames: Vec<(String, String, String)>,
    /// `(table, column)` of byte columns stored as hex text.
    pub(crate) hex_text: Vec<(String, String)>,
    /// `(table, column)` of byte columns stored as UTF-8 text.
    pub(crate) utf8_text: Vec<(String, String)>,
}

/// How a [`ColumnType::Bytes`] column is stored when it's a text column, to share one
/// another app owns ([`TableDef::bytes_text`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BytesText {
    /// Lowercase hex ([`Builder::bytes_as_hex_text`](crate::Builder::bytes_as_hex_text)).
    Hex,
    /// The bytes as the text they are: the OAuth token columns stored as text with
    /// [`Builder::store_oauth_tokens_in_plaintext`](crate::Builder::store_oauth_tokens_in_plaintext).
    /// Bytes that aren't UTF-8 are stored as lowercase hex, and every value reads back as
    /// its text's bytes.
    Utf8,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DefaultValue {
    Bool(bool),
    Int(i64),
    Text(&'static str),
    /// The current time at insert.
    Now,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OnDelete {
    Cascade,
    SetNull,
    Restrict,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Reference {
    pub table: &'static str,
    pub column: &'static str,
    pub on_delete: OnDelete,
}

/// One column. Built with const fns so `Fields` and `Model` impls can return `&'static [ColumnDef]`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ColumnDef {
    pub name: &'static str,
    pub ty: ColumnType,
    pub nullable: bool,
    pub primary_key: bool,
    pub unique: bool,
    pub index: bool,
    pub default: Option<DefaultValue>,
    pub references: Option<Reference>,
    /// Clients may set it through sign-up and update-user bodies.
    pub input: bool,
    /// Serialized to clients.
    pub returned: bool,
    /// The plugin id, `"core"` or `"app"`. Filled in when the column joins the schema.
    pub owner: &'static str,
}

impl ColumnDef {
    pub const fn new(name: &'static str, ty: ColumnType) -> Self {
        Self {
            name,
            ty,
            nullable: false,
            primary_key: false,
            unique: false,
            index: false,
            default: None,
            references: None,
            input: false,
            returned: true,
            owner: "",
        }
    }

    pub const fn primary_key(mut self) -> Self {
        self.primary_key = true;
        self
    }

    pub const fn nullable(mut self) -> Self {
        self.nullable = true;
        self
    }

    pub const fn unique(mut self) -> Self {
        self.unique = true;
        self
    }

    pub const fn index(mut self) -> Self {
        self.index = true;
        self
    }

    pub const fn default(mut self, value: DefaultValue) -> Self {
        self.default = Some(value);
        self
    }

    pub const fn references(
        mut self,
        table: &'static str,
        column: &'static str,
        on_delete: OnDelete,
    ) -> Self {
        self.references = Some(Reference {
            table,
            column,
            on_delete,
        });
        self
    }

    pub const fn input(mut self) -> Self {
        self.input = true;
        self
    }

    pub const fn hidden(mut self) -> Self {
        self.returned = false;
        self
    }
}

/// A unique constraint over several columns of one table, added with
/// [`SchemaBuilder::unique`]. A single unique column is [`ColumnDef::unique`] instead.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UniqueDef {
    pub columns: Vec<&'static str>,
    /// The plugin id, `"core"` or `"app"`.
    pub owner: &'static str,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TableDef {
    pub name: &'static str,
    pub owner: &'static str,
    pub columns: Vec<ColumnDef>,
    /// Unique constraints over several columns. Single unique columns aren't listed here.
    pub uniques: Vec<UniqueDef>,
    positions: HashMap<&'static str, usize>,
    id_storage: IdStorage,
    /// The stored name of each column, in column order. Empty until the schema is built.
    stored: Vec<String>,
    /// For each column, how it is stored as text when it's a byte column stored as text.
    bytes_text: Vec<Option<BytesText>>,
    /// For each column with a foreign key, the stored name of the column it references.
    referenced: Vec<Option<String>>,
}

impl TableDef {
    fn new(name: &'static str, owner: &'static str) -> Self {
        Self {
            name,
            owner,
            columns: Vec::new(),
            uniques: Vec::new(),
            positions: HashMap::new(),
            id_storage: IdStorage::default(),
            stored: Vec::new(),
            bytes_text: Vec::new(),
            referenced: Vec::new(),
        }
    }

    /// The stored name of the column the foreign key of the column at `position` points at.
    pub fn stored_reference(&self, position: usize) -> Option<&str> {
        match self.referenced.get(position) {
            Some(stored) => stored.as_deref(),
            None => self.columns[position].references.map(|r| r.column),
        }
    }

    /// The name the column at `position` is stored under: its declared name, unless
    /// [`ColumnNaming`] or a rename changed it. Adapters use it in every statement.
    pub fn stored_name(&self, position: usize) -> &str {
        self.stored
            .get(position)
            .map_or(self.columns[position].name, String::as_str)
    }

    /// The stored name of `column`, by its declared name.
    pub fn stored_column(&self, column: &str) -> Option<&str> {
        self.position(column).map(|i| self.stored_name(i))
    }

    /// The column stored under `stored`, the inverse of [`stored_name`](Self::stored_name).
    pub fn column_stored_as(&self, stored: &str) -> Option<&ColumnDef> {
        (0..self.columns.len())
            .find(|&i| self.stored_name(i) == stored)
            .map(|i| &self.columns[i])
    }

    /// Whether the [`ColumnType::Bytes`] column at `position` is stored as lowercase hex
    /// text instead of bytes, to share a text column another app owns
    /// ([`Builder::bytes_as_hex_text`](crate::Builder::bytes_as_hex_text)).
    pub fn is_hex_text(&self, position: usize) -> bool {
        self.bytes_text(position) == Some(BytesText::Hex)
    }

    /// How the [`ColumnType::Bytes`] column at `position` is stored as text, or `None` when
    /// it's stored as bytes.
    pub fn bytes_text(&self, position: usize) -> Option<BytesText> {
        self.bytes_text.get(position).copied().flatten()
    }

    /// How this table's [`ColumnType::Id`] columns are stored; the same for every table
    /// in a schema.
    pub fn id_storage(&self) -> IdStorage {
        self.id_storage
    }

    pub fn position(&self, column: &str) -> Option<usize> {
        self.positions.get(column).copied()
    }

    pub fn column(&self, column: &str) -> Option<&ColumnDef> {
        self.position(column).map(|i| &self.columns[i])
    }

    pub fn primary_key(&self) -> Option<&ColumnDef> {
        self.columns.iter().find(|c| c.primary_key)
    }

    /// Every set of columns the database keeps unique, primary key aside: each unique
    /// column on its own, then each [`UniqueDef`].
    pub fn unique_sets(&self) -> impl Iterator<Item = Vec<&'static str>> + '_ {
        self.columns
            .iter()
            .filter(|c| c.unique && !c.primary_key)
            .map(|c| vec![c.name])
            .chain(self.uniques.iter().map(|u| u.columns.clone()))
    }
}

/// The merged schema for one configuration: core tables, app fields, every plugin's tables
/// and columns. Immutable after `.build()`.
#[derive(Clone, Debug, Default)]
pub struct Schema {
    tables: Vec<Arc<TableDef>>,
    by_name: HashMap<&'static str, usize>,
    id_storage: IdStorage,
}

impl Schema {
    /// How [`ColumnType::Id`] columns are stored, from the configured id strategy.
    pub fn id_storage(&self) -> IdStorage {
        self.id_storage
    }

    pub fn tables(&self) -> &[Arc<TableDef>] {
        &self.tables
    }

    pub fn table(&self, name: &str) -> Option<&Arc<TableDef>> {
        self.by_name.get(name).map(|&i| &self.tables[i])
    }

    /// Panics on a table name the schema doesn't have. Only for core's own tables and
    /// models whose table was registered (checked at build time).
    pub fn expect(&self, name: &str) -> &Arc<TableDef> {
        self.table(name)
            .unwrap_or_else(|| panic!("fastauth: table `{name}` is not in the schema"))
    }
}

/// Collects tables and columns during `.build()` and reports clashes with both owners.
#[derive(Debug, Default)]
pub struct SchemaBuilder {
    tables: Vec<TableDef>,
    pub(crate) owner: &'static str,
    pub(crate) errors: Vec<String>,
}

impl SchemaBuilder {
    pub(crate) fn new() -> Self {
        Self {
            owner: "core",
            ..Self::default()
        }
    }

    /// Adds a new table owned by the current plugin.
    pub fn table(&mut self, name: &'static str, columns: &[ColumnDef]) -> &mut Self {
        if let Some(existing) = self.tables.iter().find(|t| t.name == name) {
            self.errors.push(format!(
                "table `{name}` is defined by both `{}` and `{}`",
                existing.owner, self.owner
            ));
            return self;
        }
        self.tables.push(TableDef::new(name, self.owner));
        self.extend(name, columns)
    }

    /// Adds columns to an existing table (usually `user` or `session`).
    pub fn extend(&mut self, table: &'static str, columns: &[ColumnDef]) -> &mut Self {
        let owner = self.owner;
        let Some(def) = self.tables.iter_mut().find(|t| t.name == table) else {
            self.errors
                .push(format!("`{owner}` adds columns to unknown table `{table}`"));
            return self;
        };
        for column in columns {
            if let Some(clash) = def.column(column.name) {
                self.errors.push(format!(
                    "column `{table}.{}` is defined by both `{}` and `{owner}`",
                    column.name, clash.owner
                ));
                continue;
            }
            let mut column = *column;
            column.owner = owner;
            def.positions.insert(column.name, def.columns.len());
            def.columns.push(column);
        }
        self
    }

    /// Makes `columns` of `table` unique together, enforced by the database. Adapters
    /// report a violation as `DbError::UniqueViolation` on `table` with no column.
    pub fn unique(&mut self, table: &'static str, columns: &[&'static str]) -> &mut Self {
        let owner = self.owner;
        let Some(def) = self.tables.iter_mut().find(|t| t.name == table) else {
            self.errors.push(format!(
                "`{owner}` adds a unique constraint to unknown table `{table}`"
            ));
            return self;
        };
        if columns.len() < 2 {
            self.errors.push(format!(
                "`{owner}`: a unique constraint on `{table}` needs two or more columns; \
                 use `ColumnDef::unique` for one"
            ));
            return self;
        }
        if let Some(missing) = columns.iter().find(|c| def.column(c).is_none()) {
            self.errors.push(format!(
                "`{owner}` adds a unique constraint on missing column `{table}.{missing}`"
            ));
            return self;
        }
        if !def.uniques.iter().any(|u| u.columns == columns) {
            def.uniques.push(UniqueDef {
                columns: columns.to_vec(),
                owner,
            });
        }
        self
    }

    /// Registers a model's table.
    pub fn model<M: crate::model::Model>(&mut self) -> &mut Self {
        self.table(M::TABLE, M::columns())
    }

    pub(crate) fn finish(
        mut self,
        id_storage: IdStorage,
        storage: &Storage,
    ) -> Result<Schema, Vec<String>> {
        let mut errors = std::mem::take(&mut self.errors);
        for table in &mut self.tables {
            table.stored = table
                .columns
                .iter()
                .map(|c| storage.naming.apply(c.name))
                .collect();
            table.bytes_text = vec![None; table.columns.len()];
        }
        fn find<'t>(
            tables: &'t mut [TableDef],
            (table, column): (&str, &str),
            what: &str,
            errors: &mut Vec<String>,
        ) -> Option<(&'t mut TableDef, usize)> {
            let found = tables
                .iter_mut()
                .find(|t| t.name == table)
                .and_then(|t| t.position(column).map(|i| (t, i)));
            if found.is_none() {
                errors.push(format!(
                    "{what} names `{table}.{column}`, which is not in the schema"
                ));
            }
            found
        }
        for (table, column, to) in &storage.renames {
            let target = (table.as_str(), column.as_str());
            if let Some((def, i)) = find(&mut self.tables, target, "rename_column", &mut errors) {
                def.stored[i] = to.clone();
            }
        }
        let text_columns = (storage.hex_text.iter().map(|c| (c, BytesText::Hex)))
            .chain(storage.utf8_text.iter().map(|c| (c, BytesText::Utf8)));
        for ((table, column), encoding) in text_columns {
            let target = (table.as_str(), column.as_str());
            if let Some((def, i)) = find(&mut self.tables, target, "bytes_as_hex_text", &mut errors)
            {
                if def.columns[i].ty == ColumnType::Bytes {
                    def.bytes_text[i] = Some(encoding);
                } else {
                    errors.push(format!(
                        "bytes_as_hex_text names `{table}.{column}`, which is {:?}, not Bytes",
                        def.columns[i].ty
                    ));
                }
            }
        }
        let stored: HashMap<(&str, &str), String> = self
            .tables
            .iter()
            .flat_map(|t| {
                t.columns
                    .iter()
                    .zip(&t.stored)
                    .map(|(c, s)| ((t.name, c.name), s.clone()))
            })
            .collect();
        let referenced: Vec<Vec<Option<String>>> = self
            .tables
            .iter()
            .map(|t| {
                t.columns
                    .iter()
                    .map(|c| {
                        let r = c.references?;
                        Some(
                            stored
                                .get(&(r.table, r.column))
                                .cloned()
                                .unwrap_or(r.column.to_owned()),
                        )
                    })
                    .collect()
            })
            .collect();
        for (table, referenced) in self.tables.iter_mut().zip(referenced) {
            table.referenced = referenced;
        }
        for table in &self.tables {
            let mut seen = std::collections::HashSet::new();
            for (i, stored) in table.stored.iter().enumerate() {
                if !seen.insert(stored.as_str()) {
                    errors.push(format!(
                        "two columns of `{}` are stored as `{stored}` (one is `{}`)",
                        table.name, table.columns[i].name
                    ));
                }
            }
        }
        for table in &self.tables {
            for column in &table.columns {
                if let Some(r) = column.references {
                    let target = self.tables.iter().find(|t| t.name == r.table);
                    if target.and_then(|t| t.column(r.column)).is_none() {
                        errors.push(format!(
                            "column `{}.{}` references missing `{}.{}`",
                            table.name, column.name, r.table, r.column
                        ));
                    }
                }
            }
        }
        if !errors.is_empty() {
            return Err(errors);
        }
        let by_name = self
            .tables
            .iter()
            .enumerate()
            .map(|(i, t)| (t.name, i))
            .collect();
        Ok(Schema {
            tables: self
                .tables
                .into_iter()
                .map(|mut table| {
                    table.id_storage = id_storage;
                    Arc::new(table)
                })
                .collect(),
            by_name,
            id_storage,
        })
    }
}