1use 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#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct ApiClient {
22 pub id: String,
24 pub scopes: Vec<String>,
26 pub version: Option<String>,
28 pub rate_limit_tier: Option<String>,
30 pub idempotency_scope: String,
32}
33
34impl ApiClient {
35 #[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 #[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 #[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 #[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 #[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 #[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#[must_use]
91pub fn client(request: &Request) -> Option<ApiClient> {
92 request
93 .extension::<Context>()
94 .and_then(|context| context.client.clone())
95}
96
97pub type ClientResolver = Arc<
100 dyn Fn(HeaderMap) -> Pin<Box<dyn Future<Output = laravel::Result<Option<ApiClient>>> + Send>>
101 + Send
102 + Sync,
103>;
104
105pub 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
114pub(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
141pub(crate) const DENIED: &str = "fusion_stack.scope_denied";
144
145#[derive(Clone)]
158pub struct RequiresScope {
159 pub(crate) scope: String,
160 pub(crate) description: String,
161}
162
163impl RequiresScope {
164 #[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 #[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#[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 pub const LIVE_PREFIX: &str = "fs_live_";
215 pub const TEST_PREFIX: &str = "fs_test_";
217
218 #[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 pub expires_at: Option<Timestamp>,
230 }
231
232 impl ApiKey {
233 #[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 #[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 pub(crate) fn turned_away(token: &str, production: bool, allowed: bool) -> bool {
257 production && !allowed && token.starts_with(TEST_PREFIX)
258 }
259
260 #[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 #[derive(Debug, Clone, Default)]
272 pub struct Issue {
273 pub name: String,
274 pub scopes: Vec<String>,
275 pub version: Option<String>,
278 pub rate_limit_tier: Option<String>,
279 pub expires_at: Option<Timestamp>,
282 pub test: bool,
283 }
284
285 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 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 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 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 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 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 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 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 assert!(!turned_away("fs_live_fs_test_", true, false));
439 }
440}