alibi-plugins 0.7.0

Built-in authentication plugins and API metadata for Alibi
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
use super::{
    ApiKeyCallbackContext, ApiKeyConfig, ApiKeyErrorCode, ApiKeyPlugin, ApiKeyReferences,
    config_id_matches,
};
use alibi_core::entity::AuthUser;
use alibi_core::store::ConsumeApiKeyResult;
use alibi_core::wire::{ApiKeyView, SessionView};
use alibi_core::{
    AuthContext, AuthError, AuthRequest, AuthResponse, AuthResult, BeforeRequestAction,
};
use serde::Serialize;

/// Inputs for server-only API key verification. Verification consumes one use.
pub struct VerifyApiKey<'a> {
    /// The plaintext API key presented by the caller.
    pub key: &'a str,
    /// Restrict verification to this configuration, or use the default lookup configuration.
    pub config_id: Option<&'a str>,
    /// Required resource permissions, checked before quota or rate-limit consumption.
    pub permissions: Option<&'a serde_json::Value>,
}

/// Additional information returned when a key reaches its rate limit.
#[derive(Debug, Serialize)]
pub struct ApiKeyErrorDetails {
    /// Milliseconds until the key's rate-limit window elapses.
    #[serde(rename = "tryAgainIn")]
    pub try_again_in: f64,
}

/// Upstream verification messages can contain either text or an error-code object.
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum ApiKeyErrorMessage {
    Text(String),
    CodeMessage {
        code: ApiKeyErrorCode,
        message: String,
    },
}

impl ApiKeyErrorMessage {
    fn text(&self) -> &str {
        match self {
            Self::Text(value) | Self::CodeMessage { message: value, .. } => value,
        }
    }
}

/// An API key rejection with the upstream error code and response fields.
#[derive(Debug, Serialize)]
pub struct ApiKeyValidationError {
    /// Stable upstream API key error code.
    pub code: ApiKeyErrorCode,
    /// Upstream error message.
    pub message: ApiKeyErrorMessage,
    /// Rate-limit timing, when the rejection is a rate limit.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<ApiKeyErrorDetails>,
}

impl ApiKeyValidationError {
    pub(super) fn new(code: ApiKeyErrorCode) -> Self {
        Self {
            code,
            message: ApiKeyErrorMessage::Text(code.message().to_owned()),
            details: None,
        }
    }

    pub(super) const fn status(&self) -> u16 {
        match self.code {
            ApiKeyErrorCode::NoDefaultConfiguration => 400,
            ApiKeyErrorCode::RateLimited | ApiKeyErrorCode::UsageExceeded => 429,
            ApiKeyErrorCode::InvalidApiKey
            | ApiKeyErrorCode::KeyDisabled
            | ApiKeyErrorCode::KeyExpired
            | ApiKeyErrorCode::KeyNotFound
            | ApiKeyErrorCode::UnauthorizedSession
            | ApiKeyErrorCode::InvalidPrefixLength
            | ApiKeyErrorCode::InvalidNameLength
            | ApiKeyErrorCode::MetadataDisabled
            | ApiKeyErrorCode::NoValuesToUpdate
            | ApiKeyErrorCode::KeyDisabledExpiration
            | ApiKeyErrorCode::ExpiresInTooSmall
            | ApiKeyErrorCode::ExpiresInTooLarge
            | ApiKeyErrorCode::InvalidRemaining
            | ApiKeyErrorCode::RefillAmountAndIntervalRequired
            | ApiKeyErrorCode::RefillIntervalAndAmountRequired
            | ApiKeyErrorCode::NameRequired
            | ApiKeyErrorCode::InvalidUserIdFromApiKey
            | ApiKeyErrorCode::InvalidReferenceIdFromApiKey
            | ApiKeyErrorCode::OrganizationIdRequired
            | ApiKeyErrorCode::OrganizationPluginRequired
            | ApiKeyErrorCode::UserNotMemberOfOrganization
            | ApiKeyErrorCode::InsufficientApiKeyPermissions
            | ApiKeyErrorCode::ServerOnlyProperty
            | ApiKeyErrorCode::FailedToUpdateApiKey
            | ApiKeyErrorCode::InvalidMetadataType => 401,
        }
    }

    fn response(&self) -> AuthResult<AuthResponse> {
        Ok(AuthResponse::json(self.status(), self)?)
    }
}

/// Distinguishes a rejected credential from a storage or infrastructure failure.
#[derive(Debug)]
pub enum ApiKeyVerificationError {
    /// The credential or its permissions, quota, or configuration was rejected.
    Validation(ApiKeyValidationError),
    /// An internal operation failed. The original typed error is preserved.
    Internal(AuthError),
    /// An explicitly selected validator failed before verification's catch
    /// boundary. Server endpoint adapters propagate this original typed error.
    ExplicitValidator(AuthError),
}

impl std::fmt::Display for ApiKeyVerificationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Validation(error) => f.write_str(error.message.text()),
            Self::Internal(error) | Self::ExplicitValidator(error) => {
                write!(f, "API key verification failed: {error}")
            }
        }
    }
}

impl std::error::Error for ApiKeyVerificationError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Internal(error) | Self::ExplicitValidator(error) => Some(error),
            Self::Validation(_) => None,
        }
    }
}

impl From<AuthError> for ApiKeyVerificationError {
    fn from(error: AuthError) -> Self {
        Self::Internal(error)
    }
}

impl From<ApiKeyErrorCode> for ApiKeyVerificationError {
    fn from(code: ApiKeyErrorCode) -> Self {
        Self::Validation(ApiKeyValidationError::new(code))
    }
}

impl ApiKeyPlugin {
    /// Verify a machine credential without a user session or public HTTP endpoint.
    ///
    /// A successful verification consumes quota and a rate-limit slot. Permissions
    /// and configuration mismatches do not consume usage. The returned key omits
    /// the plaintext credential and stored hash.
    ///
    /// Without `config_id`, lookup uses the default configuration's hashing
    /// setting. Validation then uses the configuration that issued the key.
    ///
    /// # Errors
    ///
    /// Returns an error if verification hooks or storage operations fail.
    pub async fn verify_api_key(
        &self,
        input: &VerifyApiKey<'_>,
        ctx: &AuthContext<impl alibi_core::AuthSchema>,
    ) -> Result<ApiKeyView, ApiKeyVerificationError> {
        self.verify_api_key_with_registration(input, None, ctx)
            .await
    }

    /// Verify with the actual caller request available to trusted predicates.
    /// This performs the same server-only verification operation as `verify_api_key`.
    ///
    /// # Errors
    ///
    /// Propagates verification-hook or storage errors for the supplied request.
    pub async fn verify_api_key_with_request(
        &self,
        input: &VerifyApiKey<'_>,
        request: &AuthRequest,
        ctx: &AuthContext<impl alibi_core::AuthSchema>,
    ) -> Result<ApiKeyView, ApiKeyVerificationError> {
        self.verify_api_key_with_registration(input, Some(request), ctx)
            .await
    }

    pub(super) async fn verify_api_key_with_registration(
        &self,
        input: &VerifyApiKey<'_>,
        request: Option<&AuthRequest>,
        ctx: &AuthContext<impl alibi_core::AuthSchema>,
    ) -> Result<ApiKeyView, ApiKeyVerificationError> {
        let view = self
            .verify_api_key_checked(input, request, ctx, true)
            .await?;
        if self
            .resolve_configuration(Some(&view.config_id))?
            .defer_updates
        {
            self.register_expired_cleanup(ctx).await?;
        }
        Ok(view)
    }

    pub(super) async fn verify_api_key_checked(
        &self,
        input: &VerifyApiKey<'_>,
        request: Option<&AuthRequest>,
        ctx: &AuthContext<impl alibi_core::AuthSchema>,
        server_operation: bool,
    ) -> Result<ApiKeyView, ApiKeyVerificationError> {
        let lookup_config = self
            .resolve_configuration(input.config_id)
            .map_err(|_error| ApiKeyErrorCode::NoDefaultConfiguration)?;
        if server_operation
            && input.config_id.is_some()
            && let Some(validator) = &lookup_config.custom_api_key_validator
            && !validator
                .validate(
                    &ApiKeyCallbackContext::new(request, ctx, &lookup_config.config_id)
                        .with_verification_input(input),
                    input.key,
                )
                .await
                .map_err(ApiKeyVerificationError::ExplicitValidator)?
        {
            return Err(ApiKeyVerificationError::Validation(ApiKeyValidationError {
                code: ApiKeyErrorCode::KeyNotFound,
                message: ApiKeyErrorMessage::CodeMessage {
                    code: ApiKeyErrorCode::InvalidApiKey,
                    message: ApiKeyErrorCode::InvalidApiKey.message().to_owned(),
                },
                details: None,
            }));
        }
        let hashed = if lookup_config.disable_key_hashing {
            input.key.to_owned()
        } else {
            Self::hash_key(input.key)
        };
        let api_key = lookup_config
            .read_key(ctx, &hashed, true)
            .await?
            .ok_or(ApiKeyErrorCode::InvalidApiKey)?;

        if input
            .config_id
            .is_some_and(|expected| !config_id_matches(&api_key.config_id, expected))
        {
            return Err(ApiKeyErrorCode::InvalidApiKey.into());
        }
        let config = self
            .resolve_configuration(Some(&api_key.config_id))
            .map_err(|_error| ApiKeyErrorCode::NoDefaultConfiguration)?;

        if server_operation
            && input.config_id.is_none()
            && let Some(validator) = &config.custom_api_key_validator
            && !validator
                .validate(
                    &ApiKeyCallbackContext::new(request, ctx, &config.config_id)
                        .with_verification_input(input),
                    input.key,
                )
                .await?
        {
            return Err(ApiKeyErrorCode::KeyNotFound.into());
        }

        if !api_key.enabled {
            return Err(ApiKeyErrorCode::KeyDisabled.into());
        }
        if let Some(expires_at) = api_key.expires_at.as_deref() {
            let expiration = chrono::DateTime::parse_from_rfc3339(expires_at).map_err(|error| {
                AuthError::internal(format!("Invalid stored API key expiration: {error}"))
            })?;
            if chrono::Utc::now() > expiration {
                Self::delete_rejected_key(&api_key, config, ctx).await?;
                return Err(ApiKeyErrorCode::KeyExpired.into());
            }
        }
        if let Some(required) = input.permissions {
            let permitted = match api_key.permissions.as_deref() {
                Some(permissions) => super::handlers::check_permissions(permissions, required)?,
                None => false,
            };
            if !permitted {
                return Err(ApiKeyErrorCode::KeyNotFound.into());
            }
        }

        // Source deletes only an initially observed zero/no-refill row.
        // A positive-snapshot loser of atomic consumption rejects without deletion.
        if api_key.remaining == Some(0.0) && api_key.refill_amount.is_none() {
            Self::delete_rejected_key(&api_key, config, ctx).await?;
            return Err(ApiKeyErrorCode::UsageExceeded.into());
        }

        if !config.uses_database() {
            let updated = Self::consume_secondary_usage(&api_key, config, ctx).await?;
            return Ok(ApiKeyView::from(&updated));
        }
        let updated = match ctx
            .database
            .consume_api_key_usage_from_snapshot(&api_key, config.rate_limit.enabled)
            .await?
        {
            ConsumeApiKeyResult::Allowed(key) => key,
            ConsumeApiKeyResult::RateLimited { try_again_in } => {
                let mut error = ApiKeyValidationError::new(ApiKeyErrorCode::RateLimited);
                error.details = Some(ApiKeyErrorDetails { try_again_in });
                return Err(ApiKeyVerificationError::Validation(error));
            }
            ConsumeApiKeyResult::UsageExhausted => {
                return Err(ApiKeyErrorCode::UsageExceeded.into());
            }
        };
        config.cache_key(updated.as_ref()).await?;
        Ok(ApiKeyView::from(updated.as_ref()))
    }

    async fn delete_rejected_key(
        key: &alibi_core::ApiKey,
        config: &ApiKeyConfig,
        ctx: &AuthContext<impl alibi_core::AuthSchema>,
    ) -> AuthResult<()> {
        if !config.defer_updates {
            return config.remove_key(ctx, key).await;
        }
        let database = std::sync::Arc::clone(&ctx.database);
        let key = key.clone();
        let config = config.clone();
        let storage = config.secondary();
        let completion = Self::start_background_work(async move {
            let deletion = async {
                if config.storage == super::ApiKeyStorageMode::SecondaryStorage {
                    let storage = storage
                        .ok_or_else(|| AuthError::internal("Secondary storage is required"))?;
                    super::storage::remove_storage(storage, &key, config.fallback_to_database)
                        .await?;
                }
                if config.uses_database() {
                    database.delete_api_key(&key.id).await?;
                }
                Ok::<_, AuthError>(())
            }
            .await;
            if let Err(error) = deletion {
                tracing::error!(%error, "Deferred update failed");
            }
            Ok(())
        })
        .await?;
        if let Some(handler) = &ctx.config.background_tasks {
            handler.handle(completion)
        } else {
            drop(completion);
            Ok(())
        }
    }

    pub(super) fn find_session_key<'a>(
        &'a self,
        req: &AuthRequest,
        ctx: &AuthContext<impl alibi_core::AuthSchema>,
    ) -> AuthResult<Option<(&'a ApiKeyConfig, String)>> {
        self.find_session_key_for_input(&req.headers, Some(req), None, ctx)
    }

    pub(super) fn find_session_key_for_input<'a>(
        &'a self,
        headers: &std::collections::HashMap<String, String>,
        request: Option<&AuthRequest>,
        endpoint: Option<&alibi_core::endpoint::EndpointCall>,
        ctx: &AuthContext<impl alibi_core::AuthSchema>,
    ) -> AuthResult<Option<(&'a ApiKeyConfig, String)>> {
        for config in self
            .configurations
            .iter()
            .filter(|config| config.enable_session_for_api_keys)
        {
            let key = match &config.custom_api_key_getter {
                Some(getter) => {
                    let mut context = ApiKeyCallbackContext::new(request, ctx, &config.config_id);
                    if let Some(endpoint) = endpoint {
                        context = context.with_endpoint(endpoint);
                    }
                    getter.get_key(&context)?
                }
                None => config.api_key_headers.iter().find_map(|header| {
                    headers
                        .get(&header.to_ascii_lowercase())
                        .filter(|key| !key.is_empty())
                        .cloned()
                }),
            };
            if let Some(key) = key.filter(|key| !key.is_empty()) {
                return Ok(Some((config, key)));
            }
        }
        Ok(None)
    }

    #[expect(
        clippy::too_many_lines,
        reason = "Keep API key validation and session substitution in one ordered middleware decision"
    )]
    pub(super) async fn api_key_session(
        &self,
        req: &AuthRequest,
        ctx: &AuthContext<impl alibi_core::AuthSchema>,
    ) -> AuthResult<Option<BeforeRequestAction>> {
        // The Source hook matcher executes before its middleware handler. A
        // getter failure at that stage becomes the dispatcher's matcher error,
        // including an intentional API error thrown by the application.
        if self
            .find_session_key(req, ctx)
            .map_err(|_error| AuthError::Api {
                status: 500,
                code: None,
                message: "An error occurred during hook matcher execution. Check the logs for more details.".into(),
            })?
            .is_none()
        {
            return Ok(None);
        }
        let (config, key) = match self.find_session_key(req, ctx) {
            Ok(Some(value)) => value,
            Ok(None) => {
                tracing::error!("API key getter did not return a key after matching");
                return Ok(Some(BeforeRequestAction::Respond(AuthResponse::new(500))));
            }
            Err(error)
                if error.status_code() >= 500
                    && !matches!(error, AuthError::Api { .. } | AuthError::Upstream { .. }) =>
            {
                tracing::error!(error = %error, "API key getter failed");
                return Ok(Some(BeforeRequestAction::Respond(AuthResponse::new(500))));
            }
            Err(error) => return Err(error),
        };

        if f64::from(
            u32::try_from(key.encode_utf16().count())
                .map_err(|error| AuthError::internal(error.to_string()))?,
        ) < config.key_length
        {
            return Ok(Some(BeforeRequestAction::Respond(AuthResponse::json(
                403,
                &ApiKeyValidationError::new(ApiKeyErrorCode::InvalidApiKey),
            )?)));
        }
        if let Some(validator) = &config.custom_api_key_validator {
            let valid = match validator
                .validate(
                    &ApiKeyCallbackContext::new(Some(req), ctx, &config.config_id),
                    &key,
                )
                .await
            {
                Ok(valid) => valid,
                Err(error)
                    if error.status_code() >= 500
                        && !matches!(error, AuthError::Api { .. } | AuthError::Upstream { .. }) =>
                {
                    tracing::error!(error = %error, "API key validator failed");
                    return Ok(Some(BeforeRequestAction::Respond(AuthResponse::new(500))));
                }
                Err(error) => return Err(error),
            };
            if !valid {
                return Ok(Some(BeforeRequestAction::Respond(AuthResponse::json(
                    403,
                    &ApiKeyValidationError::new(ApiKeyErrorCode::InvalidApiKey),
                )?)));
            }
        }
        let input = VerifyApiKey {
            key: &key,
            config_id: Some(&config.config_id),
            permissions: None,
        };
        let view = match self
            .verify_api_key_checked(&input, Some(req), ctx, false)
            .await
        {
            Ok(view) => view,
            Err(ApiKeyVerificationError::Validation(error)) => {
                return Ok(Some(BeforeRequestAction::Respond(error.response()?)));
            }
            Err(
                ApiKeyVerificationError::Internal(error)
                | ApiKeyVerificationError::ExplicitValidator(error),
            ) => {
                // At this source middleware validation stage ordinary failures
                // become an empty 500; explicit application API errors survive.
                if error.status_code() >= 500
                    && !matches!(error, AuthError::Api { .. } | AuthError::Upstream { .. })
                {
                    return Ok(Some(BeforeRequestAction::Respond(AuthResponse::new(500))));
                }
                return Err(error);
            }
        };
        if config.defer_updates {
            let completion = self.start_configured_cleanup(ctx).await?;
            if let Some(handler) = &ctx.config.background_tasks {
                if let Err(error) = handler.handle(completion) {
                    if error.status_code() >= 500
                        && !matches!(error, AuthError::Api { .. } | AuthError::Upstream { .. })
                    {
                        return Ok(Some(BeforeRequestAction::Respond(AuthResponse::new(500))));
                    }
                    return Err(error);
                }
            } else {
                drop(completion);
            }
        } else {
            self.maybe_delete_expired(ctx).await?;
        }

        if config.references != ApiKeyReferences::User {
            return Ok(Some(BeforeRequestAction::Respond(
                ApiKeyValidationError::new(ApiKeyErrorCode::InvalidReferenceIdFromApiKey)
                    .response()?,
            )));
        }
        let Some(user) = ctx.database.get_user_by_id(&view.reference_id).await? else {
            return Ok(Some(BeforeRequestAction::Respond(
                ApiKeyValidationError::new(ApiKeyErrorCode::InvalidReferenceIdFromApiKey)
                    .response()?,
            )));
        };

        let session = Self::virtual_session_from_key(&view, &key, &user, Some(req), ctx)?;
        // Upstream answers this path in its hook before the route method gate.
        if req.path() == "/get-session" {
            return Ok(Some(BeforeRequestAction::Respond(AuthResponse::json(
                200,
                &serde_json::json!({
                    "user": ctx.user_view(&user),
                    "session": session,
                }),
            )?)));
        }
        Ok(Some(BeforeRequestAction::InjectSession { session }))
    }
}

impl ApiKeyPlugin {
    pub(super) fn virtual_session_from_key<S: alibi_core::AuthSchema>(
        view: &ApiKeyView,
        key: &str,
        user: &S::User,
        request: Option<&AuthRequest>,
        ctx: &AuthContext<S>,
    ) -> AuthResult<SessionView> {
        let now = chrono::Utc::now();
        let expires_at = match view.expires_at.as_deref() {
            Some(value) => chrono::DateTime::parse_from_rfc3339(value)
                .map_err(|error| {
                    AuthError::internal(format!("Invalid stored API key expiration: {error}"))
                })?
                .with_timezone(&chrono::Utc),
            // Upstream passes its session lifetime in seconds to getDate(..., "ms").
            None => {
                now + chrono::Duration::milliseconds(ctx.config.session.expires_in.num_seconds())
            }
        };
        // Virtual principals retain the resolver's nullable result. Physical
        // session creation supplies empty defaults through RequestMeta.
        let ip_policy = request
            .and_then(|request| {
                request
                    .extensions()
                    .get::<alibi_core::config::IpAddressConfig>()
            })
            .unwrap_or_default();
        let session = SessionView {
            omitted_fields: std::collections::BTreeSet::default(),
            active_team_id: None,
            extension_fields: std::collections::BTreeMap::default(),
            id: view.id.clone(),
            token: key.to_owned(),
            user_id: user.id().into_owned(),
            created_at: now,
            updated_at: now,
            expires_at,
            ip_address: request.and_then(|request| ip_policy.resolve_ip(&request.headers)),
            user_agent: request.and_then(|request| {
                request
                    .headers
                    .iter()
                    .find(|(name, _)| name.eq_ignore_ascii_case("user-agent"))
                    .map(|(_, value)| value.clone())
            }),
            impersonated_by: None,
            active_organization_id: None,
        };
        Ok(session)
    }
}

impl std::fmt::Debug for VerifyApiKey<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("VerifyApiKey").finish_non_exhaustive()
    }
}