diesel/sqlite/connection/authorizer.rs
1//! Types for the SQLite authorizer callback.
2//!
3//! See [`sqlite3_set_authorizer`](https://sqlite.org/c3ref/set_authorizer.html)
4//! and the [action code constants](https://sqlite.org/c3ref/c_alter_table.html).
5//!
6//! The authorizer callback receives an [`AuthorizerContext`]. It is an enum
7//! with one variant per SQLite action code, and every variant carries the
8//! arguments for that action under descriptive field names, so there is no
9//! need to consult a table of what each positional argument means.
10//!
11//! Two fields recur across variants. `database` is the name of the database
12//! (`"main"`, `"temp"`, or an `ATTACH` alias) an object lives in, when SQLite
13//! reports it. `accessor` is the name of the inner-most trigger or view
14//! responsible for the access, or `None` when the access is directly from
15//! top-level SQL. A string argument is `None` when SQLite passes `NULL` or a
16//! value that is not valid UTF-8.
17
18#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
19extern crate libsqlite3_sys as ffi;
20
21#[cfg(all(target_family = "wasm", target_os = "unknown"))]
22use sqlite_wasm_rs as ffi;
23
24use super::SqliteConnection;
25
26/// Authorizing a `CREATE INDEX` statement.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28#[non_exhaustive]
29pub struct CreateIndex<'a> {
30 /// Name of the index being created.
31 pub index: Option<&'a str>,
32 /// Name of the table the index is created on.
33 pub table: Option<&'a str>,
34 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
35 pub database: Option<&'a str>,
36 /// Inner-most trigger or view responsible for the access, if any.
37 pub accessor: Option<&'a str>,
38}
39
40/// Authorizing a `CREATE TABLE` statement.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42#[non_exhaustive]
43pub struct CreateTable<'a> {
44 /// Name of the table being created.
45 pub table: Option<&'a str>,
46 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
47 pub database: Option<&'a str>,
48 /// Inner-most trigger or view responsible for the access, if any.
49 pub accessor: Option<&'a str>,
50}
51
52/// Authorizing a `CREATE TEMP INDEX` statement.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54#[non_exhaustive]
55pub struct CreateTempIndex<'a> {
56 /// Name of the index being created.
57 pub index: Option<&'a str>,
58 /// Name of the table the index is created on.
59 pub table: Option<&'a str>,
60 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
61 pub database: Option<&'a str>,
62 /// Inner-most trigger or view responsible for the access, if any.
63 pub accessor: Option<&'a str>,
64}
65
66/// Authorizing a `CREATE TEMP TABLE` statement.
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68#[non_exhaustive]
69pub struct CreateTempTable<'a> {
70 /// Name of the table being created.
71 pub table: Option<&'a str>,
72 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
73 pub database: Option<&'a str>,
74 /// Inner-most trigger or view responsible for the access, if any.
75 pub accessor: Option<&'a str>,
76}
77
78/// Authorizing a `CREATE TEMP TRIGGER` statement.
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80#[non_exhaustive]
81pub struct CreateTempTrigger<'a> {
82 /// Name of the trigger being created.
83 pub trigger: Option<&'a str>,
84 /// Name of the table the trigger is attached to.
85 pub table: Option<&'a str>,
86 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
87 pub database: Option<&'a str>,
88 /// Inner-most trigger or view responsible for the access, if any.
89 pub accessor: Option<&'a str>,
90}
91
92/// Authorizing a `CREATE TEMP VIEW` statement.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94#[non_exhaustive]
95pub struct CreateTempView<'a> {
96 /// Name of the view being created.
97 pub view: Option<&'a str>,
98 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
99 pub database: Option<&'a str>,
100 /// Inner-most trigger or view responsible for the access, if any.
101 pub accessor: Option<&'a str>,
102}
103
104/// Authorizing a `CREATE TRIGGER` statement.
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106#[non_exhaustive]
107pub struct CreateTrigger<'a> {
108 /// Name of the trigger being created.
109 pub trigger: Option<&'a str>,
110 /// Name of the table the trigger is attached to.
111 pub table: Option<&'a str>,
112 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
113 pub database: Option<&'a str>,
114 /// Inner-most trigger or view responsible for the access, if any.
115 pub accessor: Option<&'a str>,
116}
117
118/// Authorizing a `CREATE VIEW` statement.
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120#[non_exhaustive]
121pub struct CreateView<'a> {
122 /// Name of the view being created.
123 pub view: Option<&'a str>,
124 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
125 pub database: Option<&'a str>,
126 /// Inner-most trigger or view responsible for the access, if any.
127 pub accessor: Option<&'a str>,
128}
129
130/// Authorizing a `DELETE` statement.
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132#[non_exhaustive]
133pub struct Delete<'a> {
134 /// Name of the table rows are deleted from.
135 pub table: Option<&'a str>,
136 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
137 pub database: Option<&'a str>,
138 /// Inner-most trigger or view responsible for the access, if any.
139 pub accessor: Option<&'a str>,
140}
141
142/// Authorizing a `DROP INDEX` statement.
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144#[non_exhaustive]
145pub struct DropIndex<'a> {
146 /// Name of the index being dropped.
147 pub index: Option<&'a str>,
148 /// Name of the table the index belongs to.
149 pub table: Option<&'a str>,
150 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
151 pub database: Option<&'a str>,
152 /// Inner-most trigger or view responsible for the access, if any.
153 pub accessor: Option<&'a str>,
154}
155
156/// Authorizing a `DROP TABLE` statement.
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158#[non_exhaustive]
159pub struct DropTable<'a> {
160 /// Name of the table being dropped.
161 pub table: Option<&'a str>,
162 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
163 pub database: Option<&'a str>,
164 /// Inner-most trigger or view responsible for the access, if any.
165 pub accessor: Option<&'a str>,
166}
167
168/// Authorizing a `DROP TEMP INDEX` statement.
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170#[non_exhaustive]
171pub struct DropTempIndex<'a> {
172 /// Name of the index being dropped.
173 pub index: Option<&'a str>,
174 /// Name of the table the index belongs to.
175 pub table: Option<&'a str>,
176 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
177 pub database: Option<&'a str>,
178 /// Inner-most trigger or view responsible for the access, if any.
179 pub accessor: Option<&'a str>,
180}
181
182/// Authorizing a `DROP TEMP TABLE` statement.
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
184#[non_exhaustive]
185pub struct DropTempTable<'a> {
186 /// Name of the table being dropped.
187 pub table: Option<&'a str>,
188 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
189 pub database: Option<&'a str>,
190 /// Inner-most trigger or view responsible for the access, if any.
191 pub accessor: Option<&'a str>,
192}
193
194/// Authorizing a `DROP TEMP TRIGGER` statement.
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196#[non_exhaustive]
197pub struct DropTempTrigger<'a> {
198 /// Name of the trigger being dropped.
199 pub trigger: Option<&'a str>,
200 /// Name of the table the trigger is attached to.
201 pub table: Option<&'a str>,
202 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
203 pub database: Option<&'a str>,
204 /// Inner-most trigger or view responsible for the access, if any.
205 pub accessor: Option<&'a str>,
206}
207
208/// Authorizing a `DROP TEMP VIEW` statement.
209#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210#[non_exhaustive]
211pub struct DropTempView<'a> {
212 /// Name of the view being dropped.
213 pub view: Option<&'a str>,
214 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
215 pub database: Option<&'a str>,
216 /// Inner-most trigger or view responsible for the access, if any.
217 pub accessor: Option<&'a str>,
218}
219
220/// Authorizing a `DROP TRIGGER` statement.
221#[derive(Debug, Clone, Copy, PartialEq, Eq)]
222#[non_exhaustive]
223pub struct DropTrigger<'a> {
224 /// Name of the trigger being dropped.
225 pub trigger: Option<&'a str>,
226 /// Name of the table the trigger is attached to.
227 pub table: Option<&'a str>,
228 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
229 pub database: Option<&'a str>,
230 /// Inner-most trigger or view responsible for the access, if any.
231 pub accessor: Option<&'a str>,
232}
233
234/// Authorizing a `DROP VIEW` statement.
235#[derive(Debug, Clone, Copy, PartialEq, Eq)]
236#[non_exhaustive]
237pub struct DropView<'a> {
238 /// Name of the view being dropped.
239 pub view: Option<&'a str>,
240 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
241 pub database: Option<&'a str>,
242 /// Inner-most trigger or view responsible for the access, if any.
243 pub accessor: Option<&'a str>,
244}
245
246/// Authorizing an `INSERT` statement.
247#[derive(Debug, Clone, Copy, PartialEq, Eq)]
248#[non_exhaustive]
249pub struct Insert<'a> {
250 /// Name of the table rows are inserted into.
251 pub table: Option<&'a str>,
252 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
253 pub database: Option<&'a str>,
254 /// Inner-most trigger or view responsible for the access, if any.
255 pub accessor: Option<&'a str>,
256}
257
258/// Authorizing a `PRAGMA` statement.
259#[derive(Debug, Clone, Copy, PartialEq, Eq)]
260#[non_exhaustive]
261pub struct Pragma<'a> {
262 /// Name of the pragma.
263 pub name: Option<&'a str>,
264 /// Argument to the pragma, or `None` when it is queried without one.
265 pub argument: Option<&'a str>,
266 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
267 pub database: Option<&'a str>,
268 /// Inner-most trigger or view responsible for the access, if any.
269 pub accessor: Option<&'a str>,
270}
271
272/// Authorizing a column read.
273#[derive(Debug, Clone, Copy, PartialEq, Eq)]
274#[non_exhaustive]
275pub struct Read<'a> {
276 /// Name of the table being read.
277 pub table: Option<&'a str>,
278 /// Name of the column being read.
279 pub column: Option<&'a str>,
280 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
281 pub database: Option<&'a str>,
282 /// Inner-most trigger or view responsible for the access, if any.
283 pub accessor: Option<&'a str>,
284}
285
286/// Authorizing a `SELECT` statement.
287#[derive(Debug, Clone, Copy, PartialEq, Eq)]
288#[non_exhaustive]
289pub struct Select<'a> {
290 /// Inner-most trigger or view responsible for the access, if any.
291 pub accessor: Option<&'a str>,
292}
293
294/// Authorizing a transaction control operation (`BEGIN`, `COMMIT`, `ROLLBACK`).
295#[derive(Debug, Clone, Copy, PartialEq, Eq)]
296#[non_exhaustive]
297pub struct Transaction<'a> {
298 /// The operation, for example `"BEGIN"`, `"COMMIT"`, or `"ROLLBACK"`.
299 pub operation: Option<&'a str>,
300 /// Inner-most trigger or view responsible for the access, if any.
301 pub accessor: Option<&'a str>,
302}
303
304/// Authorizing an `UPDATE` statement.
305#[derive(Debug, Clone, Copy, PartialEq, Eq)]
306#[non_exhaustive]
307pub struct Update<'a> {
308 /// Name of the table being updated.
309 pub table: Option<&'a str>,
310 /// Name of the column being updated.
311 pub column: Option<&'a str>,
312 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
313 pub database: Option<&'a str>,
314 /// Inner-most trigger or view responsible for the access, if any.
315 pub accessor: Option<&'a str>,
316}
317
318/// Authorizing an `ATTACH DATABASE` statement.
319#[derive(Debug, Clone, Copy, PartialEq, Eq)]
320#[non_exhaustive]
321pub struct Attach<'a> {
322 /// Filename of the database being attached.
323 pub filename: Option<&'a str>,
324 /// Inner-most trigger or view responsible for the access, if any.
325 pub accessor: Option<&'a str>,
326}
327
328/// Authorizing a `DETACH DATABASE` statement.
329#[derive(Debug, Clone, Copy, PartialEq, Eq)]
330#[non_exhaustive]
331pub struct Detach<'a> {
332 /// Name of the database being detached.
333 pub database: Option<&'a str>,
334 /// Inner-most trigger or view responsible for the access, if any.
335 pub accessor: Option<&'a str>,
336}
337
338/// Authorizing an `ALTER TABLE` statement.
339#[derive(Debug, Clone, Copy, PartialEq, Eq)]
340#[non_exhaustive]
341pub struct AlterTable<'a> {
342 /// Database the table lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
343 pub database: Option<&'a str>,
344 /// Name of the table being altered.
345 pub table: Option<&'a str>,
346 /// Inner-most trigger or view responsible for the access, if any.
347 pub accessor: Option<&'a str>,
348}
349
350/// Authorizing a `REINDEX` statement.
351#[derive(Debug, Clone, Copy, PartialEq, Eq)]
352#[non_exhaustive]
353pub struct Reindex<'a> {
354 /// Name of the index being rebuilt.
355 pub index: Option<&'a str>,
356 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
357 pub database: Option<&'a str>,
358 /// Inner-most trigger or view responsible for the access, if any.
359 pub accessor: Option<&'a str>,
360}
361
362/// Authorizing an `ANALYZE` statement.
363#[derive(Debug, Clone, Copy, PartialEq, Eq)]
364#[non_exhaustive]
365pub struct Analyze<'a> {
366 /// Name of the table being analyzed.
367 pub table: Option<&'a str>,
368 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
369 pub database: Option<&'a str>,
370 /// Inner-most trigger or view responsible for the access, if any.
371 pub accessor: Option<&'a str>,
372}
373
374/// Authorizing a `CREATE VIRTUAL TABLE` statement.
375#[derive(Debug, Clone, Copy, PartialEq, Eq)]
376#[non_exhaustive]
377pub struct CreateVTable<'a> {
378 /// Name of the virtual table being created.
379 pub table: Option<&'a str>,
380 /// Name of the module implementing the virtual table.
381 pub module: Option<&'a str>,
382 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
383 pub database: Option<&'a str>,
384 /// Inner-most trigger or view responsible for the access, if any.
385 pub accessor: Option<&'a str>,
386}
387
388/// Authorizing a `DROP VIRTUAL TABLE` statement.
389#[derive(Debug, Clone, Copy, PartialEq, Eq)]
390#[non_exhaustive]
391pub struct DropVTable<'a> {
392 /// Name of the virtual table being dropped.
393 pub table: Option<&'a str>,
394 /// Name of the module implementing the virtual table.
395 pub module: Option<&'a str>,
396 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
397 pub database: Option<&'a str>,
398 /// Inner-most trigger or view responsible for the access, if any.
399 pub accessor: Option<&'a str>,
400}
401
402/// Authorizing a SQL function call.
403#[derive(Debug, Clone, Copy, PartialEq, Eq)]
404#[non_exhaustive]
405pub struct Function<'a> {
406 /// Name of the function being called.
407 pub function: Option<&'a str>,
408 /// Inner-most trigger or view responsible for the access, if any.
409 pub accessor: Option<&'a str>,
410}
411
412/// Authorizing a `SAVEPOINT` operation.
413#[derive(Debug, Clone, Copy, PartialEq, Eq)]
414#[non_exhaustive]
415pub struct Savepoint<'a> {
416 /// The operation, for example `"BEGIN"`, `"RELEASE"`, or `"ROLLBACK"`.
417 pub operation: Option<&'a str>,
418 /// Name of the savepoint.
419 pub name: Option<&'a str>,
420 /// Inner-most trigger or view responsible for the access, if any.
421 pub accessor: Option<&'a str>,
422}
423
424/// Authorizing a recursive `SELECT`.
425#[derive(Debug, Clone, Copy, PartialEq, Eq)]
426#[non_exhaustive]
427pub struct Recursive<'a> {
428 /// Inner-most trigger or view responsible for the access, if any.
429 pub accessor: Option<&'a str>,
430}
431
432/// An action code SQLite reported that this version of diesel does not model.
433///
434/// The raw arguments are exposed unchanged for forward compatibility.
435#[derive(Debug, Clone, Copy, PartialEq, Eq)]
436#[non_exhaustive]
437pub struct Unknown<'a> {
438 /// The raw SQLite action code.
439 pub code: i32,
440 /// The third argument to the authorizer callback, if any.
441 pub arg1: Option<&'a str>,
442 /// The fourth argument to the authorizer callback, if any.
443 pub arg2: Option<&'a str>,
444 /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
445 pub database: Option<&'a str>,
446 /// Inner-most trigger or view responsible for the access, if any.
447 pub accessor: Option<&'a str>,
448}
449
450/// Context information passed to the authorizer callback.
451///
452/// One variant per SQLite action code. Each variant carries the arguments for
453/// that action under descriptive field names, so there is no need to consult a
454/// table of what each positional argument means. The callback is invoked
455/// during SQL statement compilation (not during execution).
456///
457/// Added in SQLite 3.0.0 (June 2004).
458#[derive(Debug, Clone, Copy, PartialEq, Eq)]
459#[non_exhaustive]
460pub enum AuthorizerContext<'a> {
461 /// `CREATE INDEX`
462 CreateIndex(CreateIndex<'a>),
463 /// `CREATE TABLE`
464 CreateTable(CreateTable<'a>),
465 /// `CREATE TEMP INDEX`
466 CreateTempIndex(CreateTempIndex<'a>),
467 /// `CREATE TEMP TABLE`
468 CreateTempTable(CreateTempTable<'a>),
469 /// `CREATE TEMP TRIGGER`
470 CreateTempTrigger(CreateTempTrigger<'a>),
471 /// `CREATE TEMP VIEW`
472 CreateTempView(CreateTempView<'a>),
473 /// `CREATE TRIGGER`
474 CreateTrigger(CreateTrigger<'a>),
475 /// `CREATE VIEW`
476 CreateView(CreateView<'a>),
477 /// `DELETE`
478 Delete(Delete<'a>),
479 /// `DROP INDEX`
480 DropIndex(DropIndex<'a>),
481 /// `DROP TABLE`
482 DropTable(DropTable<'a>),
483 /// `DROP TEMP INDEX`
484 DropTempIndex(DropTempIndex<'a>),
485 /// `DROP TEMP TABLE`
486 DropTempTable(DropTempTable<'a>),
487 /// `DROP TEMP TRIGGER`
488 DropTempTrigger(DropTempTrigger<'a>),
489 /// `DROP TEMP VIEW`
490 DropTempView(DropTempView<'a>),
491 /// `DROP TRIGGER`
492 DropTrigger(DropTrigger<'a>),
493 /// `DROP VIEW`
494 DropView(DropView<'a>),
495 /// `INSERT`
496 Insert(Insert<'a>),
497 /// `PRAGMA`
498 Pragma(Pragma<'a>),
499 /// Reading a column value.
500 Read(Read<'a>),
501 /// `SELECT`
502 Select(Select<'a>),
503 /// Transaction control (`BEGIN`, `COMMIT`, `ROLLBACK`).
504 Transaction(Transaction<'a>),
505 /// `UPDATE`
506 Update(Update<'a>),
507 /// `ATTACH DATABASE`
508 Attach(Attach<'a>),
509 /// `DETACH DATABASE`
510 Detach(Detach<'a>),
511 /// `ALTER TABLE`
512 AlterTable(AlterTable<'a>),
513 /// `REINDEX`
514 Reindex(Reindex<'a>),
515 /// `ANALYZE`
516 Analyze(Analyze<'a>),
517 /// `CREATE VIRTUAL TABLE`
518 CreateVTable(CreateVTable<'a>),
519 /// `DROP VIRTUAL TABLE`
520 DropVTable(DropVTable<'a>),
521 /// A SQL function call.
522 Function(Function<'a>),
523 /// `SAVEPOINT`
524 Savepoint(Savepoint<'a>),
525 /// A recursive `SELECT`.
526 Recursive(Recursive<'a>),
527 /// An action code this version of diesel does not model.
528 Unknown(Unknown<'a>),
529}
530
531impl<'a> AuthorizerContext<'a> {
532 /// Returns `true` if this action modifies the database schema.
533 ///
534 /// Schema-modifying actions include creating, dropping, or altering
535 /// tables, indexes, triggers, views, and virtual tables, writing to the
536 /// schema table or `sqlite_dbpage`, and assigning the `writable_schema` or
537 /// `schema_version` pragma. Writes to virtual-table shadow tables are not
538 /// recognised, so use [`set_defensive`](SqliteConnection::set_defensive)
539 /// to stop ordinary SQL from corrupting the schema.
540 ///
541 /// # Example
542 ///
543 /// ```rust
544 /// # use diesel::prelude::*;
545 /// use diesel::sqlite::{SqliteConnection, AuthorizerContext, AuthorizerDecision};
546 ///
547 /// # let conn = &mut SqliteConnection::establish(":memory:").unwrap();
548 /// conn.on_authorize(|ctx| {
549 /// if ctx.is_schema_modifying() {
550 /// AuthorizerDecision::Deny
551 /// } else {
552 /// AuthorizerDecision::Allow
553 /// }
554 /// });
555 /// ```
556 pub fn is_schema_modifying(&self) -> bool {
557 matches!(
558 self,
559 Self::CreateIndex(_)
560 | Self::CreateTable(_)
561 | Self::CreateTempIndex(_)
562 | Self::CreateTempTable(_)
563 | Self::CreateTempTrigger(_)
564 | Self::CreateTempView(_)
565 | Self::CreateTrigger(_)
566 | Self::CreateView(_)
567 | Self::CreateVTable(_)
568 | Self::DropIndex(_)
569 | Self::DropTable(_)
570 | Self::DropTempIndex(_)
571 | Self::DropTempTable(_)
572 | Self::DropTempTrigger(_)
573 | Self::DropTempView(_)
574 | Self::DropTrigger(_)
575 | Self::DropView(_)
576 | Self::DropVTable(_)
577 | Self::AlterTable(_)
578 ) || self.writes_schema_storage()
579 }
580
581 /// Returns `true` for a write to the schema table or `sqlite_dbpage`, or an assignment of `writable_schema` or `schema_version`.
582 fn writes_schema_storage(&self) -> bool {
583 const SCHEMA_TABLES: [&str; 5] = [
584 "sqlite_schema",
585 "sqlite_master",
586 "sqlite_temp_schema",
587 "sqlite_temp_master",
588 "sqlite_dbpage",
589 ];
590 match self {
591 Self::Insert(Insert { table, .. })
592 | Self::Delete(Delete { table, .. })
593 | Self::Update(Update { table, .. }) => table.is_some_and(|table| {
594 SCHEMA_TABLES
595 .iter()
596 .any(|schema_table| table.eq_ignore_ascii_case(schema_table))
597 }),
598 Self::Pragma(Pragma {
599 name: Some(name),
600 argument: Some(_),
601 ..
602 }) => {
603 name.eq_ignore_ascii_case("writable_schema")
604 || name.eq_ignore_ascii_case("schema_version")
605 }
606 _ => false,
607 }
608 }
609
610 /// Builds the context from the raw authorizer callback arguments.
611 ///
612 /// `database` is the 5th callback argument (the database name) and
613 /// `accessor` is the 6th (the trigger or view responsible). The `arg1` and
614 /// `arg2` values are the 3rd and 4th arguments, whose meaning depends on
615 /// the action code per the SQLite documentation.
616 pub(crate) fn from_ffi(
617 code: i32,
618 arg1: Option<&'a str>,
619 arg2: Option<&'a str>,
620 database: Option<&'a str>,
621 accessor: Option<&'a str>,
622 ) -> Self {
623 match code {
624 ffi::SQLITE_CREATE_INDEX => Self::CreateIndex(CreateIndex {
625 index: arg1,
626 table: arg2,
627 database,
628 accessor,
629 }),
630 ffi::SQLITE_CREATE_TABLE => Self::CreateTable(CreateTable {
631 table: arg1,
632 database,
633 accessor,
634 }),
635 ffi::SQLITE_CREATE_TEMP_INDEX => Self::CreateTempIndex(CreateTempIndex {
636 index: arg1,
637 table: arg2,
638 database,
639 accessor,
640 }),
641 ffi::SQLITE_CREATE_TEMP_TABLE => Self::CreateTempTable(CreateTempTable {
642 table: arg1,
643 database,
644 accessor,
645 }),
646 ffi::SQLITE_CREATE_TEMP_TRIGGER => Self::CreateTempTrigger(CreateTempTrigger {
647 trigger: arg1,
648 table: arg2,
649 database,
650 accessor,
651 }),
652 ffi::SQLITE_CREATE_TEMP_VIEW => Self::CreateTempView(CreateTempView {
653 view: arg1,
654 database,
655 accessor,
656 }),
657 ffi::SQLITE_CREATE_TRIGGER => Self::CreateTrigger(CreateTrigger {
658 trigger: arg1,
659 table: arg2,
660 database,
661 accessor,
662 }),
663 ffi::SQLITE_CREATE_VIEW => Self::CreateView(CreateView {
664 view: arg1,
665 database,
666 accessor,
667 }),
668 ffi::SQLITE_DELETE => Self::Delete(Delete {
669 table: arg1,
670 database,
671 accessor,
672 }),
673 ffi::SQLITE_DROP_INDEX => Self::DropIndex(DropIndex {
674 index: arg1,
675 table: arg2,
676 database,
677 accessor,
678 }),
679 ffi::SQLITE_DROP_TABLE => Self::DropTable(DropTable {
680 table: arg1,
681 database,
682 accessor,
683 }),
684 ffi::SQLITE_DROP_TEMP_INDEX => Self::DropTempIndex(DropTempIndex {
685 index: arg1,
686 table: arg2,
687 database,
688 accessor,
689 }),
690 ffi::SQLITE_DROP_TEMP_TABLE => Self::DropTempTable(DropTempTable {
691 table: arg1,
692 database,
693 accessor,
694 }),
695 ffi::SQLITE_DROP_TEMP_TRIGGER => Self::DropTempTrigger(DropTempTrigger {
696 trigger: arg1,
697 table: arg2,
698 database,
699 accessor,
700 }),
701 ffi::SQLITE_DROP_TEMP_VIEW => Self::DropTempView(DropTempView {
702 view: arg1,
703 database,
704 accessor,
705 }),
706 ffi::SQLITE_DROP_TRIGGER => Self::DropTrigger(DropTrigger {
707 trigger: arg1,
708 table: arg2,
709 database,
710 accessor,
711 }),
712 ffi::SQLITE_DROP_VIEW => Self::DropView(DropView {
713 view: arg1,
714 database,
715 accessor,
716 }),
717 ffi::SQLITE_INSERT => Self::Insert(Insert {
718 table: arg1,
719 database,
720 accessor,
721 }),
722 ffi::SQLITE_PRAGMA => Self::Pragma(Pragma {
723 name: arg1,
724 argument: arg2,
725 database,
726 accessor,
727 }),
728 ffi::SQLITE_READ => Self::Read(Read {
729 table: arg1,
730 column: arg2,
731 database,
732 accessor,
733 }),
734 ffi::SQLITE_SELECT => Self::Select(Select { accessor }),
735 ffi::SQLITE_TRANSACTION => Self::Transaction(Transaction {
736 operation: arg1,
737 accessor,
738 }),
739 ffi::SQLITE_UPDATE => Self::Update(Update {
740 table: arg1,
741 column: arg2,
742 database,
743 accessor,
744 }),
745 ffi::SQLITE_ATTACH => Self::Attach(Attach {
746 filename: arg1,
747 accessor,
748 }),
749 ffi::SQLITE_DETACH => Self::Detach(Detach {
750 database: arg1,
751 accessor,
752 }),
753 ffi::SQLITE_ALTER_TABLE => Self::AlterTable(AlterTable {
754 database: arg1,
755 table: arg2,
756 accessor,
757 }),
758 ffi::SQLITE_REINDEX => Self::Reindex(Reindex {
759 index: arg1,
760 database,
761 accessor,
762 }),
763 ffi::SQLITE_ANALYZE => Self::Analyze(Analyze {
764 table: arg1,
765 database,
766 accessor,
767 }),
768 ffi::SQLITE_CREATE_VTABLE => Self::CreateVTable(CreateVTable {
769 table: arg1,
770 module: arg2,
771 database,
772 accessor,
773 }),
774 ffi::SQLITE_DROP_VTABLE => Self::DropVTable(DropVTable {
775 table: arg1,
776 module: arg2,
777 database,
778 accessor,
779 }),
780 ffi::SQLITE_FUNCTION => Self::Function(Function {
781 function: arg2,
782 accessor,
783 }),
784 ffi::SQLITE_SAVEPOINT => Self::Savepoint(Savepoint {
785 operation: arg1,
786 name: arg2,
787 accessor,
788 }),
789 ffi::SQLITE_RECURSIVE => Self::Recursive(Recursive { accessor }),
790 other => Self::Unknown(Unknown {
791 code: other,
792 arg1,
793 arg2,
794 database,
795 accessor,
796 }),
797 }
798 }
799}
800
801/// Authorizer callback decision.
802///
803/// Returned by the authorizer callback to indicate whether to allow,
804/// ignore, or deny the requested operation.
805#[derive(Debug, Clone, Copy, PartialEq, Eq)]
806pub enum AuthorizerDecision {
807 /// Allow the operation to proceed (`SQLITE_OK`).
808 Allow,
809 /// Ignore the operation (`SQLITE_IGNORE`).
810 ///
811 /// For `Read` actions, returns `NULL` instead of the column value.
812 /// For other actions, treats the operation as a no-op.
813 Ignore,
814 /// Deny the operation (`SQLITE_DENY`).
815 ///
816 /// Causes the entire SQL statement to fail with an authorization error.
817 Deny,
818}
819
820impl AuthorizerDecision {
821 /// Converts the decision to the FFI return code.
822 pub(crate) fn to_ffi(self) -> i32 {
823 match self {
824 Self::Allow => ffi::SQLITE_OK,
825 Self::Ignore => ffi::SQLITE_IGNORE,
826 Self::Deny => ffi::SQLITE_DENY,
827 }
828 }
829}
830
831impl SqliteConnection {
832 /// Registers an authorizer callback for SQL compilation access control.
833 /// Added in SQLite 3.0.0 (June 2004).
834 ///
835 /// The callback is invoked during `sqlite3_prepare()` (statement
836 /// compilation) to control access to database objects. It receives
837 /// an [`AuthorizerContext`] describing the operation and returns an
838 /// [`AuthorizerDecision`].
839 ///
840 /// The authorizer is consulted only at statement preparation, so treat it
841 /// as defense-in-depth rather than a complete sandbox. SQLite re-checks
842 /// already-prepared statements when an authorizer is installed. Removing the
843 /// authorizer clears diesel's statement cache so statements prepared while
844 /// it was active are re-prepared without it.
845 ///
846 /// The authorizer may be re-invoked during `sqlite3_step()` if a schema
847 /// change triggers statement recompilation.
848 ///
849 /// The callback must not modify the database connection. It is invoked
850 /// synchronously on the thread driving the connection, so it is never
851 /// called concurrently.
852 ///
853 /// Only one authorizer can be active at a time per connection.
854 /// Registering a new one replaces the previous. Panics in the callback
855 /// abort the process.
856 ///
857 /// See: [`sqlite3_set_authorizer`](https://sqlite.org/c3ref/set_authorizer.html)
858 ///
859 /// # Example
860 ///
861 /// ```rust
862 /// # use diesel::prelude::*;
863 /// use diesel::sqlite::{SqliteConnection, AuthorizerContext, AuthorizerDecision};
864 ///
865 /// # let conn = &mut SqliteConnection::establish(":memory:").unwrap();
866 /// conn.on_authorize(|ctx| match ctx {
867 /// AuthorizerContext::Delete(_) => AuthorizerDecision::Deny,
868 /// AuthorizerContext::DropTable(_) | AuthorizerContext::DropIndex(_) => {
869 /// AuthorizerDecision::Deny
870 /// }
871 /// _ => AuthorizerDecision::Allow,
872 /// });
873 ///
874 /// // Later: remove the authorizer
875 /// conn.remove_authorizer();
876 /// ```
877 pub fn on_authorize<F>(&mut self, hook: F)
878 where
879 F: FnMut(AuthorizerContext<'_>) -> AuthorizerDecision + Send + 'static,
880 {
881 // No cache clear is needed here. Installing a non-null authorizer makes
882 // SQLite expire every prepared statement on the connection, and because
883 // diesel prepares with `sqlite3_prepare_v3` those statements are
884 // transparently re-prepared under the new authorizer on their next step.
885 self.raw_connection.set_authorizer(hook);
886 // The public documentation doesn't explicitly state what happens with existing
887 // prepared statements, so rather be safe and nuke them. We don't
888 // expect that people change the authorizer all the time, so this should be fine
889 self.statement_cache.clear();
890 }
891
892 /// Removes the authorizer callback.
893 ///
894 /// See [`on_authorize`](Self::on_authorize) for usage example.
895 pub fn remove_authorizer(&mut self) {
896 self.raw_connection.remove_authorizer();
897 // Removing an authorizer does not expire prepared statements: SQLite
898 // expires them only when a non-null authorizer is installed. A statement
899 // prepared while the authorizer was active can have its decisions
900 // compiled in (an `Ignore` on a column read, for example, bakes a `NULL`
901 // into the statement), and nothing invalidates that cached statement on
902 // removal, so it keeps returning the old result. Clear the cache to force
903 // the next query to re-prepare without the authorizer.
904 self.statement_cache.clear();
905 }
906}
907
908// miri doesn't support callbacks yet
909#[cfg(all(test, not(miri)))]
910mod tests {
911 use super::*;
912 use crate::connection::Connection;
913 use crate::query_dsl::RunQueryDsl;
914 use std::sync::Arc;
915 use std::sync::atomic::{AtomicU32, Ordering};
916
917 fn connection() -> SqliteConnection {
918 SqliteConnection::establish(":memory:").unwrap()
919 }
920
921 #[diesel_test_helper::test]
922 fn on_authorize_deny_rejects_statement() {
923 let conn = &mut connection();
924 crate::sql_query("CREATE TABLE auth_basic (id INTEGER PRIMARY KEY)")
925 .execute(conn)
926 .unwrap();
927
928 let calls = Arc::new(AtomicU32::new(0));
929 let calls2 = calls.clone();
930
931 conn.on_authorize(move |_ctx| {
932 calls2.fetch_add(1, Ordering::Relaxed);
933 AuthorizerDecision::Deny
934 });
935
936 // The authorizer is consulted while the statement is prepared, denies
937 // it, and the statement is rejected.
938 let denied = crate::sql_query("SELECT id FROM auth_basic").execute(conn);
939 assert!(denied.is_err(), "a denied statement should fail to prepare");
940 assert!(
941 calls.load(Ordering::Relaxed) > 0,
942 "the authorizer callback should have been invoked"
943 );
944
945 // Removing the authorizer restores access.
946 conn.remove_authorizer();
947 crate::sql_query("SELECT id FROM auth_basic")
948 .execute(conn)
949 .unwrap();
950 }
951
952 #[diesel_test_helper::test]
953 fn remove_authorizer_re_prepares_cached_statements() {
954 use crate::prelude::*;
955 use crate::sqlite::AuthorizerContext;
956
957 crate::table! {
958 auth_ignore_items (id) {
959 id -> Integer,
960 }
961 }
962
963 let conn = &mut connection();
964 crate::sql_query("CREATE TABLE auth_ignore_items (id INTEGER PRIMARY KEY)")
965 .execute(conn)
966 .unwrap();
967 crate::sql_query("INSERT INTO auth_ignore_items (id) VALUES (42)")
968 .execute(conn)
969 .unwrap();
970
971 // An authorizer that ignores column reads. SQLite bakes a NULL
972 // substitution for the column into the prepared (and cached) statement.
973 // A typed query is used because raw `sql_query` is never cached.
974 conn.on_authorize(|ctx| match ctx {
975 AuthorizerContext::Read(_) => AuthorizerDecision::Ignore,
976 _ => AuthorizerDecision::Allow,
977 });
978 let ignored = auth_ignore_items::table
979 .select(auth_ignore_items::id.nullable())
980 .load::<Option<i32>>(conn)
981 .unwrap();
982 assert_eq!(
983 ignored,
984 vec![None],
985 "Ignore substitutes NULL for the column"
986 );
987
988 // SQLite does not expire prepared statements when an authorizer is
989 // removed, so `remove_authorizer` clears diesel's statement cache to
990 // force the cached statement (with its baked-in NULL) to be re-prepared.
991 conn.remove_authorizer();
992 let restored = auth_ignore_items::table
993 .select(auth_ignore_items::id.nullable())
994 .load::<Option<i32>>(conn)
995 .unwrap();
996 assert_eq!(
997 restored,
998 vec![Some(42)],
999 "after removing the authorizer the real value is returned"
1000 );
1001 }
1002
1003 #[diesel_test_helper::test]
1004 fn on_authorize_re_prepares_cached_statements() {
1005 use crate::prelude::*;
1006 use crate::sqlite::AuthorizerContext;
1007
1008 crate::table! {
1009 auth_replace_items (id) {
1010 id -> Integer,
1011 }
1012 }
1013
1014 let conn = &mut connection();
1015 crate::sql_query("CREATE TABLE auth_replace_items (id INTEGER PRIMARY KEY)")
1016 .execute(conn)
1017 .unwrap();
1018 crate::sql_query("INSERT INTO auth_replace_items (id) VALUES (42)")
1019 .execute(conn)
1020 .unwrap();
1021
1022 // A first authorizer that allows everything. The typed query is
1023 // prepared and cached while it is active, returning the real value.
1024 conn.on_authorize(|_ctx| AuthorizerDecision::Allow);
1025 let allowed = auth_replace_items::table
1026 .select(auth_replace_items::id.nullable())
1027 .load::<Option<i32>>(conn)
1028 .unwrap();
1029 assert_eq!(
1030 allowed,
1031 vec![Some(42)],
1032 "the allow-all authorizer returns the real value"
1033 );
1034
1035 // Installing the replacement authorizer expires the cached statement
1036 // (SQLite expires all prepared statements when a non-null authorizer is
1037 // set), so `sqlite3_prepare_v3` re-prepares it under the new authorizer
1038 // and it now yields NULL. This documents that no diesel-side cache clear
1039 // is required on the install path.
1040 conn.on_authorize(|ctx| match ctx {
1041 AuthorizerContext::Read(_) => AuthorizerDecision::Ignore,
1042 _ => AuthorizerDecision::Allow,
1043 });
1044 let ignored = auth_replace_items::table
1045 .select(auth_replace_items::id.nullable())
1046 .load::<Option<i32>>(conn)
1047 .unwrap();
1048 assert_eq!(
1049 ignored,
1050 vec![None],
1051 "after replacing the authorizer the new decision takes effect"
1052 );
1053 }
1054
1055 #[diesel_test_helper::test]
1056 #[expect(
1057 unsafe_code,
1058 reason = "a non-UTF-8 identifier cannot be written through `&str` SQL"
1059 )]
1060 fn non_utf8_names_are_denied_before_the_callback() {
1061 use std::sync::Mutex;
1062
1063 let conn = &mut connection();
1064 let sql = c"CREATE VIEW \"helper\xff\" AS SELECT abs(-1) AS id; CREATE VIEW items AS SELECT id FROM \"helper\xff\";";
1065 // SAFETY: the connection is live, and `sql` is a NUL-terminated string borrowed for the call.
1066 let rc = unsafe {
1067 conn.with_raw_connection(|raw| {
1068 ffi::sqlite3_exec(
1069 raw,
1070 sql.as_ptr(),
1071 None,
1072 core::ptr::null_mut(),
1073 core::ptr::null_mut(),
1074 )
1075 })
1076 };
1077 assert_eq!(rc, ffi::SQLITE_OK);
1078
1079 let abs_accessors = Arc::new(Mutex::new(Vec::new()));
1080 let abs_accessors2 = abs_accessors.clone();
1081 conn.on_authorize(move |ctx| {
1082 if let AuthorizerContext::Function(function) = ctx
1083 && function.function == Some("abs")
1084 {
1085 abs_accessors2
1086 .lock()
1087 .unwrap()
1088 .push(function.accessor.map(str::to_owned));
1089 }
1090 AuthorizerDecision::Allow
1091 });
1092
1093 let result = crate::sql_query("SELECT id FROM items").execute(conn);
1094 assert!(result.is_err());
1095 assert!(abs_accessors.lock().unwrap().iter().all(Option::is_some));
1096 }
1097
1098 #[diesel_test_helper::test]
1099 fn schema_modifying_policy_blocks_writable_schema_edits() {
1100 use crate::connection::SimpleConnection;
1101 use crate::dsl::sql;
1102 use crate::sql_types::BigInt;
1103
1104 let conn = &mut connection();
1105 conn.batch_execute(
1106 "CREATE TABLE accounts (id INTEGER PRIMARY KEY, balance INTEGER NOT NULL CHECK (balance >= 0));
1107 CREATE TRIGGER audit AFTER UPDATE ON accounts BEGIN SELECT 1; END;",
1108 )
1109 .unwrap();
1110 conn.on_authorize(|ctx| {
1111 if ctx.is_schema_modifying() {
1112 AuthorizerDecision::Deny
1113 } else {
1114 AuthorizerDecision::Allow
1115 }
1116 });
1117
1118 let _ = conn.batch_execute(
1119 "PRAGMA writable_schema = ON;
1120 DELETE FROM sqlite_schema WHERE name = 'audit';
1121 PRAGMA writable_schema = RESET;",
1122 );
1123 assert!(conn.batch_execute("PRAGMA writable_schema").is_ok());
1124 assert!(conn.batch_execute("PRAGMA schema_version").is_ok());
1125
1126 conn.remove_authorizer();
1127 let triggers: i64 =
1128 sql::<BigInt>("SELECT count(*) FROM sqlite_schema WHERE name = 'audit'")
1129 .get_result(conn)
1130 .unwrap();
1131 assert_eq!(triggers, 1);
1132 }
1133}