Skip to main content

fusion_stack/
auth.rs

1//! API clients and scopes, as the PHP package's `ResolveClient` and `AuthorizeScopes` middleware
2//! and `ApiKey` model provide them.
3//!
4//! Each request to an API route is resolved to an [`ApiClient`], or to a guest. With the
5//! `database` feature, `Authorization: Bearer fs_live_…` and `fs_test_…` keys from the `api_keys`
6//! table are resolved by the crate itself; [`Config::client_resolver`](crate::Config::client_resolver)
7//! adds your own authentication, which runs first. A client's pinned version is used when a request
8//! has no `Api-Version` header. Routes ask for scopes with [`RequiresScope`].
9
10use std::pin::Pin;
11use std::sync::Arc;
12
13use laravel::axum::http::HeaderMap;
14use laravel::http::{Middleware, Next, Request, Response};
15
16use crate::Context;
17use crate::errors::{ApiError, ApiErrorCode};
18
19/// Who made a request.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct ApiClient {
22    /// Stable and unique across ways of authenticating, such as `api_key:42`.
23    pub id: String,
24    /// Granted scopes. `*` grants every scope, and `orders:*` every `orders:` scope.
25    pub scopes: Vec<String>,
26    /// The pinned API version, used when a request has no `Api-Version` header.
27    pub version: Option<String>,
28    /// The rate limit tier, or `None` for the default tier.
29    pub rate_limit_tier: Option<String>,
30    /// Who idempotency keys belong to. Defaults to the client ID.
31    pub idempotency_scope: String,
32}
33
34impl ApiClient {
35    /// A client with no scopes, pin or tier.
36    #[must_use]
37    pub fn new(id: impl Into<String>) -> Self {
38        let id = id.into();
39        Self {
40            idempotency_scope: id.clone(),
41            id,
42            scopes: Vec::new(),
43            version: None,
44            rate_limit_tier: None,
45        }
46    }
47
48    /// Grants scopes.
49    #[must_use]
50    pub fn scopes<I: IntoIterator<Item = S>, S: Into<String>>(mut self, scopes: I) -> Self {
51        self.scopes = scopes.into_iter().map(Into::into).collect();
52        self
53    }
54
55    /// Pins the client to a version.
56    #[must_use]
57    pub fn version(mut self, version: Option<impl Into<String>>) -> Self {
58        self.version = version.map(Into::into);
59        self
60    }
61
62    /// Puts the client in a rate limit tier.
63    #[must_use]
64    pub fn rate_limit_tier(mut self, tier: Option<impl Into<String>>) -> Self {
65        self.rate_limit_tier = tier.map(Into::into);
66        self
67    }
68
69    /// Shares idempotency keys with other clients, such as every key of one account.
70    #[must_use]
71    pub fn idempotency_scope(mut self, scope: impl Into<String>) -> Self {
72        self.idempotency_scope = scope.into();
73        self
74    }
75
76    /// Whether the client was granted `scope`.
77    #[must_use]
78    pub fn has_scope(&self, scope: &str) -> bool {
79        self.scopes.iter().any(|granted| {
80            granted == "*"
81                || granted == scope
82                || granted
83                    .strip_suffix('*')
84                    .is_some_and(|prefix| prefix.ends_with(':') && scope.starts_with(prefix))
85        })
86    }
87}
88
89/// The client a request was authenticated as, or `None` for a guest.
90#[must_use]
91pub fn client(request: &Request) -> Option<ApiClient> {
92    request
93        .extension::<Context>()
94        .and_then(|context| context.client.clone())
95}
96
97/// Your own authentication: given the request's headers, the client they authenticate, or `None`
98/// to try the next way (the crate's API keys) and then treat the request as a guest's.
99pub type ClientResolver = Arc<
100    dyn Fn(HeaderMap) -> Pin<Box<dyn Future<Output = laravel::Result<Option<ApiClient>>> + Send>>
101        + Send
102        + Sync,
103>;
104
105/// Wraps an async function as a [`ClientResolver`].
106pub fn resolver<F, Fut>(resolve: F) -> ClientResolver
107where
108    F: Fn(HeaderMap) -> Fut + Send + Sync + 'static,
109    Fut: Future<Output = laravel::Result<Option<ApiClient>>> + Send + 'static,
110{
111    Arc::new(move |headers| Box::pin(resolve(headers)))
112}
113
114/// Resolves the request's client: the application's resolver, then the crate's API keys.
115pub(crate) async fn resolve(
116    resolver: Option<&ClientResolver>,
117    request: &Request,
118) -> laravel::Result<Option<ApiClient>> {
119    if let Some(resolver) = resolver
120        && let Some(client) = resolver(request.headers().clone()).await?
121    {
122        return Ok(Some(client));
123    }
124    #[cfg(feature = "database")]
125    if let Some(token) = request.bearer_token()
126        && let Some(key) = api_keys::find_by_token(token).await?
127    {
128        api_keys::touch_last_used(key.id).await?;
129        return Ok(Some(key.into_client()));
130    }
131    #[cfg(not(feature = "database"))]
132    let _ = request;
133    Ok(None)
134}
135
136/// The hidden context value that marks a request [`RequiresScope`] turned away, so its response
137/// is not kept for idempotent replays: PHP checks scopes before it looks at the key.
138pub(crate) const DENIED: &str = "fusion_stack.scope_denied";
139
140/// Route middleware that requires the client to have a scope, as `#[RequiresScope]` does in PHP.
141/// Guests get a 401 `unauthenticated`, and clients without the scope a 403 `insufficient_scope`.
142///
143/// ```no_run
144/// # use laravel::prelude::*;
145/// # async fn cancel() -> &'static str { "{}" }
146/// # fn routes(route: &mut laravel::routing::Router) {
147/// route
148///     .post("/orders/{order}/cancel", cancel)
149///     .middleware(fusion_stack::RequiresScope::new("orders:write"));
150/// # }
151/// ```
152#[derive(Clone)]
153pub struct RequiresScope {
154    pub(crate) scope: String,
155    pub(crate) description: String,
156}
157
158impl RequiresScope {
159    /// Requires `scope`, such as `orders:write`.
160    #[must_use]
161    pub fn new(scope: impl Into<String>) -> Self {
162        Self {
163            scope: scope.into(),
164            description: String::new(),
165        }
166    }
167
168    /// What the scope allows, for the docs.
169    #[must_use]
170    pub fn describe(mut self, description: impl Into<String>) -> Self {
171        self.description = description.into();
172        self
173    }
174}
175
176impl Middleware for RequiresScope {
177    async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
178        let error = match client(&request) {
179            None => ApiError::new(
180                ApiErrorCode::Unauthenticated,
181                "Authenticate to use this endpoint.",
182            ),
183            Some(client) if !client.has_scope(&self.scope) => ApiError::new(
184                ApiErrorCode::InsufficientScope,
185                format!("This request needs the [{}] scope.", self.scope),
186            )
187            .meta("required_scope", &self.scope),
188            Some(_) => return Ok(next.run(request).await),
189        };
190        laravel::context::add_hidden(DENIED, true);
191        Err(error.into_error())
192    }
193}
194
195/// API keys in the `api_keys` table, as the PHP package's `ApiKey` model keeps them: only a
196/// SHA-256 hash of each key is stored, with its prefix and last four characters to recognise it.
197#[cfg(feature = "database")]
198pub mod api_keys {
199    use laravel::db::{self, col, values};
200    use sha2::{Digest, Sha256};
201
202    use super::ApiClient;
203
204    /// The prefix of live keys.
205    pub const LIVE_PREFIX: &str = "fs_live_";
206    /// The prefix of test keys.
207    pub const TEST_PREFIX: &str = "fs_test_";
208
209    /// A key from the table.
210    #[derive(Debug, Clone, db::FromRow)]
211    pub struct ApiKey {
212        pub id: i64,
213        pub name: String,
214        pub prefix: String,
215        pub hint: String,
216        pub scopes: Option<String>,
217        pub version: Option<String>,
218        pub rate_limit_tier: Option<String>,
219    }
220
221    impl ApiKey {
222        /// The key's granted scopes.
223        #[must_use]
224        pub fn scopes(&self) -> Vec<String> {
225            self.scopes
226                .as_deref()
227                .and_then(|scopes| serde_json::from_str(scopes).ok())
228                .unwrap_or_default()
229        }
230
231        /// The client the key authenticates.
232        #[must_use]
233        pub fn into_client(self) -> ApiClient {
234            let scopes = self.scopes();
235            ApiClient::new(format!("api_key:{}", self.id))
236                .scopes(scopes)
237                .version(self.version)
238                .rate_limit_tier(self.rate_limit_tier)
239        }
240    }
241
242    /// The SHA-256 hash the table keeps of a key.
243    #[must_use]
244    pub fn hash(plain: &str) -> String {
245        Sha256::digest(plain.as_bytes())
246            .iter()
247            .map(|byte| format!("{byte:02x}"))
248            .collect()
249    }
250
251    /// What a new key is for: its name and scopes, its pin, and whether it is a test key.
252    #[derive(Debug, Clone, Default)]
253    pub struct Issue {
254        pub name: String,
255        pub scopes: Vec<String>,
256        /// The version to pin to. Pin new keys to the latest version, so later breaking changes
257        /// never reach them until they are upgraded, as PHP's `ApiKey::issue` does.
258        pub version: Option<String>,
259        pub rate_limit_tier: Option<String>,
260        pub test: bool,
261    }
262
263    /// Creates a key and returns its ID and plain-text value, which is not stored.
264    ///
265    /// # Errors
266    ///
267    /// When the key can't be written.
268    pub async fn issue(issue: Issue) -> laravel::Result<(i64, String)> {
269        let prefix = if issue.test { TEST_PREFIX } else { LIVE_PREFIX };
270        let plain = format!("{prefix}{}", laravel::str::random(40));
271        let id = insert(&plain, issue).await?;
272        Ok((id, plain))
273    }
274
275    /// Stores a key with a value you chose, such as fixed keys in a seeder.
276    ///
277    /// # Errors
278    ///
279    /// When the key can't be written, such as when the value is taken.
280    pub async fn insert(plain: &str, issue: Issue) -> laravel::Result<i64> {
281        let prefix = if plain.starts_with(TEST_PREFIX) {
282            TEST_PREFIX
283        } else {
284            LIVE_PREFIX
285        };
286        let hint: String = plain
287            .chars()
288            .rev()
289            .take(4)
290            .collect::<Vec<_>>()
291            .into_iter()
292            .rev()
293            .collect();
294        let now = laravel::now().timestamp();
295        db::table("api_keys")
296            .insert_get_id(
297                values! {
298                    name: issue.name,
299                    prefix: prefix,
300                    hint: hint,
301                    token_hash: hash(plain),
302                    scopes: serde_json::to_string(&issue.scopes).unwrap_or_default(),
303                    version: issue.version,
304                    rate_limit_tier: issue.rate_limit_tier,
305                    created_at: now,
306                    updated_at: now,
307                },
308                "id",
309            )
310            .await
311    }
312
313    /// The unrevoked key with this plain-text value. Values without a key prefix are not looked
314    /// up, so other bearer tokens cost no query.
315    ///
316    /// # Errors
317    ///
318    /// When the table can't be read.
319    pub async fn find_by_token(token: &str) -> laravel::Result<Option<ApiKey>> {
320        if !token.starts_with(LIVE_PREFIX) && !token.starts_with(TEST_PREFIX) {
321            return Ok(None);
322        }
323        db::table("api_keys")
324            .select([
325                "id",
326                "name",
327                "prefix",
328                "hint",
329                "scopes",
330                "version",
331                "rate_limit_tier",
332            ])
333            .filter(col("token_hash").eq(hash(token)))
334            .filter(col("revoked_at").is_null())
335            .first()
336            .await
337    }
338
339    /// Records a use, at most once a minute so busy keys do not write on every request.
340    pub(crate) async fn touch_last_used(id: i64) -> laravel::Result<()> {
341        use laravel::prelude::ToSpan;
342        let now = laravel::now();
343        let cutoff = now.timestamp() - 1.minute();
344        db::table("api_keys")
345            .filter(col("id").eq(id))
346            .filter(db::any([
347                col("last_used_at").is_null(),
348                col("last_used_at").lt(cutoff),
349            ]))
350            .update(values! { last_used_at: now.timestamp() })
351            .await?;
352        Ok(())
353    }
354
355    /// Revokes a key, so it no longer authenticates.
356    ///
357    /// # Errors
358    ///
359    /// When the key can't be written.
360    pub async fn revoke(id: i64) -> laravel::Result<()> {
361        db::table("api_keys")
362            .filter(col("id").eq(id))
363            .update(values! { revoked_at: laravel::now().timestamp() })
364            .await?;
365        Ok(())
366    }
367
368    /// Pins a key to a version, such as when its owner upgrades. `None` follows the default.
369    ///
370    /// # Errors
371    ///
372    /// When the key can't be written.
373    pub async fn pin_to(id: i64, version: Option<&str>) -> laravel::Result<()> {
374        db::table("api_keys")
375            .filter(col("id").eq(id))
376            .update(values! { version: version.map(str::to_owned) })
377            .await?;
378        Ok(())
379    }
380}
381
382#[cfg(test)]
383mod tests {
384    use super::ApiClient;
385
386    #[test]
387    fn scopes_match_exactly_or_by_wildcard() {
388        let client = ApiClient::new("a").scopes(["orders:*", "customers:read"]);
389        assert!(client.has_scope("orders:write"));
390        assert!(client.has_scope("customers:read"));
391        assert!(!client.has_scope("customers:write"));
392        // `orders:*` covers `orders:` scopes, not scopes that only start with `orders`.
393        assert!(!client.has_scope("ordersx:read"));
394        assert!(ApiClient::new("b").scopes(["*"]).has_scope("anything"));
395        assert!(!ApiClient::new("c").has_scope("orders:read"));
396    }
397}