Add authentication from upstream providers (#107)
All checks were successful
continuous-integration/drone/push Build is passing

Let BasicOIDC delegate authentication to upstream providers (Google, GitHub, GitLab, Keycloak...)

Reviewed-on: #107
This commit is contained in:
2023-04-27 10:10:28 +00:00
parent 4f7c56a4b8
commit 9b18b787a9
39 changed files with 1740 additions and 189 deletions

View File

@ -7,9 +7,11 @@ use actix_identity::Identity;
use actix_web::dev::Payload;
use actix_web::{web, Error, FromRequest, HttpRequest};
use crate::actors::providers_states_actor::ProviderLoginState;
use crate::actors::users_actor;
use crate::actors::users_actor::UsersActor;
use crate::actors::users_actor::{AuthorizedAuthenticationSources, UsersActor};
use crate::data::client::Client;
use crate::data::provider::{Provider, ProviderID};
use crate::data::remote_ip::RemoteIP;
use crate::data::session_identity::SessionIdentity;
use crate::data::user::{FactorID, GrantedClients, TwoFactor, User, UserID};
@ -20,22 +22,79 @@ pub enum Action<'a> {
AdminDeleteUser(&'a User),
AdminResetUserPassword(&'a User),
AdminRemoveUserFactor(&'a User, &'a TwoFactor),
AdminSetAuthorizedAuthenticationSources(&'a User, &'a AuthorizedAuthenticationSources),
AdminSetNewGrantedClientsList(&'a User, &'a GrantedClients),
AdminClear2FAHistory(&'a User),
LoginWebauthnAttempt { success: bool, user_id: UserID },
LoginWebauthnAttempt {
success: bool,
user_id: UserID,
},
StartLoginAttemptWithOpenIDProvider {
provider_id: &'a ProviderID,
state: &'a str,
},
ProviderError {
message: &'a str,
},
ProviderCBInvalidState {
state: &'a str,
},
ProviderRateLimited,
ProviderFailedGetToken {
state: &'a ProviderLoginState,
code: &'a str,
},
ProviderFailedGetUserInfo {
provider: &'a Provider,
},
ProviderEmailNotValidated {
provider: &'a Provider,
},
ProviderMissingEmailInResponse {
provider: &'a Provider,
},
ProviderAccountNotFound {
provider: &'a Provider,
email: &'a str,
},
ProviderAccountDisabled {
provider: &'a Provider,
email: &'a str,
},
ProviderAccountNotAllowedToLoginWithProvider {
provider: &'a Provider,
email: &'a str,
},
ProviderLoginFailed {
provider: &'a Provider,
email: &'a str,
},
ProviderLoginSuccessful {
provider: &'a Provider,
user: &'a User,
},
Signout,
UserNeed2FAOnLogin(&'a User),
UserSuccessfullyAuthenticated(&'a User),
UserNeedNewPasswordOnLogin(&'a User),
TryLoginWithDisabledAccount(&'a str),
TryLocalLoginFromUnauthorizedAccount(&'a str),
FailedLoginWithBadCredentials(&'a str),
UserChangedPasswordOnLogin(&'a UserID),
OTPLoginAttempt { user: &'a User, success: bool },
NewOpenIDSession { client: &'a Client },
OTPLoginAttempt {
user: &'a User,
success: bool,
},
NewOpenIDSession {
client: &'a Client,
},
ChangedHisPassword,
ClearedHisLoginHistory,
AddNewFactor(&'a TwoFactor),
Removed2FAFactor { factor_id: &'a FactorID },
Removed2FAFactor {
factor_id: &'a FactorID,
},
}
impl<'a> Action<'a> {
@ -64,6 +123,11 @@ impl<'a> Action<'a> {
Action::AdminClear2FAHistory(user) => {
format!("cleared 2FA history of {}", user.quick_identity())
}
Action::AdminSetAuthorizedAuthenticationSources(user, sources) => format!(
"update authorized authentication sources ({:?}) for user ({})",
sources,
user.quick_identity()
),
Action::AdminSetNewGrantedClientsList(user, clients) => format!(
"set new granted clients list ({:?}) for user ({})",
clients,
@ -73,6 +137,28 @@ impl<'a> Action<'a> {
true => format!("successfully performed webauthn attempt for user {user_id:?}"),
false => format!("performed FAILED webauthn attempt for user {user_id:?}"),
},
Action::StartLoginAttemptWithOpenIDProvider { provider_id, state } => format!(
"started new authentication attempt through an OpenID provider (prov={} / state={state})", provider_id.0
),
Action::ProviderError { message } =>
format!("failed provider authentication with message '{message}'"),
Action::ProviderCBInvalidState { state } =>
format!("provided invalid callback state after provider authentication: '{state}'"),
Action::ProviderRateLimited => "could not complete OpenID login because it has reached failed attempts rate limit!".to_string(),
Action::ProviderFailedGetToken {state, code} => format!("could not complete login from provider because the id_token could not be retrieved! (state={:?} code = {code})",state),
Action::ProviderFailedGetUserInfo {provider} => format!("could not get user information from userinfo endpoint of provider {}!", provider.id.0),
Action::ProviderEmailNotValidated {provider}=>format!("could not login using provider {} because its email was marked as not validated!", provider.id.0),
Action::ProviderMissingEmailInResponse {provider}=>format!("could not login using provider {} because the email was not provided by userinfo endpoint!", provider.id.0),
Action::ProviderAccountNotFound { provider, email } =>
format!("could not login using provider {} because the email {email} could not be associated to any account!", &provider.id.0),
Action::ProviderAccountDisabled { provider, email } =>
format!("could not login using provider {} because the account associated to the email {email} is disabled!", &provider.id.0),
Action::ProviderAccountNotAllowedToLoginWithProvider { provider, email } =>
format!("could not login using provider {} because the account associated to the email {email} is not allowed to authenticate using this provider!", &provider.id.0),
Action::ProviderLoginFailed { provider, email } =>
format!("could not login using provider {} with the email {email} for an unknown reason!", &provider.id.0),
Action::ProviderLoginSuccessful {provider, user} =>
format!("successfully authenticated using provider {} as {}", provider.id.0, user.quick_identity()),
Action::Signout => "signed out".to_string(),
Action::UserNeed2FAOnLogin(user) => {
format!(
@ -90,6 +176,9 @@ impl<'a> Action<'a> {
Action::TryLoginWithDisabledAccount(login) => {
format!("successfully authenticated as {login}, but this is a DISABLED ACCOUNT")
}
Action::TryLocalLoginFromUnauthorizedAccount(login) => {
format!("successfully locally authenticated as {login}, but this is a FORBIDDEN for this account!")
}
Action::FailedLoginWithBadCredentials(login) => {
format!("attempted to authenticate as {login} but with a WRONG PASSWORD")
}
@ -116,6 +205,7 @@ impl<'a> Action<'a> {
factor.quick_description(),
),
Action::Removed2FAFactor { factor_id } => format!("Removed his factor {factor_id:?}"),
}
}
}

View File

@ -2,7 +2,9 @@ use std::path::{Path, PathBuf};
use clap::Parser;
use crate::constants::{APP_NAME, CLIENTS_LIST_FILE, USERS_LIST_FILE};
use crate::constants::{
APP_NAME, CLIENTS_LIST_FILE, OIDC_PROVIDER_CB_URI, PROVIDERS_LIST_FILE, USERS_LIST_FILE,
};
/// Basic OIDC provider
#[derive(Parser, Debug, Clone)]
@ -72,6 +74,10 @@ impl AppConfig {
self.storage_path().join(CLIENTS_LIST_FILE)
}
pub fn providers_file(&self) -> PathBuf {
self.storage_path().join(PROVIDERS_LIST_FILE)
}
pub fn full_url(&self, uri: &str) -> String {
if uri.starts_with('/') {
format!("{}{}", self.website_origin, uri)
@ -80,9 +86,21 @@ impl AppConfig {
}
}
/// Get the URL where a upstream OpenID provider should redirect
/// the user after an authentication
pub fn oidc_provider_redirect_url(&self) -> String {
AppConfig::get().full_url(OIDC_PROVIDER_CB_URI)
}
pub fn domain_name(&self) -> &str {
self.website_origin.split('/').nth(2).unwrap_or(APP_NAME)
}
/// Get the domain without the port
pub fn domain_name_without_port(&self) -> &str {
let domain = self.domain_name();
domain.split_once(':').map(|i| i.0).unwrap_or(domain)
}
}
#[cfg(test)]

View File

@ -11,8 +11,10 @@ use base64::Engine as _;
use crate::utils::err::Res;
use crate::utils::string_utils::rand_str;
const JWK_USE_SIGN: &str = "sig";
/// Json Web Key <https://datatracker.ietf.org/doc/html/rfc7517>
#[derive(serde::Serialize, serde::Deserialize)]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct JsonWebKey {
#[serde(rename = "alg")]
algorithm: String,
@ -24,6 +26,8 @@ pub struct JsonWebKey {
modulus: String,
#[serde(rename = "e")]
public_exponent: String,
#[serde(rename = "use", skip_serializing_if = "Option::is_none")]
usage: Option<String>,
}
#[derive(Debug, Clone)]
@ -44,6 +48,7 @@ impl JWTSigner {
key_id: self.0.key_id().as_ref().unwrap().to_string(),
public_exponent: BASE64_URL_URL_SAFE.encode(components.e),
modulus: BASE64_URL_SAFE_NO_PAD.encode(components.n),
usage: Some(JWK_USE_SIGN.to_string()),
}
}

View File

@ -10,7 +10,9 @@ pub mod id_token;
pub mod jwt_signer;
pub mod login_redirect;
pub mod open_id_user_info;
pub mod openid_config;
pub mod openid_primitive;
pub mod provider;
pub mod provider_configuration;
pub mod remote_ip;
pub mod session_identity;
pub mod totp_key;

View File

@ -1,24 +1 @@
/// Refer to <https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims> for more information
#[derive(Debug, serde::Serialize)]
pub struct OpenIDUserInfo {
/// Subject - Identifier for the End-User at the Issuer
pub sub: String,
/// End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences.
pub name: String,
/// Given name(s) or first name(s) of the End-User. Note that in some cultures, people can have multiple given names; all can be present, with the names being separated by space characters.
pub given_name: String,
/// Surname(s) or last name(s) of the End-User. Note that in some cultures, people can have multiple family names or no family name; all can be present, with the names being separated by space characters.
pub family_name: String,
/// Shorthand name by which the End-User wishes to be referred to at the RP, such as janedoe or j.doe. This value MAY be any valid JSON string including special characters such as @, /, or whitespace. The RP MUST NOT rely upon this value being unique, as discussed in
pub preferred_username: String,
/// End-User's preferred e-mail address. Its value MUST conform to the RFC 5322 RFC5322 addr-spec syntax. The RP MUST NOT rely upon this value being unique, as discussed in Section 5.7.
pub email: String,
/// True if the End-User's e-mail address has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this e-mail address was controlled by the End-User at the time the verification was performed. The means by which an e-mail address is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating.
pub email_verified: bool,
}

View File

@ -1,37 +0,0 @@
#[derive(Debug, Clone, serde::Serialize)]
pub struct OpenIDConfig {
/// URL using the https scheme with no query or fragment component that the OP asserts as its Issuer Identifier. If Issuer discovery is supported (see Section 2), this value MUST be identical to the issuer value returned by WebFinger. This also MUST be identical to the iss Claim value in ID Tokens issued from this Issuer
pub issuer: String,
/// REQUIRED. URL of the OP's OAuth 2.0 Authorization Endpoint `OpenID.Core`
pub authorization_endpoint: String,
/// URL of the OP's OAuth 2.0 Token Endpoint `OpenID.Core`. This is REQUIRED unless only the Implicit Flow is used.
pub token_endpoint: String,
/// RECOMMENDED. URL of the OP's UserInfo Endpoint `[`OpenID.Core`]`. This URL MUST use the https scheme and MAY contain port, path, and query parameter components
pub userinfo_endpoint: String,
/// REQUIRED. URL of the OP's JSON Web Key Set `[`JWK`]` document. This contains the signing key(s) the RP uses to validate signatures from the OP. The JWK Set MAY also contain the Server's encryption key(s), which are used by RPs to encrypt requests to the Server. When both signing and encryption keys are made available, a use (Key Use) parameter value is REQUIRED for all keys in the referenced JWK Set to indicate each key's intended usage. Although some algorithms allow the same key to be used for both signatures and encryption, doing so is NOT RECOMMENDED, as it is less secure. The JWK x5c parameter MAY be used to provide X.509 representations of keys provided. When used, the bare key values MUST still be present and MUST match those in the certificate.
pub jwks_uri: String,
/// RECOMMENDED. JSON array containing a list of the OAuth 2.0 `[`RFC6749`]` scope values that this server supports. The server MUST support the openid scope value. Servers MAY choose not to advertise some supported scope values even when this parameter is used, although those defined in `[`OpenID.Core`]` SHOULD be listed, if supported.
pub scopes_supported: Vec<&'static str>,
/// REQUIRED. JSON array containing a list of the OAuth 2.0 response_type values that this OP supports. Dynamic OpenID Providers MUST support the code, id_token, and the token id_token Response Type values.
pub response_types_supported: Vec<&'static str>,
/// REQUIRED. JSON array containing a list of the Subject Identifier types that this OP supports. Valid types include pairwise and public.
pub subject_types_supported: Vec<&'static str>,
/// REQUIRED. JSON array containing a list of the JWS signing algorithms (alg values) supported by the OP for the ID Token to encode the Claims in a JWT `[`JWT`. The algorithm RS256 MUST be included. The value none MAY be supported, but MUST NOT be used unless the Response Type used returns no ID Token from the Authorization Endpoint (such as when using the Authorization Code Flow).
pub id_token_signing_alg_values_supported: Vec<&'static str>,
/// OPTIONAL. JSON array containing a list of Client Authentication methods supported by this Token Endpoint. The options are client_secret_post, client_secret_basic, client_secret_jwt, and private_key_jwt
pub token_endpoint_auth_methods_supported: Vec<&'static str>,
/// RECOMMENDED. JSON array containing a list of the Claim Names of the Claims that the OpenID Provider MAY be able to supply values for. Note that for privacy or other reasons, this might not be an exhaustive list.
pub claims_supported: Vec<&'static str>,
pub code_challenge_methods_supported: Vec<&'static str>,
}

View File

@ -0,0 +1,107 @@
//! # OpenID primitives
/// OpenID discovery information
#[derive(Debug, Clone, serde::Serialize)]
pub struct OpenIDConfig {
/// URL using the https scheme with no query or fragment component that the OP asserts as its Issuer Identifier. If Issuer discovery is supported (see Section 2), this value MUST be identical to the issuer value returned by WebFinger. This also MUST be identical to the iss Claim value in ID Tokens issued from this Issuer
pub issuer: String,
/// REQUIRED. URL of the OP's OAuth 2.0 Authorization Endpoint `OpenID.Core`
pub authorization_endpoint: String,
/// URL of the OP's OAuth 2.0 Token Endpoint `OpenID.Core`. This is REQUIRED unless only the Implicit Flow is used.
pub token_endpoint: String,
/// RECOMMENDED. URL of the OP's UserInfo Endpoint `[`OpenID.Core`]`. This URL MUST use the https scheme and MAY contain port, path, and query parameter components
pub userinfo_endpoint: String,
/// REQUIRED. URL of the OP's JSON Web Key Set `[`JWK`]` document. This contains the signing key(s) the RP uses to validate signatures from the OP. The JWK Set MAY also contain the Server's encryption key(s), which are used by RPs to encrypt requests to the Server. When both signing and encryption keys are made available, a use (Key Use) parameter value is REQUIRED for all keys in the referenced JWK Set to indicate each key's intended usage. Although some algorithms allow the same key to be used for both signatures and encryption, doing so is NOT RECOMMENDED, as it is less secure. The JWK x5c parameter MAY be used to provide X.509 representations of keys provided. When used, the bare key values MUST still be present and MUST match those in the certificate.
pub jwks_uri: String,
/// RECOMMENDED. JSON array containing a list of the OAuth 2.0 `[`RFC6749`]` scope values that this server supports. The server MUST support the openid scope value. Servers MAY choose not to advertise some supported scope values even when this parameter is used, although those defined in `[`OpenID.Core`]` SHOULD be listed, if supported.
pub scopes_supported: Vec<&'static str>,
/// REQUIRED. JSON array containing a list of the OAuth 2.0 response_type values that this OP supports. Dynamic OpenID Providers MUST support the code, id_token, and the token id_token Response Type values.
pub response_types_supported: Vec<&'static str>,
/// REQUIRED. JSON array containing a list of the Subject Identifier types that this OP supports. Valid types include pairwise and public.
pub subject_types_supported: Vec<&'static str>,
/// REQUIRED. JSON array containing a list of the JWS signing algorithms (alg values) supported by the OP for the ID Token to encode the Claims in a JWT `[`JWT`. The algorithm RS256 MUST be included. The value none MAY be supported, but MUST NOT be used unless the Response Type used returns no ID Token from the Authorization Endpoint (such as when using the Authorization Code Flow).
pub id_token_signing_alg_values_supported: Vec<&'static str>,
/// OPTIONAL. JSON array containing a list of Client Authentication methods supported by this Token Endpoint. The options are client_secret_post, client_secret_basic, client_secret_jwt, and private_key_jwt
pub token_endpoint_auth_methods_supported: Vec<&'static str>,
/// RECOMMENDED. JSON array containing a list of the Claim Names of the Claims that the OpenID Provider MAY be able to supply values for. Note that for privacy or other reasons, this might not be an exhaustive list.
pub claims_supported: Vec<&'static str>,
pub code_challenge_methods_supported: Vec<&'static str>,
}
/// OpenID token response
///
/// The content of this field is specified in
/// * OAuth specifications: https://datatracker.ietf.org/doc/html/rfc6749#section-5.1
/// * OpenID Core specifications: https://openid.net/specs/openid-connect-core-1_0.html#TokenResponse
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TokenResponse {
/// REQUIRED. The access token issued by the authorization server.
pub access_token: String,
/// REQUIRED. The type of the token issued. It MUST be "Bearer"
pub token_type: String,
/// OPTIONAL. The refresh token, which can be used to obtain new
/// access tokens using the same authorization grant
#[serde(skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<String>,
/// RECOMMENDED. The lifetime in seconds of the access token. For
/// example, the value "3600" denotes that the access token will
/// expire in one hour from the time the response was generated.
/// If omitted, the authorization server SHOULD provide the
/// expiration time via other means or document the default value.
#[serde(skip_serializing_if = "Option::is_none")]
pub expires_in: Option<u64>,
/// REQUIRED. ID Token value associated with the authenticated session.
///
/// Note: this field is marked as optionnal because it is excluded in case
/// of request of refresh token.
#[serde(skip_serializing_if = "Option::is_none")]
pub id_token: Option<String>,
}
/// Refer to <https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims> for more information
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct OpenIDUserInfo {
/// Subject - Identifier for the End-User at the Issuer
///
/// This is the only mandatory field
pub sub: String,
/// End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences.
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// Given name(s) or first name(s) of the End-User. Note that in some cultures, people can have multiple given names; all can be present, with the names being separated by space characters.
#[serde(skip_serializing_if = "Option::is_none")]
pub given_name: Option<String>,
/// Surname(s) or last name(s) of the End-User. Note that in some cultures, people can have multiple family names or no family name; all can be present, with the names being separated by space characters.
#[serde(skip_serializing_if = "Option::is_none")]
pub family_name: Option<String>,
/// Shorthand name by which the End-User wishes to be referred to at the RP, such as janedoe or j.doe. This value MAY be any valid JSON string including special characters such as @, /, or whitespace. The RP MUST NOT rely upon this value being unique, as discussed in
#[serde(skip_serializing_if = "Option::is_none")]
pub preferred_username: Option<String>,
/// End-User's preferred e-mail address. Its value MUST conform to the RFC 5322 RFC5322 addr-spec syntax. The RP MUST NOT rely upon this value being unique, as discussed in Section 5.7.
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<String>,
/// True if the End-User's e-mail address has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this e-mail address was controlled by the End-User at the time the verification was performed. The means by which an e-mail address is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating.
#[serde(skip_serializing_if = "Option::is_none")]
pub email_verified: Option<bool>,
}

89
src/data/provider.rs Normal file
View File

@ -0,0 +1,89 @@
use crate::data::entity_manager::EntityManager;
use crate::data::login_redirect::LoginRedirect;
use crate::utils::string_utils::apply_env_vars;
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
pub struct ProviderID(pub String);
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Provider {
/// The ID of the provider
pub id: ProviderID,
/// The human-readable name of the client
pub name: String,
/// A logo presented to the users of the provider
pub logo: String,
/// The registration id of BasicOIDC on the provider
pub client_id: String,
/// The registration secret of BasicOIDC on the provider
pub client_secret: String,
/// Specify the URL of the OpenID configuration URL
///
/// (.well-known/openid-configuration endpoint)
pub configuration_url: String,
}
impl Provider {
/// Get URL-encoded provider id
pub fn id_encoded(&self) -> String {
urlencoding::encode(&self.id.0).to_string()
}
/// Get the URL where the logo can be located
pub fn logo_url(&self) -> &str {
match self.logo.as_str() {
"gitea" => "/assets/img/brands/gitea.svg",
"gitlab" => "/assets/img/brands/gitlab.svg",
"github" => "/assets/img/brands/github.svg",
"microsoft" => "/assets/img/brands/microsoft.svg",
"google" => "/assets/img/brands/google.svg",
s => s,
}
}
/// Get the URL to use to login with the provider
pub fn login_url(&self, redirect_url: &LoginRedirect) -> String {
format!(
"/login_with_prov?id={}&redirect={}",
self.id_encoded(),
redirect_url.get_encoded()
)
}
}
impl PartialEq for Provider {
fn eq(&self, other: &Self) -> bool {
self.id.eq(&other.id)
}
}
impl Eq for Provider {}
pub type ProvidersManager = EntityManager<Provider>;
impl EntityManager<Provider> {
pub fn find_by_id(&self, u: &ProviderID) -> Option<Provider> {
for entry in self.iter() {
if entry.id.eq(u) {
return Some(entry.clone());
}
}
None
}
pub fn apply_environment_variables(&mut self) {
for c in self.iter_mut() {
c.id = ProviderID(apply_env_vars(&c.id.0));
c.name = apply_env_vars(&c.name);
c.logo = apply_env_vars(&c.logo);
c.client_id = apply_env_vars(&c.client_id);
c.client_secret = apply_env_vars(&c.client_secret);
c.configuration_url = apply_env_vars(&c.configuration_url);
}
}
}

View File

@ -0,0 +1,135 @@
use std::cell::RefCell;
use std::collections::HashMap;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use base64::Engine as _;
use crate::actors::providers_states_actor::ProviderLoginState;
use crate::constants::OIDC_PROVIDERS_LIFETIME;
use crate::data::app_config::AppConfig;
use crate::data::jwt_signer::JsonWebKey;
use crate::data::openid_primitive::{OpenIDUserInfo, TokenResponse};
use crate::data::provider::Provider;
use crate::utils::err::Res;
use crate::utils::time::time;
#[derive(Debug, Clone, serde::Deserialize)]
pub struct ProviderDiscovery {
pub issuer: String,
pub authorization_endpoint: String,
pub token_endpoint: String,
pub userinfo_endpoint: Option<String>,
pub jwks_uri: String,
pub claims_supported: Option<Vec<String>>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ProviderJWKs {
pub keys: Vec<JsonWebKey>,
}
/// Provider configuration
#[derive(Debug, Clone)]
pub struct ProviderConfiguration {
pub discovery: ProviderDiscovery,
//pub keys: ProviderJWKs,
pub expire: u64,
}
impl ProviderConfiguration {
/// Get the URL where a user should be redirected to authenticate
pub fn auth_url(&self, provider: &Provider, state: &ProviderLoginState) -> String {
let authorization_url = &self.discovery.authorization_endpoint;
let client_id = urlencoding::encode(&provider.client_id).to_string();
let state = urlencoding::encode(&state.state_id).to_string();
let callback_url = AppConfig::get().oidc_provider_redirect_url();
format!("{authorization_url}?response_type=code&scope=openid%20profile%20email&client_id={client_id}&state={state}&redirect_uri={callback_url}")
}
/// Retrieve the authorization token after a successful authentication, using an authorization code
pub async fn get_token(
&self,
provider: &Provider,
authorization_code: &str,
) -> Res<TokenResponse> {
let authorization =
BASE64_STANDARD.encode(format!("{}:{}", provider.client_id, provider.client_secret));
let redirect_url = AppConfig::get().oidc_provider_redirect_url();
let mut params = HashMap::new();
params.insert("grant_type", "authorization_code");
params.insert("code", authorization_code);
params.insert("redirect_uri", redirect_url.as_str());
Ok(reqwest::Client::new()
.post(&self.discovery.token_endpoint)
.header("Authorization", format!("Basic {authorization}"))
.form(&params)
.send()
.await?
.json()
.await?)
}
/// Retrieve information about the user, using given [TokenResponse]
pub async fn get_userinfo(&self, token: &TokenResponse) -> Res<OpenIDUserInfo> {
Ok(reqwest::Client::new()
.get(
self.discovery
.userinfo_endpoint
.as_ref()
.expect("Userinfo endpoint is required by this implementation!"),
)
.header("Authorization", format!("Bearer {}", token.access_token))
.send()
.await?
.json()
.await?)
}
}
thread_local! {
static THREAD_CACHE: RefCell<HashMap<String, ProviderConfiguration>> = RefCell::new(Default::default());
}
pub struct ProviderConfigurationHelper {}
impl ProviderConfigurationHelper {
/// Get or refresh the configuration for a provider
pub async fn get_configuration(provider: &Provider) -> Res<ProviderConfiguration> {
let config = THREAD_CACHE.with(|i| i.borrow().get(&provider.configuration_url).cloned());
// Refresh config cache if needed
if config.is_none() || config.as_ref().unwrap().expire < time() {
let conf = Self::fetch_configuration(provider).await?;
THREAD_CACHE.with(|i| {
i.borrow_mut()
.insert(provider.configuration_url.clone(), conf.clone())
});
return Ok(conf);
}
// We can return immediately previously extracted value
Ok(config.unwrap())
}
/// Get fresh configuration from provider
async fn fetch_configuration(provider: &Provider) -> Res<ProviderConfiguration> {
let discovery: ProviderDiscovery = reqwest::get(&provider.configuration_url)
.await?
.json()
.await?;
// let keys: ProviderJWKs = reqwest::get(&discovery.jwks_uri).await?.json().await?;
Ok(ProviderConfiguration {
discovery,
// keys,
expire: time() + OIDC_PROVIDERS_LIFETIME,
})
}
}

View File

@ -21,7 +21,7 @@ pub struct TotpKey {
impl TotpKey {
/// Generate a new TOTP key
pub fn new_random() -> Self {
let random_bytes = rand::thread_rng().gen::<[u8; 10]>();
let random_bytes = rand::thread_rng().gen::<[u8; 20]>();
Self {
encoded: base32::encode(BASE32_ALPHABET, &random_bytes),
}
@ -40,10 +40,10 @@ impl TotpKey {
pub fn url_for_user(&self, u: &User, conf: &AppConfig) -> String {
format!(
"otpauth://totp/{}:{}?secret={}&issuer={}&algorithm=SHA1&digits={}&period={}",
urlencoding::encode(conf.domain_name()),
urlencoding::encode(conf.domain_name_without_port()),
urlencoding::encode(&u.username),
self.encoded,
urlencoding::encode(conf.domain_name()),
urlencoding::encode(conf.domain_name_without_port()),
NUM_DIGITS,
PERIOD,
)
@ -53,7 +53,7 @@ impl TotpKey {
pub fn account_name(&self, u: &User, conf: &AppConfig) -> String {
format!(
"{}:{}",
urlencoding::encode(conf.domain_name()),
urlencoding::encode(conf.domain_name_without_port()),
urlencoding::encode(&u.username)
)
}

View File

@ -1,9 +1,11 @@
use std::collections::HashMap;
use std::net::IpAddr;
use crate::actors::users_actor::AuthorizedAuthenticationSources;
use crate::constants::SECOND_FACTOR_EXEMPTION_AFTER_SUCCESSFUL_LOGIN;
use crate::data::client::{Client, ClientID};
use crate::data::login_redirect::LoginRedirect;
use crate::data::provider::{Provider, ProviderID};
use crate::data::totp_key::TotpKey;
use crate::data::webauthn_manager::WebauthnPubKey;
use crate::utils::time::{fmt_time, time};
@ -114,6 +116,10 @@ impl Successful2FALogin {
}
}
fn default_true() -> bool {
true
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct User {
pub uid: UserID,
@ -142,6 +148,14 @@ pub struct User {
/// None = all services
/// Some([]) = no service
pub authorized_clients: Option<Vec<ClientID>>,
/// Authorize connection through local login
#[serde(default = "default_true")]
pub allow_local_login: bool,
/// Allowed third party providers
#[serde(default)]
pub allow_login_from_providers: Vec<ProviderID>,
}
impl User {
@ -162,6 +176,19 @@ impl User {
)
}
/// Get the list of sources from which a user can authenticate from
pub fn authorized_authentication_sources(&self) -> AuthorizedAuthenticationSources {
AuthorizedAuthenticationSources {
local: self.allow_local_login,
upstream: self.allow_login_from_providers.clone(),
}
}
/// Check if a user can authenticate using a givne provider or not
pub fn can_login_from_provider(&self, provider: &Provider) -> bool {
self.allow_login_from_providers.contains(&provider.id)
}
pub fn granted_clients(&self) -> GrantedClients {
match self.authorized_clients.as_deref() {
None => GrantedClients::AllClients,
@ -296,6 +323,8 @@ impl Default for User {
two_factor_exemption_after_successful_login: false,
last_successful_2fa: Default::default(),
authorized_clients: Some(Vec::new()),
allow_local_login: true,
allow_login_from_providers: vec![],
}
}
}

View File

@ -1,6 +1,6 @@
use std::net::IpAddr;
use crate::actors::users_actor::UsersSyncBackend;
use crate::actors::users_actor::{AuthorizedAuthenticationSources, UsersSyncBackend};
use crate::data::entity_manager::EntityManager;
use crate::data::user::{FactorID, GeneralSettings, GrantedClients, TwoFactor, User, UserID};
use crate::utils::err::{new_error, Res};
@ -41,6 +41,15 @@ fn verify_password<P: AsRef<[u8]>>(pwd: P, hash: &str) -> bool {
}
impl UsersSyncBackend for EntityManager<User> {
fn find_by_email(&self, u: &str) -> Res<Option<User>> {
for entry in self.iter() {
if entry.email.eq(u) {
return Ok(Some(entry.clone()));
}
}
Ok(None)
}
fn find_by_username_or_email(&self, u: &str) -> Res<Option<User>> {
for entry in self.iter() {
if entry.username.eq(u) || entry.email.eq(u) {
@ -143,6 +152,18 @@ impl UsersSyncBackend for EntityManager<User> {
self.remove(&user)
}
fn set_authorized_authentication_sources(
&mut self,
id: &UserID,
sources: AuthorizedAuthenticationSources,
) -> Res {
self.update_user(id, |mut user| {
user.allow_local_login = sources.local;
user.allow_login_from_providers = sources.upstream;
user
})
}
fn set_granted_2fa_clients(&mut self, id: &UserID, clients: GrantedClients) -> Res {
self.update_user(id, |mut user| {
user.authorized_clients = clients.to_user();