1mod 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86struct RateLimitDefaults {
87 enabled: bool,
88 window: Duration,
89 max: i64,
90}
91
92#[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 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 pub fn default_prefix(mut self, prefix: impl Into<String>) -> Self {
165 self.default_prefix = Some(prefix.into());
166 self
167 }
168
169 pub fn start_length(mut self, length: usize) -> Self {
172 self.start_length = length;
173 self
174 }
175
176 pub fn default_expires_in(mut self, ttl: Duration) -> Self {
178 self.default_expires_in = Some(ttl);
179 self
180 }
181
182 pub fn min_expires_in(mut self, min: Duration) -> Self {
184 self.min_expires_in = min;
185 self
186 }
187
188 pub fn max_expires_in(mut self, max: Duration) -> Self {
190 self.max_expires_in = max;
191 self
192 }
193
194 pub fn enable_metadata(mut self, enabled: bool) -> Self {
196 self.enable_metadata = enabled;
197 self
198 }
199
200 pub fn require_name(mut self, required: bool) -> Self {
202 self.require_name = required;
203 self
204 }
205
206 pub fn default_permissions(mut self, permissions: Permissions) -> Self {
208 self.default_permissions = Some(permissions);
209 self
210 }
211
212 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 pub fn disable_rate_limit(mut self) -> Self {
222 self.rate_limit.enabled = false;
223 self
224 }
225
226 pub fn header(mut self, name: HeaderName) -> Self {
228 self.header = name;
229 self
230 }
231
232 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 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#[derive(Clone, Debug, PartialEq, Eq)]
290pub struct ApiKeyCreated {
291 pub id: Id,
292 pub user_id: Id,
293}
294
295#[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
305pub 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
321pub 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 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 pub async fn create(&self, input: CreateApiKeyInput) -> Result<CreatedApiKey, AuthError> {
359 self.call(&CreateApiKey::server(self.plugin.clone()), input)
360 .await
361 }
362
363 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 pub async fn get(&self, input: GetApiKeyInput) -> Result<ApiKeyView, AuthError> {
379 self.call(&GetApiKey::server(), input).await
380 }
381
382 pub async fn update(&self, input: UpdateApiKeyInput) -> Result<ApiKeyView, AuthError> {
384 self.call(&UpdateApiKey::server(self.plugin.clone()), input)
385 .await
386 }
387
388 pub async fn delete(&self, input: DeleteApiKeyInput) -> Result<Success, AuthError> {
390 self.call(&DeleteApiKey::server(), input).await
391 }
392
393 pub async fn list(&self, input: ListApiKeysInput) -> Result<ApiKeyList, AuthError> {
395 self.call(&ListApiKeys::server(), input).await
396 }
397
398 pub async fn delete_all_expired(&self) -> Result<DeleteExpiredOutput, AuthError> {
400 self.call(&DeleteAllExpiredApiKeys, Empty {}).await
401 }
402}