Skip to content

Commit

Permalink
move helper fn's only used in tests outside of main code
Browse files Browse the repository at this point in the history
  • Loading branch information
sebadob committed Jun 25, 2024
1 parent 152dd52 commit 51f9ad9
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 50 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions src/bin/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,5 @@ josekit = "0.8"
pretty_assertions = "1"
reqwest = { workspace = true }
ring = { workspace = true }
serde = "1"
tokio-test = "*"
39 changes: 38 additions & 1 deletion src/bin/tests/common.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
#![allow(dead_code)]
use rauthy_api_types::oidc::{LoginRequest, SessionInfoResponse, TokenRequest};
use rauthy_common::constants::CSRF_HEADER;
use rauthy_common::utils::base64_url_encode;
use rauthy_common::utils::{base64_url_encode, base64_url_no_pad_decode};
use rauthy_error::{ErrorResponse, ErrorResponseType};
use rauthy_service::token_set::TokenSet;
use reqwest::header::{HeaderMap, HeaderValue, SET_COOKIE};
use reqwest::{header, Response};
use ring::digest;
use std::env;
use std::error::Error;
use std::sync::OnceLock;
use tracing::error;

#[macro_export]
macro_rules! aw {
Expand Down Expand Up @@ -206,3 +208,38 @@ pub fn code_state_from_headers(res: Response) -> Result<(String, Option<String>)

Ok((code, state))
}

// Extracts the claims from a given token into a HashMap.
// Returns an empty HashMap if no values could be extracted at all.
// CAUTION: Does not validate the token!
pub fn extract_token_claims_unverified<T>(token: &str) -> Result<T, ErrorResponse>
where
T: for<'a> serde::Deserialize<'a>,
{
let body = match token.split_once('.') {
None => None,
Some((_metadata, rest)) => rest.split_once('.').map(|(body, _validation_str)| body),
};
if body.is_none() {
return Err(ErrorResponse::new(
ErrorResponseType::Unauthorized,
"Invalid or malformed JWT Token",
));
}
let body = body.unwrap();
let b64 = base64_url_no_pad_decode(body).unwrap();

let s = String::from_utf8_lossy(b64.as_slice());
let claims = match serde_json::from_str::<T>(s.as_ref()) {
Ok(claims) => claims,
Err(err) => {
error!("Error deserializing JWT Token claims: {}", err);
return Err(ErrorResponse::new(
ErrorResponseType::BadRequest,
"Invalid JWT Token claims",
));
}
};

Ok(claims)
}
5 changes: 3 additions & 2 deletions src/bin/tests/zza_handler_cust_attrs.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
use crate::common::{get_auth_headers, get_backend_url, get_token_set};
use crate::common::{
extract_token_claims_unverified, get_auth_headers, get_backend_url, get_token_set,
};
use rauthy_api_types::clients::{ClientResponse, UpdateClientRequest};
use rauthy_api_types::oidc::JwkKeyPairAlg;
use rauthy_api_types::scopes::{ScopeRequest, ScopeResponse};
use rauthy_api_types::users::{
UserAttrConfigRequest, UserAttrConfigResponse, UserAttrValueRequest, UserAttrValuesResponse,
UserAttrValuesUpdateRequest,
};
use rauthy_common::utils::extract_token_claims_unverified;
use rauthy_models::entity::user_attr::UserAttrConfigEntity;
use rauthy_models::JwtAccessClaims;
use serde_json::Value;
Expand Down
47 changes: 0 additions & 47 deletions src/common/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,53 +100,6 @@ pub fn new_store_id() -> String {
get_rand(24)
}

// Extracts the claims from a given token into a HashMap.
// Returns an empty HashMap if no values could be extracted at all.
// CAUTION: Does not validate the token!
pub fn extract_token_claims_unverified<T>(token: &str) -> Result<T, ErrorResponse>
where
T: for<'a> serde::Deserialize<'a>,
{
let body = match token.split_once('.') {
None => None,
Some((_metadata, rest)) => rest.split_once('.').map(|(body, _validation_str)| body),
};
if body.is_none() {
return Err(ErrorResponse::new(
ErrorResponseType::Unauthorized,
"Invalid or malformed JWT Token",
));
}
let body = body.unwrap();

let b64 = match B64_URL_SAFE_NO_PAD.decode(body) {
Ok(values) => values,
Err(err) => {
error!(
"Error decoding JWT token body '{}' from base64: {}",
body, err
);
return Err(ErrorResponse::new(
ErrorResponseType::BadRequest,
"Invalid JWT Token body",
));
}
};
let s = String::from_utf8_lossy(b64.as_slice());
let claims = match serde_json::from_str::<T>(s.as_ref()) {
Ok(claims) => claims,
Err(err) => {
error!("Error deserializing JWT Token claims: {}", err);
return Err(ErrorResponse::new(
ErrorResponseType::BadRequest,
"Invalid JWT Token claims",
));
}
};

Ok(claims)
}

// TODO unify real_ip_from_req and real_ip_from_svc_req by using an impl Trait
#[inline(always)]
pub fn real_ip_from_req(req: &HttpRequest) -> Result<IpAddr, ErrorResponse> {
Expand Down

0 comments on commit 51f9ad9

Please sign in to comment.