Skip to content

Commit 1b5a7e4

Browse files
committed
code quality
1 parent 1873193 commit 1b5a7e4

File tree

7 files changed

+86
-61
lines changed

7 files changed

+86
-61
lines changed

src/bin/rs256keygen.rs

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -38,11 +38,14 @@
3838
3939
use std::fs::File;
4040
use std::io::Write;
41+
use std::io::{self};
4142
use std::path::PathBuf;
43+
use std::sync::{
44+
atomic::{AtomicBool, Ordering},
45+
Arc,
46+
};
4247
use std::thread;
4348
use std::time::Duration;
44-
use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
45-
use std::io::{self, Write as IoWrite};
4649

4750
use anyhow::{Context, Result};
4851
use clap::Parser;
@@ -106,11 +109,11 @@ fn main() -> Result<()> {
106109
let args = Args::parse();
107110

108111
println!("Generating RSA key pair with {} bits...", args.length);
109-
112+
110113
// Flag to indicate when key generation is complete
111114
let generating = Arc::new(AtomicBool::new(true));
112115
let generating_clone = generating.clone();
113-
116+
114117
// Spawn a thread to display a spinner while generating keys
115118
let spinner_handle = thread::spawn(move || {
116119
let spinner_chars = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
@@ -131,14 +134,14 @@ fn main() -> Result<()> {
131134
// Generate a new random RSA key pair with the specified bits
132135
let private_key =
133136
RsaPrivateKey::new(&mut rng, args.length).context("Failed to generate RSA private key")?;
134-
137+
135138
// Signal that generation is complete
136139
generating.store(false, Ordering::Relaxed);
137140
// Wait for spinner thread to finish
138141
spinner_handle.join().ok();
139-
142+
140143
println!("RSA key pair generation completed successfully.");
141-
144+
142145
let public_key = RsaPublicKey::from(&private_key);
143146

144147
// Convert keys to PKCS#1 PEM format

src/daemon/launch_daemon.rs

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -219,11 +219,19 @@ impl Daemon {
219219
.merge(("log_level", LogLevel::Normal));
220220

221221
// Add RS256 keys to figment
222-
if !config.visualization.rs256_public_key.is_empty() && !config.visualization.rs256_private_key.is_empty() {
222+
if !config.visualization.rs256_public_key.is_empty()
223+
&& !config.visualization.rs256_private_key.is_empty()
224+
{
223225
debug!("RS256 keys found in configuration");
224226
figment = figment
225-
.merge(("rs256_public_key", config.visualization.rs256_public_key.clone()))
226-
.merge(("rs256_private_key", config.visualization.rs256_private_key.clone()));
227+
.merge((
228+
"rs256_public_key",
229+
config.visualization.rs256_public_key.clone(),
230+
))
231+
.merge((
232+
"rs256_private_key",
233+
config.visualization.rs256_private_key.clone(),
234+
));
227235
}
228236

229237
// Configure TLS if certificates are provided

src/visualization/jwt.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -483,13 +483,13 @@ impl Issuer for JwtTokenMap {
483483
return Ok(Some(entry.grant.clone()));
484484
}
485485

486-
// Create custom validation
487-
let mut validation = Validation::new(self.algorithm);
488-
validation.validate_exp = true;
489-
validation.validate_nbf = true;
490-
validation.set_issuer(&[&self.issuer]);
491-
// We should extract the audience from the token first and then validate it
492-
// This approach is needed because we may not know the audience in advance
486+
// Create custom validation
487+
let mut validation = Validation::new(self.algorithm);
488+
validation.validate_exp = true;
489+
validation.validate_nbf = true;
490+
validation.set_issuer(&[&self.issuer]);
491+
// We should extract the audience from the token first and then validate it
492+
// This approach is needed because we may not know the audience in advance
493493

494494
let token_data = match decode::<JwtClaims>(token, &self.verification_key, &validation) {
495495
Ok(data) => data,

src/visualization/jwt_keys.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,10 +65,10 @@ use base64::prelude::*;
6565
use jsonwebtoken::jwk::{Jwk, PublicKeyUse};
6666
use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey};
6767
use rsa::pkcs1::DecodeRsaPublicKey;
68+
use rsa::sha2::Digest;
69+
use rsa::sha2::Sha256;
6870
use rsa::traits::PublicKeyParts;
6971
use rsa::RsaPublicKey;
70-
use rsa::sha2::Sha256;
71-
use rsa::sha2::Digest;
7272
use serde::{Deserialize, Serialize};
7373
use serde_json::json;
7474
use std::fs::File;

src/visualization/oidc.rs

Lines changed: 34 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,12 @@
1616
//! capabilities and configuration, including supported signing algorithms and endpoints.
1717
1818
use base64::Engine;
19-
use rocket::serde::json::{Json, Value, json};
19+
use rocket::serde::json::{json, Json, Value};
2020
use rocket::{get, State};
2121
use serde::{Deserialize, Serialize};
2222

23-
use crate::visualization::jwt_keys::JwkKeySet;
2423
use super::oxide_auth::OxideState;
24+
use crate::visualization::jwt_keys::JwkKeySet;
2525

2626
/// OpenID Connect Discovery Configuration
2727
///
@@ -32,34 +32,34 @@ use super::oxide_auth::OxideState;
3232
pub struct OpenIdConfiguration {
3333
/// URL using the https scheme with no query or fragment component that the OP asserts as its Issuer Identifier
3434
pub issuer: String,
35-
35+
3636
/// URL of the OP's OAuth 2.0 Authorization Endpoint
3737
pub authorization_endpoint: String,
38-
38+
3939
/// URL of the OP's OAuth 2.0 Token Endpoint
4040
pub token_endpoint: String,
41-
41+
4242
/// URL of the OP's JSON Web Key Set document
4343
pub jwks_uri: String,
44-
44+
4545
/// JSON array containing a list of the OAuth 2.0 response_type values that this server supports
4646
pub response_types_supported: Vec<String>,
47-
47+
4848
/// JSON array containing a list of the OAuth 2.0 Grant Type values that this server supports
4949
pub grant_types_supported: Vec<String>,
50-
50+
5151
/// JSON array containing a list of the Subject Identifier types that this server supports
5252
pub subject_types_supported: Vec<String>,
53-
53+
5454
/// JSON array containing a list of the JWS signing algorithms supported by this server for the ID Token
5555
pub id_token_signing_alg_values_supported: Vec<String>,
56-
56+
5757
/// JSON array containing a list of the JWS algorithms that this server supports for the UserInfo Endpoint
5858
pub userinfo_signing_alg_values_supported: Vec<String>,
59-
59+
6060
/// JSON array containing the scopes that this server supports
6161
pub scopes_supported: Vec<String>,
62-
62+
6363
/// JSON array containing a list of the claim names of the Claims that the OpenID Provider supports
6464
pub claims_supported: Vec<String>,
6565
}
@@ -81,20 +81,26 @@ pub struct OpenIdConfiguration {
8181
fn generate_openid_configuration(base_url: &str, state: &OxideState) -> OpenIdConfiguration {
8282
// Determine which signing algorithms are supported
8383
let mut signing_algs = vec!["HS256".to_string()];
84-
84+
8585
// If we have RS256 keys configured, add RS256
8686
log::debug!("RS256 public key length: {}", state.rs256_public_key.len());
87-
log::debug!("RS256 private key length: {}", state.rs256_private_key.len());
88-
87+
log::debug!(
88+
"RS256 private key length: {}",
89+
state.rs256_private_key.len()
90+
);
91+
8992
if !state.rs256_public_key.is_empty() && !state.rs256_private_key.is_empty() {
9093
// Add RS256 if we have keys, regardless of whether decoding succeeds
9194
signing_algs.push("RS256".to_string());
9295
log::debug!("RS256 signing algorithm added to OpenID configuration");
9396
} else {
94-
log::warn!("RS256 keys are not properly configured - public key empty: {}, private key empty: {}",
95-
state.rs256_public_key.is_empty(), state.rs256_private_key.is_empty());
97+
log::warn!(
98+
"RS256 keys are not properly configured - public key empty: {}, private key empty: {}",
99+
state.rs256_public_key.is_empty(),
100+
state.rs256_private_key.is_empty()
101+
);
96102
}
97-
103+
98104
OpenIdConfiguration {
99105
issuer: base_url.to_string(),
100106
authorization_endpoint: format!("{}/authorize", base_url),
@@ -149,10 +155,10 @@ pub async fn openid_configuration(state: &State<OxideState>) -> Json<OpenIdConfi
149155
// In a production environment, you would want to get the base URL from the request
150156
// or configuration. For simplicity, we're using a hardcoded value here.
151157
let base_url = "http://localhost:8080";
152-
158+
153159
// Generate the configuration document
154160
let config = generate_openid_configuration(base_url, state);
155-
161+
156162
Json(config)
157163
}
158164

@@ -164,9 +170,9 @@ pub async fn openid_configuration(state: &State<OxideState>) -> Json<OpenIdConfi
164170
/// issued by this server.
165171
///
166172
/// # URL
167-
///
168-
///
169-
///
173+
///
174+
///
175+
///
170176
///
171177
/// `GET /.well-known/jwks.json`
172178
///
@@ -177,17 +183,19 @@ pub async fn openid_configuration(state: &State<OxideState>) -> Json<OpenIdConfi
177183
pub async fn jwks(state: &State<OxideState>) -> Json<Value> {
178184
// Create a key set for our public keys
179185
let mut keys = vec![];
180-
186+
181187
// If we have an RS256 public key, add it to the key set
182-
if let Ok(rs256_pub_key) = base64::engine::general_purpose::STANDARD.decode(&state.rs256_public_key) {
188+
if let Ok(rs256_pub_key) =
189+
base64::engine::general_purpose::STANDARD.decode(&state.rs256_public_key)
190+
{
183191
if !rs256_pub_key.is_empty() {
184192
// Parse the PEM encoded public key
185193
if let Ok(jwk) = JwkKeySet::create_jwk_from_pem(&rs256_pub_key) {
186194
keys.push(jwk);
187195
}
188196
}
189197
}
190-
198+
191199
// Return the key set
192200
Json(json!({
193201
"keys": keys

src/visualization/server.rs

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,9 @@
5151
//! ```
5252
5353
use crate::include_png_as_base64;
54-
use base64::Engine;
54+
use crate::visualization::oidc::{jwks, openid_configuration}; // Add this import
5555
use crate::visualization::oxide_auth::{authorize, authorize_consent, refresh, token};
56-
use crate::visualization::oidc::{openid_configuration, jwks}; // Add this import
56+
use base64::Engine;
5757
use include_dir::{include_dir, Dir};
5858
use rocket::fairing::{Fairing, Info, Kind};
5959
use rocket::figment::Figment;
@@ -221,21 +221,27 @@ async fn options(_path: PathBuf) -> Result<(), std::io::Error> {
221221
pub async fn build_rocket(figment: Figment, hmac_secret: &str) -> Rocket<Build> {
222222
// Create OAuth2 state with the HMAC secret from config
223223
let mut oxide_state = OxideState::preconfigured(hmac_secret);
224-
224+
225225
// Extract RS256 keys from figment if present
226226
if let Some(private_key) = figment.extract_inner::<String>("rs256_private_key").ok() {
227227
oxide_state.rs256_private_key = private_key;
228228
}
229-
229+
230230
if let Some(public_key) = figment.extract_inner::<String>("rs256_public_key").ok() {
231231
oxide_state.rs256_public_key = public_key;
232-
232+
233233
// If we have RS256 keys, update the JWT issuer
234234
if !oxide_state.rs256_public_key.is_empty() && !oxide_state.rs256_private_key.is_empty() {
235-
if let Ok(decoded_private) = base64::engine::general_purpose::STANDARD.decode(&oxide_state.rs256_private_key) {
236-
if let Ok(decoded_public) = base64::engine::general_purpose::STANDARD.decode(&oxide_state.rs256_public_key) {
235+
if let Ok(decoded_private) =
236+
base64::engine::general_purpose::STANDARD.decode(&oxide_state.rs256_private_key)
237+
{
238+
if let Ok(decoded_public) =
239+
base64::engine::general_purpose::STANDARD.decode(&oxide_state.rs256_public_key)
240+
{
237241
// Create a new JWT issuer with RS256 keys
238-
if let Ok(jwt_issuer) = super::jwt::JwtIssuer::with_rs256_pem(&decoded_private, &decoded_public) {
242+
if let Ok(jwt_issuer) =
243+
super::jwt::JwtIssuer::with_rs256_pem(&decoded_private, &decoded_public)
244+
{
239245
oxide_state.issuer = std::sync::Arc::new(std::sync::Mutex::new(jwt_issuer));
240246
}
241247
}
@@ -361,9 +367,9 @@ pub fn build_rocket_test_instance() -> Rocket<Build> {
361367
token,
362368
refresh,
363369
openid_configuration, // Add OIDC configuration endpoint
364-
jwks, // Add JWKS endpoint
365-
// TODO: Add introspection endpoint once fixed
366-
// super::introspection::introspect,
370+
jwks, // Add JWKS endpoint
371+
// TODO: Add introspection endpoint once fixed
372+
// super::introspection::introspect,
367373
],
368374
)
369375
.mount(

tests/rs256_jwt_test.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,15 @@
44

55
use base64::Engine;
66
use jsonwebtoken::jwk::AlgorithmParameters;
7+
use jsonwebtoken::jwk::PublicKeyUse;
78
use jsonwebtoken::{Algorithm, DecodingKey};
89
use log::debug;
10+
use oxide_auth::endpoint::Issuer;
11+
use rocket::config::LogLevel;
912
use rocket::http::{ContentType, Status};
10-
use rocket::{config::LogLevel};
11-
use jsonwebtoken::jwk::PublicKeyUse;
1213
use rsa::pkcs1::{EncodeRsaPrivateKey, EncodeRsaPublicKey};
1314
use rust_photoacoustic::visualization::jwt::JwtIssuer;
1415
use rust_photoacoustic::visualization::jwt_keys::JwkKeySet;
15-
use oxide_auth::endpoint::Issuer;
1616
use serde::de;
1717
use serde_json::Value;
1818
use std::time::{SystemTime, UNIX_EPOCH};
@@ -114,7 +114,7 @@ fn test_rs256_jwt_token_generation_and_validation() {
114114
let (_, wrong_public_key_bytes, _, _) = generate_test_rs256_keys();
115115
let wrong_decoding_key = DecodingKey::from_rsa_pem(&wrong_public_key_bytes)
116116
.expect("Failed to create wrong decoding key");
117-
117+
118118
// The validation settings remain the same as above, with audience already set
119119
let wrong_verify_result =
120120
jsonwebtoken::decode::<serde_json::Value>(&token, &wrong_decoding_key, &validation);
@@ -263,7 +263,7 @@ async fn test_jwk_key_generation_from_public_key() {
263263
);
264264

265265
assert!(
266-
matches!(jwk.common.public_key_use,Some(PublicKeyUse::Signature)),
266+
matches!(jwk.common.public_key_use, Some(PublicKeyUse::Signature)),
267267
"JWK key use should be 'sig' (signature)"
268268
);
269269

0 commit comments

Comments
 (0)