Skip to content

Commit

Permalink
Updated dependencies (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
mibes404 authored May 27, 2024
1 parent edc52da commit f6edd85
Show file tree
Hide file tree
Showing 8 changed files with 91 additions and 93 deletions.
18 changes: 9 additions & 9 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,17 @@ default = ["remote-jwks"]
remote-jwks = ["reqwest", "tokio"]

[dependencies]
base64 = "0.13.0"
openssl = "0.10.35"
serde = { version = "1.0.127", features = ["derive"] }
serde_json = "1.0.66"
smallvec = "1.6.1"
reqwest = { version = "0.11.4", features = ["json"], optional = true }
tokio = { version = "1.9.0", features = ["sync"], optional = true }
openssl-sys = "0.9.65"
base64 = "0.22.1"
openssl = "0.10.64"
serde = { version = "1.0.200", features = ["derive"] }
serde_json = "1.0.116"
smallvec = "1.13.2"
reqwest = { version = "0.12.4", features = ["json"], optional = true }
tokio = { version = "1.37.0", features = ["sync"], optional = true }
openssl-sys = "0.9.102"
foreign-types = "0.3.2"
serde_with = "3.1.0"

[dev-dependencies]
axum = "0.1.3"
axum = "0.7"
tokio = { version = "1.9.0", features = ["macros", "rt-multi-thread"] }
28 changes: 14 additions & 14 deletions examples/jwks.rs
Original file line number Diff line number Diff line change
@@ -1,34 +1,35 @@
//! A JWKS server and token issuer.
//!
//! Reads private key fro `key.pem` (supports RSA, EC and Ed25519 keys). For
//! RSA, you can set the RSA_ALGO env var to use algorithms other than RS256.
//! RSA, you can set the `RSA_ALGO` env var to use algorithms other than RS256.
//!
//! Jwks will be available at http://127.0.0.1:3000/jwks
//!
//! Tokens will be issued at http://127.0.0.1:3000/token

use axum::{
prelude::*,
extract::State,
response::{IntoResponse, Json},
AddExtensionLayer,
routing::get,
Router,
};
use jwtk::{
jwk::{JwkSet, WithKid},
rsa::RsaAlgorithm,
sign, HeaderAndClaims, PublicKeyToJwk, SomePrivateKey,
};
use std::{net::Ipv4Addr, sync::Arc, time::Duration};
use std::{sync::Arc, time::Duration};

struct State {
struct AppState {
k: WithKid<SomePrivateKey>,
jwks: JwkSet,
}

async fn jwks_handler(state: extract::Extension<Arc<State>>) -> impl IntoResponse {
async fn jwks_handler(state: State<Arc<AppState>>) -> impl IntoResponse {
Json(&state.jwks).into_response()
}

async fn token_handler(state: extract::Extension<Arc<State>>) -> impl IntoResponse {
async fn token_handler(state: State<Arc<AppState>>) -> impl IntoResponse {
let mut token = HeaderAndClaims::new_dynamic();
token
.set_iss("me")
Expand Down Expand Up @@ -61,16 +62,15 @@ async fn main() -> jwtk::Result<()> {
keys: vec![k_public_jwk],
};

let state = Arc::new(State { k, jwks });
let state = Arc::new(AppState { k, jwks });

let app = route("/jwks", get(jwks_handler))
let app = Router::new()
.route("/jwks", get(jwks_handler))
.route("/token", get(token_handler))
.layer(AddExtensionLayer::new(state));
.with_state(state);

axum::Server::bind(&(Ipv4Addr::from(0), 3000).into())
.serve(app.into_make_service())
.await
.unwrap();
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();

Ok(())
}
3 changes: 1 addition & 2 deletions examples/jwks_client.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
#[cfg(feature = "remote-jwks")]
#[tokio::main]
async fn main() -> jwtk::Result<()> {
use std::time::Duration;

use jwtk::jwk::RemoteJwksVerifier;
use serde::Deserialize;
use serde_json::{Map, Value};
use std::time::Duration;

#[derive(Deserialize)]
struct Token {
Expand Down
19 changes: 10 additions & 9 deletions src/ecdsa.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use base64::Engine as _;
use foreign_types::ForeignTypeRef;
use openssl::{
bn::{BigNum, BigNumContext},
Expand All @@ -11,8 +12,8 @@ use openssl_sys::BN_bn2bin;
use smallvec::{smallvec, SmallVec};

use crate::{
jwk::Jwk, url_safe_trailing_bits, Error, PrivateKeyToJwk, PublicKeyToJwk, Result, SigningKey,
VerificationKey,
jwk::Jwk, Error, PrivateKeyToJwk, PublicKeyToJwk, Result, SigningKey, VerificationKey,
URL_SAFE_TRAILING_BITS,
};

#[non_exhaustive]
Expand Down Expand Up @@ -196,8 +197,8 @@ impl PublicKeyToJwk for EcdsaPrivateKey {
kty: "EC".into(),
use_: Some("sig".into()),
crv: Some(self.algorithm.curve_name().into()),
x: Some(base64::encode_config(x, url_safe_trailing_bits())),
y: Some(base64::encode_config(y, url_safe_trailing_bits())),
x: Some(URL_SAFE_TRAILING_BITS.encode(x)),
y: Some(URL_SAFE_TRAILING_BITS.encode(y)),
..Default::default()
})
}
Expand All @@ -211,9 +212,9 @@ impl PrivateKeyToJwk for EcdsaPrivateKey {
kty: "EC".into(),
use_: Some("sig".into()),
crv: Some(self.algorithm.curve_name().into()),
d: Some(base64::encode_config(d, url_safe_trailing_bits())),
x: Some(base64::encode_config(x, url_safe_trailing_bits())),
y: Some(base64::encode_config(y, url_safe_trailing_bits())),
d: Some(URL_SAFE_TRAILING_BITS.encode(d)),
x: Some(URL_SAFE_TRAILING_BITS.encode(x)),
y: Some(URL_SAFE_TRAILING_BITS.encode(y)),
..Default::default()
})
}
Expand Down Expand Up @@ -307,8 +308,8 @@ impl PublicKeyToJwk for EcdsaPublicKey {
kty: "EC".into(),
use_: Some("sig".into()),
crv: Some(self.algorithm.curve_name().into()),
x: Some(base64::encode_config(x, url_safe_trailing_bits())),
y: Some(base64::encode_config(y, url_safe_trailing_bits())),
x: Some(URL_SAFE_TRAILING_BITS.encode(x)),
y: Some(URL_SAFE_TRAILING_BITS.encode(y)),
..Default::default()
})
}
Expand Down
21 changes: 10 additions & 11 deletions src/eddsa.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
use std::ptr;

use crate::{
jwk::Jwk, Error, PrivateKeyToJwk, PublicKeyToJwk, Result, SigningKey, VerificationKey,
URL_SAFE_TRAILING_BITS,
};
use base64::Engine as _;
use foreign_types::ForeignType;
use openssl::{
error::ErrorStack,
pkey::{PKey, Private, Public},
sign::{Signer, Verifier},
};
use smallvec::SmallVec;

use crate::{
jwk::Jwk, url_safe_trailing_bits, Error, PrivateKeyToJwk, PublicKeyToJwk, Result, SigningKey,
VerificationKey,
};
use std::ptr;

#[derive(Debug, Clone)]
pub struct Ed25519PrivateKey {
Expand Down Expand Up @@ -100,7 +99,7 @@ impl PublicKeyToJwk for Ed25519PrivateKey {
Ok(Jwk {
kty: "OKP".into(),
crv: Some("Ed25519".into()),
x: Some(base64::encode_config(bytes, url_safe_trailing_bits())),
x: Some(URL_SAFE_TRAILING_BITS.encode(bytes)),
..Jwk::default()
})
}
Expand All @@ -113,8 +112,8 @@ impl PrivateKeyToJwk for Ed25519PrivateKey {
Ok(Jwk {
kty: "OKP".into(),
crv: Some("Ed25519".into()),
d: Some(base64::encode_config(d, url_safe_trailing_bits())),
x: Some(base64::encode_config(x, url_safe_trailing_bits())),
d: Some(URL_SAFE_TRAILING_BITS.encode(d)),
x: Some(URL_SAFE_TRAILING_BITS.encode(x)),
..Jwk::default()
})
}
Expand Down Expand Up @@ -181,7 +180,7 @@ impl PublicKeyToJwk for Ed25519PublicKey {
Ok(Jwk {
kty: "OKP".into(),
crv: Some("Ed25519".into()),
x: Some(base64::encode_config(bytes, url_safe_trailing_bits())),
x: Some(URL_SAFE_TRAILING_BITS.encode(bytes)),
..Jwk::default()
})
}
Expand Down
38 changes: 16 additions & 22 deletions src/jwk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,15 @@
//!
//! Only public keys are really supported for now.

use std::collections::{BTreeMap, HashMap};

use crate::{
ecdsa::{EcdsaAlgorithm, EcdsaPrivateKey, EcdsaPublicKey},
eddsa::{Ed25519PrivateKey, Ed25519PublicKey},
rsa::{RsaAlgorithm, RsaPrivateKey, RsaPublicKey},
some::SomePublicKey,
url_safe_trailing_bits, verify, verify_only, Error, Header, HeaderAndClaims, PublicKeyToJwk,
Result, SigningKey, SomePrivateKey, VerificationKey,
verify, verify_only, Error, Header, HeaderAndClaims, PublicKeyToJwk, Result, SigningKey,
SomePrivateKey, VerificationKey, URL_SAFE_TRAILING_BITS,
};
use base64::Engine as _;
use openssl::{
bn::BigNum,
hash::{hash, MessageDigest},
Expand All @@ -20,6 +19,7 @@ use openssl::{
};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::Value;
use std::collections::{BTreeMap, HashMap};

// TODO: private key jwk.

Expand Down Expand Up @@ -80,8 +80,8 @@ impl Jwk {
match &*self.kty {
"RSA" => match (self.alg.as_deref(), &self.n, &self.e) {
(alg, Some(ref n), Some(ref e)) => {
let n = base64::decode_config(n, url_safe_trailing_bits())?;
let e = base64::decode_config(e, url_safe_trailing_bits())?;
let n = URL_SAFE_TRAILING_BITS.decode(n)?;
let e = URL_SAFE_TRAILING_BITS.decode(e)?;
// If `alg` is specified, the key will only verify
// signatures generated by ONLY this specific `alg`,
// otherwise it will verify signatures generated by ANY RSA
Expand All @@ -100,8 +100,8 @@ impl Jwk {
"EC" => match (self.crv.as_deref(), &self.x, &self.y) {
// For EC keys `crv` is required.
(Some(crv), Some(ref x), Some(ref y)) => {
let x = base64::decode_config(x, url_safe_trailing_bits())?;
let y = base64::decode_config(y, url_safe_trailing_bits())?;
let x = URL_SAFE_TRAILING_BITS.decode(x)?;
let y = URL_SAFE_TRAILING_BITS.decode(y)?;
let alg = EcdsaAlgorithm::from_curve_name(crv)?;
return Ok(SomePublicKey::Ecdsa(EcdsaPublicKey::from_coordinates(
&x, &y, alg,
Expand All @@ -111,7 +111,7 @@ impl Jwk {
},
"OKP" => match (self.crv.as_deref(), &self.x) {
(Some(crv), Some(ref x)) => {
let x = base64::decode_config(x, url_safe_trailing_bits())?;
let x = URL_SAFE_TRAILING_BITS.decode(x)?;
match crv {
"Ed25519" => {
return Ok(SomePublicKey::Ed25519(Ed25519PublicKey::from_bytes(&x)?));
Expand Down Expand Up @@ -139,10 +139,7 @@ impl Jwk {
match (self.d.as_deref(), self.n.as_deref(), self.e.as_deref()) {
(Some(d), Some(n), Some(e)) => {
fn decode(x: &str) -> Result<BigNum> {
Ok(BigNum::from_slice(&base64::decode_config(
x,
url_safe_trailing_bits(),
)?)?)
Ok(BigNum::from_slice(&URL_SAFE_TRAILING_BITS.decode(x)?)?)
}
let d = decode(d)?;
let n = decode(n)?;
Expand Down Expand Up @@ -185,17 +182,17 @@ impl Jwk {
) {
(Some(crv), Some(d), Some(x), Some(y)) => {
let alg = EcdsaAlgorithm::from_curve_name(crv)?;
let d = base64::decode_config(d, url_safe_trailing_bits())?;
let x = base64::decode_config(x, url_safe_trailing_bits())?;
let y = base64::decode_config(y, url_safe_trailing_bits())?;
let d = URL_SAFE_TRAILING_BITS.decode(d)?;
let x = URL_SAFE_TRAILING_BITS.decode(x)?;
let y = URL_SAFE_TRAILING_BITS.decode(y)?;
EcdsaPrivateKey::from_private_components(alg, &d, &x, &y).map(Into::into)
}
_ => Err(Error::UnsupportedOrInvalidKey),
}
}
"OKP" => match (self.crv.as_deref(), self.d.as_deref()) {
(Some("Ed25519"), Some(d)) => {
let d = base64::decode_config(d, url_safe_trailing_bits())?;
let d = URL_SAFE_TRAILING_BITS.decode(d)?;
Ed25519PrivateKey::from_bytes(&d).map(Into::into)
}
_ => Err(Error::UnsupportedOrInvalidKey),
Expand Down Expand Up @@ -260,10 +257,7 @@ impl Jwk {

/// Get key thumbprint with SHA-256, base64url-encoded.
pub fn get_thumbprint_sha256_base64(&self) -> Result<String> {
Ok(base64::encode_config(
self.get_thumbprint_sha256()?,
url_safe_trailing_bits(),
))
Ok(URL_SAFE_TRAILING_BITS.encode(self.get_thumbprint_sha256()?))
}
}

Expand Down Expand Up @@ -341,7 +335,7 @@ impl JwkSetVerifier {

let mut header = parts.next().ok_or(Error::InvalidToken)?.as_bytes();

let header_r = base64::read::DecoderReader::new(&mut header, url_safe_trailing_bits());
let header_r = base64::read::DecoderReader::new(&mut header, &URL_SAFE_TRAILING_BITS);
let header: Header = serde_json::from_reader(header_r)?;

if let Some(kid) = header.kid {
Expand Down
Loading

0 comments on commit f6edd85

Please sign in to comment.