fusion-stack-laravel-rust 0.2.1

Fusion Stack for Laravel for Rust: versioned, documented JSON APIs with standard errors
Documentation
//! API clients and scopes, as the PHP package's `ResolveClient` and `AuthorizeScopes` middleware
//! and `ApiKey` model provide them.
//!
//! Each request to an API route is resolved to an [`ApiClient`], or to a guest. With the
//! `database` feature, `Authorization: Bearer fs_live_…` and `fs_test_…` keys from the `api_keys`
//! table are resolved by the crate itself; [`Config::client_resolver`](crate::Config::client_resolver)
//! adds your own authentication, which runs first. A client's pinned version is used when a request
//! has no `Api-Version` header. Routes ask for scopes with [`RequiresScope`].

use std::pin::Pin;
use std::sync::Arc;

use laravel::axum::http::HeaderMap;
use laravel::http::{Middleware, Next, Request, Response};

use crate::Context;
use crate::errors::{ApiError, ApiErrorCode};

/// Who made a request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApiClient {
    /// Stable and unique across ways of authenticating, such as `api_key:42`.
    pub id: String,
    /// Granted scopes. `*` grants every scope, and `orders:*` every `orders:` scope.
    pub scopes: Vec<String>,
    /// The pinned API version, used when a request has no `Api-Version` header.
    pub version: Option<String>,
    /// The rate limit tier, or `None` for the default tier.
    pub rate_limit_tier: Option<String>,
    /// Who idempotency keys belong to. Defaults to the client ID.
    pub idempotency_scope: String,
}

impl ApiClient {
    /// A client with no scopes, pin or tier.
    #[must_use]
    pub fn new(id: impl Into<String>) -> Self {
        let id = id.into();
        Self {
            idempotency_scope: id.clone(),
            id,
            scopes: Vec::new(),
            version: None,
            rate_limit_tier: None,
        }
    }

    /// Grants scopes.
    #[must_use]
    pub fn scopes<I: IntoIterator<Item = S>, S: Into<String>>(mut self, scopes: I) -> Self {
        self.scopes = scopes.into_iter().map(Into::into).collect();
        self
    }

    /// Pins the client to a version.
    #[must_use]
    pub fn version(mut self, version: Option<impl Into<String>>) -> Self {
        self.version = version.map(Into::into);
        self
    }

    /// Puts the client in a rate limit tier.
    #[must_use]
    pub fn rate_limit_tier(mut self, tier: Option<impl Into<String>>) -> Self {
        self.rate_limit_tier = tier.map(Into::into);
        self
    }

    /// Shares idempotency keys with other clients, such as every key of one account.
    #[must_use]
    pub fn idempotency_scope(mut self, scope: impl Into<String>) -> Self {
        self.idempotency_scope = scope.into();
        self
    }

    /// Whether the client was granted `scope`.
    #[must_use]
    pub fn has_scope(&self, scope: &str) -> bool {
        self.scopes.iter().any(|granted| {
            granted == "*"
                || granted == scope
                || granted
                    .strip_suffix('*')
                    .is_some_and(|prefix| prefix.ends_with(':') && scope.starts_with(prefix))
        })
    }
}

/// The client a request was authenticated as, or `None` for a guest.
#[must_use]
pub fn client(request: &Request) -> Option<ApiClient> {
    request
        .extension::<Context>()
        .and_then(|context| context.client.clone())
}

/// Your own authentication: given the request's headers, the client they authenticate, or `None`
/// to try the next way (the crate's API keys) and then treat the request as a guest's.
pub type ClientResolver = Arc<
    dyn Fn(HeaderMap) -> Pin<Box<dyn Future<Output = laravel::Result<Option<ApiClient>>> + Send>>
        + Send
        + Sync,
>;

/// Wraps an async function as a [`ClientResolver`].
pub fn resolver<F, Fut>(resolve: F) -> ClientResolver
where
    F: Fn(HeaderMap) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = laravel::Result<Option<ApiClient>>> + Send + 'static,
{
    Arc::new(move |headers| Box::pin(resolve(headers)))
}

/// Resolves the request's client: the application's resolver, then the crate's API keys.
pub(crate) async fn resolve(
    resolver: Option<&ClientResolver>,
    request: &Request,
) -> laravel::Result<Option<ApiClient>> {
    if let Some(resolver) = resolver
        && let Some(client) = resolver(request.headers().clone()).await?
    {
        return Ok(Some(client));
    }
    #[cfg(feature = "database")]
    if let Some(token) = request.bearer_token()
        && let Some(key) = api_keys::find_by_token(token).await?
    {
        api_keys::touch_last_used(key.id).await?;
        return Ok(Some(key.into_client()));
    }
    #[cfg(not(feature = "database"))]
    let _ = request;
    Ok(None)
}

/// The hidden context value that marks a request [`RequiresScope`] turned away, so its response
/// is not kept for idempotent replays: PHP checks scopes before it looks at the key.
pub(crate) const DENIED: &str = "fusion_stack.scope_denied";

/// Route middleware that requires the client to have a scope, as `#[RequiresScope]` does in PHP.
/// Guests get a 401 `unauthenticated`, and clients without the scope a 403 `insufficient_scope`.
///
/// ```no_run
/// # use laravel::prelude::*;
/// # async fn cancel() -> &'static str { "{}" }
/// # fn routes(route: &mut laravel::routing::Router) {
/// route
///     .post("/orders/{order}/cancel", cancel)
///     .middleware(fusion_stack::RequiresScope::new("orders:write"));
/// # }
/// ```
#[derive(Clone)]
pub struct RequiresScope {
    pub(crate) scope: String,
    pub(crate) description: String,
}

impl RequiresScope {
    /// Requires `scope`, such as `orders:write`.
    #[must_use]
    pub fn new(scope: impl Into<String>) -> Self {
        Self {
            scope: scope.into(),
            description: String::new(),
        }
    }

    /// What the scope allows, for the docs.
    #[must_use]
    pub fn describe(mut self, description: impl Into<String>) -> Self {
        self.description = description.into();
        self
    }
}

impl Middleware for RequiresScope {
    async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
        let error = match client(&request) {
            None => ApiError::new(
                ApiErrorCode::Unauthenticated,
                "Authenticate to use this endpoint.",
            ),
            Some(client) if !client.has_scope(&self.scope) => ApiError::new(
                ApiErrorCode::InsufficientScope,
                format!("This request needs the [{}] scope.", self.scope),
            )
            .meta("required_scope", &self.scope),
            Some(_) => return Ok(next.run(request).await),
        };
        laravel::context::add_hidden(DENIED, true);
        Err(error.into_error())
    }
}

/// API keys in the `api_keys` table, as the PHP package's `ApiKey` model keeps them: only a
/// SHA-256 hash of each key is stored, with its prefix and last four characters to recognise it.
#[cfg(feature = "database")]
pub mod api_keys {
    use laravel::db::{self, col, values};
    use sha2::{Digest, Sha256};

    use super::ApiClient;

    /// The prefix of live keys.
    pub const LIVE_PREFIX: &str = "fs_live_";
    /// The prefix of test keys.
    pub const TEST_PREFIX: &str = "fs_test_";

    /// A key from the table.
    #[derive(Debug, Clone, db::FromRow)]
    pub struct ApiKey {
        pub id: i64,
        pub name: String,
        pub prefix: String,
        pub hint: String,
        pub scopes: Option<String>,
        pub version: Option<String>,
        pub rate_limit_tier: Option<String>,
    }

    impl ApiKey {
        /// The key's granted scopes.
        #[must_use]
        pub fn scopes(&self) -> Vec<String> {
            self.scopes
                .as_deref()
                .and_then(|scopes| serde_json::from_str(scopes).ok())
                .unwrap_or_default()
        }

        /// The client the key authenticates.
        #[must_use]
        pub fn into_client(self) -> ApiClient {
            let scopes = self.scopes();
            ApiClient::new(format!("api_key:{}", self.id))
                .scopes(scopes)
                .version(self.version)
                .rate_limit_tier(self.rate_limit_tier)
        }
    }

    /// The SHA-256 hash the table keeps of a key.
    #[must_use]
    pub fn hash(plain: &str) -> String {
        Sha256::digest(plain.as_bytes())
            .iter()
            .map(|byte| format!("{byte:02x}"))
            .collect()
    }

    /// What a new key is for: its name and scopes, its pin, and whether it is a test key.
    #[derive(Debug, Clone, Default)]
    pub struct Issue {
        pub name: String,
        pub scopes: Vec<String>,
        /// The version to pin to. Pin new keys to the latest version, so later breaking changes
        /// never reach them until they are upgraded, as PHP's `ApiKey::issue` does.
        pub version: Option<String>,
        pub rate_limit_tier: Option<String>,
        pub test: bool,
    }

    /// Creates a key and returns its ID and plain-text value, which is not stored.
    ///
    /// # Errors
    ///
    /// When the key can't be written.
    pub async fn issue(issue: Issue) -> laravel::Result<(i64, String)> {
        let prefix = if issue.test { TEST_PREFIX } else { LIVE_PREFIX };
        let plain = format!("{prefix}{}", laravel::str::random(40));
        let id = insert(&plain, issue).await?;
        Ok((id, plain))
    }

    /// Stores a key with a value you chose, such as fixed keys in a seeder.
    ///
    /// # Errors
    ///
    /// When the key can't be written, such as when the value is taken.
    pub async fn insert(plain: &str, issue: Issue) -> laravel::Result<i64> {
        let prefix = if plain.starts_with(TEST_PREFIX) {
            TEST_PREFIX
        } else {
            LIVE_PREFIX
        };
        let hint: String = plain
            .chars()
            .rev()
            .take(4)
            .collect::<Vec<_>>()
            .into_iter()
            .rev()
            .collect();
        let now = laravel::now().timestamp();
        db::table("api_keys")
            .insert_get_id(
                values! {
                    name: issue.name,
                    prefix: prefix,
                    hint: hint,
                    token_hash: hash(plain),
                    scopes: serde_json::to_string(&issue.scopes).unwrap_or_default(),
                    version: issue.version,
                    rate_limit_tier: issue.rate_limit_tier,
                    created_at: now,
                    updated_at: now,
                },
                "id",
            )
            .await
    }

    /// The unrevoked key with this plain-text value. Values without a key prefix are not looked
    /// up, so other bearer tokens cost no query.
    ///
    /// # Errors
    ///
    /// When the table can't be read.
    pub async fn find_by_token(token: &str) -> laravel::Result<Option<ApiKey>> {
        if !token.starts_with(LIVE_PREFIX) && !token.starts_with(TEST_PREFIX) {
            return Ok(None);
        }
        db::table("api_keys")
            .select([
                "id",
                "name",
                "prefix",
                "hint",
                "scopes",
                "version",
                "rate_limit_tier",
            ])
            .filter(col("token_hash").eq(hash(token)))
            .filter(col("revoked_at").is_null())
            .first()
            .await
    }

    /// Records a use, at most once a minute so busy keys do not write on every request.
    pub(crate) async fn touch_last_used(id: i64) -> laravel::Result<()> {
        use laravel::prelude::ToSpan;
        let now = laravel::now();
        let cutoff = now.timestamp() - 1.minute();
        db::table("api_keys")
            .filter(col("id").eq(id))
            .filter(db::any([
                col("last_used_at").is_null(),
                col("last_used_at").lt(cutoff),
            ]))
            .update(values! { last_used_at: now.timestamp() })
            .await?;
        Ok(())
    }

    /// Revokes a key, so it no longer authenticates.
    ///
    /// # Errors
    ///
    /// When the key can't be written.
    pub async fn revoke(id: i64) -> laravel::Result<()> {
        db::table("api_keys")
            .filter(col("id").eq(id))
            .update(values! { revoked_at: laravel::now().timestamp() })
            .await?;
        Ok(())
    }

    /// Pins a key to a version, such as when its owner upgrades. `None` follows the default.
    ///
    /// # Errors
    ///
    /// When the key can't be written.
    pub async fn pin_to(id: i64, version: Option<&str>) -> laravel::Result<()> {
        db::table("api_keys")
            .filter(col("id").eq(id))
            .update(values! { version: version.map(str::to_owned) })
            .await?;
        Ok(())
    }
}

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

    #[test]
    fn scopes_match_exactly_or_by_wildcard() {
        let client = ApiClient::new("a").scopes(["orders:*", "customers:read"]);
        assert!(client.has_scope("orders:write"));
        assert!(client.has_scope("customers:read"));
        assert!(!client.has_scope("customers:write"));
        // `orders:*` covers `orders:` scopes, not scopes that only start with `orders`.
        assert!(!client.has_scope("ordersx:read"));
        assert!(ApiClient::new("b").scopes(["*"]).has_scope("anything"));
        assert!(!ApiClient::new("c").has_scope("orders:read"));
    }
}