Skip to main content

fastauth_plugin_api_key/
lib.rs

1//! API keys for [fastauth](https://github.com/lassejlv/fastauth): per-user keys with expiry,
2//! usage limits that refill, per-key rate limits and permissions. The routes, JSON and error
3//! codes match Better Auth's `apiKey` plugin, so its `apiKeyClient` works unchanged.
4//!
5//! Only the SHA-256 of a key is stored; `/api-key/create` returns the key once. With
6//! `.sessions(true)`, a request carrying a key in `x-api-key` (or the configured header) gets
7//! a session for the key's owner that exists only for that request, so every
8//! `Session<AppAuth>` extractor accepts API keys with no handler changes. Each such request
9//! counts against the key's rate limit (10 per day by default; see `ApiKeys::rate_limit`).
10//!
11//! ```
12//! use fastauth_core::prelude::*;
13//! use fastauth_plugin_api_key::{ApiKeys, ApiKeysExt, CreateApiKeyInput};
14//!
15//! # tokio_test(async {
16//! let auth: Auth<MemoryAdapter, (), plugins![ApiKeys]> = FastAuth::builder()
17//!     .secret(Secret::from_bytes(vec![1u8; 32]))
18//!     .base_url("http://localhost:3000")
19//!     .database(MemoryAdapter::new())
20//!     .email_password(EmailPassword::default())
21//!     .plugin(ApiKeys::new().default_prefix("ak_"))
22//!     .build()?;
23//! # let user = auth.api().create_user(fastauth_core::routes::CreateUserInput {
24//! #     email: "ada@example.com".into(), name: "Ada".into(), ..Default::default()
25//! # }).await?;
26//! let created = auth
27//!     .api_keys()
28//!     .create(CreateApiKeyInput {
29//!         name: Some("ci".into()),
30//!         user_id: Some(user.id.clone()),
31//!         ..Default::default()
32//!     })
33//!     .await?;
34//! assert!(created.key.starts_with("ak_"));
35//!
36//! let verified = auth.api_keys().verify(&created.key, None).await?;
37//! assert!(verified.valid);
38//! # Ok::<(), Box<dyn std::error::Error>>(())
39//! # });
40//! # fn tokio_test<F: std::future::Future>(f: F) -> F::Output {
41//! #     tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(f)
42//! # }
43//! ```
44//!
45//! Without the plugin registered, `auth.api_keys()` doesn't compile:
46//!
47//! ```compile_fail
48//! use fastauth_core::prelude::*;
49//! use fastauth_plugin_api_key::ApiKeysExt;
50//!
51//! let auth: Auth<MemoryAdapter> = FastAuth::builder()
52//!     .secret(Secret::from_bytes(vec![1u8; 32]))
53//!     .base_url("http://localhost:3000")
54//!     .database(MemoryAdapter::new())
55//!     .build()
56//!     .unwrap();
57//! let _keys = auth.api_keys();
58//! ```
59//!
60//! Fields that change what a key may do (`remaining`, `refill*`, `rateLimit*`,
61//! `permissions`) are server-only: over HTTP they answer `SERVER_ONLY_PROPERTY`, through
62//! `auth.api_keys()` they are accepted. `/api-key/verify` and
63//! `/api-key/delete-all-expired-api-keys` have no HTTP route, as in Better Auth.
64
65mod endpoints;
66mod error;
67mod model;
68mod verify;
69
70use fastauth_core::plugin_prelude::*;
71use http::HeaderName;
72
73pub use endpoints::{
74    ApiKeyList, ApiKeyView, CreateApiKey, CreateApiKeyInput, CreatedApiKey,
75    DeleteAllExpiredApiKeys, DeleteApiKey, DeleteApiKeyInput, DeleteExpiredOutput, GetApiKey,
76    GetApiKeyInput, ListApiKeys, ListApiKeysInput, SortDirection, Success, UpdateApiKey,
77    UpdateApiKeyInput, VerifyApiKey, VerifyApiKeyInput, VerifyError, VerifyOutput,
78};
79pub use error::ApiKeyError;
80pub use model::{ApiKey, Permissions};
81
82type KeyGetter = Arc<dyn Fn(&HeaderMap) -> Option<String> + Send + Sync>;
83
84/// The defaults new keys get for their per-key rate limit.
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86struct RateLimitDefaults {
87    enabled: bool,
88    window: Duration,
89    max: i64,
90}
91
92/// The API key plugin: `.plugin(ApiKeys::new().default_prefix("ak_"))`.
93///
94/// Defaults match Better Auth: 64-character keys with no prefix, the first 6 characters
95/// stored as `start`, no default expiry, `expiresIn` between 1 and 365 days, metadata off,
96/// a rate limit of 10 verifications per day per key, and no sessions from keys until
97/// `.sessions(true)`.
98#[derive(Clone)]
99pub struct ApiKeys {
100    key_length: usize,
101    default_prefix: Option<String>,
102    start_length: usize,
103    default_expires_in: Option<Duration>,
104    min_expires_in: Duration,
105    max_expires_in: Duration,
106    enable_metadata: bool,
107    require_name: bool,
108    default_permissions: Option<Permissions>,
109    rate_limit: RateLimitDefaults,
110    header: HeaderName,
111    getter: Option<KeyGetter>,
112    sessions: bool,
113}
114
115impl std::fmt::Debug for ApiKeys {
116    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117        f.debug_struct("ApiKeys")
118            .field("key_length", &self.key_length)
119            .field("default_prefix", &self.default_prefix)
120            .field("header", &self.header)
121            .field("sessions", &self.sessions)
122            .finish_non_exhaustive()
123    }
124}
125
126impl Default for ApiKeys {
127    fn default() -> Self {
128        Self {
129            key_length: 64,
130            default_prefix: None,
131            start_length: 6,
132            default_expires_in: None,
133            min_expires_in: Duration::days(1),
134            max_expires_in: Duration::days(365),
135            enable_metadata: false,
136            require_name: false,
137            default_permissions: None,
138            rate_limit: RateLimitDefaults {
139                enabled: true,
140                window: Duration::days(1),
141                max: 10,
142            },
143            header: HeaderName::from_static("x-api-key"),
144            getter: None,
145            sessions: false,
146        }
147    }
148}
149
150impl ApiKeys {
151    pub fn new() -> Self {
152        Self::default()
153    }
154
155    /// Random characters per key, after the prefix (default 64). Keys shorter than this are
156    /// refused by the session resolver with 403 `INVALID_API_KEY` before any lookup.
157    pub fn key_length(mut self, length: usize) -> Self {
158        assert!(length >= 16, "API keys need at least 16 random characters");
159        self.key_length = length;
160        self
161    }
162
163    /// The prefix keys start with unless the create request names one, e.g. `"ak_"`.
164    pub fn default_prefix(mut self, prefix: impl Into<String>) -> Self {
165        self.default_prefix = Some(prefix.into());
166        self
167    }
168
169    /// How many leading characters of each key are stored as `start` (default 6; 0 stores
170    /// none).
171    pub fn start_length(mut self, length: usize) -> Self {
172        self.start_length = length;
173        self
174    }
175
176    /// The expiry of keys created without `expiresIn` (default: never).
177    pub fn default_expires_in(mut self, ttl: Duration) -> Self {
178        self.default_expires_in = Some(ttl);
179        self
180    }
181
182    /// The smallest `expiresIn` a create or update may ask for (default 1 day).
183    pub fn min_expires_in(mut self, min: Duration) -> Self {
184        self.min_expires_in = min;
185        self
186    }
187
188    /// The largest `expiresIn` a create or update may ask for (default 365 days).
189    pub fn max_expires_in(mut self, max: Duration) -> Self {
190        self.max_expires_in = max;
191        self
192    }
193
194    /// Lets keys carry a JSON object of `metadata` (default off).
195    pub fn enable_metadata(mut self, enabled: bool) -> Self {
196        self.enable_metadata = enabled;
197        self
198    }
199
200    /// Refuses creates without a `name` with `NAME_REQUIRED` (default off).
201    pub fn require_name(mut self, required: bool) -> Self {
202        self.require_name = required;
203        self
204    }
205
206    /// The permissions keys created without `permissions` get.
207    pub fn default_permissions(mut self, permissions: Permissions) -> Self {
208        self.default_permissions = Some(permissions);
209        self
210    }
211
212    /// The per-key rate limit new keys get: `max` verifications per `window`
213    /// (default 10 per day). The server API can set other values per key.
214    pub fn rate_limit(mut self, window: Duration, max: i64) -> Self {
215        self.rate_limit.window = window;
216        self.rate_limit.max = max;
217        self
218    }
219
220    /// Turns per-key rate limiting off for every key, whatever the key says.
221    pub fn disable_rate_limit(mut self) -> Self {
222        self.rate_limit.enabled = false;
223        self
224    }
225
226    /// The header the session resolver reads keys from (default `x-api-key`).
227    pub fn header(mut self, name: HeaderName) -> Self {
228        self.header = name;
229        self
230    }
231
232    /// Reads the key from the request some other way (e.g. `Authorization: Bearer`).
233    /// Replaces the header lookup.
234    pub fn key_getter(
235        mut self,
236        getter: impl Fn(&HeaderMap) -> Option<String> + Send + Sync + 'static,
237    ) -> Self {
238        self.getter = Some(Arc::new(getter));
239        self
240    }
241
242    /// Whether requests carrying a key get a session for its owner, like Better Auth's
243    /// `enableSessionForAPIKeys` (default off). Off, keys are only checked through
244    /// `auth.api_keys().verify(..)`. On, every such request is a verification and counts
245    /// against the key's rate limit and `remaining`.
246    pub fn sessions(mut self, enabled: bool) -> Self {
247        self.sessions = enabled;
248        self
249    }
250
251    fn key_from(&self, headers: &HeaderMap) -> Option<String> {
252        match &self.getter {
253            Some(getter) => getter(headers),
254            None => headers
255                .get(&self.header)
256                .and_then(|v| v.to_str().ok())
257                .map(str::to_owned),
258        }
259        .filter(|key| !key.is_empty())
260    }
261}
262
263impl Plugin for ApiKeys {
264    const ID: &'static str = "api-key";
265    type Requires = ();
266    type UserFields = ();
267    type SessionFields = ();
268
269    fn schema(&self, schema: &mut SchemaBuilder) {
270        schema.model::<ApiKey>();
271    }
272
273    fn init<D: Adapter>(self: &Arc<Self>, app: &mut PluginBuilder<'_, D>) {
274        app.endpoint(CreateApiKey::client(self.clone()))
275            .endpoint(GetApiKey::client())
276            .endpoint(UpdateApiKey::client(self.clone()))
277            .endpoint(DeleteApiKey::client())
278            .endpoint(ListApiKeys::client())
279            .server_endpoint::<VerifyApiKey>()
280            .server_endpoint::<DeleteAllExpiredApiKeys>()
281            .errors::<ApiKeyError>();
282        if self.sessions {
283            app.session_resolver(verify::KeyResolver(self.clone()));
284        }
285    }
286}
287
288/// Emitted when a key is created.
289#[derive(Clone, Debug, PartialEq, Eq)]
290pub struct ApiKeyCreated {
291    pub id: Id,
292    pub user_id: Id,
293}
294
295/// Emitted when a key is deleted through `/api-key/delete`.
296#[derive(Clone, Debug, PartialEq, Eq)]
297pub struct ApiKeyDeleted {
298    pub id: Id,
299    pub user_id: Id,
300}
301
302impl Event for ApiKeyCreated {}
303impl Event for ApiKeyDeleted {}
304
305/// `auth.api_keys()`: the server API. Only compiles on an `Auth` with `ApiKeys` registered.
306pub trait ApiKeysExt: AuthInstance + Sized {
307    fn api_keys<I>(&self) -> ApiKeysApi<'_, Self>
308    where
309        Self: HasPlugin<ApiKeys, I>,
310    {
311        ApiKeysApi {
312            auth: self,
313            plugin: self.plugin_arc().clone(),
314            headers: HeaderMap::new(),
315        }
316    }
317}
318
319impl<A: AuthInstance> ApiKeysExt for A {}
320
321/// Calls the API key endpoints without HTTP, as the server: server-only fields are accepted,
322/// and `user_id` names the owner when no session is passed with `headers`.
323pub struct ApiKeysApi<'a, A> {
324    auth: &'a A,
325    plugin: Arc<ApiKeys>,
326    headers: HeaderMap,
327}
328
329impl<A> std::fmt::Debug for ApiKeysApi<'_, A> {
330    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
331        f.write_str("ApiKeysApi")
332    }
333}
334
335impl<A: AuthInstance> ApiKeysApi<'_, A> {
336    /// Acts for the session in these request headers. A `user_id` in an input must then
337    /// name the same user.
338    pub fn headers(mut self, headers: &HeaderMap) -> Self {
339        self.headers = headers.clone();
340        self
341    }
342
343    async fn call<E: Endpoint<A::Db>>(
344        &self,
345        endpoint: &E,
346        input: E::Input,
347    ) -> Result<E::Output, AuthError> {
348        Ok(self
349            .auth
350            .api()
351            .headers(&self.headers)
352            .call(endpoint, input)
353            .await?
354            .data)
355    }
356
357    /// Creates a key. The response's `key` is the only copy of it.
358    pub async fn create(&self, input: CreateApiKeyInput) -> Result<CreatedApiKey, AuthError> {
359        self.call(&CreateApiKey::server(self.plugin.clone()), input)
360            .await
361    }
362
363    /// Verifies `key` and counts the use against its limits. A refused key is
364    /// `Ok` with `valid: false` and the error; `Err` is for failures unrelated to the key.
365    pub async fn verify(
366        &self,
367        key: &str,
368        permissions: Option<Permissions>,
369    ) -> Result<VerifyOutput, AuthError> {
370        let input = VerifyApiKeyInput {
371            key: key.to_owned(),
372            permissions,
373        };
374        self.call(&VerifyApiKey(self.plugin.clone()), input).await
375    }
376
377    /// One key of its owner.
378    pub async fn get(&self, input: GetApiKeyInput) -> Result<ApiKeyView, AuthError> {
379        self.call(&GetApiKey::server(), input).await
380    }
381
382    /// Changes a key.
383    pub async fn update(&self, input: UpdateApiKeyInput) -> Result<ApiKeyView, AuthError> {
384        self.call(&UpdateApiKey::server(self.plugin.clone()), input)
385            .await
386    }
387
388    /// Deletes a key.
389    pub async fn delete(&self, input: DeleteApiKeyInput) -> Result<Success, AuthError> {
390        self.call(&DeleteApiKey::server(), input).await
391    }
392
393    /// The keys of one owner.
394    pub async fn list(&self, input: ListApiKeysInput) -> Result<ApiKeyList, AuthError> {
395        self.call(&ListApiKeys::server(), input).await
396    }
397
398    /// Deletes every expired key.
399    pub async fn delete_all_expired(&self) -> Result<DeleteExpiredOutput, AuthError> {
400        self.call(&DeleteAllExpiredApiKeys, Empty {}).await
401    }
402}