Develop first version (#1)
continuous-integration/drone/push Build is passing Details

Create first version of the library

The code is mainly taken from

* https://gitea.communiquons.org/pierre/oidc-test-client
* https://gitea.communiquons.org/pierre/BasicOIDC

with little improvements.

Reviewed-on: #1
This commit is contained in:
Pierre Hubert 2023-04-29 07:49:35 +00:00
parent 37259391f1
commit 394e29ae55
11 changed files with 1861 additions and 4 deletions

15
.drone.yml Normal file
View File

@ -0,0 +1,15 @@
---
kind: pipeline
type: docker
name: default
steps:
- name: cargo_check
image: rust
commands:
- rustup component add clippy
- cargo clippy --all-features -- -D warnings
- cargo clippy -- -D warnings
- cargo test --all-features

1317
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,27 @@
[package]
name = "light-openid"
version = "0.1.0"
version = "1.0.0"
edition = "2021"
repository = "https://gitea.communiquons.org/pierre/light-openid"
authors = ["Pierre HUBERT <pierre.git@communiquons.org>"]
readme = "README.md"
description = "Lightweight OpenID primitves & client"
license = "GPL-2.0-or-later"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
log = "0.4.17"
reqwest = { version = "0.11.17", features = ["json"] }
base64 = "0.21.0"
serde = { version = "1.0.160", features = ["derive"] }
serde_json = "1.0.96"
urlencoding = "2.1.2"
# Dependencies for crypto wrapper
bincode = { version = "2.0.0-rc.3", optional = true }
aes-gcm = { version = "0.10.1", optional = true }
rand = { version = "0.8.5", optional = true }
[features]
crypto-wrapper = ["bincode", "aes-gcm", "rand"]

64
README.md Normal file
View File

@ -0,0 +1,64 @@
# Light OpenID
[![Build Status](https://drone.communiquons.org/api/badges/pierre/light-openid/status.svg)](https://drone.communiquons.org/pierre/light-openid)
[![Crate](https://img.shields.io/crates/v/light-openid.svg)](https://crates.io/crates/light-openid)
Lightweight OpenID primitives & client. This package can be used to turn an application into an OpenID relying party.
> **Warning !** This crate has not been audited, use at your own risks!
>
> It is your responsibility to implement the routes (start & finish authentication) that interacts
> with the `OpenIDConfig` helper structure.
>
> Moreover, only a very small subset of OpenID specifications are supported :
> * `code` authorization flow
> * The scopes `openid profile email` are hard coded and cannot be changed
> * User info retrieval using `userinfo` endpoint
## Basic usage
```rust
let config = OpenIDConfig::load_from_url(&AppConfig::get().configuration_url).await.unwrap();
// Start authentication
let auth_url = config.gen_authorization_url("client_id", "state", "redirect_uri");
redirect_user(auth_url);
// Finish authentication
let token_response = config.request_token("client_id", "client_secret", "code", "redirect_uri").await.unwrap();
let user_info = config.request_user_info(&token_response).await.unwrap();
// user_info now contains profile info of user
```
## Feature `crypto-wrapper`
`CryptoWrapper` is a helper that can encrypt to base64-encoded string structures:
```rust
#[derive(Encode, Decode, Eq, PartialEq, Debug)]
struct Message(String);
fun test() {
let wrapper = CryptoWrapper::new_random();
let msg = Message("Hello world".to_string());
let enc = wrapper.encrypt(&msg).unwrap();
let dec: Message = wrapper.decrypt( & enc).unwrap();
assert_eq!(dec, msg);
}
```
> Note : In order to use `CryptoWrapper` on your own, you must add `bincode>=2.0` as one of your own dependencies. This is not required if you decide use `BasicStateManager`.
`BasicStateManager` is a helper that uses `CryptoWrapper` to generate and validates states for OpenID authentication:
```rust
let ip = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1));
let manager = BasicStateManager::new();
let state = manager.gen_state(ip).unwrap();
assert!(manager.validate_state(ip, &state).is_ok());
```
## Complete example
A complete example usage of this crate can be found here:
[https://gitea.communiquons.org/pierre/oidc-test-client](https://gitea.communiquons.org/pierre/oidc-test-client)

112
src/basic_state_manager.rs Normal file
View File

@ -0,0 +1,112 @@
//! # Basic state manager
//!
//! The state manager included in this module can be used to
//! generate basic and stateless states for applications with
//! minimum security requirements. The states contains the IP
//! address of the client in an encrypted way, and expires 15
//! minutes after issuance.
use std::error::Error;
use std::fmt;
use crate::crypto_wrapper::CryptoWrapper;
use crate::time_utils::time;
use bincode::{Decode, Encode};
use std::net::IpAddr;
#[derive(Encode, Decode, Debug)]
struct State {
ip: IpAddr,
expire: u64,
}
impl State {
pub fn new(ip: IpAddr) -> Self {
Self {
ip,
expire: time() + 15 * 60,
}
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
enum StateError {
InvalidIp,
Expired,
}
impl Error for StateError {}
impl fmt::Display for StateError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "StateManager error {:?}", self)
}
}
/// Basic state manager. Can be used to prevent CRSF by encrypting
/// a token containing a lifetime and the IP address of the user
pub struct BasicStateManager(CryptoWrapper);
impl BasicStateManager {
/// Initialize the state manager by creating a random encryption key. This function
/// should be called only one, ideally in the main function of the application
pub fn new() -> Self {
Self(CryptoWrapper::new_random())
}
/// Initialize state manager with a given CryptoWrapper
pub fn new_with_wrapper(wrapper: CryptoWrapper) -> Self {
Self(wrapper)
}
/// Generate a new state
pub fn gen_state(&self, ip: IpAddr) -> Result<String, Box<dyn Error>> {
let state = State::new(ip);
self.0.encrypt(&state)
}
/// Validate given state on callback URL
pub fn validate_state(&self, ip: IpAddr, state: &str) -> Result<(), Box<dyn Error>> {
let state: State = self.0.decrypt(state)?;
if state.ip != ip {
return Err(Box::new(StateError::InvalidIp));
}
if state.expire < time() {
return Err(Box::new(StateError::Expired));
}
Ok(())
}
}
impl Default for BasicStateManager {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod test {
use crate::basic_state_manager::BasicStateManager;
use std::net::{IpAddr, Ipv4Addr};
const IP_1: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1));
const IP_2: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 2));
#[test]
fn valid_state() {
let manager = BasicStateManager::new();
let state = manager.gen_state(IP_1).unwrap();
assert!(manager.validate_state(IP_1, &state).is_ok());
}
#[test]
fn invalid_ip() {
let manager = BasicStateManager::new();
let state = manager.gen_state(IP_1).unwrap();
assert!(manager.validate_state(IP_2, &state).is_err());
}
}

82
src/client.rs Normal file
View File

@ -0,0 +1,82 @@
//! # Open ID client implementation
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use base64::Engine;
use std::collections::HashMap;
use std::error::Error;
use crate::primitives::{OpenIDConfig, OpenIDTokenResponse, OpenIDUserInfo};
impl OpenIDConfig {
/// Load OpenID configuration from a given .well-known/openid-configuration URL
pub async fn load_from_url(url: &str) -> Result<Self, Box<dyn Error>> {
Ok(reqwest::get(url).await?.json().await?)
}
/// Get the authorization URL where a user should be redirect to perform authentication
pub fn gen_authorization_url(
&self,
client_id: &str,
state: &str,
redirect_uri: &str,
) -> String {
let client_id = urlencoding::encode(client_id);
let state = urlencoding::encode(state);
let redirect_uri = urlencoding::encode(redirect_uri);
format!("{}?response_type=code&scope=openid%20profile%20email&client_id={client_id}&state={state}&redirect_uri={redirect_uri}", self.authorization_endpoint)
}
/// Query the token endpoint
///
/// This endpoint returns both the parsed and the raw response, to allow handling
/// of bonus fields
pub async fn request_token(
&self,
client_id: &str,
client_secret: &str,
code: &str,
redirect_uri: &str,
) -> Result<(OpenIDTokenResponse, String), Box<dyn Error>> {
let authorization = BASE64_STANDARD.encode(format!("{}:{}", client_id, client_secret));
let mut params = HashMap::new();
params.insert("grant_type", "authorization_code");
params.insert("code", code);
params.insert("redirect_uri", redirect_uri);
let response = reqwest::Client::new()
.post(&self.token_endpoint)
.header("Authorization", format!("Basic {authorization}"))
.form(&params)
.send()
.await?
.text()
.await?;
Ok((serde_json::from_str(&response)?, response))
}
/// Query the UserInfo endpoint.
///
/// This endpoint should be use after having successfully retrieved the token
///
/// This endpoint returns both the parsed value and the raw response, in case of presence
/// of additional fields
pub async fn request_user_info(
&self,
token: &OpenIDTokenResponse,
) -> Result<(OpenIDUserInfo, String), Box<dyn Error>> {
let response = reqwest::Client::new()
.get(self.userinfo_endpoint.as_ref().expect(
"This client only support information retrieval through userinfo endpoint!",
))
.header("Authorization", format!("Bearer {}", token.access_token))
.send()
.await?
.text()
.await?;
Ok((serde_json::from_str(&response)?, response))
}
}

100
src/crypto_wrapper.rs Normal file
View File

@ -0,0 +1,100 @@
use std::error::Error;
use std::io::ErrorKind;
use aes_gcm::aead::{Aead, OsRng};
use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce};
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use base64::Engine as _;
use bincode::{Decode, Encode};
use rand::Rng;
/// The lenght of the nonce used to initialize encryption
const NONCE_LEN: usize = 12;
/// CryptoWrapper is a library that can be used to encrypt and decrypt some data marked
/// that derives [Encode] and [Decode] traits using AES encryption
pub struct CryptoWrapper {
key: Key<Aes256Gcm>,
}
impl CryptoWrapper {
/// Generate a new memory wrapper
pub fn new_random() -> Self {
Self {
key: Aes256Gcm::generate_key(&mut OsRng),
}
}
/// Encrypt some data, returning the result as a base64-encoded string
pub fn encrypt<T: Encode + Decode>(&self, data: &T) -> Result<String, Box<dyn Error>> {
let aes_key = Aes256Gcm::new(&self.key);
let nonce_bytes = rand::thread_rng().gen::<[u8; NONCE_LEN]>();
let serialized_data = bincode::encode_to_vec(data, bincode::config::standard())?;
let mut enc = aes_key
.encrypt(Nonce::from_slice(&nonce_bytes), serialized_data.as_slice())
.unwrap();
enc.extend_from_slice(&nonce_bytes);
Ok(BASE64_STANDARD.encode(enc))
}
/// Decrypt some data previously encrypted using the [`CryptoWrapper::encrypt`] method
pub fn decrypt<T: Decode>(&self, input: &str) -> Result<T, Box<dyn Error>> {
let bytes = BASE64_STANDARD.decode(input)?;
if bytes.len() < NONCE_LEN {
return Err(Box::new(std::io::Error::new(
ErrorKind::Other,
"Input string is smaller than nonce!",
)));
}
let (enc, nonce) = bytes.split_at(bytes.len() - NONCE_LEN);
assert_eq!(nonce.len(), NONCE_LEN);
let aes_key = Aes256Gcm::new(&self.key);
let dec = match aes_key.decrypt(Nonce::from_slice(nonce), enc) {
Ok(d) => d,
Err(e) => {
log::error!("Failed to decrypt wrapped data! {:#?}", e);
return Err(Box::new(std::io::Error::new(
ErrorKind::Other,
"Failed to decrypt wrapped data!",
)));
}
};
Ok(bincode::decode_from_slice(&dec, bincode::config::standard())?.0)
}
}
#[cfg(test)]
mod test {
use crate::crypto_wrapper::CryptoWrapper;
use bincode::{Decode, Encode};
#[derive(Encode, Decode, Eq, PartialEq, Debug)]
struct Message(String);
#[test]
fn encrypt_and_decrypt() {
let wrapper = CryptoWrapper::new_random();
let msg = Message("Pierre was here".to_string());
let enc = wrapper.encrypt(&msg).unwrap();
let dec: Message = wrapper.decrypt(&enc).unwrap();
assert_eq!(dec, msg)
}
#[test]
fn encrypt_and_decrypt_invalid() {
let wrapper_1 = CryptoWrapper::new_random();
let wrapper_2 = CryptoWrapper::new_random();
let msg = Message("Pierre was here".to_string());
let enc = wrapper_1.encrypt(&msg).unwrap();
wrapper_2.decrypt::<Message>(&enc).unwrap_err();
}
}

17
src/lib.rs Normal file
View File

@ -0,0 +1,17 @@
//! # Light OpenID
//!
//! Basic implementation of OpenID protocol, with primitives and basic client.
//!
//! See https://gitea.communiquons.org/pierre/oidc-test-client for an example of usage of this library
pub mod client;
pub mod primitives;
#[cfg(feature = "crypto-wrapper")]
mod time_utils;
#[cfg(feature = "crypto-wrapper")]
pub mod crypto_wrapper;
#[cfg(feature = "crypto-wrapper")]
pub mod basic_state_manager;

View File

@ -1,3 +0,0 @@
fn main() {
println!("Hello, world!");
}

115
src/primitives.rs Normal file
View File

@ -0,0 +1,115 @@
//! # OpenID primitives
//!
//! These primitives might be incomplete, but sufficient for a basic OpenID usage.
/// OpenID discovery information, typically distributed on http://provider/.well-known/openid-configuration
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct OpenIDConfig {
/// URL using the https scheme with no query or fragment component that the OP asserts as its Issuer Identifier. If Issuer discovery is supported (see Section 2), this value MUST be identical to the issuer value returned by WebFinger. This also MUST be identical to the iss Claim value in ID Tokens issued from this Issuer
pub issuer: String,
/// REQUIRED. URL of the OP's OAuth 2.0 Authorization Endpoint `OpenID.Core`
pub authorization_endpoint: String,
/// URL of the OP's OAuth 2.0 Token Endpoint `OpenID.Core`. This is REQUIRED unless only the Implicit Flow is used.
pub token_endpoint: String,
/// RECOMMENDED. URL of the OP's UserInfo Endpoint `[`OpenID.Core`]`. This URL MUST use the https scheme and MAY contain port, path, and query parameter components
#[serde(skip_serializing_if = "Option::is_none")]
pub userinfo_endpoint: Option<String>,
/// REQUIRED. URL of the OP's JSON Web Key Set `[`JWK`]` document. This contains the signing key(s) the RP uses to validate signatures from the OP. The JWK Set MAY also contain the Server's encryption key(s), which are used by RPs to encrypt requests to the Server. When both signing and encryption keys are made available, a use (Key Use) parameter value is REQUIRED for all keys in the referenced JWK Set to indicate each key's intended usage. Although some algorithms allow the same key to be used for both signatures and encryption, doing so is NOT RECOMMENDED, as it is less secure. The JWK x5c parameter MAY be used to provide X.509 representations of keys provided. When used, the bare key values MUST still be present and MUST match those in the certificate.
pub jwks_uri: String,
/// RECOMMENDED. JSON array containing a list of the OAuth 2.0 `[`RFC6749`]` scope values that this server supports. The server MUST support the openid scope value. Servers MAY choose not to advertise some supported scope values even when this parameter is used, although those defined in `[`OpenID.Core`]` SHOULD be listed, if supported.
#[serde(skip_serializing_if = "Option::is_none")]
pub scopes_supported: Option<Vec<String>>,
/// REQUIRED. JSON array containing a list of the OAuth 2.0 response_type values that this OP supports. Dynamic OpenID Providers MUST support the code, id_token, and the token id_token Response Type values.
pub response_types_supported: Vec<String>,
/// REQUIRED. JSON array containing a list of the Subject Identifier types that this OP supports. Valid types include pairwise and public.
pub subject_types_supported: Vec<String>,
/// REQUIRED. JSON array containing a list of the JWS signing algorithms (alg values) supported by the OP for the ID Token to encode the Claims in a JWT `[`JWT`. The algorithm RS256 MUST be included. The value none MAY be supported, but MUST NOT be used unless the Response Type used returns no ID Token from the Authorization Endpoint (such as when using the Authorization Code Flow).
pub id_token_signing_alg_values_supported: Vec<String>,
/// OPTIONAL. JSON array containing a list of Client Authentication methods supported by this Token Endpoint. The options are client_secret_post, client_secret_basic, client_secret_jwt, and private_key_jwt
#[serde(skip_serializing_if = "Option::is_none")]
pub token_endpoint_auth_methods_supported: Option<Vec<String>>,
/// RECOMMENDED. JSON array containing a list of the Claim Names of the Claims that the OpenID Provider MAY be able to supply values for. Note that for privacy or other reasons, this might not be an exhaustive list.
#[serde(skip_serializing_if = "Option::is_none")]
pub claims_supported: Option<Vec<String>>,
/// OPTIONAL JSON array containing a list of Proof Key for Code Exchange (PKCE)
#[serde(skip_serializing_if = "Option::is_none")]
pub code_challenge_methods_supported: Option<Vec<String>>,
}
/// OpenID token response
///
/// The content of this field is specified in
/// * OAuth specifications: https://datatracker.ietf.org/doc/html/rfc6749#section-5.1
/// * OpenID Core specifications: https://openid.net/specs/openid-connect-core-1_0.html#TokenResponse
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct OpenIDTokenResponse {
/// REQUIRED. The access token issued by the authorization server.
pub access_token: String,
/// REQUIRED. The type of the token issued. It MUST be "Bearer"
pub token_type: String,
/// OPTIONAL. The refresh token, which can be used to obtain new
/// access tokens using the same authorization grant
#[serde(skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<String>,
/// RECOMMENDED. The lifetime in seconds of the access token. For
/// example, the value "3600" denotes that the access token will
/// expire in one hour from the time the response was generated.
/// If omitted, the authorization server SHOULD provide the
/// expiration time via other means or document the default value.
#[serde(skip_serializing_if = "Option::is_none")]
pub expires_in: Option<u64>,
/// REQUIRED. ID Token value associated with the authenticated session.
///
/// Note: this field is marked as optionnal because it is excluded in case
/// of request of refresh token.
#[serde(skip_serializing_if = "Option::is_none")]
pub id_token: Option<String>,
}
/// Refer to <https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims> for more information
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct OpenIDUserInfo {
/// Subject - Identifier for the End-User at the Issuer
///
/// This is the only mandatory field
pub sub: String,
/// End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences.
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// Given name(s) or first name(s) of the End-User. Note that in some cultures, people can have multiple given names; all can be present, with the names being separated by space characters.
#[serde(skip_serializing_if = "Option::is_none")]
pub given_name: Option<String>,
/// Surname(s) or last name(s) of the End-User. Note that in some cultures, people can have multiple family names or no family name; all can be present, with the names being separated by space characters.
#[serde(skip_serializing_if = "Option::is_none")]
pub family_name: Option<String>,
/// Shorthand name by which the End-User wishes to be referred to at the RP, such as janedoe or j.doe. This value MAY be any valid JSON string including special characters such as @, /, or whitespace. The RP MUST NOT rely upon this value being unique, as discussed in
#[serde(skip_serializing_if = "Option::is_none")]
pub preferred_username: Option<String>,
/// End-User's preferred e-mail address. Its value MUST conform to the RFC 5322 RFC5322 addr-spec syntax. The RP MUST NOT rely upon this value being unique, as discussed in Section 5.7.
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<String>,
/// True if the End-User's e-mail address has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this e-mail address was controlled by the End-User at the time the verification was performed. The means by which an e-mail address is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating.
#[serde(skip_serializing_if = "Option::is_none")]
pub email_verified: Option<bool>,
}

19
src/time_utils.rs Normal file
View File

@ -0,0 +1,19 @@
use std::time::{SystemTime, UNIX_EPOCH};
/// Get current time since epoch, in seconds
pub fn time() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
#[cfg(test)]
mod test {
use crate::time_utils::time;
#[test]
fn time_is_recent_enough() {
assert!(time() > 1682750570);
}
}