fusion-stack-laravel-rust 0.3.0

Fusion Stack for Laravel for Rust: versioned, documented JSON APIs with standard errors
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! 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(
    config: &crate::Config,
    request: &Request,
) -> laravel::Result<Option<ApiClient>> {
    if let Some(resolver) = config.client_resolver.as_ref()
        && let Some(client) = resolver(request.headers().clone()).await?
    {
        return Ok(Some(client));
    }
    #[cfg(feature = "database")]
    if let Some(token) = request.bearer_token()
        && !api_keys::turned_away(
            token,
            laravel::config().app.env.is_production(),
            config.test_keys_in_production,
        )
        && 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.
/// A key works until it is revoked or reaches `expires_at`. An `fs_test_` key is for development
/// and staging: production turns it away unless
/// [`Config::test_keys_in_production`](crate::Config::test_keys_in_production) is on.
#[cfg(feature = "database")]
pub mod api_keys {
    use laravel::db::{self, col, values};
    use laravel::time::Timestamp;
    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>,
        /// When the key stops working, or `None` for a key that never expires.
        pub expires_at: Option<Timestamp>,
    }

    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)
        }
    }

    /// Whether a key is turned away before it is looked up: a test key in production, unless the
    /// application allows them. Test keys are for development and staging, where they are
    /// easiest to leak, as in the PHP package.
    pub(crate) fn turned_away(token: &str, production: bool, allowed: bool) -> bool {
        production && !allowed && token.starts_with(TEST_PREFIX)
    }

    /// 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, when it expires, 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>,
        /// When the key stops working, such as `(laravel::now() + 90.days()).timestamp()`, or
        /// `None` for a key that never expires.
        pub expires_at: Option<Timestamp>,
        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,
                    expires_at: issue.expires_at,
                    created_at: now,
                    updated_at: now,
                },
                "id",
            )
            .await
    }

    /// The key with this plain-text value, unless it is revoked or expired. Values without a key
    /// prefix are not looked up, so other bearer tokens cost no query. The `FusionStack`
    /// middleware also turns away test keys in production.
    ///
    /// # 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",
                "expires_at",
            ])
            .filter(col("token_hash").eq(hash(token)))
            .filter(col("revoked_at").is_null())
            .filter(db::any([
                col("expires_at").is_null(),
                col("expires_at").gt(laravel::now().timestamp()),
            ]))
            .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"));
    }

    #[cfg(feature = "database")]
    #[test]
    fn only_production_turns_test_keys_away_unless_they_are_allowed() {
        use super::api_keys::turned_away;

        // (key, production, allowed) => turned away
        assert!(turned_away("fs_test_abc", true, false));
        assert!(!turned_away("fs_test_abc", true, true));
        assert!(!turned_away("fs_test_abc", false, false));
        assert!(!turned_away("fs_live_abc", true, false));
        // The prefix is what counts, not `test` somewhere in the key.
        assert!(!turned_away("fs_live_fs_test_", true, false));
    }
}