KeySet

Struct KeySet 

Source
pub struct KeySet {
    pub keys: Vec<Key>,
}
Expand description

A JSON Web Key Set (RFC 7517 Section 5).

A KeySet contains a collection of keys that can be looked up by various criteria such as key ID (kid), algorithm, or key use.

§RFC Compliance

Per RFC 7517 Section 5:

“Implementations SHOULD ignore JWKs within a JWK Set that use ‘kty’ (key type) values that are not understood by them”

This implementation follows this guidance by silently skipping keys with unknown kty values during deserialization rather than failing.

§Examples

Parse a JWKS from JSON:

use jwk_simple::KeySet;

let json = r#"{
    "keys": [
        {
            "kty": "RSA",
            "kid": "key-1",
            "use": "sig",
            "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",
            "e": "AQAB"
        }
    ]
}"#;

let jwks: KeySet = serde_json::from_str(json).unwrap();
assert_eq!(jwks.len(), 1);

Keys with unknown kty values are silently skipped:

use jwk_simple::KeySet;

let json = r#"{
    "keys": [
        {"kty": "UNKNOWN", "data": "ignored"},
        {"kty": "oct", "k": "AQAB"}
    ]
}"#;

let jwks: KeySet = serde_json::from_str(json).unwrap();
assert_eq!(jwks.len(), 1); // Only the "oct" key is included

Fields§

§keys: Vec<Key>

The collection of keys.

Implementations§

Source§

impl KeySet

Source

pub fn new() -> Self

Creates a new empty KeySet.

§Examples
use jwk_simple::KeySet;

let jwks = KeySet::new();
assert!(jwks.is_empty());
Source

pub fn from_keys(keys: Vec<Key>) -> Self

Creates a KeySet from a vector of keys.

§Examples
use jwk_simple::{KeySet, Key};

let keys = vec![]; // Would contain Key instances
let jwks = KeySet::from_keys(keys);
Source

pub fn len(&self) -> usize

Returns the number of keys in the set.

Source

pub fn is_empty(&self) -> bool

Returns true if the set contains no keys.

Source

pub fn add_key(&mut self, key: Key)

Adds a key to the set.

§Examples
use jwk_simple::{KeySet, Key};

let mut jwks = KeySet::new();
// jwks.add_key(some_jwk);
Source

pub fn remove_by_kid(&mut self, kid: &str) -> Option<Key>

Removes and returns a key by its ID.

§Arguments
  • kid - The key ID to look for.
§Returns

The removed key, or None if not found.

Source

pub fn find_by_kid(&self, kid: &str) -> Option<&Key>

Finds a key by its ID (kid).

§Arguments
  • kid - The key ID to look for.
§Returns

A reference to the key, or None if not found.

§Examples
use jwk_simple::KeySet;

let json = r#"{"keys": [{"kty": "oct", "kid": "my-key", "k": "AQAB"}]}"#;
let jwks: KeySet = serde_json::from_str(json).unwrap();

let key = jwks.find_by_kid("my-key");
assert!(key.is_some());

let missing = jwks.find_by_kid("unknown");
assert!(missing.is_none());
Source

pub fn find_by_alg(&self, alg: &Algorithm) -> Vec<&Key>

Finds all keys with the specified algorithm.

§Arguments
  • alg - The algorithm to filter by.
§Returns

A vector of references to matching keys.

§Examples
use jwk_simple::{KeySet, Algorithm};

let json = r#"{"keys": [{"kty": "RSA", "alg": "RS256", "n": "AQAB", "e": "AQAB"}]}"#;
let jwks: KeySet = serde_json::from_str(json).unwrap();

let rs256_keys = jwks.find_by_alg(&Algorithm::Rs256);
assert_eq!(rs256_keys.len(), 1);
Source

pub fn find_by_kty(&self, kty: KeyType) -> Vec<&Key>

Finds all keys with the specified key type.

§Arguments
  • kty - The key type to filter by.
§Returns

A vector of references to matching keys.

Source

pub fn find_by_use(&self, key_use: KeyUse) -> Vec<&Key>

Finds all keys with the specified use.

§Arguments
  • key_use - The key use to filter by.
§Returns

A vector of references to matching keys.

§Examples
use jwk_simple::{KeySet, KeyUse};

let json = r#"{"keys": [{"kty": "RSA", "use": "sig", "n": "AQAB", "e": "AQAB"}]}"#;
let jwks: KeySet = serde_json::from_str(json).unwrap();

let signing_keys = jwks.find_by_use(KeyUse::Signature);
assert_eq!(signing_keys.len(), 1);
Source

pub fn signing_keys(&self) -> Vec<&Key>

Finds all signing keys.

A key is considered a signing key if:

  • It has use: "sig", OR
  • It has no use specified (default behavior for signature keys)
§Returns

A vector of references to signing keys.

Source

pub fn encryption_keys(&self) -> Vec<&Key>

Finds all encryption keys.

§Returns

A vector of references to encryption keys.

Source

pub fn first_signing_key(&self) -> Option<&Key>

Returns the first signing key, if any.

This is a convenience method for cases where only one signing key is expected.

§Examples
use jwk_simple::KeySet;

let json = r#"{"keys": [{"kty": "RSA", "use": "sig", "n": "AQAB", "e": "AQAB"}]}"#;
let jwks: KeySet = serde_json::from_str(json).unwrap();

let key = jwks.first_signing_key().expect("expected a signing key");
Source

pub fn first(&self) -> Option<&Key>

Returns the first key, if any.

§Examples
use jwk_simple::KeySet;

let jwks = KeySet::new();
assert!(jwks.first().is_none());
Source

pub fn iter(&self) -> impl Iterator<Item = &Key>

Returns an iterator over the keys.

Source

pub fn validate(&self) -> Result<()>

Validates all keys in the set.

§Errors

Returns the first validation error encountered, if any.

Source

pub fn find_by_thumbprint(&self, thumbprint: &str) -> Option<&Key>

Finds a key by its JWK thumbprint.

§Arguments
  • thumbprint - The base64url-encoded SHA-256 thumbprint.
§Returns

A reference to the key, or None if not found.

Trait Implementations§

Source§

impl Clone for KeySet

Source§

fn clone(&self) -> KeySet

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for KeySet

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for KeySet

Source§

fn default() -> KeySet

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for KeySet

Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl FromIterator<Key> for KeySet

Source§

fn from_iter<I: IntoIterator<Item = Key>>(iter: I) -> Self

Creates a value from an iterator. Read more
Source§

impl Index<usize> for KeySet

Source§

type Output = Key

The returned type after indexing.
Source§

fn index(&self, index: usize) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl<'a> IntoIterator for &'a KeySet

Source§

type Item = &'a Key

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, Key>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl IntoIterator for KeySet

Source§

type Item = Key

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<Key>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl KeySource for KeySet

Source§

fn get_key<'life0, 'life1, 'async_trait>( &'life0 self, kid: &'life1 str, ) -> Pin<Box<dyn Future<Output = Result<Option<Key>>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Gets a key by its key ID (kid). Read more
Source§

fn get_keyset<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = Result<KeySet>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Gets all available keys as a KeySet. Read more
Source§

impl Serialize for KeySet

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl Freeze for KeySet

§

impl RefUnwindSafe for KeySet

§

impl Send for KeySet

§

impl Sync for KeySet

§

impl Unpin for KeySet

§

impl UnwindSafe for KeySet

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,