Skip to main content

alibi_plugins/
lib.rs

1//! Built-in authentication plugins for Alibi.
2
3#![cfg_attr(
4    test,
5    allow(
6        unused_results,
7        unreachable_pub,
8        reason = "test code intentionally discards setup return values and exposes helpers broadly"
9    )
10)]
11
12#[cfg(all(feature = "native-tls", feature = "rustls"))]
13compile_error!(
14    "features `native-tls` and `rustls` are mutually exclusive. \
15     Enable exactly one of them: \
16     for `native-tls` (default), remove the `rustls` feature; \
17     for `rustls`, set `default-features = false, features = [\"rustls\"]`."
18);
19
20#[cfg(not(any(feature = "native-tls", feature = "rustls")))]
21compile_error!(
22    "one of the TLS backends must be enabled: \
23     enable either the `native-tls` (default) or `rustls` feature."
24);
25
26/// Expand to the `OpenAPI` metadata methods of a plugin whose documentation
27/// comes entirely from its registered routes.
28macro_rules! route_openapi_metadata {
29    ($schema:ident) => {
30        fn static_openapi_metadata(&self) -> alibi_core::PluginOpenApiMetadata {
31            crate::metadata::plugin_metadata(
32                <Self as alibi_core::AuthPlugin<$schema>>::name(self),
33                &<Self as alibi_core::AuthPlugin<$schema>>::routes(self),
34            )
35        }
36
37        fn openapi_metadata(
38            &self,
39            ctx: &alibi_core::AuthInitContext<$schema>,
40        ) -> alibi_core::PluginOpenApiMetadata {
41            crate::metadata::instance_plugin_metadata(
42                <Self as alibi_core::AuthPlugin<$schema>>::name(self),
43                &<Self as alibi_core::AuthPlugin<$schema>>::routes(self),
44                ctx,
45            )
46        }
47    };
48}
49
50pub mod access;
51pub mod account_management;
52pub mod admin;
53pub mod anonymous;
54pub mod api_key;
55pub(crate) mod authentication_helpers;
56pub mod bearer;
57pub mod captcha;
58pub mod custom_session;
59pub mod device_authorization;
60pub mod email_otp;
61pub mod email_password;
62pub mod email_verification;
63mod endpoint;
64pub mod haveibeenpwned;
65pub mod helpers;
66pub mod jwt;
67pub mod last_login_method;
68pub mod magic_link;
69pub mod metadata;
70pub mod multi_session;
71pub mod oauth;
72pub mod oauth_popup;
73pub mod oauth_proxy;
74pub mod oauth_token_conversion;
75pub mod one_tap;
76pub mod one_time_token;
77pub mod open_api;
78pub mod organization;
79pub mod passkey;
80pub mod password_management;
81mod passwordless_numeric;
82pub mod phone_number;
83pub mod session_management;
84pub mod siwe;
85pub(crate) mod token_crypto;
86pub mod two_factor;
87pub mod user_management;
88
89// LCOV_EXCL_START
90#[cfg(test)]
91pub(crate) mod test_helpers {
92    use alibi_core::config::AuthConfig;
93    use alibi_core::wire::{SessionView, UserView};
94    use alibi_core::{AuthContext, AuthRequest, CreateSession, CreateUser, HttpMethod};
95    use alibi_seaorm::store::__private_test_support::bundled_schema::BundledSchema;
96    use alibi_seaorm::{Database, SeaOrmStore};
97    use chrono::{Duration, Utc};
98    use std::collections::HashMap;
99    use std::sync::Arc;
100
101    pub type TestDatabase = dyn alibi_core::store::AuthStore<BundledSchema>;
102
103    pub fn create_test_config() -> AuthConfig {
104        AuthConfig::new("test-secret-key-at-least-32-chars-long")
105    }
106
107    pub async fn create_test_database() -> Arc<TestDatabase> {
108        let database = Database::connect("sqlite::memory:")
109            .await
110            .expect("sqlite test database should connect");
111        alibi_seaorm::store::__private_test_support::migrator::run_migrations(&database)
112            .await
113            .expect("sqlite test migrations should run");
114        Arc::new(SeaOrmStore::<BundledSchema>::new(
115            Arc::new(create_test_config()),
116            database,
117        ))
118    }
119
120    pub async fn create_test_context() -> AuthContext<BundledSchema> {
121        create_test_context_with_config(create_test_config()).await
122    }
123
124    pub fn create_test_context_blocking() -> AuthContext<BundledSchema> {
125        tokio::runtime::Builder::new_current_thread()
126            .enable_all()
127            .build()
128            .expect("test runtime should build")
129            .block_on(create_test_context())
130    }
131
132    pub async fn create_test_context_with_config(config: AuthConfig) -> AuthContext<BundledSchema> {
133        let config = Arc::new(config);
134        let database = create_test_database().await;
135        AuthContext::new(config, database)
136    }
137
138    pub async fn create_user(
139        ctx: &AuthContext<impl alibi_core::AuthSchema>,
140        create_user: CreateUser,
141    ) -> UserView {
142        let user = ctx.database.create_user(create_user).await.unwrap();
143        UserView::from(&user)
144    }
145
146    pub async fn create_session(
147        ctx: &AuthContext<impl alibi_core::AuthSchema>,
148        user_id: String,
149        expires_in: Duration,
150    ) -> SessionView {
151        let create_session = CreateSession {
152            additional_fields: alibi_core::field_policy::FieldValues::default(),
153            token: None,
154            active_team_id: None,
155            user_id,
156            expires_at: Utc::now() + expires_in,
157            ip_address: Some("127.0.0.1".to_owned()),
158            user_agent: Some("test-agent".to_owned()),
159            impersonated_by: None,
160            active_organization_id: None,
161        };
162        let session = ctx.database.create_session(create_session).await.unwrap();
163        SessionView::from(&session)
164    }
165
166    pub async fn create_user_and_session(
167        ctx: &AuthContext<impl alibi_core::AuthSchema>,
168        user_data: CreateUser,
169        session_expires_in: Duration,
170    ) -> (UserView, SessionView) {
171        let user = create_user(ctx, user_data).await;
172        let session = create_session(ctx, user.id.clone(), session_expires_in).await;
173        (user, session)
174    }
175
176    pub async fn create_test_context_with_user(
177        create_user: CreateUser,
178        session_expires_in: Duration,
179    ) -> (AuthContext<BundledSchema>, UserView, SessionView) {
180        let ctx = create_test_context().await;
181        let (user, session) = create_user_and_session(&ctx, create_user, session_expires_in).await;
182        (ctx, user, session)
183    }
184
185    pub fn create_auth_request(
186        method: HttpMethod,
187        path: &str,
188        token: Option<&str>,
189        body: Option<Vec<u8>>,
190        query: HashMap<String, String>,
191    ) -> AuthRequest {
192        let mut headers = HashMap::new();
193        if let Some(token) = token {
194            let config = create_test_config();
195            headers.insert(
196                "cookie".to_owned(),
197                format!(
198                    "{}={}",
199                    config.session.cookie_name,
200                    alibi_core::utils::cookie_utils::sign_cookie_value(
201                        token,
202                        config.current_secret()
203                    )
204                ),
205            );
206        }
207
208        AuthRequest::from_parts(method, path.to_owned(), headers, body, query)
209    }
210
211    pub fn create_auth_request_no_query(
212        method: HttpMethod,
213        path: &str,
214        token: Option<&str>,
215        body: Option<Vec<u8>>,
216    ) -> AuthRequest {
217        create_auth_request(method, path, token, body, HashMap::new())
218    }
219
220    pub fn create_auth_json_request_no_query(
221        method: HttpMethod,
222        path: &str,
223        token: Option<&str>,
224        body: Option<serde_json::Value>,
225    ) -> AuthRequest {
226        create_auth_json_request(method, path, token, body, HashMap::new())
227    }
228
229    pub fn create_auth_json_request(
230        method: HttpMethod,
231        path: &str,
232        token: Option<&str>,
233        body: Option<serde_json::Value>,
234        query: HashMap<String, String>,
235    ) -> AuthRequest {
236        let mut req = create_auth_request(
237            method,
238            path,
239            token,
240            body.map(|b| serde_json::to_vec(&b).unwrap()),
241            query,
242        );
243        req.headers
244            .insert("content-type".to_owned(), "application/json".to_owned());
245        req
246    }
247}
248// LCOV_EXCL_STOP
249
250pub use account_management::AccountManagementPlugin;
251pub use admin::{
252    AdminBannedUserMessage, AdminBannedUserMessageHandler, AdminConfig, AdminPlugin,
253    RolePermissions,
254};
255pub use alibi_core::PasswordHasher;
256pub use anonymous::{
257    AnonymousConfig, AnonymousIdentity, AnonymousLink, AnonymousPlugin, LinkAnonymousAccount,
258};
259pub use api_key::{
260    ApiKeyCallbackContext, ApiKeyConfig, ApiKeyDefaultPermissions, ApiKeyErrorMessage,
261    ApiKeyGenerationOptions, ApiKeyGenerator, ApiKeyGetter, ApiKeyPermissions, ApiKeyPlugin,
262    ApiKeyValidator, DeleteExpiredApiKeysResponse,
263};
264pub use bearer::{BearerConfig, BearerPlugin};
265pub use captcha::{CaptchaConfig, CaptchaPlugin, CaptchaProvider};
266pub use custom_session::{CustomSessionPlugin, SessionTransform};
267pub use device_authorization::DeviceAuthorizationPlugin;
268pub use email_otp::{EmailOtpConfig, EmailOtpPlugin, SendEmailOtp};
269pub use email_password::{EmailPasswordConfig, EmailPasswordPlugin};
270pub use email_verification::{
271    EmailVerificationConfig, EmailVerificationHook, EmailVerificationPlugin, SendVerificationEmail,
272};
273pub use haveibeenpwned::{HaveIBeenPwnedConfig, HaveIBeenPwnedPlugin, PwnedPasswordClient};
274pub use last_login_method::{
275    BeforeStoreLastLoginMethodCookie, LastLoginMethodConfig, LastLoginMethodContext,
276    LastLoginMethodPlugin, ResolveLastLoginMethod,
277};
278pub use magic_link::{MagicLinkConfig, MagicLinkPlugin, SendMagicLink};
279pub use multi_session::{MultiSessionConfig, MultiSessionPlugin};
280pub use oauth::OAuthPlugin;
281pub use oauth_popup::OAuthPopupPlugin;
282pub use oauth_proxy::{OAuthProxyConfig, OAuthProxyPlugin};
283pub use one_tap::{OAuthJwksSource, OneTapClientId, OneTapConfig, OneTapPlugin};
284pub use open_api::{OpenApiConfig, OpenApiPlugin};
285pub use organization::{
286    OrganizationConfig, OrganizationCreatePatch, OrganizationCreatedContext,
287    OrganizationCreationHooks, OrganizationDraftContext, OrganizationMemberCreatePatch,
288    OrganizationMemberDraftContext, OrganizationPlugin,
289};
290pub use passkey::{
291    AuthenticationResult, PasskeyAuthenticationAfterVerification, PasskeyAuthenticationConfig,
292    PasskeyAuthenticationContext, PasskeyAuthenticatorSelection, PasskeyConfig, PasskeyExtensions,
293    PasskeyExtensionsResolver, PasskeyOptionsContext, PasskeyPlugin,
294    PasskeyRegistrationAfterVerification, PasskeyRegistrationConfig, PasskeyRegistrationContext,
295    PasskeyRegistrationOverride, PasskeyRegistrationUser, PasskeyUserResolver,
296    VerifiedPasskeyAuthentication, VerifiedPasskeyRegistration,
297};
298pub use password_management::{
299    PasswordManagementConfig, PasswordManagementPlugin, SendResetPassword,
300};
301pub use phone_number::{PhoneNumberConfig, PhoneNumberPlugin, SendPhoneOtp};
302pub use session_management::SessionManagementPlugin;
303pub use siwe::{SiweConfig, SiwePlugin};
304pub use two_factor::{
305    SendTwoFactorOtp, TwoFactorBackupCipher, TwoFactorBackupStorage, TwoFactorConfig,
306    TwoFactorOtpCipher, TwoFactorOtpHasher, TwoFactorOtpStorage, TwoFactorPlugin,
307};
308pub use user_management::{
309    ChangeEmailConfig, DeleteUserConfig, SendChangeEmailConfirmation, UserManagementConfig,
310    UserManagementPlugin,
311};
312
313#[derive(Debug, serde::Serialize, serde::Deserialize)]
314pub(crate) struct StatusResponse {
315    status: bool,
316}