Skip to main content

sqlive/
authorization.rs

1//! The authorizer: the rules the engine enforces on every statement, then
2//! the policy its host supplies.
3
4use std::collections::BTreeSet;
5use std::sync::{Arc, Mutex, OnceLock};
6
7use panic_as_error::locks::lock_unpoisoned;
8use panic_as_error::Bug;
9
10use rusqlite::hooks::{AuthAction, AuthContext, Authorization};
11
12use crate::{ReadCapture, ReadFrame, ReadSet, Scopes, WholeViews};
13
14/// Whose statement SQLite is preparing.
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum Owner {
17    /// The app's statement, or an object of the app's it runs.
18    App,
19    /// The host's own statement, and the host's own objects it runs.
20    Host,
21    /// A trigger or view of the app's that a host statement runs.
22    AppTriggerOfHost,
23}
24
25/// The scopes the statement is prepared in that the policy asks about.
26#[derive(Clone, Copy, Debug)]
27pub struct StatementScope {
28    /// Whether it is prepared in a bulk write.
29    pub bulk: bool,
30    /// Whether it is prepared in the host's local scope (`HostSql::local_scope`).
31    pub local: bool,
32}
33
34/// One action SQLite reports, as the authorizer asks the policy about it.
35pub struct PolicyAction<'a> {
36    /// What the statement does, as SQLite reports it.
37    pub action: AuthAction<'a>,
38    /// The schema the action touches, `main`, `temp` or an attached one.
39    pub database: Option<&'a str>,
40    /// The trigger or view whose code the action runs in, if any.
41    pub accessor: Option<&'a str>,
42    /// Whose statement it is: the host's own or the app's.
43    pub owner: Owner,
44    /// The scope the statement runs in.
45    pub scope: StatementScope,
46}
47
48/// What the engine's error asks of the host's failure and refusal types:
49/// errors that cross threads, which the engine finds again inside SQLite's.
50pub trait HostError: std::error::Error + Send + Sync + 'static {}
51
52impl<T: std::error::Error + Send + Sync + 'static> HostError for T {}
53
54/// What the host adds to the authorizer's rules.
55pub trait Policy: Sized + Send + Sync + 'static {
56    /// What the policy refuses a statement with.
57    type Refusal: HostError;
58    /// What the host's handle fails with: the host's own failures, and
59    /// sqlive's, which the host converts into this type through `From`.
60    type Failure: HostError + Clone + From<crate::EngineFailure<Self::Failure, Self::Refusal>>;
61    /// Judge an action the authorizer's rules allowed; `Err` refuses the
62    /// statement with it. A host statement's actions come here too, so the
63    /// policy sees every action allowed.
64    fn judge(&self, action: &PolicyAction<'_>) -> Result<(), Self::Refusal>;
65    /// Judge an app statement's text before it is prepared.
66    fn check_sql(&self, tokens: &[crate::sql::Token]) -> Result<(), Self::Refusal>;
67    /// A new app call begins: forget what the last statement left.
68    fn begin_app_call(&self);
69    /// Whether `name`, a trigger or view, is the host's own object.
70    fn host_object(&self, name: &str) -> bool;
71    /// What the policy adds to the app statement cache's key.
72    fn statement_key(&self) -> u64;
73    /// A part of the host's work the policy judges differently, which the
74    /// host runs through `HostSql::within`.
75    type Scope;
76    /// Work in `scope` begins.
77    fn enter(&self, scope: &Self::Scope);
78    /// Work in `scope` ended, on any path out of it, a panic's included.
79    fn leave(&self, scope: &Self::Scope);
80    /// Read again what the policy keeps of the connection's schema: all of
81    /// it, or what changed since it last read. The connection calls it with
82    /// `Refresh::Whole` as it opens and with `Refresh::Changed` before each
83    /// app statement, and the host through `refresh_policy`.
84    fn refresh(
85        &self,
86        sql: &crate::connection::HostSql<Self>,
87        extent: Refresh,
88    ) -> rusqlite::Result<()>;
89}
90
91/// The error a connection judged by `P` returns.
92pub type PolicyError<P> = crate::Error<<P as Policy>::Failure, <P as Policy>::Refusal>;
93
94/// How much of the schema the policy reads again.
95#[derive(Clone, Copy, Debug, PartialEq, Eq)]
96pub enum Refresh {
97    /// All of it, as the connection opens.
98    Whole,
99    /// What the statements since it last read changed.
100    Changed,
101}
102
103/// The state an app statement is judged in as it is prepared: the same SQL
104/// can be allowed in one and refused in another.
105#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
106pub(crate) struct AppContext {
107    writing: bool,
108    reading: bool,
109    /// Whether it records what it reads for a live query: a statement first
110    /// prepared in a one-shot read recorded nothing to replay.
111    capturing: bool,
112    /// The policy's part of the cache key, so statements the policy judges
113    /// differently get different entries.
114    policy: u64,
115}
116
117/// One call of a SQL function registered through a connection's setup.
118pub struct FunctionCall<'a, P: Policy> {
119    context: &'a rusqlite::functions::Context<'a>,
120    owner: Owner,
121    state: &'a Mutex<AuthorizationState<P>>,
122}
123
124impl<'a, P: Policy> FunctionCall<'a, P> {
125    /// The function's arguments.
126    pub fn context(&self) -> &'a rusqlite::functions::Context<'a> {
127        self.context
128    }
129
130    /// Whose statement runs the function: the host's own, or the app's.
131    pub fn owner(&self) -> Owner {
132        self.owner
133    }
134
135    /// Refuse the statement running the function with `refusal`, in place
136    /// of the message the function's own failure carries.
137    pub fn deny(&self, refusal: P::Refusal) {
138        lock_unpoisoned(self.state).denied = Some(crate::Error::Refused(refusal));
139    }
140}
141
142/// Every change to the state but the authorizer's own is whole before it
143/// can panic, and the authorizer catches its own panic (`callback`), so the
144/// lock is taken as it is.
145pub(crate) struct SqlAuthorization<P: Policy> {
146    state: Arc<Mutex<AuthorizationState<P>>>,
147    /// The handle the connection serves, once it serves one, which a panic
148    /// in the authorizer fails.
149    handle: Arc<OnceLock<crate::Handle<P::Failure>>>,
150    /// The views and tables a live query reads whole.
151    whole: Arc<WholeViews>,
152    /// What the host adds to the rules. The authorizer asks it after its own
153    /// rules allow an action.
154    policy: Arc<P>,
155}
156
157struct AuthorizationState<P: Policy> {
158    internal: bool,
159    writing: bool,
160    stepping: bool,
161    observed: Option<StatementReads>,
162    /// The tables of `main` a bulk write's statements, and the triggers and
163    /// foreign-key actions SQLite compiles into them, may change, lowercase;
164    /// `None` outside a bulk write.
165    bulk: Option<BTreeSet<String>>,
166    /// Whether app SQL runs in the host's local scope, which the policy
167    /// judges as it chooses.
168    local: bool,
169    /// Whether app SQL runs in a read, which may only read.
170    reading: bool,
171    /// What a live query's statements read, while one of its runs reads.
172    reads: Option<ReadCapture>,
173    altering: bool,
174    denied: Option<PolicyError<P>>,
175    /// The authorizer panicked with this: the state may be half-changed, so
176    /// it refuses every later statement with it (E15).
177    broken: Option<Bug>,
178    /// Panic in the next judgment, as a bug in the authorizer would.
179    #[cfg(any(test, feature = "test-utils"))]
180    panic_next: bool,
181    /// Panic in the next call of one of the host's SQL functions, as a bug in
182    /// it would.
183    #[cfg(any(test, feature = "test-utils"))]
184    panic_next_function: bool,
185}
186
187impl<P: Policy> SqlAuthorization<P> {
188    /// An authorizer that asks `policy` about each action its own rules
189    /// allow.
190    pub(crate) fn new(whole: Arc<WholeViews>, policy: Arc<P>) -> Self {
191        Self {
192            state: Arc::new(Mutex::new(AuthorizationState {
193                internal: false,
194                writing: false,
195                stepping: false,
196                observed: None,
197                bulk: None,
198                local: false,
199                reading: false,
200                reads: None,
201                altering: false,
202                denied: None,
203                broken: None,
204                #[cfg(any(test, feature = "test-utils"))]
205                panic_next: false,
206                #[cfg(any(test, feature = "test-utils"))]
207                panic_next_function: false,
208            })),
209            handle: Arc::new(OnceLock::new()),
210            whole,
211            policy,
212        }
213    }
214
215    /// The views and tables a live query reads whole.
216    pub(crate) fn whole_views(&self) -> &WholeViews {
217        &self.whole
218    }
219
220    /// Panic in the next judgment, as a bug in the authorizer would.
221    #[cfg(any(test, feature = "test-utils"))]
222    pub(crate) fn panic_next(&self) {
223        lock_unpoisoned(&self.state).panic_next = true;
224    }
225
226    /// Panic in the next call of one of the host's SQL functions.
227    #[cfg(any(test, feature = "test-utils"))]
228    pub(crate) fn panic_next_function(&self) {
229        lock_unpoisoned(&self.state).panic_next_function = true;
230    }
231
232    /// What wraps the host's SQL functions as the connection registers them.
233    pub(crate) fn functions(&self) -> HostFunctions<P> {
234        HostFunctions { state: Arc::clone(&self.state) }
235    }
236
237    /// The connection now serves `handle`, which a panic in its authorizer
238    /// fails.
239    pub(crate) fn serve(&self, handle: crate::Handle<P::Failure>) {
240        if self.handle.set(handle).is_err() {
241            unreachable!("a connection serves one handle");
242        }
243    }
244
245    pub(crate) fn callback(&self) -> impl FnMut(AuthContext<'_>) -> Authorization + Send + 'static {
246        let state = Arc::clone(&self.state);
247        let handle = Arc::clone(&self.handle);
248        let policy = Arc::clone(&self.policy);
249        move |context| {
250            let mut state = lock_unpoisoned(&state);
251            if let Some(bug) = &state.broken {
252                state.denied = Some(crate::Error::HandleFailed(bug.clone()));
253                return Authorization::Deny;
254            }
255            // SQLite's authorizer can't fail, and rusqlite turns its panic
256            // into an error that names no bug, so the authorizer keeps it:
257            // what it was changing may be half-changed, so the handle fails
258            // and this connection refuses every later statement, repeating
259            // the bug its first refusal returned (E15).
260            match panic_as_error::caught_sync("authorize a statement", || {
261                state.judge(context, &*policy)
262            }) {
263                Ok(authorization) => authorization,
264                Err(bug) => {
265                    if let Some(handle) = handle.get() {
266                        handle.fail_with_bug(bug.clone());
267                    }
268                    state.denied = Some(crate::Error::Bug(bug.clone()));
269                    state.broken = Some(bug);
270                    Authorization::Deny
271                }
272            }
273        }
274    }
275
276    pub(crate) fn internal(&self) -> InternalSql<'_, P> {
277        let mut state = lock_unpoisoned(&self.state);
278        let previous = state.internal;
279        state.internal = true;
280        InternalSql { state: &self.state, previous }
281    }
282
283    pub(crate) fn observe_reads(&self) -> ObservedReads<'_, P> {
284        let mut state = lock_unpoisoned(&self.state);
285        assert!(state.observed.is_none(), "read observation cannot nest");
286        state.observed = Some(StatementReads::default());
287        ObservedReads(&self.state)
288    }
289
290    pub(crate) fn write(&self) -> WriteSql<'_, P> {
291        let mut state = lock_unpoisoned(&self.state);
292        assert!(!state.writing, "write SQL scope cannot nest");
293        state.writing = true;
294        WriteSql(&self.state)
295    }
296
297    /// A bulk write's SQL: a write's, judged by the policy in the bulk scope,
298    /// recording instead each table of `main` its statements change.
299    pub(crate) fn bulk(&self) -> BulkSql<'_, P> {
300        let mut state = lock_unpoisoned(&self.state);
301        assert!(!state.writing, "write SQL scope cannot nest");
302        state.writing = true;
303        state.bulk = Some(BTreeSet::new());
304        BulkSql(&self.state)
305    }
306
307    /// App SQL the host runs in a scope of its own, inside a transaction
308    /// it holds: a write's, judged by the policy in the local scope. In a
309    /// bulk write, the tables it changes count among the bulk write's.
310    pub(crate) fn local(&self) -> LocalSql<'_, P> {
311        let mut state = lock_unpoisoned(&self.state);
312        assert!(!state.local, "local SQL scope cannot nest");
313        state.local = true;
314        let writing = std::mem::replace(&mut state.writing, true);
315        LocalSql { state: &self.state, writing }
316    }
317
318    pub(crate) fn step(&self) -> StepSql<'_, P> {
319        let mut state = lock_unpoisoned(&self.state);
320        assert!(!state.stepping, "SQL step scope cannot nest");
321        state.stepping = true;
322        StepSql(&self.state)
323    }
324
325    pub(crate) fn begin_app_call(&self) {
326        let mut state = lock_unpoisoned(&self.state);
327        state.denied = None;
328        state.altering = false;
329        drop(state);
330        self.policy.begin_app_call();
331    }
332
333    /// A one-shot read's SQL: it may only read, and records nothing of
334    /// what it reads, since nothing runs it again.
335    pub(crate) fn reading(&self) -> ReadingSql<'_, P> {
336        let mut state = lock_unpoisoned(&self.state);
337        assert!(!state.reading, "read scopes cannot nest");
338        state.reading = true;
339        ReadingSql(&self.state)
340    }
341
342    /// A live query's run's SQL: it may only read, and records what it
343    /// reads, so a commit that changes it runs the query again (ยง4).
344    pub(crate) fn live_reading(&self) -> ReadingSql<'_, P> {
345        let reading = self.reading();
346        lock_unpoisoned(&self.state).reads = Some(ReadCapture::new(Arc::clone(&self.whole)));
347        reading
348    }
349
350    pub(crate) fn reads(&self) -> ReadSet {
351        let mut state = lock_unpoisoned(&self.state);
352        state.reads.as_mut().expect("active read scope").reads()
353    }
354
355    /// Whether the authorizer is recording what statements read or change.
356    /// It learns that only while a statement is prepared, so such a
357    /// statement must not come from the cache.
358    pub(crate) fn recording(&self) -> bool {
359        let state = lock_unpoisoned(&self.state);
360        state.reads.is_some() || state.observed.is_some()
361    }
362
363    /// What decides how the authorizer judges an app statement it prepares,
364    /// or `None` while preparing has effects beyond judging and recording
365    /// reads, as in the host's own SQL, a migration's, a bulk write's or the
366    /// local scope's: then each statement is prepared afresh. A bulk write's
367    /// statement is also compiled for a connection with no pre-update hook,
368    /// so SQLite may empty a table in one step there; kept, it would empty
369    /// one so under a write's hook too, unseen. The policy judges a statement
370    /// of the local scope by rules of its own, so a statement a write kept
371    /// would run in the local scope without them, and one the local scope
372    /// kept would run in a write under them.
373    pub(crate) fn app_context(&self) -> Option<AppContext> {
374        let state = lock_unpoisoned(&self.state);
375        if state.internal
376            || state.observed.is_some()
377            || state.bulk.is_some()
378            || state.local
379            || state.altering
380        {
381            return None;
382        }
383        Some(AppContext {
384            writing: state.writing,
385            reading: state.reading,
386            capturing: state.reads.is_some(),
387            policy: self.policy.statement_key(),
388        })
389    }
390
391    /// The reads the statement being prepared recorded, so a later use of
392    /// it, prepared already, records them too.
393    pub(crate) fn statement_reads(&self) -> ReadFrame {
394        lock_unpoisoned(&self.state)
395            .reads
396            .as_mut()
397            .map(|reads| reads.statement())
398            .unwrap_or_default()
399    }
400
401    /// Record the reads an already prepared statement made when it was
402    /// prepared.
403    pub(crate) fn replay_reads(&self, recorded: &ReadFrame) {
404        if let Some(reads) = &mut lock_unpoisoned(&self.state).reads {
405            reads.replay(recorded);
406        }
407    }
408
409    pub(crate) fn begin_read_statement(&self) {
410        if let Some(reads) = &mut lock_unpoisoned(&self.state).reads {
411            reads.begin();
412        }
413    }
414
415    /// Whether the statements prepared now record what they read for a
416    /// live query.
417    pub(crate) fn capturing_reads(&self) -> bool {
418        lock_unpoisoned(&self.state).reads.is_some()
419    }
420
421    /// Run the host's own SQL for the statement being read, as its metadata,
422    /// without recording its reads for the statement.
423    pub(crate) fn unrecorded<T>(&self, run: impl FnOnce() -> T) -> T {
424        let reads = lock_unpoisoned(&self.state).reads.take();
425        let result = {
426            let _internal = self.internal();
427            run()
428        };
429        lock_unpoisoned(&self.state).reads = reads;
430        result
431    }
432
433    /// Run SQL of the host's own for the statement being read, judged as app
434    /// SQL is, without recording its reads for the statement: it reads only
435    /// what the statement read.
436    pub(crate) fn judged_unrecorded<T>(
437        &self,
438        run: impl FnOnce() -> rusqlite::Result<T>,
439    ) -> rusqlite::Result<T> {
440        let reads = lock_unpoisoned(&self.state).reads.take();
441        self.begin_app_call();
442        let result = self.app_result(run());
443        lock_unpoisoned(&self.state).reads = reads;
444        result
445    }
446
447    /// End the statement begun last: each table it read in the scope
448    /// `scopes` gives it, or whole when `scopes` gives none.
449    pub(crate) fn record_statement(&self, scopes: &Scopes) {
450        let mut state = lock_unpoisoned(&self.state);
451        let Some(reads) = &mut state.reads else {
452            return;
453        };
454        reads.end(scopes);
455    }
456
457    pub(crate) fn check_sql(&self, sql: &str) -> rusqlite::Result<()> {
458        // FTS prepares PRAGMA data_version itself. Permit that internal read,
459        // while keeping direct app PRAGMAs outside the SQL capability.
460        let tokens = crate::sql::tokens(sql)?;
461        if tokens.first().is_some_and(|token| token.word("pragma")) {
462            let error: PolicyError<P> = crate::Error::StatementForbidden { operation: "PRAGMA" };
463            return Err(rusqlite::Error::UserFunctionError(Box::new(error)));
464        }
465        self.policy.check_sql(&tokens).map_err(|refusal| {
466            rusqlite::Error::UserFunctionError(Box::new(
467                crate::Error::<P::Failure, P::Refusal>::Refused(refusal),
468            ))
469        })
470    }
471
472    pub(crate) fn app_result<T>(&self, result: rusqlite::Result<T>) -> rusqlite::Result<T> {
473        let denied = lock_unpoisoned(&self.state).denied.take();
474        match denied {
475            Some(error) => Err(rusqlite::Error::UserFunctionError(Box::new(error))),
476            None => result,
477        }
478    }
479}
480
481/// Wraps the host's SQL functions, sharing the authorizer's state: the
482/// function learns whose statement runs it, and its refusal or panic fails
483/// that statement.
484pub(crate) struct HostFunctions<P: Policy> {
485    state: Arc<Mutex<AuthorizationState<P>>>,
486}
487
488impl<P: Policy> HostFunctions<P> {
489    /// `function`, one of the host's SQL functions named `name`, as the
490    /// connection registers it. rusqlite turns a function's panic into an
491    /// error that names no bug, so the function keeps it: the statement
492    /// fails with the bug's text, and the app's call with `crate::Error::Bug`
493    /// (E15). A function changes nothing, so the connection goes on.
494    pub(crate) fn function<T: rusqlite::types::ToSql>(
495        &self,
496        name: &'static str,
497        function: impl Fn(&FunctionCall<'_, P>) -> rusqlite::Result<T> + Send + 'static,
498    ) -> impl Fn(&mut rusqlite::functions::Context<'_>) -> rusqlite::Result<T> + Send + 'static
499    {
500        let state = Arc::clone(&self.state);
501        move |context| {
502            let called = panic_as_error::caught_sync(name, || {
503                #[cfg(any(test, feature = "test-utils"))]
504                assert!(
505                    !std::mem::take(&mut lock_unpoisoned(&state).panic_next_function),
506                    "{name} lost its argument"
507                );
508                let owner = if lock_unpoisoned(&state).internal { Owner::Host } else { Owner::App };
509                function(&FunctionCall { context: &*context, owner, state: &state })
510            });
511            called.unwrap_or_else(|bug| {
512                lock_unpoisoned(&state).denied = Some(crate::Error::Bug(bug.clone()));
513                let error: PolicyError<P> = crate::Error::Bug(bug);
514                Err(rusqlite::Error::UserFunctionError(Box::new(error)))
515            })
516        }
517    }
518}
519
520pub(crate) struct InternalSql<'a, P: Policy> {
521    state: &'a Mutex<AuthorizationState<P>>,
522    previous: bool,
523}
524
525/// What the statements prepared while observing read: each column, in the
526/// order first read, and each function they call, ASCII lowercase.
527#[derive(Clone, Default)]
528pub struct StatementReads {
529    /// Each column read, by its name alone, in the order first read.
530    pub columns: Vec<String>,
531    /// Each function called, ASCII lowercase.
532    pub functions: BTreeSet<String>,
533}
534
535pub(crate) struct ObservedReads<'a, P: Policy>(&'a Mutex<AuthorizationState<P>>);
536
537impl<P: Policy> ObservedReads<'_, P> {
538    pub(crate) fn reads(&self) -> StatementReads {
539        lock_unpoisoned(self.0).observed.as_ref().expect("observing reads").clone()
540    }
541}
542
543impl<P: Policy> Drop for ObservedReads<'_, P> {
544    fn drop(&mut self) {
545        lock_unpoisoned(self.0).observed = None;
546    }
547}
548
549/// The scope the app's write SQL runs in, from its making until it drops.
550pub struct WriteSql<'a, P: Policy>(&'a Mutex<AuthorizationState<P>>);
551
552impl<P: Policy> Drop for WriteSql<'_, P> {
553    fn drop(&mut self) {
554        lock_unpoisoned(self.0).writing = false;
555    }
556}
557
558/// A bulk write's SQL scope; it ends with the write's SQL.
559pub(crate) struct BulkSql<'a, P: Policy>(&'a Mutex<AuthorizationState<P>>);
560
561impl<P: Policy> BulkSql<'_, P> {
562    /// The tables of `main` the write's statements changed so far, as live
563    /// queries name them.
564    pub(crate) fn changed(&self) -> BTreeSet<String> {
565        lock_unpoisoned(self.0).bulk.clone().expect("a bulk write records the tables it changes")
566    }
567}
568
569impl<P: Policy> Drop for BulkSql<'_, P> {
570    fn drop(&mut self) {
571        let mut state = lock_unpoisoned(self.0);
572        state.writing = false;
573        state.bulk = None;
574    }
575}
576
577/// The host's local SQL scope; it ends as it drops.
578pub struct LocalSql<'a, P: Policy> {
579    state: &'a Mutex<AuthorizationState<P>>,
580    /// Whether app SQL was writing as the scope began.
581    writing: bool,
582}
583
584impl<P: Policy> Drop for LocalSql<'_, P> {
585    fn drop(&mut self) {
586        let mut state = lock_unpoisoned(self.state);
587        state.local = false;
588        state.writing = self.writing;
589    }
590}
591
592pub(crate) struct StepSql<'a, P: Policy>(&'a Mutex<AuthorizationState<P>>);
593
594impl<P: Policy> Drop for StepSql<'_, P> {
595    fn drop(&mut self) {
596        lock_unpoisoned(self.0).stepping = false;
597    }
598}
599
600pub(crate) struct ReadingSql<'a, P: Policy>(&'a Mutex<AuthorizationState<P>>);
601
602impl<P: Policy> Drop for ReadingSql<'_, P> {
603    fn drop(&mut self) {
604        let mut state = lock_unpoisoned(self.0);
605        state.reading = false;
606        state.reads = None;
607    }
608}
609
610impl<P: Policy> Drop for InternalSql<'_, P> {
611    fn drop(&mut self) {
612        lock_unpoisoned(self.state).internal = self.previous;
613    }
614}
615
616impl<P: Policy> AuthorizationState<P> {
617    /// Whose statement `accessor`, the innermost trigger or view being
618    /// prepared, if any, belongs to.
619    fn owner(&self, accessor: Option<&str>, policy: &P) -> Owner {
620        match accessor {
621            _ if !self.internal => Owner::App,
622            Some(name) if !policy.host_object(name) => Owner::AppTriggerOfHost,
623            _ => Owner::Host,
624        }
625    }
626
627    /// Judge the statement being prepared, `context`, recording what it
628    /// reads and changes.
629    fn judge(&mut self, context: AuthContext<'_>, policy: &P) -> Authorization {
630        #[cfg(any(test, feature = "test-utils"))]
631        assert!(!std::mem::take(&mut self.panic_next), "the authorizer's state is past repair");
632        if let (
633            AuthAction::Insert { table_name }
634            | AuthAction::Update { table_name, .. }
635            | AuthAction::Delete { table_name },
636            Some(tables),
637            Some("main"),
638        ) = (context.action, &mut self.bulk, context.database_name)
639        {
640            tables.insert(table_name.to_ascii_lowercase());
641        }
642        if let AuthAction::Read { table_name, column_name } = context.action {
643            if let Some(reads) = &mut self.reads {
644                reads.read(table_name, column_name, context.accessor);
645            }
646            if let Some(observed) = &mut self.observed {
647                if !column_name.is_empty() && !observed.columns.iter().any(|c| c == column_name) {
648                    observed.columns.push(column_name.into());
649                }
650            }
651        }
652        if let AuthAction::Function { function_name } = context.action {
653            if let Some(observed) = &mut self.observed {
654                observed.functions.insert(function_name.to_ascii_lowercase());
655            }
656        }
657        let owner = self.owner(context.accessor, policy);
658        let judged = match owner {
659            Owner::Host => Ok(()),
660            Owner::App | Owner::AppTriggerOfHost => self.refusal(context),
661        }
662        .and_then(|()| {
663            policy
664                .judge(&PolicyAction {
665                    action: context.action,
666                    database: context.database_name,
667                    accessor: context.accessor,
668                    owner,
669                    scope: StatementScope { bulk: self.bulk.is_some(), local: self.local },
670                })
671                .map_err(crate::Error::Refused)
672        });
673        match judged {
674            Ok(()) => Authorization::Allow,
675            Err(error) => {
676                self.denied = Some(error);
677                Authorization::Deny
678            }
679        }
680    }
681
682    /// The error that refuses `context` by the authorizer's own rules, if
683    /// any.
684    fn refusal(&mut self, context: AuthContext<'_>) -> Result<(), PolicyError<P>> {
685        use AuthAction::*;
686        // FTS5 reads the database's data version as it prepares a statement
687        // over its table, in a read or in a write that changes its index, as
688        // a local trigger keeping a search index does. Reading it changes
689        // nothing; app SQL can't name it, since a PRAGMA statement and the
690        // pragma_ table functions stay refused.
691        if matches!(context.action, Pragma { pragma_name: "data_version", pragma_value: None }) {
692            return Ok(());
693        }
694        if self.reading
695            && !matches!(context.action, Read { .. } | Select | Function { .. } | Recursive)
696        {
697            return Err(crate::Error::StatementForbidden {
698                operation: "writing through a read context",
699            });
700        }
701        if self.writing
702            && matches!(
703                context.action,
704                CreateTable { .. }
705                    | CreateTempTable { .. }
706                    | DropTable { .. }
707                    | DropTempTable { .. }
708                    | CreateVtable { .. }
709                    | DropVtable { .. }
710                    | AlterTable { .. }
711                    | CreateIndex { .. }
712                    | CreateTempIndex { .. }
713                    | DropIndex { .. }
714                    | DropTempIndex { .. }
715                    | CreateTrigger { .. }
716                    | CreateTempTrigger { .. }
717                    | DropTrigger { .. }
718                    | DropTempTrigger { .. }
719                    | CreateView { .. }
720                    | CreateTempView { .. }
721                    | DropView { .. }
722                    | DropTempView { .. }
723            )
724        {
725            return Err(crate::Error::StatementForbidden {
726                operation: "schema changes in a write",
727            });
728        }
729        if matches!(context.action, AlterTable { .. }) {
730            self.altering = true;
731        }
732        // SQLite compiles this read-only check as part of ALTER ADD COLUMN.
733        // The permission lasts for this statement, never the following one.
734        let internal_check = self.altering;
735        let forbidden = match context.action {
736            // The session extension initializes its table metadata lazily from
737            // its pre-update hook. App SQL was already authorized at prepare;
738            // no app row-mapping callback runs with this permission enabled.
739            Pragma { pragma_name: "table_xinfo", pragma_value: Some(_) }
740                if self.stepping && context.database_name == Some("main") =>
741            {
742                None
743            }
744            Pragma { pragma_name: "quick_check", .. } if internal_check => None,
745            Read { table_name: "pragma_quick_check", .. } if internal_check => None,
746            // Statistics aren't data: a write's capture would record them,
747            // and the host gathers them itself.
748            Analyze { .. } if self.writing => Some("ANALYZE in a write"),
749            Transaction { .. } | Savepoint { .. } => Some("transaction control"),
750            Attach { .. } | Detach { .. } => Some("attaching or detaching databases"),
751            Pragma { .. } => Some("PRAGMA"),
752            Function { function_name } if function_name.eq_ignore_ascii_case("load_extension") => {
753                Some("loading an extension")
754            }
755            Read { table_name, .. } if table_name.to_ascii_lowercase().starts_with("pragma_") => {
756                Some("PRAGMA")
757            }
758            _ => None,
759        };
760        match forbidden {
761            Some(operation) => Err(crate::Error::StatementForbidden { operation }),
762            None => Ok(()),
763        }
764    }
765}
766
767#[cfg(test)]
768#[path = "authorization_tests.rs"]
769pub(crate) mod tests;