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 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
136pub(crate) const DENIED: &str = "fusion_stack.scope_denied";
139
140#[derive(Clone)]
153pub struct RequiresScope {
154 pub(crate) scope: String,
155 pub(crate) description: String,
156}
157
158impl RequiresScope {
159 #[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 #[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#[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 pub const LIVE_PREFIX: &str = "fs_live_";
206 pub const TEST_PREFIX: &str = "fs_test_";
208
209 #[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 #[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 #[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 #[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 #[derive(Debug, Clone, Default)]
253 pub struct Issue {
254 pub name: String,
255 pub scopes: Vec<String>,
256 pub version: Option<String>,
259 pub rate_limit_tier: Option<String>,
260 pub test: bool,
261 }
262
263 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 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 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 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 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 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 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}