1mod metadata_sort;
2
3use super::ApiKeyPlugin;
4use super::types::{
5 ApiKeyView, CreateKeyRequest, CreateKeyResponse, DeleteKeyRequest, ListKeysQuery,
6 ListKeysResponse, UpdateKeyRequest,
7};
8use crate::helpers;
9use alibi_core::{ApiKey, AuthContext, AuthResult, CreateApiKey, UpdateApiKey};
10
11impl ApiKeyPlugin {
12 pub async fn create_key(
19 &self,
20 ctx: &AuthContext<impl alibi_core::AuthSchema>,
21 body: &CreateKeyRequest,
22 ) -> AuthResult<CreateKeyResponse> {
23 use validator::Validate as _;
24 body.validate()
25 .map_err(|error| alibi_core::AuthError::Validation(error.to_string()))?;
26 let user_id = body
27 .user_id
28 .as_deref()
29 .filter(|id| !id.is_empty())
30 .ok_or_else(|| super::api_key_error(super::ApiKeyErrorCode::UnauthorizedSession))?;
31 create_key_for_user(body, user_id, self, ctx, None).await
32 }
33
34 pub async fn update_key(
41 &self,
42 ctx: &AuthContext<impl alibi_core::AuthSchema>,
43 body: &UpdateKeyRequest,
44 ) -> AuthResult<ApiKeyView> {
45 use validator::Validate as _;
46 body.validate()
47 .map_err(|error| alibi_core::AuthError::Validation(error.to_string()))?;
48 let user_id = body
49 .user_id
50 .as_deref()
51 .filter(|id| !id.is_empty())
52 .ok_or_else(|| super::api_key_error(super::ApiKeyErrorCode::UnauthorizedSession))?;
53 update_key_for_user(body, user_id, self, ctx).await
54 }
55}
56
57pub(super) fn check_permissions(
64 key_permissions_json: &str,
65 required: &serde_json::Value,
66) -> AuthResult<bool> {
67 use alibi_core::utils::json::{JsValue, parse_value};
68 let Some(required_map) = required.as_object().filter(|map| !map.is_empty()) else {
69 return Ok(false);
70 };
71 let Ok(permitted) = parse_value(key_permissions_json) else {
72 return Ok(false);
73 };
74 if !json_truthy(&permitted) {
75 return Ok(false);
76 }
77 for (resource, requested) in required_map {
78 let allowed = permitted.get(resource).or_else(|| {
79 let index = resource.parse::<usize>().ok()?;
80 (index.to_string() == *resource)
81 .then(|| permitted.as_array()?.get(index))
82 .flatten()
83 });
84 let Some(allowed) = allowed.filter(|value| json_truthy(value)) else {
85 return Ok(false);
86 };
87 let (actions, any) = if let Some(actions) = requested.as_array() {
88 (actions.as_slice(), false)
89 } else if let Some(request) = requested.as_object() {
90 let Some(actions) = request.get("actions").and_then(serde_json::Value::as_array) else {
91 return Ok(false);
92 };
93 (
94 actions.as_slice(),
95 request.get("connector").and_then(serde_json::Value::as_str) == Some("OR"),
96 )
97 } else {
98 return Err(alibi_core::AuthError::internal(
99 "Invalid access control request",
100 ));
101 };
102 if actions.is_empty() {
103 return Ok(false);
104 }
105 let mut authorized = false;
106 for action in actions {
107 let admitted = if let Some(action) = action.as_str() {
108 match allowed {
109 JsValue::Array(values) => values.iter().any(|value| {
110 value
111 .as_str()
112 .is_some_and(|value| value == action && !revived_permission_date(value))
113 }),
114 JsValue::String(value) if !revived_permission_date(value) => {
115 value.contains(action)
116 }
117 JsValue::Null
118 | JsValue::Bool(_)
119 | JsValue::Number(_)
120 | JsValue::Object(_)
121 | JsValue::String(_) => {
122 return Err(alibi_core::AuthError::internal(
123 "Stored permission actions do not support includes",
124 ));
125 }
126 }
127 } else {
128 false
129 };
130 if any && admitted {
131 authorized = true;
132 break;
133 }
134 if !any && !admitted {
135 return Ok(false);
136 }
137 authorized |= admitted;
138 }
139 if !authorized {
140 return Ok(false);
141 }
142 }
143 Ok(true)
144}
145
146fn revived_permission_date(value: &str) -> bool {
150 alibi_core::utils::datetime::normalize_json_date(value).is_some()
151}
152
153pub(crate) async fn create_key_core(
154 body: &CreateKeyRequest,
155 user_id: impl AsRef<str>,
156 plugin: &ApiKeyPlugin,
157 ctx: &AuthContext<impl alibi_core::AuthSchema>,
158 request: Option<&alibi_core::AuthRequest>,
159) -> AuthResult<CreateKeyResponse> {
160 _ = plugin.resolve_configuration(body.config_id.as_deref())?;
161 if body.refill_amount.is_some()
162 || body.refill_interval.is_some()
163 || body.rate_limit_max.is_some()
164 || body.rate_limit_time_window.is_some()
165 || body.rate_limit_enabled.is_some()
166 || body.permissions.is_some()
167 || body.remaining.is_some()
168 {
169 return Err(super::api_key_error(
170 super::ApiKeyErrorCode::ServerOnlyProperty,
171 ));
172 }
173 if body.user_id.is_some() {
174 return Err(super::api_key_error(
175 super::ApiKeyErrorCode::UnauthorizedSession,
176 ));
177 }
178 create_key_for_user(body, user_id.as_ref(), plugin, ctx, request).await
179}
180
181#[expect(
182 clippy::too_many_lines,
183 reason = "Keep key policy checks, hook callbacks, and persistence in their observable request order"
184)]
185pub(super) async fn create_key_for_user(
186 body: &CreateKeyRequest,
187 user_id: &str,
188 plugin: &ApiKeyPlugin,
189 ctx: &AuthContext<impl alibi_core::AuthSchema>,
190 request: Option<&alibi_core::AuthRequest>,
191) -> AuthResult<CreateKeyResponse> {
192 let config = plugin.resolve_configuration(body.config_id.as_deref())?;
193 let reference_id = match config.references {
194 super::ApiKeyReferences::User => user_id.to_owned(),
195 super::ApiKeyReferences::Organization => {
196 let organization_id = body
197 .organization_id
198 .as_deref()
199 .filter(|id| !id.is_empty())
200 .ok_or_else(|| {
201 super::api_key_error(super::ApiKeyErrorCode::OrganizationIdRequired)
202 })?;
203 helpers::require_org_api_key_permission(ctx, user_id, organization_id, "create")
204 .await?;
205 organization_id.to_owned()
206 }
207 };
208
209 ApiKeyPlugin::validate_metadata(config, body.metadata.as_ref())?;
210 ApiKeyPlugin::validate_refill(
211 body.refill_interval.filter(|value| *value != 0.0),
212 body.refill_amount.filter(|value| *value != 0.0),
213 )?;
214 let effective_expires_in = ApiKeyPlugin::validate_expires_in(config, body.expires_in)?;
215 ApiKeyPlugin::validate_prefix(config, body.prefix.as_deref())?;
216 ApiKeyPlugin::validate_name(config, body.name.as_deref(), true)?;
217
218 plugin.maybe_delete_expired(ctx).await?;
219 let (full_key, hash, start) = if let Some(generator) = &config.custom_key_generator {
220 let full_key = generator
221 .generate_key(&super::ApiKeyGenerationOptions {
222 length: config.key_length,
223 prefix: body
224 .prefix
225 .as_deref()
226 .filter(|prefix| !prefix.is_empty())
227 .or(config.prefix.as_deref()),
228 })
229 .await?;
230 let hash = if config.disable_key_hashing {
231 full_key.clone()
232 } else {
233 ApiKeyPlugin::hash_key(&full_key)
234 };
235 let start = ApiKeyPlugin::starting_characters(&full_key, config.starting_characters_length);
236 (full_key, hash, start)
237 } else {
238 ApiKeyPlugin::generate_key(config, body.prefix.as_deref())?
239 };
240 let dynamic_permissions = match &config.default_permissions_callback {
241 Some(callback) => Some(
242 callback
243 .default_permissions(
244 &reference_id,
245 &super::ApiKeyCallbackContext::new(request, ctx, &config.config_id),
246 )
247 .await?,
248 ),
249 None => None,
250 };
251 let input = CreateApiKey {
252 reference_id,
253 config_id: config.config_id.clone(),
254 name: body.name.clone(),
255 prefix: body.prefix.clone().or_else(|| config.prefix.clone()),
256 key_hash: hash,
257 start: config.store_starting_characters.then_some(start),
258 expires_at: expiration_date(effective_expires_in)?,
259 remaining: body.remaining,
260 rate_limit_enabled: body.rate_limit_enabled.unwrap_or(config.rate_limit.enabled),
261 rate_limit_time_window: body
262 .rate_limit_time_window
263 .or(Some(config.rate_limit.time_window)),
264 rate_limit_max: body.rate_limit_max.or(Some(config.rate_limit.max_requests)),
265 refill_interval: body.refill_interval,
266 refill_amount: body.refill_amount,
267 permissions: body
268 .permissions
269 .as_ref()
270 .or(dynamic_permissions.as_ref())
271 .or(config.default_permissions.as_ref())
272 .map(alibi_core::utils::json::to_string)
273 .transpose()?,
274 metadata: Some(alibi_core::utils::json::to_string(
277 body.metadata
278 .as_ref()
279 .filter(|value| json_truthy(value))
280 .unwrap_or(&alibi_core::utils::json::JsValue::Null),
281 )?),
282 enabled: true,
283 };
284 let api_key = config.create_stored_key(ctx, input).await?;
285 let mut api_key = ApiKeyView::from(&api_key);
286 api_key.metadata = body
288 .metadata
289 .as_ref()
290 .map(alibi_core::utils::json::JsValue::to_json_value)
291 .transpose()?;
292 Ok(CreateKeyResponse {
293 key: full_key,
294 api_key,
295 })
296}
297
298fn json_truthy(value: &alibi_core::utils::json::JsValue) -> bool {
299 use alibi_core::utils::json::JsValue;
300 match value {
301 JsValue::Null => false,
302 JsValue::Bool(value) => *value,
303 JsValue::Number(value) => *value != 0.0 && !value.is_nan(),
304 JsValue::String(value) => !value.is_empty(),
305 JsValue::Array(_) | JsValue::Object(_) => true,
306 }
307}
308
309#[expect(
310 clippy::as_conversions,
311 clippy::cast_possible_truncation,
312 clippy::cast_precision_loss,
313 reason = "JavaScript-compatible numbers deliberately retain IEEE754 rounding and guarded integer coercion at the wire or adapter boundary"
314)]
315fn expiration_date(seconds: Option<f64>) -> AuthResult<Option<String>> {
316 let Some(seconds) = seconds.filter(|seconds| *seconds != 0.0 && !seconds.is_nan()) else {
317 return Ok(None);
318 };
319 let milliseconds = chrono::Utc::now().timestamp_millis() as f64 + seconds * 1000.0;
320 if !milliseconds.is_finite() || milliseconds.abs() > 8_640_000_000_000_000.0 {
321 return Err(alibi_core::AuthError::internal("Invalid Date"));
322 }
323 let date = chrono::DateTime::from_timestamp_millis(milliseconds.trunc() as i64)
324 .ok_or_else(|| alibi_core::AuthError::internal("Invalid Date"))?;
325 Ok(Some(
326 date.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
327 ))
328}
329
330pub(crate) async fn get_key_core(
331 id: &str,
332 config_id: Option<&str>,
333 user_id: impl AsRef<str>,
334 plugin: &ApiKeyPlugin,
335 ctx: &AuthContext<impl alibi_core::AuthSchema>,
336) -> AuthResult<ApiKeyView> {
337 let config = plugin.resolve_configuration(config_id)?;
338 let api_key = helpers::get_owned_api_key(ctx, config, id, user_id.as_ref(), "read").await?;
339 plugin.maybe_delete_expired(ctx).await?;
340 Ok(ApiKeyView::from(&api_key))
341}
342
343pub(crate) async fn list_keys_core(
344 user_id: impl AsRef<str>,
345 query: &ListKeysQuery,
346 plugin: &ApiKeyPlugin,
347 ctx: &AuthContext<impl alibi_core::AuthSchema>,
348) -> AuthResult<ListKeysResponse> {
349 let organization_id = query.organization_id.as_deref().filter(|id| !id.is_empty());
350 if let Some(organization_id) = organization_id {
351 helpers::require_org_api_key_permission(ctx, user_id.as_ref(), organization_id, "read")
352 .await?;
353 }
354 let reference_id = query
355 .organization_id
356 .as_deref()
357 .unwrap_or_else(|| user_id.as_ref());
358 let references = if organization_id.is_some() {
359 super::ApiKeyReferences::Organization
360 } else {
361 super::ApiKeyReferences::User
362 };
363 let config_id = query.config_id.as_deref().filter(|id| !id.is_empty());
364 if config_id.is_some() {
365 _ = plugin.resolve_configuration(config_id)?;
366 }
367
368 let keys = if let Some(config_id) = config_id {
369 plugin
370 .resolve_configuration(Some(config_id))?
371 .list_stored_keys(
372 ctx,
373 reference_id,
374 query.sort_by.as_deref(),
375 query.sort_direction.as_deref(),
376 )
377 .await?
378 } else {
379 plugin
380 .list_storage_keys(
381 ctx,
382 reference_id,
383 query.sort_by.as_deref(),
384 query.sort_direction.as_deref(),
385 )
386 .await?
387 };
388 let mut views: Vec<ApiKeyView> = keys
389 .iter()
390 .filter(|key| {
391 let key_references = plugin
392 .configurations
393 .iter()
394 .find(|config| super::config_id_matches(&key.config_id, &config.config_id))
395 .map(|config| config.references)
396 .unwrap_or_default();
397 key.reference_id == reference_id
398 && key_references == references
399 && config_id.is_none_or(|id| super::config_id_matches(&key.config_id, id))
400 })
401 .map(ApiKeyView::from)
402 .collect();
403
404 let total = views.len();
405 if let Some(offset) = query.offset {
406 views = views.split_off(offset.min(views.len()));
407 }
408 if let Some(limit) = query.limit {
409 views.truncate(limit);
410 }
411 plugin.maybe_delete_expired(ctx).await?;
412 Ok(ListKeysResponse {
413 api_keys: views,
414 total,
415 limit: query.limit,
416 offset: query.offset,
417 })
418}
419
420fn compare_numbers(left: Option<f64>, right: Option<f64>) -> std::cmp::Ordering {
421 match (left, right) {
422 (Some(left), Some(right)) => left.total_cmp(&right),
423 (None, None) => std::cmp::Ordering::Equal,
424 (None, Some(_)) => std::cmp::Ordering::Less,
425 (Some(_), None) => std::cmp::Ordering::Greater,
426 }
427}
428
429fn compare_strings(
430 left: Option<&str>,
431 right: Option<&str>,
432 from_database: bool,
433) -> std::cmp::Ordering {
434 match (left, right) {
435 (Some(left), Some(right)) if !from_database => {
436 left.encode_utf16().cmp(right.encode_utf16())
437 }
438 _ => left.cmp(&right),
439 }
440}
441
442fn compare_metadata(left: Option<&str>, right: Option<&str>) -> AuthResult<std::cmp::Ordering> {
443 use alibi_core::utils::{
444 javascript::string_to_number,
445 json::{JsValue, parse_value},
446 };
447 let left = left.map(parse_value).transpose()?.unwrap_or(JsValue::Null);
448 let right = right.map(parse_value).transpose()?.unwrap_or(JsValue::Null);
449 match (left.is_null(), right.is_null()) {
450 (true, true) => return Ok(std::cmp::Ordering::Equal),
451 (true, false) => return Ok(std::cmp::Ordering::Less),
452 (false, true) => return Ok(std::cmp::Ordering::Greater),
453 (false, false) => {}
454 }
455 let primitive = |value: JsValue| match value {
456 JsValue::Array(_) | JsValue::Object(_) => value
457 .coerce_string()
458 .map(JsValue::String)
459 .map_err(alibi_core::AuthError::internal),
460 value => Ok(value),
461 };
462 let left = primitive(left)?;
463 let right = primitive(right)?;
464 if let (JsValue::String(left), JsValue::String(right)) = (&left, &right) {
465 return Ok(compare_strings(Some(left), Some(right), false));
466 }
467 let number = |value: &JsValue| match value {
468 JsValue::Null => Some(0.0),
469 JsValue::Bool(value) => Some(f64::from(*value)),
470 JsValue::Number(value) => Some(*value),
471 JsValue::String(value) => string_to_number(value),
472 JsValue::Array(_) | JsValue::Object(_) => None,
473 };
474 Ok(number(&left)
475 .zip(number(&right))
476 .and_then(|(left, right)| left.partial_cmp(&right))
477 .unwrap_or(std::cmp::Ordering::Equal))
478}
479
480pub(super) fn sort_keys(
481 keys: &mut [ApiKey],
482 sort_by: &str,
483 direction: Option<&str>,
484 from_database: bool,
485) -> AuthResult<()> {
486 if sort_by == "metadata" && !from_database {
487 return metadata_sort::sort(keys, direction);
488 }
489 keys.sort_by(|left, right| {
490 let a = ApiKeyView::from(left);
491 let b = ApiKeyView::from(right);
492 let strings = |left, right| compare_strings(left, right, from_database);
493 let ordering = match sort_by {
494 "key" => strings(Some(&left.key_hash), Some(&right.key_hash)),
495 "id" => strings(Some(&a.id), Some(&b.id)),
496 "name" => strings(a.name.as_deref(), b.name.as_deref()),
497 "start" => strings(a.start.as_deref(), b.start.as_deref()),
498 "prefix" => strings(a.prefix.as_deref(), b.prefix.as_deref()),
499 "referenceId" => strings(Some(&a.reference_id), Some(&b.reference_id)),
500 "configId" => strings(Some(&a.config_id), Some(&b.config_id)),
501 "permissions" => strings(left.permissions.as_deref(), right.permissions.as_deref()),
502 "metadata" => strings(left.metadata.as_deref(), right.metadata.as_deref()),
503 "enabled" => a.enabled.cmp(&b.enabled),
504 "rateLimitEnabled" => a.rate_limit_enabled.cmp(&b.rate_limit_enabled),
505 "createdAt" => a.created_at.cmp(&b.created_at),
506 "updatedAt" => a.updated_at.cmp(&b.updated_at),
507 "expiresAt" => a.expires_at.cmp(&b.expires_at),
508 "lastRequest" => a.last_request.cmp(&b.last_request),
509 "lastRefillAt" => a.last_refill_at.cmp(&b.last_refill_at),
510 "remaining" => compare_numbers(a.remaining, b.remaining),
511 "requestCount" => compare_numbers(a.request_count, b.request_count),
512 "rateLimitMax" => compare_numbers(a.rate_limit_max, b.rate_limit_max),
513 "rateLimitTimeWindow" => {
514 compare_numbers(a.rate_limit_time_window, b.rate_limit_time_window)
515 }
516 "refillAmount" => compare_numbers(a.refill_amount, b.refill_amount),
517 "refillInterval" => compare_numbers(a.refill_interval, b.refill_interval),
518 _ => std::cmp::Ordering::Equal,
519 };
520 if direction == Some("desc") {
521 ordering.reverse()
522 } else {
523 ordering
524 }
525 });
526 Ok(())
527}
528
529pub(crate) async fn update_key_core(
530 body: &UpdateKeyRequest,
531 user_id: impl AsRef<str>,
532 plugin: &ApiKeyPlugin,
533 ctx: &AuthContext<impl alibi_core::AuthSchema>,
534) -> AuthResult<ApiKeyView> {
535 if body
536 .user_id
537 .as_deref()
538 .is_some_and(|id| !id.is_empty() && id != user_id.as_ref())
539 {
540 return Err(super::api_key_error(
541 super::ApiKeyErrorCode::UnauthorizedSession,
542 ));
543 }
544 if body.refill_amount.is_some()
545 || body.refill_interval.is_some()
546 || body.rate_limit_max.is_some()
547 || body.rate_limit_time_window.is_some()
548 || body.rate_limit_enabled.is_some()
549 || body.remaining.is_some()
550 || body.permissions.is_some()
551 {
552 return Err(super::api_key_error(
553 super::ApiKeyErrorCode::ServerOnlyProperty,
554 ));
555 }
556 update_key_for_user(body, user_id.as_ref(), plugin, ctx).await
557}
558
559pub(super) async fn update_key_for_user(
560 body: &UpdateKeyRequest,
561 user_id: &str,
562 plugin: &ApiKeyPlugin,
563 ctx: &AuthContext<impl alibi_core::AuthSchema>,
564) -> AuthResult<ApiKeyView> {
565 let config = plugin.resolve_configuration(body.config_id.as_deref())?;
566 _ = helpers::get_owned_api_key(ctx, config, &body.key_id, user_id, "update").await?;
567 ApiKeyPlugin::validate_name(config, body.name.as_deref(), false)?;
568
569 let expires_at = match body.expires_in {
570 None => None,
571 Some(_) if config.key_expiration.disable_custom_expires_time => {
572 return Err(super::api_key_error(
573 super::ApiKeyErrorCode::KeyDisabledExpiration,
574 ));
575 }
576 Some(None) => Some(None),
577 Some(Some(seconds)) => {
578 let validated = ApiKeyPlugin::validate_expires_in(config, Some(seconds))?;
579 Some(expiration_date(validated)?)
580 }
581 };
582 let metadata = body.metadata.as_ref().filter(|_| config.enable_metadata);
583 if let Some(metadata) = metadata
584 && !(metadata.is_null() || metadata.is_object() || metadata.is_array())
585 {
586 return Err(super::api_key_error(
587 super::ApiKeyErrorCode::InvalidMetadataType,
588 ));
589 }
590 ApiKeyPlugin::validate_refill(body.refill_interval, body.refill_amount)?;
591 if body.name.is_none()
592 && body.enabled.is_none()
593 && expires_at.is_none()
594 && metadata.is_none()
595 && body.remaining.is_none()
596 && body.refill_amount.is_none()
597 && body.refill_interval.is_none()
598 && body.rate_limit_enabled.is_none()
599 && body.rate_limit_time_window.is_none()
600 && body.rate_limit_max.is_none()
601 && body.permissions.is_none()
602 {
603 return Err(super::api_key_error(
604 super::ApiKeyErrorCode::NoValuesToUpdate,
605 ));
606 }
607 let update = UpdateApiKey {
608 name: body.name.clone(),
609 enabled: body.enabled,
610 remaining: body.remaining,
611 rate_limit_enabled: body.rate_limit_enabled,
612 rate_limit_time_window: body.rate_limit_time_window,
613 rate_limit_max: body.rate_limit_max,
614 refill_interval: body.refill_interval,
615 refill_amount: body.refill_amount,
616 permissions: body
617 .permissions
618 .as_ref()
619 .map(alibi_core::utils::json::to_string)
620 .transpose()?,
621 metadata: metadata
622 .map(alibi_core::utils::json::to_string)
623 .transpose()?,
624 expires_at,
625 ..Default::default()
626 };
627 let updated = config.update_stored_key(ctx, &body.key_id, update).await?;
628 plugin.maybe_delete_expired(ctx).await?;
629 Ok(ApiKeyView::from(&updated))
630}
631
632pub(crate) async fn delete_key_core(
633 body: &DeleteKeyRequest,
634 user_id: impl AsRef<str>,
635 plugin: &ApiKeyPlugin,
636 ctx: &AuthContext<impl alibi_core::AuthSchema>,
637) -> AuthResult<serde_json::Value> {
638 let config = plugin.resolve_configuration(body.config_id.as_deref())?;
639 let key =
640 helpers::get_owned_api_key(ctx, config, &body.key_id, user_id.as_ref(), "delete").await?;
641 config.remove_key(ctx, &key).await?;
642 plugin.maybe_delete_expired(ctx).await?;
643 Ok(serde_json::json!({ "success": true }))
644}