glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Who a piece of work acts for: a signed-in user, an organisation, or
//! the system itself. Glacier's name for what Phoenix calls a scope.
//!
//! This is the seam 0.4's accounts build on: requests will set the access
//! from the signed-in user, and queries will be limited to what it may
//! see. For now it records who work is done for, and work that runs for
//! nobody in particular (webhooks, pruning, recurring jobs) says so
//! explicitly, with a reason:
//!
//! ```ignore
//! glacier::access::unscoped("nightly digest", async {
//!     // …
//! })
//! .await
//! ```

use std::any::Any;
use std::future::Future;
use std::sync::Arc;

use crate::db::Value;
use crate::error::{Error, Result};

/// Who work is done for. An app declares its own, `module OrgAccess do
/// implements Access … end` in `.glacier`, and a request's comes from its
/// middleware (`ctx.set_access(…)`).
pub trait Access: Send + Sync + 'static {
    /// For logs and traces: `user:12`, `org:3`, `system (webhooks)`.
    fn describe(&self) -> String;

    /// The value a model's owner column takes for this access (`org_id`
    /// is the org's id), or `None` when it owns no such rows. What
    /// `Post::for(access)` limits a query to, and what a record built from
    /// it gets.
    fn owns(&self, column: &str) -> Option<Value> {
        let _ = column;
        None
    }

    /// The access itself, so a caller can ask for its own type.
    fn as_any(&self) -> &dyn Any;

    /// What a job queued for this access keeps of it, to rebuild it when
    /// it runs (`{"kind": "OrgAccess", "org": 42, …}`): ids, not records.
    /// `None` (the default) for an access that isn't carried into jobs.
    fn reference(&self) -> Option<serde_json::Value> {
        None
    }
}

/// An access a job can rebuild from its [`reference`](Access::reference),
/// loading its records again: a member removed from an org since the job
/// was queued no longer has that access, so the job fails rather than
/// acting for them. `module X do implements Access` generates it.
pub trait Rebuild: Access + Sized {
    /// The `kind` its references carry.
    const KIND: &'static str;

    /// The access a reference names, loaded and checked again.
    fn rebuild(reference: serde_json::Value) -> impl Future<Output = Result<Self>> + Send;
}

/// A field of an Access, kept in its reference by id and loaded again
/// when it's rebuilt: any model, by its primary key.
pub trait AccessField: Sized {
    fn reference(&self) -> serde_json::Value;
    fn rebuild(reference: serde_json::Value) -> impl Future<Output = Result<Self>> + Send;
}

impl<M: crate::model::Model + Send> AccessField for M {
    fn reference(&self) -> serde_json::Value {
        match self.id_value() {
            Value::Int(id) => serde_json::Value::from(id),
            other => serde_json::Value::from(other.to_text()),
        }
    }

    fn rebuild(reference: serde_json::Value) -> impl Future<Output = Result<Self>> + Send {
        let id = match reference {
            serde_json::Value::Number(n) => Value::Int(n.as_i64().unwrap_or_default()),
            other => Value::Text(other.as_str().unwrap_or_default().to_owned()),
        };
        M::find(id)
    }
}

/// An access being loaded again from its reference.
type Rebuilding = std::pin::Pin<Box<dyn Future<Output = Result<Arc<dyn Access>>> + Send>>;

type Rebuilder = fn(serde_json::Value) -> Rebuilding;

static KINDS: std::sync::RwLock<std::collections::BTreeMap<&'static str, Rebuilder>> =
    std::sync::RwLock::new(std::collections::BTreeMap::new());

/// Lets jobs rebuild `A`: what `glacier::app!()` does for each of the
/// app's Access types.
pub fn register<A: Rebuild>() {
    fn rebuild<A: Rebuild>(reference: serde_json::Value) -> Rebuilding {
        Box::pin(async move { Ok(Arc::new(A::rebuild(reference).await?) as Arc<dyn Access>) })
    }
    KINDS
        .write()
        .unwrap_or_else(|e| e.into_inner())
        .insert(A::KIND, rebuild::<A>);
}

/// The access a reference names, rebuilt by its registered kind.
pub(crate) async fn rebuild(reference: serde_json::Value) -> Result<Arc<dyn Access>> {
    let kind = reference["kind"].as_str().unwrap_or_default().to_owned();
    let rebuild = KINDS
        .read()
        .unwrap_or_else(|e| e.into_inner())
        .get(kind.as_str())
        .copied()
        .ok_or_else(|| Error::internal(format!("no Access is registered as `{kind}`")))?;
    rebuild(reference).await
}

/// The access a request runs with, as its middleware set it.
#[derive(Clone)]
pub struct RequestAccess(pub Arc<dyn Access>);

impl std::ops::Deref for RequestAccess {
    type Target = dyn Access;

    fn deref(&self) -> &(dyn Access + 'static) {
        &*self.0
    }
}

/// The request's access stands for the access it holds, so it passes
/// wherever an access goes: `Post::for(&access)`.
impl Access for RequestAccess {
    fn describe(&self) -> String {
        self.0.describe()
    }

    fn owns(&self, column: &str) -> Option<Value> {
        self.0.owns(column)
    }

    fn as_any(&self) -> &dyn Any {
        self.0.as_any()
    }
}

impl AsRef<RequestAccess> for RequestAccess {
    fn as_ref(&self) -> &RequestAccess {
        self
    }
}

impl RequestAccess {
    /// The access as the app's type, `OrgAccess.of(access)` in
    /// `.glacier`: `404 Not Found` when it's another kind (a user with no
    /// org), as a record from another tenant would be.
    ///
    /// # Errors
    ///
    /// `404 Not Found` when the access is another type.
    pub fn of<A: Access + Clone>(&self) -> Result<A> {
        self.0
            .as_any()
            .downcast_ref::<A>()
            .cloned()
            .ok_or_else(Error::not_found)
    }
}

/// Work done for nobody in particular, with why.
#[derive(Debug, Clone, Copy)]
pub struct SystemAccess {
    pub reason: &'static str,
}

impl Access for SystemAccess {
    fn describe(&self) -> String {
        format!("system ({})", self.reason)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

tokio::task_local! {
    static CURRENT: Arc<dyn Access>;
}

/// The access the current work runs with, if any.
/// Whether the work in hand may change a shared row (a `global` owned
/// model's row with no owner): only outside any access, or `unscoped`.
pub(crate) fn may_change_shared() -> bool {
    current().is_none_or(|access| access.as_any().is::<SystemAccess>())
}

pub fn current() -> Option<Arc<dyn Access>> {
    CURRENT
        .try_with(Arc::clone)
        .ok()
        .or_else(|| crate::current::get::<RequestAccess>().map(|access| access.0))
}

/// The access the current work runs with, as a request's is: `access`
/// in a job's `perform`.
///
/// # Errors
///
/// `401 Unauthorized` when the work runs for no one.
pub fn required() -> Result<RequestAccess> {
    current()
        .map(RequestAccess)
        .ok_or_else(|| Error::new(http::StatusCode::UNAUTHORIZED, "no access"))
}

/// Whether reading an owned model without its access is an error (in
/// tests) rather than a warning.
static STRICT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Makes reading an owned model without its access an error: what
/// Glacier's test harness does, so a test that requests every action
/// finds an action that forgot `Model.for(access)`.
pub fn strict(on: bool) {
    STRICT.store(on, std::sync::atomic::Ordering::Relaxed);
}

/// A query on an owned model (`table`) that didn't go through
/// `Model.for(access)`: fine for work that runs for no one or for the
/// system (`unscoped`), an error in tests and a warning otherwise when it
/// runs for someone.
pub(crate) fn check_unscoped(table: &str) -> Result<()> {
    let Some(access) = current() else {
        return Ok(());
    };
    if access.as_any().is::<SystemAccess>() {
        return Ok(());
    }
    let message = format!(
        "`{table}` read for {} without its access: read it through `Model.for(access)`, \
         or inside `glacier::access::unscoped(\"why\", …)`",
        access.describe()
    );
    if STRICT.load(std::sync::atomic::Ordering::Relaxed) {
        return Err(Error::internal(message));
    }
    tracing::warn!(target: "glacier::access", "{message}");
    Ok(())
}

/// Runs `fut` for `access`.
pub async fn with_access<F: Future>(access: impl Access, fut: F) -> F::Output {
    CURRENT.scope(Arc::new(access), fut).await
}

/// Runs `fut` for an access already shared, as a rebuilt job's is.
pub(crate) async fn with_shared<F: Future>(access: Arc<dyn Access>, fut: F) -> F::Output {
    CURRENT.scope(access, fut).await
}

/// Runs `fut` for the system, saying why: what webhooks, pruning and
/// recurring jobs run as. In 0.4 it's the explicit way past the limits a
/// user's access puts on queries.
pub async fn unscoped<F: Future>(reason: &'static str, fut: F) -> F::Output {
    with_access(SystemAccess { reason }, fut).await
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn work_knows_who_it_is_for() {
        assert!(current().is_none());
        let seen = unscoped("pruning", async { current().map(|a| a.describe()) }).await;
        assert_eq!(seen.as_deref(), Some("system (pruning)"));
    }
}