Merge branch 'feat_oidc_id_token'
This commit is contained in:
commit
fe5e2dcd97
32 changed files with 496 additions and 104 deletions
|
|
@ -43,6 +43,15 @@ argh = { workspace = true }
|
|||
sqlx = { workspace = true }
|
||||
uuid = { workspace = true }
|
||||
url = { workspace = true }
|
||||
pem = "3.0.4"
|
||||
|
||||
# For now, we test if it's viable, and later we will fork it to fix the build (cf. issue
|
||||
# https://github.com/informationsea/jsonwebkey-rs#1 )
|
||||
[dependencies.jsonwebkey-convert]
|
||||
path = "/home/mbess/workspace/foss/rust_libs/jsonwebkey-rs/jsonwebkey-convert"
|
||||
features = ["simple_asn1", "pem"]
|
||||
|
||||
pem = "3.0.4"
|
||||
|
||||
[build-dependencies]
|
||||
minijinja-embed = "2.3.1"
|
||||
|
|
|
|||
|
|
@ -4,9 +4,9 @@ use fully_pub::fully_pub;
|
|||
use log::error;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use kernel::models::authorization::Authorization;
|
||||
use kernel::{models::authorization::Authorization, repositories::users::get_user_by_id};
|
||||
use crate::{
|
||||
services::{app_session::AppClientSession, session::create_token}, token_claims::AppUserTokenClaims, AppState
|
||||
services::{app_session::AppClientSession, session::create_token}, token_claims::{OAuth2AccessTokenClaims, OIDCIdTokenClaims}, AppState
|
||||
};
|
||||
|
||||
const AUTHORIZATION_CODE_TTL_SECONDS: i64 = 120;
|
||||
|
|
@ -22,6 +22,7 @@ struct AccessTokenRequestParams {
|
|||
#[derive(Serialize, Deserialize)]
|
||||
#[fully_pub]
|
||||
struct AccessTokenResponse {
|
||||
id_token: String,
|
||||
access_token: String,
|
||||
token_type: String,
|
||||
expires_in: u64
|
||||
|
|
@ -60,6 +61,7 @@ pub async fn get_access_token(
|
|||
).into_response();
|
||||
}
|
||||
};
|
||||
|
||||
// 2.2. Validate that the authorization code is not expired
|
||||
let is_code_valid = authorization.last_used_at
|
||||
.map_or(false, |ts| {
|
||||
|
|
@ -72,19 +74,38 @@ pub async fn get_access_token(
|
|||
).into_response();
|
||||
}
|
||||
|
||||
// 3. Generate JWT for oauth2 client user session
|
||||
let jwt = create_token(
|
||||
// 2.3. Fetch user resource owner
|
||||
let user = get_user_by_id(&app_state.db, &authorization.user_id)
|
||||
.await
|
||||
.expect("Expected to get user from authorization.");
|
||||
|
||||
// 3.1. Generate JWT for OAuth2 client user session
|
||||
let access_token_jwt = create_token(
|
||||
&app_state.config,
|
||||
&app_state.secrets,
|
||||
AppUserTokenClaims::new(
|
||||
&app_client_session.client_id,
|
||||
&authorization.user_id,
|
||||
OAuth2AccessTokenClaims::new(
|
||||
&app_state.config,
|
||||
&user,
|
||||
authorization.scopes.to_vec()
|
||||
)
|
||||
);
|
||||
// 3.2. Generate id_token for OIDC client
|
||||
let id_token_claims = OIDCIdTokenClaims::new(
|
||||
&app_state.config,
|
||||
&app_client_session.client_id,
|
||||
user.clone(),
|
||||
authorization.nonce.clone()
|
||||
);
|
||||
let id_token_jwt = create_token(
|
||||
&app_state.config,
|
||||
&app_state.secrets,
|
||||
id_token_claims
|
||||
);
|
||||
// 4. return JWT
|
||||
let access_token_res = AccessTokenResponse {
|
||||
access_token: jwt,
|
||||
token_type: "jwt".to_string(),
|
||||
id_token: id_token_jwt,
|
||||
access_token: access_token_jwt,
|
||||
token_type: "Bearer".to_string(),
|
||||
expires_in: 3600
|
||||
};
|
||||
Json(access_token_res).into_response()
|
||||
|
|
|
|||
45
lib/http_server/src/controllers/api/openid/keys.rs
Normal file
45
lib/http_server/src/controllers/api/openid/keys.rs
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
use jsonwebkey_convert::RSAPublicKey;
|
||||
use jsonwebkey_convert::der::FromPem;
|
||||
|
||||
use axum::{extract::State, response::IntoResponse, Json};
|
||||
use fully_pub::fully_pub;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::AppState;
|
||||
|
||||
// /// JSON Web Key
|
||||
// /// @See https://www.rfc-editor.org/rfc/rfc7517.html
|
||||
// #[derive(Serialize)]
|
||||
// #[fully_pub]
|
||||
// struct RsaJWK {
|
||||
// #[serde(rename = "use")]
|
||||
// utilisation: String,
|
||||
// alg: String,
|
||||
// kid: String,
|
||||
// #[serde(rename = "modulus")]
|
||||
// modulus: String,
|
||||
// exp: String
|
||||
// }
|
||||
|
||||
/// JSON Web Key set
|
||||
/// @See https://www.rfc-editor.org/rfc/rfc7517.html
|
||||
#[derive(Serialize)]
|
||||
#[fully_pub]
|
||||
struct JWKs {
|
||||
keys: Vec<RSAPublicKey>
|
||||
}
|
||||
|
||||
pub async fn get_signing_public_keys(
|
||||
State(app_state): State<AppState>,
|
||||
) -> impl IntoResponse {
|
||||
let pem_data = app_state.secrets.signing_keypair.0;
|
||||
|
||||
// extract modulus and exp number from ASN.1 encoded PCKS 1 package
|
||||
let rsa_jwk = RSAPublicKey::from_pem(pem_data)
|
||||
.expect("Expected to decode PEM public key");
|
||||
dbg!(&rsa_jwk);
|
||||
|
||||
Json(JWKs {
|
||||
keys: vec![rsa_jwk]
|
||||
}).into_response()
|
||||
}
|
||||
|
|
@ -1 +1,2 @@
|
|||
pub mod well_known;
|
||||
pub mod keys;
|
||||
|
|
|
|||
|
|
@ -6,6 +6,8 @@ use strum::IntoEnumIterator;
|
|||
|
||||
use crate::AppState;
|
||||
|
||||
/// Manifest used by OpenID Connect clients
|
||||
/// @See https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
|
||||
#[derive(Serialize)]
|
||||
#[fully_pub]
|
||||
struct WellKnownOpenIdConfiguration {
|
||||
|
|
@ -15,7 +17,9 @@ struct WellKnownOpenIdConfiguration {
|
|||
userinfo_endpoint: String,
|
||||
scopes_supported: Vec<String>,
|
||||
response_types_supported: Vec<String>,
|
||||
token_endpoint_auth_methods_supported: Vec<String>
|
||||
token_endpoint_auth_methods_supported: Vec<String>,
|
||||
id_token_signing_alg_values_supported: Vec<String>,
|
||||
jwks_uri: String
|
||||
}
|
||||
|
||||
pub async fn get_well_known_openid_configuration(
|
||||
|
|
@ -30,5 +34,9 @@ pub async fn get_well_known_openid_configuration(
|
|||
scopes_supported: AuthorizationScope::iter().map(|v| v.to_string()).collect(),
|
||||
response_types_supported: vec!["code".into()],
|
||||
token_endpoint_auth_methods_supported: vec!["client_secret_basic".into()],
|
||||
id_token_signing_alg_values_supported: vec!["RS256".into()],
|
||||
jwks_uri: format!("{}/.well-known/jwks", base_url)
|
||||
// jwks_uri:
|
||||
// subject_types_supported
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ use axum::{extract::State, response::IntoResponse, Extension, Json};
|
|||
use fully_pub::fully_pub;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::{token_claims::AppUserTokenClaims, AppState};
|
||||
use crate::{token_claims::OAuth2AccessTokenClaims, AppState};
|
||||
use kernel::models::user::User;
|
||||
|
||||
#[derive(Serialize)]
|
||||
|
|
@ -18,11 +18,11 @@ struct ReadUserBasicExtract {
|
|||
|
||||
pub async fn read_user_basic(
|
||||
State(app_state): State<AppState>,
|
||||
Extension(token_claims): Extension<AppUserTokenClaims>,
|
||||
Extension(token_claims): Extension<OAuth2AccessTokenClaims>,
|
||||
) -> impl IntoResponse {
|
||||
// 1. This handler require app user authentification (JWT)
|
||||
let user_res = sqlx::query_as::<_, User>("SELECT * FROM users WHERE id = $1")
|
||||
.bind(&token_claims.user_id)
|
||||
.bind(&token_claims.sub)
|
||||
.fetch_one(&app_state.db.0)
|
||||
.await
|
||||
.expect("To get user from claim");
|
||||
|
|
|
|||
|
|
@ -7,9 +7,7 @@ use serde::{Deserialize, Serialize};
|
|||
use url::Url;
|
||||
use uuid::Uuid;
|
||||
|
||||
use kernel::{
|
||||
models::{authorization::Authorization, config::AppAuthorizeFlow}
|
||||
};
|
||||
use kernel::models::{authorization::Authorization, config::AppAuthorizeFlow};
|
||||
use utils::get_random_alphanumerical;
|
||||
use crate::{
|
||||
renderer::TemplateRenderer, services::oauth2::{parse_scope, verify_redirect_uri}, token_claims::UserTokenClaims, AppState
|
||||
|
|
@ -25,6 +23,7 @@ struct AuthorizationParams {
|
|||
redirect_uri: String,
|
||||
/// An opaque value used by the client to maintain state between the request and callback
|
||||
state: String,
|
||||
nonce: Option<String>
|
||||
}
|
||||
|
||||
fn redirect_to_client(
|
||||
|
|
@ -34,7 +33,7 @@ fn redirect_to_client(
|
|||
let target_url = format!("{}?code={}&state={}",
|
||||
authorization_params.redirect_uri,
|
||||
authorization_code,
|
||||
authorization_params.state,
|
||||
authorization_params.state
|
||||
);
|
||||
debug!("Redirecting to {}", target_url);
|
||||
|
||||
|
|
@ -56,6 +55,7 @@ pub async fn authorize_form(
|
|||
query_params: Query<AuthorizationParams>
|
||||
) -> impl IntoResponse {
|
||||
let Query(authorization_params) = query_params;
|
||||
dbg!(&authorization_params);
|
||||
|
||||
// 1. Verify the app details
|
||||
let app = match app_state.config.applications
|
||||
|
|
@ -116,9 +116,10 @@ pub async fn authorize_form(
|
|||
// Create new auth code
|
||||
let authorization_code = get_random_alphanumerical(32);
|
||||
// Update last used timestamp for this authorization
|
||||
let _result = sqlx::query("UPDATE authorizations SET code = $2, last_used_at = $3 WHERE id = $1")
|
||||
let _result = sqlx::query("UPDATE authorizations SET code = $2, nonce = $3, last_used_at = $4 WHERE id = $1")
|
||||
.bind(existing_authorization.id)
|
||||
.bind(authorization_code.clone())
|
||||
.bind(authorization_params.nonce.clone())
|
||||
.bind(Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true))
|
||||
.execute(&app_state.db.0)
|
||||
.await.unwrap();
|
||||
|
|
@ -172,6 +173,7 @@ pub async fn perform_authorize(
|
|||
Extension(token_claims): Extension<UserTokenClaims>,
|
||||
Form(authorize_form): Form<AuthorizationParams>
|
||||
) -> impl IntoResponse {
|
||||
dbg!(&authorize_form);
|
||||
// 1. Get the app details
|
||||
let app = match app_state.config.applications
|
||||
.iter()
|
||||
|
|
@ -203,6 +205,7 @@ pub async fn perform_authorize(
|
|||
client_id: app.client_id.clone(),
|
||||
scopes: sqlx::types::Json(scopes),
|
||||
code: authorization_code.clone(),
|
||||
nonce: authorize_form.nonce.clone(),
|
||||
last_used_at: Some(Utc::now()),
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
|
|
@ -210,14 +213,15 @@ pub async fn perform_authorize(
|
|||
// 3. Save authorization in DB with state
|
||||
let res = sqlx::query("
|
||||
INSERT INTO authorizations
|
||||
(id, user_id, client_id, scopes, code, last_used_at, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
(id, user_id, client_id, scopes, code, nonce, last_used_at, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
")
|
||||
.bind(authorization.id.clone())
|
||||
.bind(authorization.user_id)
|
||||
.bind(authorization.client_id)
|
||||
.bind(authorization.scopes)
|
||||
.bind(authorization.code)
|
||||
.bind(authorization.nonce)
|
||||
.bind(authorization.last_used_at.map(|x| x.to_rfc3339_opts(SecondsFormat::Millis, true)))
|
||||
.bind(authorization.created_at.to_rfc3339_opts(SecondsFormat::Millis, true))
|
||||
.execute(&app_state.db.0)
|
||||
|
|
|
|||
|
|
@ -91,8 +91,8 @@ pub async fn perform_login(
|
|||
.await.unwrap();
|
||||
|
||||
let jwt_max_age = Duration::days(15);
|
||||
let claims = UserTokenClaims::new(&user.id, jwt_max_age);
|
||||
let jwt = create_token(&app_state.secrets, claims);
|
||||
let claims = UserTokenClaims::new(&app_state.config, &user.id, jwt_max_age);
|
||||
let jwt = create_token(&app_state.config, &app_state.secrets, claims);
|
||||
|
||||
// TODO: handle keep_session boolean from form and specify cookie max age only if this setting
|
||||
// is true
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ use utils::parse_basic_auth;
|
|||
|
||||
use crate::{
|
||||
services::{app_session::AppClientSession, session::verify_token},
|
||||
token_claims::AppUserTokenClaims,
|
||||
token_claims::OAuth2AccessTokenClaims,
|
||||
AppState
|
||||
};
|
||||
|
||||
|
|
@ -102,14 +102,16 @@ pub async fn enforce_jwt_auth_middleware(
|
|||
);
|
||||
}
|
||||
};
|
||||
let token_claims: AppUserTokenClaims = match verify_token(&app_state.secrets, jwt) {
|
||||
Ok(val) => val,
|
||||
Err(_e) => {
|
||||
return Err(
|
||||
(StatusCode::UNAUTHORIZED, Html("Unauthorized: The provided JWT is invalid."))
|
||||
);
|
||||
}
|
||||
};
|
||||
let token_claims: OAuth2AccessTokenClaims =
|
||||
match verify_token(&app_state.config, &app_state.secrets, jwt) {
|
||||
Ok(val) => val,
|
||||
Err(_e) => {
|
||||
dbg!(_e);
|
||||
return Err(
|
||||
(StatusCode::UNAUTHORIZED, Html("Unauthorized: The provided JWT is invalid."))
|
||||
);
|
||||
}
|
||||
};
|
||||
req.extensions_mut().insert(token_claims);
|
||||
Ok(next.run(req).await)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,18 +28,20 @@ pub async fn auth_middleware(
|
|||
return Ok(next.run(req).await)
|
||||
}
|
||||
};
|
||||
let token_claims: UserTokenClaims = match verify_token(&app_state.secrets, jwt) {
|
||||
Ok(val) => val,
|
||||
Err(_e) => {
|
||||
// UserWebGUI: delete invalid JWT cookie
|
||||
return Err(
|
||||
(
|
||||
cookies.remove(WEB_GUI_JWT_COOKIE_NAME),
|
||||
Redirect::to(&original_uri.to_string())
|
||||
)
|
||||
);
|
||||
}
|
||||
};
|
||||
let token_claims: UserTokenClaims =
|
||||
match verify_token(&app_state.config, &app_state.secrets, jwt) {
|
||||
Ok(val) => val,
|
||||
Err(_e) => {
|
||||
dbg!(&_e);
|
||||
// UserWebGUI: delete invalid JWT cookie
|
||||
return Err(
|
||||
(
|
||||
cookies.remove(WEB_GUI_JWT_COOKIE_NAME),
|
||||
Redirect::to(&original_uri.to_string())
|
||||
)
|
||||
);
|
||||
}
|
||||
};
|
||||
req.extensions_mut().insert(token_claims);
|
||||
Ok(next.run(req).await)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -51,7 +51,8 @@ pub fn build_router(server_config: &ServerConfig, app_state: AppState) -> Router
|
|||
.route("/api/user-assets/:asset_id", get(api::public_assets::get_user_asset));
|
||||
|
||||
let well_known_routes = Router::new()
|
||||
.route("/.well-known/openid-configuration", get(api::openid::well_known::get_well_known_openid_configuration));
|
||||
.route("/.well-known/openid-configuration", get(api::openid::well_known::get_well_known_openid_configuration))
|
||||
.route("/.well-known/jwks", get(api::openid::keys::get_signing_public_keys));
|
||||
|
||||
Router::new()
|
||||
.merge(public_routes)
|
||||
|
|
|
|||
|
|
@ -12,9 +12,16 @@ pub fn verify_redirect_uri(app: &Application, input_redirect_uri: &str) -> bool
|
|||
pub fn parse_scope(scope_str: &str) -> Result<Vec<AuthorizationScope>> {
|
||||
let mut scopes: Vec<AuthorizationScope> = vec![];
|
||||
for part in scope_str.split(' ') {
|
||||
scopes.push(
|
||||
AuthorizationScope::from_str(part).context("Cannot parse space-delimited scope.")?
|
||||
)
|
||||
if part == "openid" {
|
||||
scopes.push(AuthorizationScope::UserReadBasic);
|
||||
scopes.push(AuthorizationScope::UserReadRoles);
|
||||
continue;
|
||||
}
|
||||
if part == "profile" || part == "email" {
|
||||
continue;
|
||||
}
|
||||
scopes.push(AuthorizationScope::from_str(part).context("Cannot parse space-delimited scope.")?);
|
||||
}
|
||||
dbg!(&scopes);
|
||||
Ok(scopes)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,24 +1,37 @@
|
|||
use anyhow::Result;
|
||||
use serde::{de::DeserializeOwned, Serialize};
|
||||
use jsonwebtoken::{encode, decode, Header, Algorithm, Validation, EncodingKey, DecodingKey};
|
||||
use kernel::context::AppSecrets;
|
||||
use kernel::{context::AppSecrets, models::config::Config};
|
||||
|
||||
|
||||
pub fn create_token<T: Serialize>(secrets: &AppSecrets, claims: T) -> String {
|
||||
pub fn create_token<T: Serialize>(
|
||||
_config: &Config,
|
||||
secrets: &AppSecrets,
|
||||
claims: T
|
||||
) -> String {
|
||||
let token = encode(
|
||||
&Header::default(),
|
||||
&Header::new(Algorithm::RS256),
|
||||
&claims,
|
||||
&EncodingKey::from_secret(secrets.jwt_secret.as_bytes())
|
||||
&EncodingKey::from_rsa_pem(&secrets.signing_keypair.1)
|
||||
.expect("To build encoding key from signing key.")
|
||||
).expect("Create token");
|
||||
|
||||
token
|
||||
}
|
||||
|
||||
pub fn verify_token<T: DeserializeOwned>(secrets: &AppSecrets, jwt: &str) -> Result<T> {
|
||||
pub fn verify_token<T: DeserializeOwned>(
|
||||
config: &Config,
|
||||
secrets: &AppSecrets,
|
||||
jwt: &str
|
||||
) -> Result<T> {
|
||||
let mut validation = Validation::new(Algorithm::RS256);
|
||||
validation.set_issuer(&[config.instance.base_uri.clone()]);
|
||||
validation.set_audience(&[config.instance.base_uri.clone()]);
|
||||
let token_data = decode::<T>(
|
||||
jwt,
|
||||
&DecodingKey::from_secret(secrets.jwt_secret.as_bytes()),
|
||||
&Validation::new(Algorithm::HS256)
|
||||
&DecodingKey::from_rsa_pem(&secrets.signing_keypair.0)
|
||||
.expect("To build decoding key from signing key."),
|
||||
&validation
|
||||
)?;
|
||||
|
||||
Ok(token_data.claims)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
use fully_pub::fully_pub;
|
||||
use jsonwebtoken::get_current_timestamp;
|
||||
use kernel::models::authorization::AuthorizationScope;
|
||||
use kernel::models::{authorization::AuthorizationScope, config::Config, user::User};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use time::Duration;
|
||||
|
||||
|
|
@ -12,41 +12,91 @@ struct UserTokenClaims {
|
|||
/// token expiration
|
||||
exp: u64,
|
||||
/// token issuer
|
||||
iss: String
|
||||
iss: String,
|
||||
// TODO: add roles
|
||||
/// token audience
|
||||
aud: String
|
||||
}
|
||||
|
||||
impl UserTokenClaims {
|
||||
pub fn new(user_id: &str, max_age: Duration) -> Self {
|
||||
pub fn new(config: &Config, user_id: &str, max_age: Duration) -> Self {
|
||||
UserTokenClaims {
|
||||
sub: user_id.into(),
|
||||
exp: get_current_timestamp() + max_age.whole_seconds() as u64,
|
||||
iss: "Minauthator".into()
|
||||
iss: config.instance.base_uri.clone(),
|
||||
aud: config.instance.base_uri.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Access token for OAuth2 defined in RFC 9068
|
||||
/// @See https://datatracker.ietf.org/doc/html/rfc9068
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
#[fully_pub]
|
||||
struct AppUserTokenClaims {
|
||||
/// combined subject
|
||||
client_id: String,
|
||||
user_id: String,
|
||||
scopes: Vec<AuthorizationScope>,
|
||||
/// token expiration
|
||||
struct OAuth2AccessTokenClaims {
|
||||
/// Token issuer (URI to the issuer)
|
||||
iss: String,
|
||||
/// Audiance (In this case, the audiance is equal to the issuer)
|
||||
aud: String,
|
||||
/// End-user id assigned by the issuer (user_id)
|
||||
sub: String,
|
||||
/// Token expiration
|
||||
exp: u64,
|
||||
/// token issuer
|
||||
iss: String
|
||||
/// List of OAuth 2 scopes asked by the client
|
||||
scopes: Vec<AuthorizationScope>
|
||||
}
|
||||
|
||||
impl AppUserTokenClaims {
|
||||
pub fn new(client_id: &str, user_id: &str, scopes: Vec<AuthorizationScope>) -> Self {
|
||||
AppUserTokenClaims {
|
||||
client_id: client_id.into(),
|
||||
user_id: user_id.into(),
|
||||
scopes,
|
||||
impl OAuth2AccessTokenClaims {
|
||||
pub fn new(config: &Config, user: &User, scopes: Vec<AuthorizationScope>) -> Self {
|
||||
OAuth2AccessTokenClaims {
|
||||
iss: config.instance.base_uri.clone(),
|
||||
aud: config.instance.base_uri.clone(),
|
||||
sub: user.id.clone(),
|
||||
exp: get_current_timestamp() + 86_000,
|
||||
iss: "Minauth".into()
|
||||
scopes,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// @See https://openid.net/specs/openid-connect-core-1_0.html#IDToken
|
||||
/// @See https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
#[fully_pub]
|
||||
struct OIDCIdTokenClaims {
|
||||
/// Token expiration
|
||||
exp: u64,
|
||||
/// Token issuer (URI to the issuer)
|
||||
iss: String,
|
||||
/// Audiance (client_id)
|
||||
aud: String,
|
||||
/// End-user id assigned by the issuer (user_id)
|
||||
sub: String,
|
||||
/// additional claims
|
||||
name: Option<String>,
|
||||
email: Option<String>,
|
||||
preferred_username: Option<String>,
|
||||
roles: Vec<String>,
|
||||
nonce: Option<String>
|
||||
}
|
||||
|
||||
impl OIDCIdTokenClaims {
|
||||
pub fn new(
|
||||
config: &Config,
|
||||
client_id: &str,
|
||||
user: User,
|
||||
nonce: Option<String>
|
||||
) -> Self {
|
||||
OIDCIdTokenClaims {
|
||||
iss: config.instance.base_uri.clone(),
|
||||
aud: client_id.into(),
|
||||
sub: user.id,
|
||||
exp: get_current_timestamp() + 86_000,
|
||||
email: user.email,
|
||||
name: user.full_name,
|
||||
preferred_username: Some(user.handle),
|
||||
roles: user.roles.0,
|
||||
nonce
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
pub const DEFAULT_DB_PATH: &str = "/var/lib/minauthator/minauthator.db";
|
||||
pub const DEFAULT_ASSETS_PATH: &str = "/usr/local/lib/minauthator/assets";
|
||||
pub const DEFAULT_CONFIG_PATH: &str = "/etc/minauthator/config.toml";
|
||||
pub const DEFAULT_SIGNING_KEY_PATH: &str = "/etc/minauthator/secrets/jwt.key.pem";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
use std::{env, fs};
|
||||
use std::{env, fs, path::Path};
|
||||
use anyhow::{Result, Context, anyhow};
|
||||
use fully_pub::fully_pub;
|
||||
|
||||
use log::info;
|
||||
use sqlx::{Pool, Sqlite};
|
||||
use crate::{
|
||||
consts::{DEFAULT_CONFIG_PATH, DEFAULT_DB_PATH}, database::prepare_database, models::config::Config, repositories::storage::Storage
|
||||
consts::{DEFAULT_CONFIG_PATH, DEFAULT_DB_PATH, DEFAULT_SIGNING_KEY_PATH},
|
||||
database::prepare_database,
|
||||
models::config::Config,
|
||||
repositories::storage::Storage
|
||||
};
|
||||
|
||||
/// get server config
|
||||
|
|
@ -26,9 +28,18 @@ struct StartKernelConfig {
|
|||
#[derive(Debug, Clone)]
|
||||
#[fully_pub]
|
||||
struct AppSecrets {
|
||||
jwt_secret: String
|
||||
/// RSA keypair (public, private) used to signed the JWT issued by minauthator in PEM conainer format
|
||||
signing_keypair: (Vec<u8>, Vec<u8>)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[fully_pub]
|
||||
struct ComputedConfig {
|
||||
signing_public_key: Vec<u8>,
|
||||
signing_private_key: Vec<u8>
|
||||
}
|
||||
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[fully_pub]
|
||||
struct KernelContext {
|
||||
|
|
@ -37,6 +48,19 @@ struct KernelContext {
|
|||
storage: Storage
|
||||
}
|
||||
|
||||
fn get_signing_keypair(key_path: &str) -> Result<(Vec<u8>, Vec<u8>)> {
|
||||
let key_path = Path::new(key_path);
|
||||
let pub_key_path = key_path.with_extension("pub");
|
||||
let private_key: Vec<u8> = fs::read_to_string(&key_path)
|
||||
.context(format!("Failed to read private key from path {:?}.", key_path))?
|
||||
.as_bytes().to_vec();
|
||||
let public_key: Vec<u8> = fs::read_to_string(&pub_key_path)
|
||||
.context(format!("Failed to read public key from path {:?}.", pub_key_path))?
|
||||
.as_bytes().to_vec();
|
||||
|
||||
Ok((public_key, private_key))
|
||||
}
|
||||
|
||||
pub async fn get_kernel_context(start_config: StartKernelConfig) -> Result<KernelContext> {
|
||||
env_logger::init();
|
||||
let _ = dotenvy::dotenv();
|
||||
|
|
@ -50,10 +74,13 @@ pub async fn get_kernel_context(start_config: StartKernelConfig) -> Result<Kerne
|
|||
let config: Config = get_config(config_path)
|
||||
.expect("Cannot get config.");
|
||||
|
||||
let signing_key_path = config.signing_key.clone().unwrap_or(DEFAULT_SIGNING_KEY_PATH.to_string());
|
||||
|
||||
// optionally load dotenv file
|
||||
let _ = dotenvy::dotenv();
|
||||
|
||||
let secrets = AppSecrets {
|
||||
jwt_secret: env::var("APP_JWT_SECRET")
|
||||
.context("Expected APP_JWT_SECRET environment variable to exists.")?
|
||||
signing_keypair: get_signing_keypair(&signing_key_path)?
|
||||
};
|
||||
|
||||
Ok(KernelContext {
|
||||
|
|
|
|||
|
|
@ -25,6 +25,8 @@ struct Authorization {
|
|||
client_id: String,
|
||||
scopes: Json<Vec<AuthorizationScope>>,
|
||||
|
||||
nonce: Option<String>,
|
||||
|
||||
/// defined in https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.2
|
||||
code: String,
|
||||
last_used_at: Option<DateTime<Utc>>,
|
||||
|
|
|
|||
|
|
@ -66,11 +66,6 @@ struct Role {
|
|||
struct Config {
|
||||
instance: InstanceConfig,
|
||||
applications: Vec<Application>,
|
||||
roles: Vec<Role>
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[fully_pub]
|
||||
struct AppSecrets {
|
||||
jwt_secret: String
|
||||
roles: Vec<Role>,
|
||||
signing_key: Option<String>
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ enum UserStatus {
|
|||
Active
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow, Deserialize, Serialize, Debug)]
|
||||
#[derive(sqlx::FromRow, Deserialize, Serialize, Debug, Clone)]
|
||||
#[fully_pub]
|
||||
struct User {
|
||||
/// uuid
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue