Skip to content

Support offline validation of JWTs and RBAC #602

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/zitadel/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -176,3 +176,4 @@ path = "examples/rocket_webapi_oauth_interception_jwtprofile.rs"
name = "service_account_authentication"
required-features = ["credentials"]
path = "examples/service_account_authentication.rs"

81 changes: 36 additions & 45 deletions crates/zitadel/src/actix/introspection/extractor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,9 @@ use actix_web::dev::Payload;
use actix_web::error::{ErrorInternalServerError, ErrorUnauthorized};
use actix_web::{Error, FromRequest, HttpRequest};
use custom_error::custom_error;
use openidconnect::TokenIntrospectionResponse;
use std::collections::HashMap;

use crate::actix::introspection::config::IntrospectionConfig;
use crate::oidc::introspection::{introspect, IntrospectionError, ZitadelIntrospectionResponse};
use crate::oidc::introspection::{claims::ZitadelClaims, introspect, IntrospectionError};

custom_error! {
/// Error type for extractor related errors.
Expand All @@ -22,43 +20,31 @@ custom_error! {
NoUserId = "introspection result contained no user id",
}

/// Struct for the handler function that requires an authenticated user.
/// Contains various information about the given token. The fields are optional
/// since a machine user does not have a profile or (varying by scope) not all
/// fields are returned from the introspection endpoint.
#[derive(Debug)]
pub struct IntrospectedUser {
/// UserID of the introspected user (OIDC Field "sub").
pub user_id: String,
pub username: Option<String>,
pub name: Option<String>,
pub given_name: Option<String>,
pub family_name: Option<String>,
pub preferred_username: Option<String>,
pub email: Option<String>,
pub email_verified: Option<bool>,
pub locale: Option<String>,
pub project_roles: Option<HashMap<String, HashMap<String, String>>>,
pub metadata: Option<HashMap<String, String>>,
}

impl From<ZitadelIntrospectionResponse> for IntrospectedUser {
fn from(response: ZitadelIntrospectionResponse) -> Self {
Self {
user_id: response.sub().unwrap().to_string(),
username: response.username().map(|s| s.to_string()),
name: response.extra_fields().name.clone(),
given_name: response.extra_fields().given_name.clone(),
family_name: response.extra_fields().family_name.clone(),
preferred_username: response.extra_fields().preferred_username.clone(),
email: response.extra_fields().email.clone(),
email_verified: response.extra_fields().email_verified,
locale: response.extra_fields().locale.clone(),
project_roles: response.extra_fields().project_roles.clone(),
metadata: response.extra_fields().metadata.clone(),
}
}
}
/// Type alias for the extracted user.
///
/// The extracted user will always be valid when fetched in request function arguments.
/// If not, the API will return with an appropriate error.
///
/// # Example
///
/// ```
/// use actix_web::{get, HttpResponse, Responder};
/// use zitadel::actix::introspection::IntrospectedUser;
///
/// #[get("/protected")]
/// async fn protected_route(user: IntrospectedUser) -> impl Responder {
/// if !user.has_role("admin") {
/// return HttpResponse::Forbidden().body("Admin access required");
/// }
///
/// if user.has_role_in_project("project123", "editor") {
/// return HttpResponse::Ok().body("Hello Editor");
/// }
///
/// HttpResponse::Ok().body("Hello Admin")
/// }
/// ```
pub type IntrospectedUser = ZitadelClaims;

impl FromRequest for IntrospectedUser {
type Error = Error;
Expand Down Expand Up @@ -115,12 +101,17 @@ impl FromRequest for IntrospectedUser {
));
}

let result = result.unwrap();
match result.active() {
true if result.sub().is_some() => Ok(result.into()),
false => Err(ErrorUnauthorized(IntrospectionExtractorError::Inactive)),
_ => Err(ErrorUnauthorized(IntrospectionExtractorError::NoUserId)),
let claims = result.unwrap();

if !claims.active {
return Err(ErrorUnauthorized(IntrospectionExtractorError::Inactive));
}

if claims.sub.is_empty() {
return Err(ErrorUnauthorized(IntrospectionExtractorError::NoUserId));
}

Ok(claims)
})
}
}
Expand Down
112 changes: 32 additions & 80 deletions crates/zitadel/src/axum/introspection/user.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use std::collections::HashMap;
use std::fmt::Debug;

use crate::axum::introspection::IntrospectionState;
use axum::http::StatusCode;
Expand All @@ -13,10 +12,9 @@ use axum_extra::headers::authorization::Bearer;
use axum_extra::headers::Authorization;
use axum_extra::TypedHeader;
use custom_error::custom_error;
use openidconnect::TokenIntrospectionResponse;
use serde_json::json;

use crate::oidc::introspection::{introspect, IntrospectionError, ZitadelIntrospectionResponse};
use crate::oidc::introspection::{claims::ZitadelClaims, introspect, IntrospectionError};

custom_error! {
/// Error type for guard related errors.
Expand Down Expand Up @@ -54,61 +52,31 @@ impl IntoResponse for IntrospectionGuardError {
}
}

/// Struct for the extracted user. The extracted user will always be valid, when fetched in a
/// request function arguments. If not the api will return with an appropriate error.
/// Type alias for the extracted user.
///
/// The extracted user will always be valid when fetched in request function arguments.
/// If not, the API will return with an appropriate error.
///
/// It can be used as a basis for further customized authorization checks with a custom extractor
/// or an extension trait.
/// # Example
///
/// ```
/// use axum::http::StatusCode;
/// use axum::response::IntoResponse;
/// use zitadel::axum::introspection::IntrospectedUser;
///
/// enum Role {
/// Admin,
/// Client
/// }
///
/// async fn my_handler(user: IntrospectedUser) -> impl IntoResponse {
/// if !user.has_role(Role::Admin, "MY-ORG-ID") {
/// if !user.has_role("admin") {
/// return StatusCode::FORBIDDEN.into_response();
/// }
/// "Hello Admin".into_response()
/// }
///
/// trait MyAuthorizationChecks {
/// fn has_role(&self, role: Role, org_id: &str) -> bool;
/// }
///
/// impl MyAuthorizationChecks for IntrospectedUser {
/// fn has_role(&self, role: Role, org_id: &str) -> bool {
/// let role = match role {
/// Role::Admin => "Admin",
/// Role::Client => "Client",
/// };
/// self.project_roles.as_ref()
/// .and_then(|roles| roles.get(role))
/// .map(|org_ids| org_ids.contains_key(org_id))
/// .unwrap_or(false)
///
/// if user.has_role_in_project("project123", "editor") {
/// return "Hello Editor".into_response();
/// }
///
/// "Hello Admin".into_response()
/// }
/// ```
#[derive(Debug)]
pub struct IntrospectedUser {
/// UserID of the introspected user (OIDC Field "sub").
pub user_id: String,
pub username: Option<String>,
pub name: Option<String>,
pub given_name: Option<String>,
pub family_name: Option<String>,
pub preferred_username: Option<String>,
pub email: Option<String>,
pub email_verified: Option<bool>,
pub locale: Option<String>,
pub project_roles: Option<HashMap<String, HashMap<String, String>>>,
pub metadata: Option<HashMap<String, String>>,
}
pub type IntrospectedUser = ZitadelClaims;

impl<S> FromRequestParts<S> for IntrospectedUser
where
Expand Down Expand Up @@ -166,37 +134,17 @@ where
)
.await;

let user: Result<IntrospectedUser, IntrospectionGuardError> = match res {
Ok(res) => match res.active() {
true if res.sub().is_some() => Ok(res.into()),
false => Err(IntrospectionGuardError::Inactive),
_ => Err(IntrospectionGuardError::NoUserId),
},
Err(source) => return Err(IntrospectionGuardError::Introspection { source }),
};

user
}
}
let claims = res.map_err(|source| IntrospectionGuardError::Introspection { source })?;

impl From<ZitadelIntrospectionResponse> for IntrospectedUser {
fn from(response: ZitadelIntrospectionResponse) -> Self {
Self {
user_id: response.sub().unwrap().to_string(),
username: response.username().map(|s| s.to_string()),
name: response.extra_fields().name.clone(),
given_name: response.extra_fields().given_name.clone(),
family_name: response.extra_fields().family_name.clone(),
preferred_username: response.extra_fields().preferred_username.clone(),
email: response.extra_fields().email.clone(),
email_verified: response.extra_fields().email_verified,
locale: response.extra_fields().locale.clone(),
project_roles: response.extra_fields().project_roles.clone(),
metadata: response.extra_fields().metadata.clone(),
if claims.sub.is_empty() {
return Err(IntrospectionGuardError::NoUserId);
}

Ok(claims)
}
}


#[cfg(test)]
mod tests {
#![allow(clippy::all)]
Expand Down Expand Up @@ -229,7 +177,7 @@ mod tests {
async fn authed(user: IntrospectedUser) -> impl IntoResponse {
format!(
"Hello authorized user: {:?} with id {}",
user.username, user.user_id
user.username, user.sub
)
}

Expand Down Expand Up @@ -362,7 +310,6 @@ mod tests {
use super::*;
use crate::oidc::introspection::cache::in_memory::InMemoryIntrospectionCache;
use crate::oidc::introspection::cache::IntrospectionCache;
use crate::oidc::introspection::ZitadelIntrospectionExtraTokenFields;
use chrono::{TimeDelta, Utc};
use http_body_util::BodyExt;
use std::ops::Add;
Expand Down Expand Up @@ -393,12 +340,17 @@ mod tests {
let cache = Arc::new(InMemoryIntrospectionCache::default());
let app = app_witch_cache(cache.clone()).await;

let mut res = ZitadelIntrospectionResponse::new(
true,
ZitadelIntrospectionExtraTokenFields::default(),
);
res.set_sub(Some("cached_sub".to_string()));
res.set_exp(Some(Utc::now().add(TimeDelta::days(1))));
use crate::oidc::introspection::claims::ZitadelClaims;
let res = ZitadelClaims {
sub: "cached_sub".to_string(),
iss: "https://test.zitadel.cloud".to_string(),
aud: vec!["test".to_string()],
username: Some("cached_user".to_string()),
exp: Utc::now().add(TimeDelta::days(1)).timestamp(),
iat: Utc::now().timestamp(),
active: true,
..Default::default()
};
cache.set(PERSONAL_ACCESS_TOKEN, res).await;

let response = app
Expand Down Expand Up @@ -454,7 +406,7 @@ mod tests {

let cached_response = cache.get(PERSONAL_ACCESS_TOKEN).await.unwrap();

assert!(text.contains(cached_response.sub().unwrap()));
assert!(text.contains(&cached_response.username.unwrap()));
}
}
}
6 changes: 3 additions & 3 deletions crates/zitadel/src/credentials/service_account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
use openidconnect::{
core::{CoreProviderMetadata, CoreTokenType},
http::HeaderMap,
EmptyExtraTokenFields, IssuerUrl, OAuth2TokenResponse, StandardTokenResponse,
EmptyExtraTokenFields, HttpClientError, IssuerUrl, OAuth2TokenResponse, StandardTokenResponse,
};
use reqwest::{
header::{ACCEPT, CONTENT_TYPE},
Expand Down Expand Up @@ -70,7 +70,7 @@ custom_error! {
Json{source: serde_json::Error} = "could not parse json: {source}",
Key{source: jsonwebtoken::errors::Error} = "could not parse RSA key: {source}",
AudienceUrl{source: openidconnect::url::ParseError} = "audience url could not be parsed: {source}",
DiscoveryError{source: Box<dyn std::error::Error>} = "could not discover OIDC document: {source}",
DiscoveryError{source: openidconnect::DiscoveryError<HttpClientError<openidconnect::reqwest::Error>>} = "could not discover OIDC document: {source}",
TokenEndpointMissing = "OIDC document does not contain token endpoint",
HttpError{source: openidconnect::reqwest::Error} = "http error: {source}",
UrlEncodeError = "could not encode url params for token request",
Expand Down Expand Up @@ -241,7 +241,7 @@ impl ServiceAccount {
let metadata = CoreProviderMetadata::discover_async(issuer, &async_http_client)
.await
.map_err(|e| ServiceAccountError::DiscoveryError {
source: Box::new(e),
source: e,
})?;

let jwt = self.create_signed_jwt(audience)?;
Expand Down
Loading