Skip to main content

fastauth_plugin_api_key/
endpoints.rs

1//! The `/api-key/*` endpoints, their inputs and outputs.
2
3use fastauth_core::plugin_prelude::*;
4use serde::Deserializer;
5
6use crate::model::{ApiKey, Permissions};
7use crate::verify::{Failure, verify};
8use crate::{ApiKeyCreated, ApiKeyDeleted, ApiKeyError, ApiKeys};
9
10const NAME_LENGTH: std::ops::RangeInclusive<usize> = 1..=32;
11const PREFIX_LENGTH: std::ops::RangeInclusive<usize> = 1..=32;
12const KEY_ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
13
14/// An API key as clients see it: every column except the hash, camelCase, with the owner
15/// as `referenceId` (and `userId`) like Better Auth.
16#[derive(Clone, Debug, Serialize)]
17#[serde(rename_all = "camelCase")]
18pub struct ApiKeyView {
19    pub id: Id,
20    /// Always `"default"`: fastauth has one key configuration.
21    pub config_id: &'static str,
22    pub name: Option<String>,
23    pub start: Option<String>,
24    pub prefix: Option<String>,
25    pub reference_id: Id,
26    pub user_id: Id,
27    pub refill_interval: Option<i64>,
28    pub refill_amount: Option<i64>,
29    #[serde(with = "time::serde::rfc3339::option")]
30    pub last_refill_at: Option<OffsetDateTime>,
31    pub enabled: bool,
32    pub rate_limit_enabled: bool,
33    pub rate_limit_time_window: Option<i64>,
34    pub rate_limit_max: Option<i64>,
35    pub request_count: i64,
36    pub remaining: Option<i64>,
37    #[serde(with = "time::serde::rfc3339::option")]
38    pub last_request: Option<OffsetDateTime>,
39    #[serde(with = "time::serde::rfc3339::option")]
40    pub expires_at: Option<OffsetDateTime>,
41    #[serde(with = "time::serde::rfc3339")]
42    pub created_at: OffsetDateTime,
43    #[serde(with = "time::serde::rfc3339")]
44    pub updated_at: OffsetDateTime,
45    pub metadata: Option<serde_json::Value>,
46    pub permissions: Option<Permissions>,
47}
48
49impl From<ApiKey> for ApiKeyView {
50    fn from(key: ApiKey) -> Self {
51        Self {
52            id: key.id,
53            config_id: "default",
54            name: key.name,
55            start: key.start,
56            prefix: key.prefix,
57            reference_id: key.user_id.clone(),
58            user_id: key.user_id,
59            refill_interval: key.refill_interval,
60            refill_amount: key.refill_amount,
61            last_refill_at: key.last_refill_at,
62            enabled: key.enabled,
63            rate_limit_enabled: key.rate_limit_enabled,
64            rate_limit_time_window: key.rate_limit_time_window,
65            rate_limit_max: key.rate_limit_max,
66            request_count: key.request_count,
67            remaining: key.remaining,
68            last_request: key.last_request,
69            expires_at: key.expires_at,
70            created_at: key.created_at,
71            updated_at: key.updated_at,
72            metadata: key.metadata.map(|m| m.0).filter(|m| !m.is_null()),
73            permissions: key.permissions.map(|p| p.0),
74        }
75    }
76}
77
78/// `{ "success": true }`.
79#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
80pub struct Success {
81    pub success: bool,
82}
83
84/// `Some(None)` for an explicit `null`, `None` when the field is absent.
85fn double_option<'de, T: Deserialize<'de>, D: Deserializer<'de>>(
86    deserializer: D,
87) -> Result<Option<Option<T>>, D::Error> {
88    Option::<T>::deserialize(deserializer).map(Some)
89}
90
91fn invalid(message: &'static str) -> AuthError {
92    AuthError::bad_request(codes::INVALID_BODY, message)
93}
94
95/// Who the request acts for. Client requests use the session and may not name a user;
96/// server calls use the session, or `userId` when there is none.
97fn owner(
98    session: Option<&SessionView>,
99    user_id: Option<Id>,
100    trusted: bool,
101    missing: AuthError,
102) -> Result<Id, AuthError> {
103    let session = session.map(|s| s.user.id.clone());
104    if !trusted {
105        if user_id.is_some() {
106            return Err(ApiKeyError::UnauthorizedSession.into());
107        }
108        return session.ok_or(missing);
109    }
110    match (session, user_id) {
111        (Some(session), Some(user)) if session != user => {
112            Err(ApiKeyError::UnauthorizedSession.into())
113        }
114        (Some(id), _) | (None, Some(id)) => Ok(id),
115        (None, None) => Err(ApiKeyError::UnauthorizedSession.into()),
116    }
117}
118
119/// The caller's key `id`, or `KEY_NOT_FOUND` (also for another user's key).
120async fn owned_key<D: Adapter, A>(
121    ctx: &Ctx<D, A>,
122    id: &Id,
123    owner: &Id,
124) -> Result<ApiKey, AuthError> {
125    ctx.db()
126        .find::<ApiKey>(ApiKey::ID.eq(id))
127        .one()
128        .await?
129        .filter(|key| &key.user_id == owner)
130        .ok_or_else(|| ApiKeyError::KeyNotFound.into())
131}
132
133fn check_expires_in(plugin: &ApiKeys, seconds: i64) -> Result<Duration, AuthError> {
134    if seconds < 1 {
135        return Err(invalid("expiresIn must be at least 1"));
136    }
137    let expires_in = Duration::seconds(seconds);
138    if expires_in < plugin.min_expires_in {
139        return Err(ApiKeyError::ExpiresInIsTooSmall.into());
140    }
141    if expires_in > plugin.max_expires_in {
142        return Err(ApiKeyError::ExpiresInIsTooLarge.into());
143    }
144    Ok(expires_in)
145}
146
147fn check_name(name: &str) -> Result<(), AuthError> {
148    if NAME_LENGTH.contains(&name.chars().count()) {
149        Ok(())
150    } else {
151        Err(ApiKeyError::InvalidNameLength.into())
152    }
153}
154
155fn check_refill(amount: Option<i64>, interval: Option<i64>) -> Result<(), AuthError> {
156    match (amount, interval) {
157        (Some(_), None) => Err(ApiKeyError::RefillAmountAndIntervalRequired.into()),
158        (None, Some(_)) => Err(ApiKeyError::RefillIntervalAndAmountRequired.into()),
159        (Some(amount), _) if amount < 1 => Err(invalid("refillAmount must be at least 1")),
160        _ => Ok(()),
161    }
162}
163
164fn check_non_negative(values: &[Option<i64>]) -> Result<(), AuthError> {
165    if values.iter().flatten().any(|v| *v < 0) {
166        return Err(invalid("numbers must not be negative"));
167    }
168    Ok(())
169}
170
171/// `POST /api-key/create`.
172#[derive(Clone, Debug)]
173pub struct CreateApiKey {
174    plugin: Arc<ApiKeys>,
175    trusted: bool,
176}
177
178impl CreateApiKey {
179    /// The HTTP route: server-only fields are refused, the session owns the key.
180    pub fn client(plugin: Arc<ApiKeys>) -> Self {
181        Self {
182            plugin,
183            trusted: false,
184        }
185    }
186
187    /// The server API: every field is accepted, and `userId` names the owner when there is
188    /// no session.
189    pub fn server(plugin: Arc<ApiKeys>) -> Self {
190        Self {
191            plugin,
192            trusted: true,
193        }
194    }
195}
196
197/// The body of `/api-key/create`. Fields marked server-only answer `SERVER_ONLY_PROPERTY`
198/// when they come from a client.
199#[derive(Clone, Debug, Default, Deserialize)]
200#[serde(rename_all = "camelCase")]
201pub struct CreateApiKeyInput {
202    pub name: Option<String>,
203    /// Seconds until the key expires. Default: the plugin's `default_expires_in`.
204    pub expires_in: Option<i64>,
205    /// Overrides the plugin's default prefix: letters, digits, `_` and `-`.
206    pub prefix: Option<String>,
207    /// Requires `enable_metadata`; must be a JSON object.
208    pub metadata: Option<serde_json::Value>,
209    /// Server-only. Verifications allowed before the key is used up.
210    pub remaining: Option<i64>,
211    /// Server-only, with `refill_interval`.
212    pub refill_amount: Option<i64>,
213    /// Server-only, milliseconds, with `refill_amount`.
214    pub refill_interval: Option<i64>,
215    /// Server-only, milliseconds.
216    pub rate_limit_time_window: Option<i64>,
217    /// Server-only.
218    pub rate_limit_max: Option<i64>,
219    /// Server-only.
220    pub rate_limit_enabled: Option<bool>,
221    /// Server-only.
222    pub permissions: Option<Permissions>,
223    /// Server-only: the owner when there is no session.
224    pub user_id: Option<Id>,
225}
226
227/// The created key plus the full `key`, the only time it is shown.
228#[derive(Clone, Debug, Serialize)]
229pub struct CreatedApiKey {
230    #[serde(flatten)]
231    pub api_key: ApiKeyView,
232    pub key: String,
233}
234
235impl<D: Adapter> Endpoint<D> for CreateApiKey {
236    const METHOD: Method = Method::POST;
237    const PATH: &'static str = "/api-key/create";
238    type Access = MaybeAuthenticated;
239    type Input = CreateApiKeyInput;
240    type Output = CreatedApiKey;
241
242    async fn call(
243        &self,
244        ctx: Ctx<D, MaybeAuthenticated>,
245        input: CreateApiKeyInput,
246    ) -> Result<CreatedApiKey, AuthError> {
247        let plugin = &self.plugin;
248        let server_only = input.remaining.is_some()
249            || input.refill_amount.is_some()
250            || input.refill_interval.is_some()
251            || input.rate_limit_time_window.is_some()
252            || input.rate_limit_max.is_some()
253            || input.rate_limit_enabled.is_some()
254            || input.permissions.is_some();
255        if !self.trusted && server_only {
256            return Err(ApiKeyError::ServerOnlyProperty.into());
257        }
258        let user_id = owner(
259            ctx.session(),
260            input.user_id,
261            self.trusted,
262            ApiKeyError::UnauthorizedSession.into(),
263        )?;
264        let metadata = input.metadata.filter(|m| !m.is_null());
265        if let Some(metadata) = &metadata {
266            if !plugin.enable_metadata {
267                return Err(ApiKeyError::MetadataDisabled.into());
268            }
269            if !metadata.is_object() {
270                return Err(ApiKeyError::InvalidMetadataType.into());
271            }
272        }
273        check_refill(input.refill_amount, input.refill_interval)?;
274        check_non_negative(&[
275            input.remaining,
276            input.refill_interval,
277            input.rate_limit_time_window,
278            input.rate_limit_max,
279        ])?;
280        let expires_in = input
281            .expires_in
282            .map(|seconds| check_expires_in(plugin, seconds))
283            .transpose()?;
284        if let Some(prefix) = &input.prefix {
285            if !PREFIX_LENGTH.contains(&prefix.len()) {
286                return Err(ApiKeyError::InvalidPrefixLength.into());
287            }
288            if !prefix
289                .bytes()
290                .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
291            {
292                return Err(invalid(
293                    "Invalid prefix format, must be alphanumeric and contain only underscores and hyphens.",
294                ));
295            }
296        }
297        match &input.name {
298            Some(name) => check_name(name)?,
299            None if plugin.require_name => return Err(ApiKeyError::NameRequired.into()),
300            None => {}
301        }
302
303        let prefix = input.prefix.or_else(|| plugin.default_prefix.clone());
304        let key = format!(
305            "{}{}",
306            prefix.as_deref().unwrap_or(""),
307            random_string(plugin.key_length, KEY_ALPHABET)
308        );
309        let start =
310            (plugin.start_length > 0).then(|| key.chars().take(plugin.start_length).collect());
311        let now = ctx.now();
312        let row = ApiKey {
313            id: ctx.new_id()?,
314            name: input.name,
315            start,
316            prefix,
317            key_hash: Hash::sha256(&key),
318            user_id,
319            enabled: true,
320            expires_at: expires_in
321                .or(plugin.default_expires_in)
322                .map(|ttl| now + ttl),
323            rate_limit_enabled: input
324                .rate_limit_enabled
325                .unwrap_or(plugin.rate_limit.enabled),
326            rate_limit_time_window: Some(
327                input
328                    .rate_limit_time_window
329                    .unwrap_or(plugin.rate_limit.window.whole_milliseconds() as i64),
330            ),
331            rate_limit_max: Some(input.rate_limit_max.unwrap_or(plugin.rate_limit.max)),
332            request_count: 0,
333            last_request: None,
334            remaining: input.remaining.or(input.refill_amount),
335            refill_amount: input.refill_amount,
336            refill_interval: input.refill_interval,
337            last_refill_at: None,
338            permissions: input
339                .permissions
340                .or_else(|| plugin.default_permissions.clone())
341                .map(Json),
342            metadata: metadata.map(Json),
343            created_at: now,
344            updated_at: now,
345        };
346        let row = ctx.db().insert(&row).await?;
347        ctx.emit(ApiKeyCreated {
348            id: row.id.clone(),
349            user_id: row.user_id.clone(),
350        });
351        Ok(CreatedApiKey {
352            api_key: row.into(),
353            key,
354        })
355    }
356}
357
358/// `GET /api-key/get?id=..`.
359#[derive(Clone, Copy, Debug)]
360pub struct GetApiKey {
361    trusted: bool,
362}
363
364impl GetApiKey {
365    /// The HTTP route: the session's own keys only.
366    pub fn client() -> Self {
367        Self { trusted: false }
368    }
369
370    /// The server API: `userId` names the owner when there is no session.
371    pub fn server() -> Self {
372        Self { trusted: true }
373    }
374}
375
376/// The query of `/api-key/get`.
377#[derive(Clone, Debug, Deserialize)]
378#[serde(rename_all = "camelCase")]
379pub struct GetApiKeyInput {
380    pub id: Id,
381    /// Server-only: the owner when there is no session.
382    #[serde(default)]
383    pub user_id: Option<Id>,
384}
385
386impl<D: Adapter> Endpoint<D> for GetApiKey {
387    const METHOD: Method = Method::GET;
388    const PATH: &'static str = "/api-key/get";
389    type Access = MaybeAuthenticated;
390    type Input = GetApiKeyInput;
391    type Output = ApiKeyView;
392
393    async fn call(
394        &self,
395        ctx: Ctx<D, MaybeAuthenticated>,
396        input: GetApiKeyInput,
397    ) -> Result<ApiKeyView, AuthError> {
398        let owner = owner(
399            ctx.session(),
400            input.user_id,
401            self.trusted,
402            AuthError::unauthorized(),
403        )?;
404        Ok(owned_key(&ctx, &input.id, &owner).await?.into())
405    }
406}
407
408/// `POST /api-key/update`.
409#[derive(Clone, Debug)]
410pub struct UpdateApiKey {
411    plugin: Arc<ApiKeys>,
412    trusted: bool,
413}
414
415impl UpdateApiKey {
416    /// The HTTP route: server-only fields are refused.
417    pub fn client(plugin: Arc<ApiKeys>) -> Self {
418        Self {
419            plugin,
420            trusted: false,
421        }
422    }
423
424    /// The server API: every field is accepted.
425    pub fn server(plugin: Arc<ApiKeys>) -> Self {
426        Self {
427            plugin,
428            trusted: true,
429        }
430    }
431}
432
433/// The body of `/api-key/update`. Absent fields are left alone. `Some(None)` (JSON
434/// `null`) clears `expires_in`, `metadata` and `permissions`.
435#[derive(Clone, Debug, Deserialize)]
436#[serde(rename_all = "camelCase")]
437pub struct UpdateApiKeyInput {
438    pub key_id: Id,
439    /// Server-only: the owner when there is no session.
440    #[serde(default)]
441    pub user_id: Option<Id>,
442    #[serde(default)]
443    pub name: Option<String>,
444    #[serde(default)]
445    pub enabled: Option<bool>,
446    /// Seconds from now; `null` removes the expiry.
447    #[serde(default, deserialize_with = "double_option")]
448    pub expires_in: Option<Option<i64>>,
449    /// Ignored unless `enable_metadata` is on.
450    #[serde(default, deserialize_with = "double_option")]
451    pub metadata: Option<Option<serde_json::Value>>,
452    /// Server-only, at least 1.
453    #[serde(default)]
454    pub remaining: Option<i64>,
455    /// Server-only, with `refill_interval`.
456    #[serde(default)]
457    pub refill_amount: Option<i64>,
458    /// Server-only, with `refill_amount`.
459    #[serde(default)]
460    pub refill_interval: Option<i64>,
461    /// Server-only.
462    #[serde(default)]
463    pub rate_limit_enabled: Option<bool>,
464    /// Server-only.
465    #[serde(default)]
466    pub rate_limit_time_window: Option<i64>,
467    /// Server-only.
468    #[serde(default)]
469    pub rate_limit_max: Option<i64>,
470    /// Server-only.
471    #[serde(default, deserialize_with = "double_option")]
472    pub permissions: Option<Option<Permissions>>,
473}
474
475impl UpdateApiKeyInput {
476    /// An update of `key_id` that changes nothing yet.
477    pub fn new(key_id: impl Into<Id>) -> Self {
478        Self {
479            key_id: key_id.into(),
480            user_id: None,
481            name: None,
482            enabled: None,
483            expires_in: None,
484            metadata: None,
485            remaining: None,
486            refill_amount: None,
487            refill_interval: None,
488            rate_limit_enabled: None,
489            rate_limit_time_window: None,
490            rate_limit_max: None,
491            permissions: None,
492        }
493    }
494}
495
496impl<D: Adapter> Endpoint<D> for UpdateApiKey {
497    const METHOD: Method = Method::POST;
498    const PATH: &'static str = "/api-key/update";
499    type Access = MaybeAuthenticated;
500    type Input = UpdateApiKeyInput;
501    type Output = ApiKeyView;
502
503    async fn call(
504        &self,
505        ctx: Ctx<D, MaybeAuthenticated>,
506        input: UpdateApiKeyInput,
507    ) -> Result<ApiKeyView, AuthError> {
508        let owner = owner(
509            ctx.session(),
510            input.user_id,
511            self.trusted,
512            ApiKeyError::UnauthorizedSession.into(),
513        )?;
514        let server_only = input.remaining.is_some()
515            || input.refill_amount.is_some()
516            || input.refill_interval.is_some()
517            || input.rate_limit_enabled.is_some()
518            || input.rate_limit_time_window.is_some()
519            || input.rate_limit_max.is_some()
520            || input.permissions.is_some();
521        if !self.trusted && server_only {
522            return Err(ApiKeyError::ServerOnlyProperty.into());
523        }
524        let key = owned_key(&ctx, &input.key_id, &owner).await?;
525
526        let mut changed = false;
527        let mut update = ctx.db().update::<ApiKey>(ApiKey::ID.eq(&key.id));
528        if let Some(name) = input.name {
529            check_name(&name)?;
530            update = update.set(ApiKey::NAME, Some(name));
531            changed = true;
532        }
533        if let Some(enabled) = input.enabled {
534            update = update.set(ApiKey::ENABLED, enabled);
535            changed = true;
536        }
537        if let Some(expires_in) = input.expires_in {
538            let expires_at = expires_in
539                .map(|seconds| check_expires_in(&self.plugin, seconds))
540                .transpose()?
541                .map(|ttl| ctx.now() + ttl);
542            update = update.set(ApiKey::EXPIRES_AT, expires_at);
543            changed = true;
544        }
545        if let Some(metadata) = input.metadata.filter(|_| self.plugin.enable_metadata) {
546            let metadata = metadata.filter(|m| !m.is_null());
547            if metadata.as_ref().is_some_and(|m| !m.is_object()) {
548                return Err(ApiKeyError::InvalidMetadataType.into());
549            }
550            update = update.set(ApiKey::METADATA, metadata.map(Json));
551            changed = true;
552        }
553        if let Some(remaining) = input.remaining {
554            if remaining < 1 {
555                return Err(invalid("remaining must be at least 1"));
556            }
557            update = update.set(ApiKey::REMAINING, Some(remaining));
558            changed = true;
559        }
560        if input.refill_amount.is_some() || input.refill_interval.is_some() {
561            check_refill(input.refill_amount, input.refill_interval)?;
562            check_non_negative(&[input.refill_interval])?;
563            update = update
564                .set(ApiKey::REFILL_AMOUNT, input.refill_amount)
565                .set(ApiKey::REFILL_INTERVAL, input.refill_interval);
566            changed = true;
567        }
568        check_non_negative(&[input.rate_limit_time_window, input.rate_limit_max])?;
569        if let Some(enabled) = input.rate_limit_enabled {
570            update = update.set(ApiKey::RATE_LIMIT_ENABLED, enabled);
571            changed = true;
572        }
573        if let Some(window) = input.rate_limit_time_window {
574            update = update.set(ApiKey::RATE_LIMIT_TIME_WINDOW, Some(window));
575            changed = true;
576        }
577        if let Some(max) = input.rate_limit_max {
578            update = update.set(ApiKey::RATE_LIMIT_MAX, Some(max));
579            changed = true;
580        }
581        if let Some(permissions) = input.permissions {
582            update = update.set(ApiKey::PERMISSIONS, permissions.map(Json));
583            changed = true;
584        }
585        if !changed {
586            return Err(ApiKeyError::NoValuesToUpdate.into());
587        }
588        update.exec().await?;
589        Ok(owned_key(&ctx, &key.id, &owner).await?.into())
590    }
591}
592
593/// `POST /api-key/delete`.
594#[derive(Clone, Copy, Debug)]
595pub struct DeleteApiKey {
596    trusted: bool,
597}
598
599impl DeleteApiKey {
600    /// The HTTP route: the session's own keys only.
601    pub fn client() -> Self {
602        Self { trusted: false }
603    }
604
605    /// The server API: `userId` names the owner when there is no session.
606    pub fn server() -> Self {
607        Self { trusted: true }
608    }
609}
610
611/// The body of `/api-key/delete`.
612#[derive(Clone, Debug, Deserialize)]
613#[serde(rename_all = "camelCase")]
614pub struct DeleteApiKeyInput {
615    pub key_id: Id,
616    /// Server-only: the owner when there is no session.
617    #[serde(default)]
618    pub user_id: Option<Id>,
619}
620
621impl<D: Adapter> Endpoint<D> for DeleteApiKey {
622    const METHOD: Method = Method::POST;
623    const PATH: &'static str = "/api-key/delete";
624    type Access = MaybeAuthenticated;
625    type Input = DeleteApiKeyInput;
626    type Output = Success;
627
628    async fn call(
629        &self,
630        ctx: Ctx<D, MaybeAuthenticated>,
631        input: DeleteApiKeyInput,
632    ) -> Result<Success, AuthError> {
633        let owner = owner(
634            ctx.session(),
635            input.user_id,
636            self.trusted,
637            AuthError::unauthorized(),
638        )?;
639        let key = owned_key(&ctx, &input.key_id, &owner).await?;
640        ctx.db().delete::<ApiKey>(ApiKey::ID.eq(&key.id)).await?;
641        ctx.emit(ApiKeyDeleted {
642            id: key.id,
643            user_id: key.user_id,
644        });
645        Ok(Success { success: true })
646    }
647}
648
649/// `GET /api-key/list`.
650#[derive(Clone, Copy, Debug)]
651pub struct ListApiKeys {
652    trusted: bool,
653}
654
655impl ListApiKeys {
656    /// The HTTP route: the session's own keys.
657    pub fn client() -> Self {
658        Self { trusted: false }
659    }
660
661    /// The server API: `userId` names the owner when there is no session.
662    pub fn server() -> Self {
663        Self { trusted: true }
664    }
665}
666
667/// Sort order for `/api-key/list`.
668#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
669#[serde(rename_all = "lowercase")]
670pub enum SortDirection {
671    #[default]
672    Asc,
673    Desc,
674}
675
676/// The query of `/api-key/list`.
677#[derive(Clone, Debug, Default, Deserialize)]
678#[serde(rename_all = "camelCase")]
679pub struct ListApiKeysInput {
680    pub limit: Option<u64>,
681    pub offset: Option<u64>,
682    /// A field name: `createdAt` (the default), `updatedAt`, `name`, `expiresAt`,
683    /// `lastRequest`, `remaining`, `requestCount` or `enabled`.
684    pub sort_by: Option<String>,
685    pub sort_direction: Option<SortDirection>,
686    /// Server-only: the owner when there is no session.
687    pub user_id: Option<Id>,
688}
689
690/// `{ "apiKeys": [..], "total": n, "limit": .., "offset": .. }`.
691#[derive(Clone, Debug, Serialize)]
692#[serde(rename_all = "camelCase")]
693pub struct ApiKeyList {
694    pub api_keys: Vec<ApiKeyView>,
695    /// Every key the owner has, ignoring `limit` and `offset`.
696    pub total: u64,
697    #[serde(skip_serializing_if = "Option::is_none")]
698    pub limit: Option<u64>,
699    #[serde(skip_serializing_if = "Option::is_none")]
700    pub offset: Option<u64>,
701}
702
703impl<D: Adapter> Endpoint<D> for ListApiKeys {
704    const METHOD: Method = Method::GET;
705    const PATH: &'static str = "/api-key/list";
706    type Access = MaybeAuthenticated;
707    type Input = ListApiKeysInput;
708    type Output = ApiKeyList;
709
710    async fn call(
711        &self,
712        ctx: Ctx<D, MaybeAuthenticated>,
713        input: ListApiKeysInput,
714    ) -> Result<ApiKeyList, AuthError> {
715        let owner = owner(
716            ctx.session(),
717            input.user_id,
718            self.trusted,
719            AuthError::unauthorized(),
720        )?;
721        let column = match input.sort_by.as_deref().unwrap_or("createdAt") {
722            "createdAt" => ApiKey::CREATED_AT.name(),
723            "updatedAt" => ApiKey::UPDATED_AT.name(),
724            "name" => ApiKey::NAME.name(),
725            "expiresAt" => ApiKey::EXPIRES_AT.name(),
726            "lastRequest" => ApiKey::LAST_REQUEST.name(),
727            "remaining" => ApiKey::REMAINING.name(),
728            "requestCount" => ApiKey::REQUEST_COUNT.name(),
729            "enabled" => ApiKey::ENABLED.name(),
730            _ => return Err(invalid("sortBy names an unknown field")),
731        };
732        let order = match input.sort_direction.unwrap_or_default() {
733            SortDirection::Asc => Order::Asc,
734            SortDirection::Desc => Order::Desc,
735        };
736        let db = ctx.db();
737        let mut find = db
738            .find::<ApiKey>(ApiKey::USER_ID.eq(&owner))
739            .order_by((column, order));
740        if let Some(limit) = input.limit {
741            find = find.limit(limit);
742        }
743        if let Some(offset) = input.offset {
744            find = find.offset(offset);
745        }
746        let keys = find.all().await?;
747        let total = db.count::<ApiKey>(ApiKey::USER_ID.eq(&owner)).await?;
748        Ok(ApiKeyList {
749            api_keys: keys.into_iter().map(ApiKeyView::from).collect(),
750            total,
751            limit: input.limit,
752            offset: input.offset,
753        })
754    }
755}
756
757/// `/api-key/verify`. Server-only, like Better Auth: not routed over HTTP, called through
758/// `auth.api_keys().verify(..)`.
759#[derive(Clone, Debug)]
760pub struct VerifyApiKey(pub Arc<ApiKeys>);
761
762/// The input of `/api-key/verify`.
763#[derive(Clone, Debug, Deserialize)]
764#[serde(rename_all = "camelCase")]
765pub struct VerifyApiKeyInput {
766    pub key: String,
767    /// Every action of every resource listed must be granted to the key.
768    #[serde(default)]
769    pub permissions: Option<Permissions>,
770}
771
772/// Why verification failed: Better Auth's `{ "message", "code" }`, plus
773/// `details.tryAgainIn` (milliseconds) for `RATE_LIMITED`.
774#[derive(Clone, Debug, PartialEq, Serialize)]
775pub struct VerifyError {
776    pub message: String,
777    pub code: String,
778    #[serde(skip_serializing_if = "Option::is_none")]
779    pub details: Option<serde_json::Value>,
780}
781
782/// `{ "valid": true, "error": null, "key": {..} }`, or `valid: false` with an error and
783/// `key: null`.
784#[derive(Clone, Debug, Serialize)]
785pub struct VerifyOutput {
786    pub valid: bool,
787    pub error: Option<VerifyError>,
788    pub key: Option<ApiKeyView>,
789}
790
791impl<D: Adapter> Endpoint<D> for VerifyApiKey {
792    const METHOD: Method = Method::POST;
793    const PATH: &'static str = "/api-key/verify";
794    type Access = Public;
795    type Input = VerifyApiKeyInput;
796    type Output = VerifyOutput;
797
798    async fn call(&self, ctx: Ctx<D>, input: VerifyApiKeyInput) -> Result<VerifyOutput, AuthError> {
799        match verify(&ctx, &self.0, &input.key, input.permissions.as_ref()).await {
800            Ok(key) => Ok(VerifyOutput {
801                valid: true,
802                error: None,
803                key: Some(key.into()),
804            }),
805            Err(Failure::Key {
806                error,
807                try_again_in,
808            }) => {
809                let error = AuthError::from(error);
810                Ok(VerifyOutput {
811                    valid: false,
812                    error: Some(VerifyError {
813                        message: error.message().to_owned(),
814                        code: error.code().to_owned(),
815                        details: try_again_in.map(|ms| serde_json::json!({ "tryAgainIn": ms })),
816                    }),
817                    key: None,
818                })
819            }
820            Err(Failure::Other(error)) => Err(error),
821        }
822    }
823}
824
825/// `/api-key/delete-all-expired-api-keys`. Server-only, like Better Auth.
826#[derive(Clone, Copy, Debug)]
827pub struct DeleteAllExpiredApiKeys;
828
829/// `{ "success": true, "error": null }`.
830#[derive(Clone, Debug, Serialize)]
831pub struct DeleteExpiredOutput {
832    pub success: bool,
833    pub error: Option<String>,
834    /// How many keys were deleted (a fastauth addition).
835    pub deleted: u64,
836}
837
838impl<D: Adapter> Endpoint<D> for DeleteAllExpiredApiKeys {
839    const METHOD: Method = Method::POST;
840    const PATH: &'static str = "/api-key/delete-all-expired-api-keys";
841    type Access = Public;
842    type Input = Empty;
843    type Output = DeleteExpiredOutput;
844
845    async fn call(&self, ctx: Ctx<D>, _: Empty) -> Result<DeleteExpiredOutput, AuthError> {
846        let deleted = ctx
847            .db()
848            .delete::<ApiKey>(
849                ApiKey::EXPIRES_AT
850                    .is_not_null()
851                    .and(ApiKey::EXPIRES_AT.lt(Some(ctx.now()))),
852            )
853            .await?;
854        Ok(DeleteExpiredOutput {
855            success: true,
856            error: None,
857            deleted,
858        })
859    }
860}