Skip to main content

fastauth_plugin_api_key/
verify.rs

1//! Key verification: the checks, the usage counters, and the session resolver built on them.
2
3use fastauth_core::adapter::DbError;
4use fastauth_core::model::Col;
5use fastauth_core::plugin_prelude::*;
6use fastauth_core::value::ColumnValue;
7
8use crate::model::{ApiKey, Permissions};
9use crate::{ApiKeyError, ApiKeys};
10
11/// Why a key failed verification: a key error clients see (with the rate limit's retry
12/// delay), or something else that went wrong.
13pub(crate) enum Failure {
14    Key {
15        error: ApiKeyError,
16        try_again_in: Option<i64>,
17    },
18    Other(AuthError),
19}
20
21impl From<ApiKeyError> for Failure {
22    fn from(error: ApiKeyError) -> Self {
23        Failure::Key {
24            error,
25            try_again_in: None,
26        }
27    }
28}
29
30impl From<AuthError> for Failure {
31    fn from(error: AuthError) -> Self {
32        Failure::Other(error)
33    }
34}
35
36impl From<DbError> for Failure {
37    fn from(error: DbError) -> Self {
38        Failure::Other(error.into())
39    }
40}
41
42impl From<Failure> for AuthError {
43    fn from(failure: Failure) -> Self {
44        match failure {
45            Failure::Key { error, .. } => error.into(),
46            Failure::Other(error) => error,
47        }
48    }
49}
50
51/// The counters one successful verification writes.
52#[derive(PartialEq)]
53struct Usage {
54    remaining: Option<i64>,
55    last_refill_at: Option<OffsetDateTime>,
56    request_count: i64,
57    last_request: Option<OffsetDateTime>,
58}
59
60impl Usage {
61    fn of(key: &ApiKey) -> Self {
62        Self {
63            remaining: key.remaining,
64            last_refill_at: key.last_refill_at,
65            request_count: key.request_count,
66            last_request: key.last_request,
67        }
68    }
69}
70
71fn millis(ms: i64) -> Duration {
72    Duration::milliseconds(ms)
73}
74
75/// What this verification does to `key`'s counters, or why it is refused. Pure: the caller
76/// writes the result with a conditional update, and recomputes it from a fresh row when
77/// another request changed the counters first.
78fn consume(plugin: &ApiKeys, key: &ApiKey, now: OffsetDateTime) -> Result<Usage, Failure> {
79    let mut usage = Usage::of(key);
80
81    if let Some(remaining) = key.remaining {
82        let refill = match (key.refill_interval, key.refill_amount) {
83            (Some(interval), Some(amount)) if interval > 0 && amount > 0 => {
84                let last = key.last_refill_at.unwrap_or(key.created_at);
85                (now - last > millis(interval)).then_some(amount)
86            }
87            _ => None,
88        };
89        if let Some(amount) = refill {
90            usage.remaining = Some(amount - 1);
91            usage.last_refill_at = Some(now);
92        } else if remaining > 0 {
93            usage.remaining = Some(remaining - 1);
94        } else {
95            return Err(ApiKeyError::UsageExceeded.into());
96        }
97    }
98
99    if !plugin.rate_limit.enabled || !key.rate_limit_enabled {
100        usage.last_request = Some(now);
101        return Ok(usage);
102    }
103    let (Some(window), Some(max)) = (key.rate_limit_time_window, key.rate_limit_max) else {
104        return Ok(usage);
105    };
106    let since = key.last_request.map(|last| now - last);
107    match since {
108        Some(since) if since <= millis(window) && key.request_count >= max => {
109            let wait = millis(window) - since;
110            return Err(Failure::Key {
111                error: ApiKeyError::RateLimited,
112                try_again_in: Some(wait.whole_milliseconds().max(0) as i64),
113            });
114        }
115        Some(since) if since <= millis(window) => usage.request_count = key.request_count + 1,
116        _ => usage.request_count = 1,
117    }
118    usage.last_request = Some(now);
119    Ok(usage)
120}
121
122/// `column = value`, or `column IS NULL` for `None`.
123fn same<T: ColumnValue + Clone>(
124    column: Col<ApiKey, Option<T>>,
125    value: &Option<T>,
126) -> Where<ApiKey> {
127    match value {
128        Some(v) => column.eq(Some(v.clone())),
129        None => column.is_null(),
130    }
131}
132
133/// Whether `granted` covers every action of every resource in `requested`. An empty request
134/// is refused, as Better Auth's `role().authorize` does.
135pub(crate) fn authorized(granted: &Permissions, requested: &Permissions) -> bool {
136    !requested.is_empty()
137        && requested.iter().all(|(resource, actions)| {
138            granted
139                .get(resource)
140                .is_some_and(|allowed| actions.iter().all(|a| allowed.contains(a)))
141        })
142}
143
144/// How many times a verification re-reads the row after losing a race before giving up.
145/// Every lost race means another request's update went through, so this only runs out
146/// under extreme contention on one key.
147const MAX_ATTEMPTS: usize = 64;
148
149/// Verifies `key`: it exists, is enabled and unexpired, has the requested permissions, has
150/// usage left (refilling it when due) and is within its rate limit. Returns the row with the
151/// counters this verification wrote.
152///
153/// The counters change with one conditional update that only applies while `remaining`,
154/// `last_refill_at`, `request_count` and `last_request` still hold the values the decision
155/// was made from (compare-and-swap). When another request got there first the update
156/// matches no row, and the decision is made again from a fresh read. So concurrent
157/// verifications can't spend the same unit of `remaining` or the same rate-limit slot, on
158/// any adapter whose `UPDATE ... WHERE` is atomic per row, without needing increment
159/// support in the adapter contract.
160pub(crate) async fn verify<D: Adapter, A>(
161    ctx: &Ctx<D, A>,
162    plugin: &ApiKeys,
163    key: &str,
164    permissions: Option<&Permissions>,
165) -> Result<ApiKey, Failure> {
166    let db = ctx.db();
167    let Some(mut row) = db
168        .find::<ApiKey>(ApiKey::KEY_HASH.eq(Hash::sha256(key)))
169        .one()
170        .await?
171    else {
172        return Err(ApiKeyError::InvalidApiKey.into());
173    };
174    if !row.enabled {
175        return Err(ApiKeyError::KeyDisabled.into());
176    }
177    if row.expires_at.is_some_and(|at| ctx.now() > at) {
178        db.delete::<ApiKey>(ApiKey::ID.eq(&row.id)).await?;
179        return Err(ApiKeyError::KeyExpired.into());
180    }
181    if let Some(requested) = permissions {
182        let granted = row.permissions.as_ref().map(|p| &p.0);
183        if !granted.is_some_and(|granted| authorized(granted, requested)) {
184            return Err(ApiKeyError::KeyNotFound.into());
185        }
186    }
187    if row.remaining == Some(0) && row.refill_amount.is_none() {
188        db.delete::<ApiKey>(ApiKey::ID.eq(&row.id)).await?;
189        return Err(ApiKeyError::UsageExceeded.into());
190    }
191
192    for _ in 0..MAX_ATTEMPTS {
193        let now = ctx.now();
194        let usage = consume(plugin, &row, now)?;
195        if usage == Usage::of(&row) {
196            return Ok(row);
197        }
198        let guard = ApiKey::ID
199            .eq(&row.id)
200            .and(same(ApiKey::REMAINING, &row.remaining))
201            .and(same(ApiKey::LAST_REFILL_AT, &row.last_refill_at))
202            .and(ApiKey::REQUEST_COUNT.eq(row.request_count))
203            .and(same(ApiKey::LAST_REQUEST, &row.last_request));
204        let updated = db
205            .update::<ApiKey>(guard)
206            .set(ApiKey::REMAINING, usage.remaining)
207            .set(ApiKey::LAST_REFILL_AT, usage.last_refill_at)
208            .set(ApiKey::REQUEST_COUNT, usage.request_count)
209            .set(ApiKey::LAST_REQUEST, usage.last_request)
210            .set(ApiKey::UPDATED_AT, now)
211            .exec()
212            .await?;
213        if updated == 1 {
214            row.remaining = usage.remaining;
215            row.last_refill_at = usage.last_refill_at;
216            row.request_count = usage.request_count;
217            row.last_request = usage.last_request;
218            row.updated_at = now;
219            return Ok(row);
220        }
221        row = db
222            .find::<ApiKey>(ApiKey::ID.eq(&row.id))
223            .one()
224            .await?
225            .ok_or(ApiKeyError::InvalidApiKey)?;
226    }
227    Err(ApiKeyError::FailedToUpdateApiKey.into())
228}
229
230/// Turns the configured header (or the custom getter's value) into an ephemeral session for
231/// the key's owner. Requests without one pass through untouched.
232pub(crate) struct KeyResolver(pub(crate) Arc<ApiKeys>);
233
234impl<D: Adapter> SessionResolver<D> for KeyResolver {
235    async fn resolve(
236        &self,
237        ctx: &Ctx<D>,
238        headers: &HeaderMap,
239    ) -> Result<Option<Resolved>, AuthError> {
240        let Some(key) = self.0.key_from(headers) else {
241            return Ok(None);
242        };
243        if key.len() < self.0.key_length {
244            return Err(AuthError::new(
245                StatusCode::FORBIDDEN,
246                "INVALID_API_KEY",
247                "Invalid API key.",
248            ));
249        }
250        let row = verify(ctx, &self.0, &key, None).await?;
251        Ok(Some(Resolved::User(row.user_id)))
252    }
253}