1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum Owner {
17 App,
19 Host,
21 AppTriggerOfHost,
23}
24
25#[derive(Clone, Copy, Debug)]
27pub struct StatementScope {
28 pub bulk: bool,
30 pub local: bool,
32}
33
34pub struct PolicyAction<'a> {
36 pub action: AuthAction<'a>,
38 pub database: Option<&'a str>,
40 pub accessor: Option<&'a str>,
42 pub owner: Owner,
44 pub scope: StatementScope,
46}
47
48pub trait HostError: std::error::Error + Send + Sync + 'static {}
51
52impl<T: std::error::Error + Send + Sync + 'static> HostError for T {}
53
54pub trait Policy: Sized + Send + Sync + 'static {
56 type Refusal: HostError;
58 type Failure: HostError + Clone + From<crate::EngineFailure<Self::Failure, Self::Refusal>>;
61 fn judge(&self, action: &PolicyAction<'_>) -> Result<(), Self::Refusal>;
65 fn check_sql(&self, tokens: &[crate::sql::Token]) -> Result<(), Self::Refusal>;
67 fn begin_app_call(&self);
69 fn host_object(&self, name: &str) -> bool;
71 fn statement_key(&self) -> u64;
73 type Scope;
76 fn enter(&self, scope: &Self::Scope);
78 fn leave(&self, scope: &Self::Scope);
80 fn refresh(
85 &self,
86 sql: &crate::connection::HostSql<Self>,
87 extent: Refresh,
88 ) -> rusqlite::Result<()>;
89}
90
91pub type PolicyError<P> = crate::Error<<P as Policy>::Failure, <P as Policy>::Refusal>;
93
94#[derive(Clone, Copy, Debug, PartialEq, Eq)]
96pub enum Refresh {
97 Whole,
99 Changed,
101}
102
103#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
106pub(crate) struct AppContext {
107 writing: bool,
108 reading: bool,
109 capturing: bool,
112 policy: u64,
115}
116
117pub 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 pub fn context(&self) -> &'a rusqlite::functions::Context<'a> {
127 self.context
128 }
129
130 pub fn owner(&self) -> Owner {
132 self.owner
133 }
134
135 pub fn deny(&self, refusal: P::Refusal) {
138 lock_unpoisoned(self.state).denied = Some(crate::Error::Refused(refusal));
139 }
140}
141
142pub(crate) struct SqlAuthorization<P: Policy> {
146 state: Arc<Mutex<AuthorizationState<P>>>,
147 handle: Arc<OnceLock<crate::Handle<P::Failure>>>,
150 whole: Arc<WholeViews>,
152 policy: Arc<P>,
155}
156
157struct AuthorizationState<P: Policy> {
158 internal: bool,
159 writing: bool,
160 stepping: bool,
161 observed: Option<StatementReads>,
162 bulk: Option<BTreeSet<String>>,
166 local: bool,
169 reading: bool,
171 reads: Option<ReadCapture>,
173 altering: bool,
174 denied: Option<PolicyError<P>>,
175 broken: Option<Bug>,
178 #[cfg(any(test, feature = "test-utils"))]
180 panic_next: bool,
181 #[cfg(any(test, feature = "test-utils"))]
184 panic_next_function: bool,
185}
186
187impl<P: Policy> SqlAuthorization<P> {
188 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 pub(crate) fn whole_views(&self) -> &WholeViews {
217 &self.whole
218 }
219
220 #[cfg(any(test, feature = "test-utils"))]
222 pub(crate) fn panic_next(&self) {
223 lock_unpoisoned(&self.state).panic_next = true;
224 }
225
226 #[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 pub(crate) fn functions(&self) -> HostFunctions<P> {
234 HostFunctions { state: Arc::clone(&self.state) }
235 }
236
237 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 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 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 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 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 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 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 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 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 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 pub(crate) fn capturing_reads(&self) -> bool {
418 lock_unpoisoned(&self.state).reads.is_some()
419 }
420
421 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 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 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 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
481pub(crate) struct HostFunctions<P: Policy> {
485 state: Arc<Mutex<AuthorizationState<P>>>,
486}
487
488impl<P: Policy> HostFunctions<P> {
489 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#[derive(Clone, Default)]
528pub struct StatementReads {
529 pub columns: Vec<String>,
531 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
549pub 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
558pub(crate) struct BulkSql<'a, P: Policy>(&'a Mutex<AuthorizationState<P>>);
560
561impl<P: Policy> BulkSql<'_, P> {
562 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
577pub struct LocalSql<'a, P: Policy> {
579 state: &'a Mutex<AuthorizationState<P>>,
580 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 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 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 fn refusal(&mut self, context: AuthContext<'_>) -> Result<(), PolicyError<P>> {
685 use AuthAction::*;
686 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 let internal_check = self.altering;
735 let forbidden = match context.action {
736 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 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;