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    config: &crate::Config,
117    request: &Request,
118) -> laravel::Result<Option<ApiClient>> {
119    if let Some(resolver) = config.client_resolver.as_ref()
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        && !api_keys::turned_away(
127            token,
128            laravel::config().app.env.is_production(),
129            config.test_keys_in_production,
130        )
131        && let Some(key) = api_keys::find_by_token(token).await?
132    {
133        api_keys::touch_last_used(key.id).await?;
134        return Ok(Some(key.into_client()));
135    }
136    #[cfg(not(feature = "database"))]
137    let _ = request;
138    Ok(None)
139}
140
141/// The hidden context value that marks a request [`RequiresScope`] turned away, so its response
142/// is not kept for idempotent replays: PHP checks scopes before it looks at the key.
143pub(crate) const DENIED: &str = "fusion_stack.scope_denied";
144
145/// Route middleware that requires the client to have a scope, as `#[RequiresScope]` does in PHP.
146/// Guests get a 401 `unauthenticated`, and clients without the scope a 403 `insufficient_scope`.
147///
148/// ```no_run
149/// # use laravel::prelude::*;
150/// # async fn cancel() -> &'static str { "{}" }
151/// # fn routes(route: &mut laravel::routing::Router) {
152/// route
153///     .post("/orders/{order}/cancel", cancel)
154///     .middleware(fusion_stack::RequiresScope::new("orders:write"));
155/// # }
156/// ```
157#[derive(Clone)]
158pub struct RequiresScope {
159    pub(crate) scope: String,
160    pub(crate) description: String,
161}
162
163impl RequiresScope {
164    /// Requires `scope`, such as `orders:write`.
165    #[must_use]
166    pub fn new(scope: impl Into<String>) -> Self {
167        Self {
168            scope: scope.into(),
169            description: String::new(),
170        }
171    }
172
173    /// What the scope allows, for the docs.
174    #[must_use]
175    pub fn describe(mut self, description: impl Into<String>) -> Self {
176        self.description = description.into();
177        self
178    }
179}
180
181impl Middleware for RequiresScope {
182    async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
183        let error = match client(&request) {
184            None => ApiError::new(
185                ApiErrorCode::Unauthenticated,
186                "Authenticate to use this endpoint.",
187            ),
188            Some(client) if !client.has_scope(&self.scope) => ApiError::new(
189                ApiErrorCode::InsufficientScope,
190                format!("This request needs the [{}] scope.", self.scope),
191            )
192            .meta("required_scope", &self.scope),
193            Some(_) => return Ok(next.run(request).await),
194        };
195        laravel::context::add_hidden(DENIED, true);
196        Err(error.into_error())
197    }
198}
199
200/// API keys in the `api_keys` table, as the PHP package's `ApiKey` model keeps them: only a
201/// SHA-256 hash of each key is stored, with its prefix and last four characters to recognise it.
202/// A key works until it is revoked or reaches `expires_at`. An `fs_test_` key is for development
203/// and staging: production turns it away unless
204/// [`Config::test_keys_in_production`](crate::Config::test_keys_in_production) is on.
205#[cfg(feature = "database")]
206pub mod api_keys {
207    use laravel::db::{self, col, values};
208    use laravel::time::Timestamp;
209    use sha2::{Digest, Sha256};
210
211    use super::ApiClient;
212
213    /// The prefix of live keys.
214    pub const LIVE_PREFIX: &str = "fs_live_";
215    /// The prefix of test keys.
216    pub const TEST_PREFIX: &str = "fs_test_";
217
218    /// A key from the table.
219    #[derive(Debug, Clone, db::FromRow)]
220    pub struct ApiKey {
221        pub id: i64,
222        pub name: String,
223        pub prefix: String,
224        pub hint: String,
225        pub scopes: Option<String>,
226        pub version: Option<String>,
227        pub rate_limit_tier: Option<String>,
228        /// When the key stops working, or `None` for a key that never expires.
229        pub expires_at: Option<Timestamp>,
230    }
231
232    impl ApiKey {
233        /// The key's granted scopes.
234        #[must_use]
235        pub fn scopes(&self) -> Vec<String> {
236            self.scopes
237                .as_deref()
238                .and_then(|scopes| serde_json::from_str(scopes).ok())
239                .unwrap_or_default()
240        }
241
242        /// The client the key authenticates.
243        #[must_use]
244        pub fn into_client(self) -> ApiClient {
245            let scopes = self.scopes();
246            ApiClient::new(format!("api_key:{}", self.id))
247                .scopes(scopes)
248                .version(self.version)
249                .rate_limit_tier(self.rate_limit_tier)
250        }
251    }
252
253    /// Whether a key is turned away before it is looked up: a test key in production, unless the
254    /// application allows them. Test keys are for development and staging, where they are
255    /// easiest to leak, as in the PHP package.
256    pub(crate) fn turned_away(token: &str, production: bool, allowed: bool) -> bool {
257        production && !allowed && token.starts_with(TEST_PREFIX)
258    }
259
260    /// The SHA-256 hash the table keeps of a key.
261    #[must_use]
262    pub fn hash(plain: &str) -> String {
263        Sha256::digest(plain.as_bytes())
264            .iter()
265            .map(|byte| format!("{byte:02x}"))
266            .collect()
267    }
268
269    /// What a new key is for: its name and scopes, its pin, when it expires, and whether it is a
270    /// test key.
271    #[derive(Debug, Clone, Default)]
272    pub struct Issue {
273        pub name: String,
274        pub scopes: Vec<String>,
275        /// The version to pin to. Pin new keys to the latest version, so later breaking changes
276        /// never reach them until they are upgraded, as PHP's `ApiKey::issue` does.
277        pub version: Option<String>,
278        pub rate_limit_tier: Option<String>,
279        /// When the key stops working, such as `(laravel::now() + 90.days()).timestamp()`, or
280        /// `None` for a key that never expires.
281        pub expires_at: Option<Timestamp>,
282        pub test: bool,
283    }
284
285    /// Creates a key and returns its ID and plain-text value, which is not stored.
286    ///
287    /// # Errors
288    ///
289    /// When the key can't be written.
290    pub async fn issue(issue: Issue) -> laravel::Result<(i64, String)> {
291        let prefix = if issue.test { TEST_PREFIX } else { LIVE_PREFIX };
292        let plain = format!("{prefix}{}", laravel::str::random(40));
293        let id = insert(&plain, issue).await?;
294        Ok((id, plain))
295    }
296
297    /// Stores a key with a value you chose, such as fixed keys in a seeder.
298    ///
299    /// # Errors
300    ///
301    /// When the key can't be written, such as when the value is taken.
302    pub async fn insert(plain: &str, issue: Issue) -> laravel::Result<i64> {
303        let prefix = if plain.starts_with(TEST_PREFIX) {
304            TEST_PREFIX
305        } else {
306            LIVE_PREFIX
307        };
308        let hint: String = plain
309            .chars()
310            .rev()
311            .take(4)
312            .collect::<Vec<_>>()
313            .into_iter()
314            .rev()
315            .collect();
316        let now = laravel::now().timestamp();
317        db::table("api_keys")
318            .insert_get_id(
319                values! {
320                    name: issue.name,
321                    prefix: prefix,
322                    hint: hint,
323                    token_hash: hash(plain),
324                    scopes: serde_json::to_string(&issue.scopes).unwrap_or_default(),
325                    version: issue.version,
326                    rate_limit_tier: issue.rate_limit_tier,
327                    expires_at: issue.expires_at,
328                    created_at: now,
329                    updated_at: now,
330                },
331                "id",
332            )
333            .await
334    }
335
336    /// The key with this plain-text value, unless it is revoked or expired. Values without a key
337    /// prefix are not looked up, so other bearer tokens cost no query. The `FusionStack`
338    /// middleware also turns away test keys in production.
339    ///
340    /// # Errors
341    ///
342    /// When the table can't be read.
343    pub async fn find_by_token(token: &str) -> laravel::Result<Option<ApiKey>> {
344        if !token.starts_with(LIVE_PREFIX) && !token.starts_with(TEST_PREFIX) {
345            return Ok(None);
346        }
347        db::table("api_keys")
348            .select([
349                "id",
350                "name",
351                "prefix",
352                "hint",
353                "scopes",
354                "version",
355                "rate_limit_tier",
356                "expires_at",
357            ])
358            .filter(col("token_hash").eq(hash(token)))
359            .filter(col("revoked_at").is_null())
360            .filter(db::any([
361                col("expires_at").is_null(),
362                col("expires_at").gt(laravel::now().timestamp()),
363            ]))
364            .first()
365            .await
366    }
367
368    /// Records a use, at most once a minute so busy keys do not write on every request.
369    pub(crate) async fn touch_last_used(id: i64) -> laravel::Result<()> {
370        use laravel::prelude::ToSpan;
371        let now = laravel::now();
372        let cutoff = now.timestamp() - 1.minute();
373        db::table("api_keys")
374            .filter(col("id").eq(id))
375            .filter(db::any([
376                col("last_used_at").is_null(),
377                col("last_used_at").lt(cutoff),
378            ]))
379            .update(values! { last_used_at: now.timestamp() })
380            .await?;
381        Ok(())
382    }
383
384    /// Revokes a key, so it no longer authenticates.
385    ///
386    /// # Errors
387    ///
388    /// When the key can't be written.
389    pub async fn revoke(id: i64) -> laravel::Result<()> {
390        db::table("api_keys")
391            .filter(col("id").eq(id))
392            .update(values! { revoked_at: laravel::now().timestamp() })
393            .await?;
394        Ok(())
395    }
396
397    /// Pins a key to a version, such as when its owner upgrades. `None` follows the default.
398    ///
399    /// # Errors
400    ///
401    /// When the key can't be written.
402    pub async fn pin_to(id: i64, version: Option<&str>) -> laravel::Result<()> {
403        db::table("api_keys")
404            .filter(col("id").eq(id))
405            .update(values! { version: version.map(str::to_owned) })
406            .await?;
407        Ok(())
408    }
409}
410
411#[cfg(test)]
412mod tests {
413    use super::ApiClient;
414
415    #[test]
416    fn scopes_match_exactly_or_by_wildcard() {
417        let client = ApiClient::new("a").scopes(["orders:*", "customers:read"]);
418        assert!(client.has_scope("orders:write"));
419        assert!(client.has_scope("customers:read"));
420        assert!(!client.has_scope("customers:write"));
421        // `orders:*` covers `orders:` scopes, not scopes that only start with `orders`.
422        assert!(!client.has_scope("ordersx:read"));
423        assert!(ApiClient::new("b").scopes(["*"]).has_scope("anything"));
424        assert!(!ApiClient::new("c").has_scope("orders:read"));
425    }
426
427    #[cfg(feature = "database")]
428    #[test]
429    fn only_production_turns_test_keys_away_unless_they_are_allowed() {
430        use super::api_keys::turned_away;
431
432        // (key, production, allowed) => turned away
433        assert!(turned_away("fs_test_abc", true, false));
434        assert!(!turned_away("fs_test_abc", true, true));
435        assert!(!turned_away("fs_test_abc", false, false));
436        assert!(!turned_away("fs_live_abc", true, false));
437        // The prefix is what counts, not `test` somewhere in the key.
438        assert!(!turned_away("fs_live_fs_test_", true, false));
439    }
440}