Skip to main content

glacier/
access.rs

1//! Who a piece of work acts for: a signed-in user, an organisation, or
2//! the system itself. Glacier's name for what Phoenix calls a scope.
3//!
4//! This is the seam 0.4's accounts build on: requests will set the access
5//! from the signed-in user, and queries will be limited to what it may
6//! see. For now it records who work is done for, and work that runs for
7//! nobody in particular (webhooks, pruning, recurring jobs) says so
8//! explicitly, with a reason:
9//!
10//! ```ignore
11//! glacier::access::unscoped("nightly digest", async {
12//!     // …
13//! })
14//! .await
15//! ```
16
17use std::any::Any;
18use std::future::Future;
19use std::sync::Arc;
20
21use crate::db::Value;
22use crate::error::{Error, Result};
23
24/// Who work is done for. An app declares its own, `module OrgAccess do
25/// implements Access … end` in `.glacier`, and a request's comes from its
26/// middleware (`ctx.set_access(…)`).
27pub trait Access: Send + Sync + 'static {
28    /// For logs and traces: `user:12`, `org:3`, `system (webhooks)`.
29    fn describe(&self) -> String;
30
31    /// The value a model's owner column takes for this access (`org_id`
32    /// is the org's id), or `None` when it owns no such rows. What
33    /// `Post::for(access)` limits a query to, and what a record built from
34    /// it gets.
35    fn owns(&self, column: &str) -> Option<Value> {
36        let _ = column;
37        None
38    }
39
40    /// The access itself, so a caller can ask for its own type.
41    fn as_any(&self) -> &dyn Any;
42
43    /// What a job queued for this access keeps of it, to rebuild it when
44    /// it runs (`{"kind": "OrgAccess", "org": 42, …}`): ids, not records.
45    /// `None` (the default) for an access that isn't carried into jobs.
46    fn reference(&self) -> Option<serde_json::Value> {
47        None
48    }
49}
50
51/// An access a job can rebuild from its [`reference`](Access::reference),
52/// loading its records again: a member removed from an org since the job
53/// was queued no longer has that access, so the job fails rather than
54/// acting for them. `module X do implements Access` generates it.
55pub trait Rebuild: Access + Sized {
56    /// The `kind` its references carry.
57    const KIND: &'static str;
58
59    /// The access a reference names, loaded and checked again.
60    fn rebuild(reference: serde_json::Value) -> impl Future<Output = Result<Self>> + Send;
61}
62
63/// A field of an Access, kept in its reference by id and loaded again
64/// when it's rebuilt: any model, by its primary key.
65pub trait AccessField: Sized {
66    fn reference(&self) -> serde_json::Value;
67    fn rebuild(reference: serde_json::Value) -> impl Future<Output = Result<Self>> + Send;
68}
69
70impl<M: crate::model::Model + Send> AccessField for M {
71    fn reference(&self) -> serde_json::Value {
72        match self.id_value() {
73            Value::Int(id) => serde_json::Value::from(id),
74            other => serde_json::Value::from(other.to_text()),
75        }
76    }
77
78    fn rebuild(reference: serde_json::Value) -> impl Future<Output = Result<Self>> + Send {
79        let id = match reference {
80            serde_json::Value::Number(n) => Value::Int(n.as_i64().unwrap_or_default()),
81            other => Value::Text(other.as_str().unwrap_or_default().to_owned()),
82        };
83        M::find(id)
84    }
85}
86
87/// An access being loaded again from its reference.
88type Rebuilding = std::pin::Pin<Box<dyn Future<Output = Result<Arc<dyn Access>>> + Send>>;
89
90type Rebuilder = fn(serde_json::Value) -> Rebuilding;
91
92static KINDS: std::sync::RwLock<std::collections::BTreeMap<&'static str, Rebuilder>> =
93    std::sync::RwLock::new(std::collections::BTreeMap::new());
94
95/// Lets jobs rebuild `A`: what `glacier::app!()` does for each of the
96/// app's Access types.
97pub fn register<A: Rebuild>() {
98    fn rebuild<A: Rebuild>(reference: serde_json::Value) -> Rebuilding {
99        Box::pin(async move { Ok(Arc::new(A::rebuild(reference).await?) as Arc<dyn Access>) })
100    }
101    KINDS
102        .write()
103        .unwrap_or_else(|e| e.into_inner())
104        .insert(A::KIND, rebuild::<A>);
105}
106
107/// The access a reference names, rebuilt by its registered kind.
108pub(crate) async fn rebuild(reference: serde_json::Value) -> Result<Arc<dyn Access>> {
109    let kind = reference["kind"].as_str().unwrap_or_default().to_owned();
110    let rebuild = KINDS
111        .read()
112        .unwrap_or_else(|e| e.into_inner())
113        .get(kind.as_str())
114        .copied()
115        .ok_or_else(|| Error::internal(format!("no Access is registered as `{kind}`")))?;
116    rebuild(reference).await
117}
118
119/// The access a request runs with, as its middleware set it.
120#[derive(Clone)]
121pub struct RequestAccess(pub Arc<dyn Access>);
122
123impl std::ops::Deref for RequestAccess {
124    type Target = dyn Access;
125
126    fn deref(&self) -> &(dyn Access + 'static) {
127        &*self.0
128    }
129}
130
131/// The request's access stands for the access it holds, so it passes
132/// wherever an access goes: `Post::for(&access)`.
133impl Access for RequestAccess {
134    fn describe(&self) -> String {
135        self.0.describe()
136    }
137
138    fn owns(&self, column: &str) -> Option<Value> {
139        self.0.owns(column)
140    }
141
142    fn as_any(&self) -> &dyn Any {
143        self.0.as_any()
144    }
145}
146
147impl AsRef<RequestAccess> for RequestAccess {
148    fn as_ref(&self) -> &RequestAccess {
149        self
150    }
151}
152
153impl RequestAccess {
154    /// The access as the app's type, `OrgAccess.of(access)` in
155    /// `.glacier`: `404 Not Found` when it's another kind (a user with no
156    /// org), as a record from another tenant would be.
157    ///
158    /// # Errors
159    ///
160    /// `404 Not Found` when the access is another type.
161    pub fn of<A: Access + Clone>(&self) -> Result<A> {
162        self.0
163            .as_any()
164            .downcast_ref::<A>()
165            .cloned()
166            .ok_or_else(Error::not_found)
167    }
168}
169
170/// Work done for nobody in particular, with why.
171#[derive(Debug, Clone, Copy)]
172pub struct SystemAccess {
173    pub reason: &'static str,
174}
175
176impl Access for SystemAccess {
177    fn describe(&self) -> String {
178        format!("system ({})", self.reason)
179    }
180
181    fn as_any(&self) -> &dyn Any {
182        self
183    }
184}
185
186tokio::task_local! {
187    static CURRENT: Arc<dyn Access>;
188}
189
190/// The access the current work runs with, if any.
191/// Whether the work in hand may change a shared row (a `global` owned
192/// model's row with no owner): only outside any access, or `unscoped`.
193pub(crate) fn may_change_shared() -> bool {
194    current().is_none_or(|access| access.as_any().is::<SystemAccess>())
195}
196
197pub fn current() -> Option<Arc<dyn Access>> {
198    CURRENT
199        .try_with(Arc::clone)
200        .ok()
201        .or_else(|| crate::current::get::<RequestAccess>().map(|access| access.0))
202}
203
204/// The access the current work runs with, as a request's is: `access`
205/// in a job's `perform`.
206///
207/// # Errors
208///
209/// `401 Unauthorized` when the work runs for no one.
210pub fn required() -> Result<RequestAccess> {
211    current()
212        .map(RequestAccess)
213        .ok_or_else(|| Error::new(http::StatusCode::UNAUTHORIZED, "no access"))
214}
215
216/// Whether reading an owned model without its access is an error (in
217/// tests) rather than a warning.
218static STRICT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
219
220/// Makes reading an owned model without its access an error: what
221/// Glacier's test harness does, so a test that requests every action
222/// finds an action that forgot `Model.for(access)`.
223pub fn strict(on: bool) {
224    STRICT.store(on, std::sync::atomic::Ordering::Relaxed);
225}
226
227/// A query on an owned model (`table`) that didn't go through
228/// `Model.for(access)`: fine for work that runs for no one or for the
229/// system (`unscoped`), an error in tests and a warning otherwise when it
230/// runs for someone.
231pub(crate) fn check_unscoped(table: &str) -> Result<()> {
232    let Some(access) = current() else {
233        return Ok(());
234    };
235    if access.as_any().is::<SystemAccess>() {
236        return Ok(());
237    }
238    let message = format!(
239        "`{table}` read for {} without its access: read it through `Model.for(access)`, \
240         or inside `glacier::access::unscoped(\"why\", …)`",
241        access.describe()
242    );
243    if STRICT.load(std::sync::atomic::Ordering::Relaxed) {
244        return Err(Error::internal(message));
245    }
246    tracing::warn!(target: "glacier::access", "{message}");
247    Ok(())
248}
249
250/// Runs `fut` for `access`.
251pub async fn with_access<F: Future>(access: impl Access, fut: F) -> F::Output {
252    CURRENT.scope(Arc::new(access), fut).await
253}
254
255/// Runs `fut` for an access already shared, as a rebuilt job's is.
256pub(crate) async fn with_shared<F: Future>(access: Arc<dyn Access>, fut: F) -> F::Output {
257    CURRENT.scope(access, fut).await
258}
259
260/// Runs `fut` for the system, saying why: what webhooks, pruning and
261/// recurring jobs run as. In 0.4 it's the explicit way past the limits a
262/// user's access puts on queries.
263pub async fn unscoped<F: Future>(reason: &'static str, fut: F) -> F::Output {
264    with_access(SystemAccess { reason }, fut).await
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270
271    #[tokio::test]
272    async fn work_knows_who_it_is_for() {
273        assert!(current().is_none());
274        let seen = unscoped("pruning", async { current().map(|a| a.describe()) }).await;
275        assert_eq!(seen.as_deref(), Some("system (pruning)"));
276    }
277}