ones-oidc 0.3.7

ONES OpenID Connect client for Rust
Documentation
use jsonwebtoken::EncodingKey;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use crate::errors::UtilsError;

/// Reads contents of a file at the given path into a byte vector
fn read_file(path: &str) -> Result<Vec<u8>, std::io::Error> {
    let path = Path::new(path);
    if !path.exists() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            format!("File not found: {}", path.display()),
        ));
    }
    let mut file = File::open(path)?;
    let mut contents = Vec::new();
    file.read_to_end(&mut contents)?;
    Ok(contents)
}

/// Converts raw bytes into a JWT encoding key
fn bytes_to_encoding_key(bytes: Vec<u8>) -> Result<EncodingKey, UtilsError> {
    EncodingKey::from_rsa_pem(&bytes)
        .map_err(|e| UtilsError::InvalidPrivateKey(format!("Invalid RSA PEM key format: {}", e)))
}

/// Reads and parses a private key file at the given path
///
/// # Arguments
/// * `path` - Path to the RSA private key file in PEM format
///
/// # Returns
/// * `Result<EncodingKey, UtilsError>` - The parsed encoding key or an error
pub fn read_private_key(path: &str) -> Result<EncodingKey, UtilsError> {
    let bytes = read_file(path)?;
    bytes_to_encoding_key(bytes)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_invalid_path() {
        let result = read_private_key("nonexistent.key");
        assert!(result.is_err());
        // Should return IO error for nonexistent file
        match result {
            Err(UtilsError::IoError(_)) => {}, // Expected
            _ => panic!("Expected IoError"),
        }
    }
}