Skip to main content

alibi_plugins/helpers/
mod.rs

1//! Shared helpers for plugin implementations.
2mod api_key_authorization;
3mod credentials;
4mod sessions;
5
6use alibi_core::error::codes;
7use alibi_core::{AuthContext, AuthError, CreateUser};
8pub use api_key_authorization::{get_owned_api_key, require_org_api_key_permission};
9pub use credentials::{get_credential_account, get_credential_password_hash, user_has_password};
10pub use sessions::{
11    admin_banned_user_message, admin_plugin_enabled, delete_session_cookie_headers,
12    expires_in_to_at, get_cookie, issue_user_session, issue_user_session_record,
13    issue_user_session_with_fields, issue_user_session_with_fields_record,
14    issue_user_session_with_overrides, issue_user_session_with_overrides_record, response_session,
15};
16pub(crate) use sessions::{
17    completed_response_session, create_user_session_record, issue_selected_user_session_record,
18    ordinary_session, record_completed_session, record_completed_session_record,
19    record_completed_session_user_view, response_has_session_cookie,
20};
21
22/// Join the configured auth origin and mount path for links sent to users.
23pub(crate) fn auth_base_url(config: &alibi_core::AuthConfig) -> String {
24    let origin = config.base_url.trim_end_matches('/');
25    let path = config.base_path.trim_matches('/');
26    if path.is_empty() {
27        origin.to_owned()
28    } else {
29        format!("{origin}/{path}")
30    }
31}
32
33/// Wrap an ordinary application callback failure as an empty HTTP 500; explicit
34/// API errors keep their public status and body.
35pub(crate) fn callback_failure(error: AuthError) -> AuthError {
36    if matches!(
37        error,
38        AuthError::Api { .. } | AuthError::Upstream { .. } | AuthError::CallbackFailure(_)
39    ) {
40        error
41    } else {
42        AuthError::CallbackFailure(Box::new(error))
43    }
44}
45
46/// Run detached work that keeps the caller's endpoint and request-hook contexts,
47/// so it can outlive an aggregate that rejects early.
48pub(crate) fn spawn_in_request_context(work: impl Future<Output = ()> + Send + 'static) {
49    let endpoint = alibi_core::endpoint::current_endpoint_call_context();
50    let hook = alibi_core::hooks::current_request_hook_context();
51    _ = tokio::spawn(async move {
52        let work = alibi_core::hooks::with_optional_request_hook_context(hook, work);
53        if let Some(endpoint) = endpoint {
54            alibi_core::endpoint::with_endpoint_call_context(endpoint, work).await;
55        } else {
56            work.await;
57        }
58    });
59}
60
61/// The documented 401 for a request without an authenticated session.
62pub(crate) const fn unauthorized() -> AuthError {
63    AuthError::Upstream {
64        status: 401,
65        code: codes::UNAUTHORIZED,
66        message: "Unauthorized",
67    }
68}
69
70/// Map a missing session to the documented 401, passing other errors through.
71pub(crate) fn unauthorized_if_unauthenticated(error: AuthError) -> AuthError {
72    if matches!(error, AuthError::Unauthenticated) {
73        unauthorized()
74    } else {
75        error
76    }
77}
78
79/// Like [`unauthorized_if_unauthenticated`], also for a session or user that
80/// no longer exists.
81pub(crate) fn unauthorized_if_session_missing(error: AuthError) -> AuthError {
82    if matches!(
83        error,
84        AuthError::Unauthenticated | AuthError::SessionNotFound | AuthError::UserNotFound
85    ) {
86        unauthorized()
87    } else {
88        error
89    }
90}
91
92/// Result of issuing a real session for a user.
93pub struct IssuedSession<S: alibi_core::AuthSchema> {
94    pub user: S::User,
95    pub session: S::Session,
96}
97
98/// Actual session issuance with retained adapter output for framework callbacks
99/// and separately filtered public responses.
100pub struct IssuedSessionRecord<S: alibi_core::AuthSchema> {
101    pub user: alibi_core::AdapterRecord<S::User>,
102    pub session: alibi_core::AdapterRecord<S::Session>,
103}
104impl<S: alibi_core::AuthSchema> IssuedSessionRecord<S> {
105    fn into_stored(self) -> IssuedSession<S> {
106        IssuedSession {
107            user: self.user.into_stored(),
108            session: self.session.into_stored(),
109        }
110    }
111}
112
113/// Original rows used by the handler that issued the completed session.
114/// This is a callback observation; authorization still uses a current session read.
115pub(crate) struct CompletedSession<S: alibi_core::AuthSchema> {
116    pub(crate) user: S::User,
117    pub(crate) session: S::Session,
118    pub(crate) user_view: Option<alibi_core::wire::UserView>,
119    user_record: Option<alibi_core::AdapterRecord<S::User>>,
120    session_record: Option<alibi_core::AdapterRecord<S::Session>>,
121}
122impl<S: alibi_core::AuthSchema> CompletedSession<S> {
123    pub(crate) fn callback_user(&self, ctx: &AuthContext<S>) -> alibi_core::UserView {
124        self.user_view.clone().unwrap_or_else(|| {
125            self.user_record.as_ref().map_or_else(
126                || ctx.trusted_user_view(&self.user),
127                |record| ctx.trusted_user_view(record),
128            )
129        })
130    }
131    pub(crate) fn callback_session(&self, ctx: &AuthContext<S>) -> alibi_core::SessionView {
132        self.session_record.as_ref().map_or_else(
133            || ctx.trusted_session_view(&self.session),
134            |record| ctx.trusted_session_view(record),
135        )
136    }
137}
138
139/// Session issuance failures that callers may need to surface differently from
140/// a generic auth error (for example OAuth callback redirects).
141#[derive(Debug)]
142pub enum SessionIssueError {
143    Auth(AuthError),
144    Banned { message: String },
145}
146
147impl SessionIssueError {
148    #[must_use]
149    pub fn into_auth_error(self) -> AuthError {
150        match self {
151            Self::Auth(error) => error,
152            Self::Banned { message } => AuthError::banned_user(message),
153        }
154    }
155
156    #[must_use]
157    pub const fn banned_message(&self) -> Option<&str> {
158        match self {
159            Self::Banned { message } => Some(message.as_str()),
160            Self::Auth(_) => None,
161        }
162    }
163}
164
165impl From<AuthError> for SessionIssueError {
166    fn from(value: AuthError) -> Self {
167        Self::Auth(value)
168    }
169}
170
171/// Trusted fields for the initial session insert in a custom sign-in flow.
172///
173/// These values pass through configured field policies and session creation
174/// hooks. Use only after authenticating the user and authorizing the requested
175/// organization, team, or impersonation; issuance does not check membership.
176/// The issuer owns the session token, user ID, and expiry.
177#[derive(Clone, Debug, Default)]
178pub struct SessionOverrides {
179    /// Application-defined session fields declared by the schema and configuration.
180    pub additional_fields: alibi_core::field_policy::FieldValues,
181    /// The trusted administrator responsible for impersonation, if any.
182    pub impersonated_by: Option<String>,
183    /// The organization selected by the application for this session.
184    pub active_organization_id: Option<String>,
185    /// The team selected by the application for this session.
186    pub active_team_id: Option<String>,
187}
188
189impl<S: alibi_core::AuthSchema> std::fmt::Debug for IssuedSession<S> {
190    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
191        f.debug_struct("IssuedSession").finish_non_exhaustive()
192    }
193}
194
195/// Apply the configured default admin role to a new user when the caller
196/// didn't set an explicit role.
197pub fn apply_default_role(
198    ctx: &AuthContext<impl alibi_core::AuthSchema>,
199    create_user: &mut CreateUser,
200) {
201    // The registered admin create transform runs after identity validation.
202    // Preserve that ordering for policy-enabled instances.
203    if ctx.config.user_validation.is_some() || create_user.role.is_some() {
204        return;
205    }
206
207    if let Some(default_role) = ctx
208        .get_metadata("admin.default_role")
209        .and_then(|value| value.as_str())
210    {
211        create_user.role = Some(default_role.to_owned());
212    }
213}