### Implement Default for ClaimsValidationRules Source: https://docs.rs/pasetors/latest/pasetors/claims/struct Provides a default implementation for `ClaimsValidationRules`, creating an instance with its default configuration. This is often used for initial setup or when no specific rules are immediately applied. ```rust fn default() -> Self ``` -------------------------------- ### Implement Any for T Source: https://docs.rs/pasetors/latest/pasetors/token/struct Provides a way to get the 'TypeId' of any type T, which is part of the 'Any' trait. This allows for runtime type identification. ```rust impl Any for T where T: 'static + ?Sized, ``` -------------------------------- ### Get AsymmetricSecretKey as bytes in Rust Source: https://docs.rs/pasetors/latest/pasetors/keys/struct Returns a byte-slice representation of the AsymmetricSecretKey. This method is useful for inspecting or serializing the key. ```rust pub fn as_bytes(&self) -> &[u8] ``` -------------------------------- ### PASETO Token with Custom Footer and Claims Source: https://docs.rs/pasetors/latest/pasetors/index Shows how to create a PASETO token with a custom footer containing registered and additional claims, including a key ID. It covers key generation, footer construction, signing the token, and subsequently verifying and parsing the footer from a received token. ```rust use pasetors::paserk::{FormatAsPaserk, Id}; use pasetors::claims::{Claims, ClaimsValidationRules}; use pasetors::footer::Footer; use pasetors::keys::{Generate, AsymmetricKeyPair}; use pasetors::{public, Public, version4::V4}; use pasetors::token::UntrustedToken; use core::convert::TryFrom; // Generate the key used to later sign a token. let kp = AsymmetricKeyPair::::generate()?; // Serialize the public key to PASERK "pid". let mut pid = Id::from(&kp.public); // Add the "pid" to the "kid" claim of a footer. let mut footer = Footer::new(); footer.key_id(&pid); footer.add_additional("custom_footer_claim", "custom_value")?; let mut claims = Claims::new()?; let pub_token = public::sign(&kp.secret, &claims, Some(&footer), Some(b"implicit assertion"))?; // If we receive a token that needs to be verified, we can still try to parse a Footer from it // as long one was used during creation, if we don't know it beforehand. let validation_rules = ClaimsValidationRules::new(); let untrusted_token = UntrustedToken::::try_from(&pub_token)?; let trusted_token = public::verify(&kp.public, &untrusted_token, &validation_rules, None, Some(b"implicit assertion"))?; let trusted_footer = Footer::try_from(&trusted_token)?; let mut kid = String::new(); pid.fmt(&mut kid).unwrap(); assert_eq!(trusted_footer.get_claim("kid").unwrap().as_str().unwrap(), kid); ``` -------------------------------- ### Create and Verify Public PASETO Tokens (Rust) Source: https://docs.rs/pasetors/latest/pasetors/index Demonstrates how to create and verify public PASETO tokens using the `pasetors` library. This involves generating asymmetric key pairs, signing claims with custom data, and then verifying the token against the public key and predefined validation rules. Custom claims are not automatically validated. ```rust use pasetors::claims::{Claims, ClaimsValidationRules}; use pasetors::keys::{Generate, AsymmetricKeyPair, AsymmetricSecretKey, AsymmetricPublicKey}; use pasetors::{public, Public, version4::V4}; use pasetors::token::{UntrustedToken, TrustedToken}; use core::convert::TryFrom; // Setup the default claims, which include `iat` and `nbf` as the current time and `exp` of one hour. // Add a custom `data` claim as well. let mut claims = Claims::new()?; claims.add_additional("data", "A public, signed message")?; // Generate the keys and sign the claims. let kp = AsymmetricKeyPair::::generate()?; let pub_token = public::sign(&kp.secret, &claims, None, Some(b"implicit assertion"))?; // Decide how we want to validate the claims after verifying the token itself. // The default verifies the `nbf`, `iat` and `exp` claims. `nbf` and `iat` are always // expected to be present. // NOTE: Custom claims, defined through `add_additional()`, are not validated. This must be done // manually. let validation_rules = ClaimsValidationRules::new(); let untrusted_token = UntrustedToken::::try_from(&pub_token)?; let trusted_token = public::verify(&kp.public, &untrusted_token, &validation_rules, None, Some(b"implicit assertion"))?; assert_eq!(&claims, trusted_token.payload_claims().unwrap()); let claims = trusted_token.payload_claims().unwrap(); println!("{:?}", claims.get_claim("data")); println!("{:?}", claims.get_claim("iat")); ``` -------------------------------- ### Create and Modify Footer - Rust Source: https://docs.rs/pasetors/latest/pasetors/footer/struct Demonstrates creating a new `Footer` instance and modifying its properties. Methods like `new()`, `max_keys()`, `max_len()`, `key_id()`, and `add_additional()` allow for initialization and customization of footer claims. Error handling is included for invalid claims or PASERK types. ```rust pub fn new() -> Self pub fn max_keys(&mut self, max_keys: usize) pub fn max_len(&mut self, max_len: usize) pub fn key_id(&mut self, id: &Id) pub fn add_additional(&mut self, claim: &str, value: &str) -> Result<(), Error> ``` -------------------------------- ### PASERK Serialization and Deserialization of Symmetric Keys Source: https://docs.rs/pasetors/latest/pasetors/index Demonstrates the process of generating a symmetric key, serializing it into the PASERK format, and then deserializing it back into a usable symmetric key object. This is essential for securely storing and transmitting symmetric keys. ```rust use pasetors::paserk::FormatAsPaserk; use pasetors::keys::{Generate, SymmetricKey}; use pasetors::version4::V4; use core::convert::TryFrom; // Generate the key and serialize to and from PASERK. let sk = SymmetricKey::::generate()?; let mut paserk = String::new(); sk.fmt(&mut paserk).unwrap(); let sk = SymmetricKey::::try_from(paserk.as_str())?; ``` -------------------------------- ### Create and Verify Local PASETO Tokens (Rust) Source: https://docs.rs/pasetors/latest/pasetors/index Illustrates the process of creating and verifying local PASETO tokens using symmetric encryption. This involves generating a symmetric key, encrypting claims (including custom data), and then decrypting and verifying the token with the same symmetric key and validation rules. Custom claims require manual validation. ```rust use pasetors::claims::{Claims, ClaimsValidationRules}; use pasetors::keys::{Generate, SymmetricKey}; use pasetors::{local, Local, version4::V4}; use pasetors::token::UntrustedToken; use core::convert::TryFrom; // Setup the default claims, which include `iat` and `nbf` as the current time and `exp` of one hour. // Add a custom `data` claim as well. let mut claims = Claims::new()?; claims.add_additional("data", "A secret, encrypted message")?; // Generate the key and encrypt the claims. let sk = SymmetricKey::::generate()?; let token = local::encrypt(&sk, &claims, None, Some(b"implicit assertion"))?; // Decide how we want to validate the claims after verifying the token itself. // The default verifies the `nbf`, `iat` and `exp` claims. `nbf` and `iat` are always // expected to be present. // NOTE: Custom claims, defined through `add_additional()`, are not validated. This must be done // manually. let validation_rules = ClaimsValidationRules::new(); let untrusted_token = UntrustedToken::::try_from(&token)?; let trusted_token = local::decrypt(&sk, &untrusted_token, &validation_rules, None, Some(b"implicit assertion"))?; assert_eq!(&claims, trusted_token.payload_claims().unwrap()); let claims = trusted_token.payload_claims().unwrap(); println!("{:?}", claims.get_claim("data")); println!("{:?}", claims.get_claim("iat")); ``` -------------------------------- ### Footer Instance Creation and Modification Source: https://docs.rs/pasetors/latest/pasetors/footer/struct Methods for creating a new Footer instance and modifying its properties. ```APIDOC ## Footer Instance Management ### Method `new()` ### Description Creates a new `Footer` instance with default settings. ### Returns - `Self` - A new `Footer` instance. ### Method `max_keys(&mut self, max_keys: usize)` ### Description Changes the default maximum number of named keys within an object. **NOTE**: This should generally not be changed unless you understand the specific problem it addresses. ### Parameters - **max_keys** (`usize`) - The new maximum number of keys. ### Method `max_len(&mut self, max_len: usize)` ### Description Changes the default maximum length of the JSON-encoded string. **NOTE**: This should generally not be changed unless you understand the specific problem it addresses. ### Parameters - **max_len** (`usize`) - The new maximum length. ``` -------------------------------- ### Implement CloneToUninit for Generic Type T Source: https://docs.rs/pasetors/latest/pasetors/keys/struct Provides an unsafe implementation of `CloneToUninit` for any type `T` that implements `Clone`. This experimental, nightly-only API allows copying data from `self` to an uninitialized memory location pointed to by `dest`. Use with caution as it requires manual memory management. ```rust impl CloneToUninit for T where T: Clone, { unsafe fn clone_to_uninit(&self, dest: *mut u8) { // Implementation detail: This requires careful pointer manipulation and knowledge of T's layout. // For example, if T is Copy, you could do: // *(dest as *mut T) = self.clone(); } } ``` -------------------------------- ### Rust: Implement nightly-only `CloneToUninit` for `T` Source: https://docs.rs/pasetors/latest/pasetors/footer/struct A nightly-only experimental API that allows cloning a value into an uninitialized memory location. Requires the `T` type to implement `Clone`. Use with caution due to its `unsafe` nature. ```rust impl CloneToUninit for T where T: Clone, { unsafe fn clone_to_uninit(&self, dest: *mut u8); } ``` -------------------------------- ### Footer Trait Implementations - Rust Source: https://docs.rs/pasetors/latest/pasetors/footer/struct Details the trait implementations for the `Footer` struct. This includes `Clone` for copying, `Debug` for formatting, `Default` for creating a default instance, `PartialEq` and `Eq` for equality comparisons, and `TryFrom` for converting a `TrustedToken` into a `Footer`. Auto trait implementations like `Send`, `Sync`, and `Unpin` are also listed. ```rust impl Clone for Footer impl Debug for Footer impl Default for Footer impl PartialEq for Footer impl Eq for Footer impl TryFrom<&TrustedToken> for Footer ``` -------------------------------- ### Setting and Validating Registered Claims (Rust) Source: https://docs.rs/pasetors/latest/pasetors/index Shows how to set and validate standard registered claims (like `iss`, `sub`, `aud`, `exp`, `nbf`, `jti`) and custom claims within the `pasetors` library. It demonstrates overriding default times for `iat`, `nbf`, and `exp`, and configuring specific validation rules for issuer, subject, audience, and token identifier. ```rust use pasetors::claims::{Claims, ClaimsValidationRules}; // `iat`, `nbf` and `exp` have been set automatically, but could also be overridden. let mut claims = Claims::new()?; claims.issuer("paragonie.com")?; claims.subject("test")?; claims.audience("pie-hosted.com")?; claims.expiration("2039-01-01T00:00:00+00:00")?; claims.not_before("2038-04-01T00:00:00+00:00")?; claims.issued_at("2038-03-17T00:00:00+00:00")?; claims.token_identifier("87IFSGFgPNtQNNuw0AtuLttPYFfYwOkjhqdWcLoYQHvL")?; let mut validation_rules = ClaimsValidationRules::new(); validation_rules.validate_issuer_with("paragonie.com"); validation_rules.validate_subject_with("test"); validation_rules.validate_audience_with("pie-hosted.com"); validation_rules.validate_token_identifier_with("87IFSGFgPNtQNNuw0AtuLttPYFfYwOkjhqdWcLoYQHvL"); // The token has been set to be issued in the future and not valid yet, so validation fails. assert!(validation_rules.validate_claims(&claims).is_err()); ``` -------------------------------- ### Trait Implementations Source: https://docs.rs/pasetors/latest/pasetors/footer/struct Overview of standard traits implemented for the Footer struct. ```APIDOC ## Trait Implementations for Footer ### `Clone` - `clone(&self) -> Footer`: Returns a duplicate of the value. - `clone_from(&mut self, source: &Self)`: Performs copy-assignment from `source`. ### `Debug` - `fmt(&self, f: &mut Formatter<'_>) -> Result`: Formats the value using the given formatter. ### `Default` - `default() -> Self`: Returns the default value for the type. ### `PartialEq` - `eq(&self, other: &Footer) -> bool`: Tests for equality between two `Footer` instances. - `ne(&self, other: &Rhs) -> bool`: Tests for inequality. ### `TryFrom<&TrustedToken>` - `type Error = Error`: The error type returned on conversion failure. - `try_from(value: &TrustedToken) -> Result`: Attempts to convert a `TrustedToken` into a `Footer`. ### `Eq` - Implements the `Eq` trait. ### `StructuralPartialEq` - Implements the `StructuralPartialEq` trait. ### Auto Trait Implementations - `Freeze`, `RefUnwindSafe`, `Send`, `Sync`, `Unpin`, `UnwindSafe` are implemented. ``` -------------------------------- ### Footer Struct and Constants Source: https://docs.rs/pasetors/latest/pasetors/footer/struct Details about the Footer struct, its available constants, and their meanings. ```APIDOC ## Struct Footer A footer with optional claims that are JSON-encoded. Available on **crate feature `std`** only. ### Constants - **REGISTERED_CLAIMS**: `[&'static str; 2]` - Keys for registered claims in the footer, reserved for PASETO usage. - **DISALLOWED_FOOTER**: `[&'static str; 8]` - All PASERK types that are unsafe in the footer within this library. - **DEFAULT_MAX_KEYS**: `usize` = 512 - Maximum number of named keys within an object. See PASETO docs for the reason behind this limit. - **DEFAULT_MAX_LEN**: `usize` = 8192 - Maximum length of the JSON-encoded string. See PASETO docs for the reason behind this limit. - **MAX_RECURSION_DEPTH**: `usize` = 128 - Maximum recursion depth for JSON parsing, set by `serde_json`. ``` -------------------------------- ### Implement TryFrom<&str> for AsymmetricSecretKey Source: https://docs.rs/pasetors/latest/pasetors/keys/struct Allows conversion from a string slice to an `AsymmetricSecretKey` of version V3. This functionality is available via the `paserk` crate feature. The conversion can return an error specific to the `paserk` crate. ```rust impl TryFrom<&str> for AsymmetricSecretKey { type Error = Error; fn try_from(value: &str) -> Result { // Implementation details... } } ``` -------------------------------- ### Claim Management Source: https://docs.rs/pasetors/latest/pasetors/footer/struct APIs for adding, checking, and retrieving claims within a Footer. ```APIDOC ## Claim Operations ### Method `add_additional(&mut self, claim: &str, value: &str) -> Result<(), Error>` ### Description Adds an additional claim to the footer. If the `claim` already exists, it will be replaced. ### Parameters - **claim** (`&str`) - The name of the claim to add. - **value** (`&str`) - The value of the claim. ### Returns - `Ok(())` on success. - `Err(Error)` if: - `claim` is a reserved claim (see `Self::REGISTERED_CLAIMS`). - `value` is any of the disallowed PASERK types (see `Self::DISALLOWED_FOOTER`). ### Method `contains_claim(&self, claim: &str) -> bool` ### Description Checks if a specific claim has been added to the footer. ### Parameters - **claim** (`&str`) - The name of the claim to check. ### Returns - `true` if the claim exists, `false` otherwise. ### Method `get_claim(&self, claim: &str) -> Option<&Value>` ### Description Retrieves the value of a specific claim from the footer. ### Parameters - **claim** (`&str`) - The name of the claim to retrieve. ### Returns - `Some(&Value)` if the claim exists. - `None` if the claim does not exist. ### Method `key_id(&mut self, id: &Id)` ### Description Sets the `kid` claim for the footer. If it already exists, it will be replaced. ### Parameters - **id** (`&Id`) - The key ID to set. ``` -------------------------------- ### Implement PartialEq for PASETO V3 Struct Source: https://docs.rs/pasetors/latest/pasetors/version3/struct This code demonstrates the implementation of the `PartialEq` trait for the `V3` struct, allowing for equality comparisons between `V3` instances using `==` and `!=` operators. ```rust fn eq(&self, other: &V3) -> bool fn ne(&self, other: &Rhs) -> bool ``` -------------------------------- ### Implement TryFrom<&str> for AsymmetricSecretKey Source: https://docs.rs/pasetors/latest/pasetors/keys/struct Enables conversion from a string slice to an `AsymmetricSecretKey` of version V4. This feature requires the `paserk` crate feature to be enabled. Errors during conversion are of the type `Error` defined within the `paserk` crate. ```rust impl TryFrom<&str> for AsymmetricSecretKey { type Error = Error; fn try_from(value: &str) -> Result { // Implementation details... } } ``` -------------------------------- ### Create and Validate Non-Expiring PASETO Tokens Source: https://docs.rs/pasetors/latest/pasetors/index Demonstrates how to create PASETO claims and set them to be non-expiring. It also shows how to configure validation rules to allow these non-expiring tokens. This is useful for tokens that should remain valid indefinitely until explicitly revoked. ```rust use pasetors::claims::{Claims, ClaimsValidationRules}; // Non-expiring tokens let mut claims = Claims::new()?; claims.add_additional("data", "A public, signed message")?; claims.non_expiring(); // Now claims can be validated as non-expiring when we define the validation rule as: let mut validation_rules = ClaimsValidationRules::new(); validation_rules.allow_non_expiring(); ``` -------------------------------- ### Implement Generic Conversions for PASETO V3 Source: https://docs.rs/pasetors/latest/pasetors/version3/struct This code showcases blanket implementations of generic conversion traits such as `From`, `Into`, `TryFrom`, and `TryInto` for the `V3` struct and other types. These enable flexible data transformations. ```rust fn from(t: T) -> T fn into(self) -> U fn try_from(value: U) -> Result>::Error> fn try_into(self) -> Result>::Error> ``` -------------------------------- ### Implement Generic Type Conversions (TryFrom, TryInto) Source: https://docs.rs/pasetors/latest/pasetors/keys/struct Provides generic implementations for `TryFrom` and `TryInto` traits for any type `T`. These allow attempting conversions between types where one can be created from the other, returning a `Result` to handle potential conversion failures. The `Error` type depends on the specific `TryFrom` implementation. ```rust impl TryFrom for T where U: Into, { type Error = Infallible; // Or a specific error type fn try_from(value: U) -> Result>::Error> { // Implementation details... Ok(value.into()) } } impl TryInto for T where U: TryFrom, { type Error = >::Error; fn try_into(self) -> Result>::Error> { U::try_from(self) } } ``` -------------------------------- ### Implement CloneToUninit for T Source: https://docs.rs/pasetors/latest/pasetors/token/struct Provides an unsafe method 'clone_to_uninit' for cloning a value into uninitialized memory. This is an experimental, nightly-only API and requires the type T to implement 'Clone'. ```rust impl CloneToUninit for T where T: Clone, ``` -------------------------------- ### Implement Generic Type Conversions (From, Into) Source: https://docs.rs/pasetors/latest/pasetors/keys/struct Offers generic implementations for the `From` and `Into` traits for any type `T`. `From` allows creating a `T` from another type, while `Into` allows converting `T` into `U` if `U` implements `From`. These conversions are typically infallible. ```rust impl From for T { fn from(t: T) -> T { t } } impl Into for T where U: From, { fn into(self) -> U { U::from(self) } } ``` -------------------------------- ### Footer Parsing and Serialization Source: https://docs.rs/pasetors/latest/pasetors/footer/struct Methods for parsing footer data from bytes or strings and serializing it back to a string. ```APIDOC ## Parsing and Serialization ### Method `parse_bytes(&mut self, bytes: &[u8]) -> Result<(), Error>` ### Description Attempts to create a `Footer` instance from a sequence of bytes. ### Parameters - **bytes** (`&[u8]`) - The byte slice representing the footer data. ### Returns - `Ok(())` on success. - `Err(Error)` if: - `bytes` contains non-UTF-8 sequences. - `bytes` does not decode as valid JSON. - The top-most JSON object does not decode to a map. - Registered claims exist but are not `String`s. - JSON maps/arrays exceed the recursion depth of 128. - The maximum number of named keys is exceeded. - The maximum JSON-encoded string length is exceeded. ### Method `parse_string(&mut self, string: &str) -> Result<(), Error>` ### Description Attempts to parse a `Footer` instance from a string. ### Parameters - **string** (`&str`) - The string representing the footer data. ### Returns - `Ok(())` on success. - `Err(Error)` if: - `string` does not decode as valid JSON. - The top-most JSON object does not decode to a map. - Registered claims exist but are not `String`s. - JSON maps/arrays exceed the recursion depth of 128. - The maximum number of named keys is exceeded. - The maximum JSON-encoded string length is exceeded. ### Method `to_string(&self) -> Result` ### Description Returns the JSON serialized representation of the `Footer` instance. ### Returns - `Ok(String)` containing the JSON representation. - `Err(Error)` if the `Footer` cannot be serialized as JSON. ``` -------------------------------- ### ClaimsValidationRules API Source: https://docs.rs/pasetors/latest/pasetors/claims/struct This section details the methods available for creating, configuring, and using ClaimsValidationRules to validate PASETO claims. ```APIDOC ## ClaimsValidationRules ### Description The validation rules that are used to validate a set of `Claims`. Available on **crate feature`std`** only. ### Methods #### `new()` ```rust pub fn new() -> Self ``` Create a new `ClaimsValidationRules` instance, setting: * validation of `iat`, `nbf`, `exp` true #### `disable_valid_at()` ```rust pub fn disable_valid_at(&mut self) ``` Disables the validation of `iat` and `nbf`, from the `ValidAt` validation pattern. `iat` and `nbf` may still be present in the `Claims` payload, at validation time, but will not be parsed. This means, you can disable this validation without modifying the creation of your `Claims`. In case of using `allow_non_expiring()`, the validation expects no `exp` claim to be present within the payload. To disable the entire `ValidAt` pattern, specify also `allow_non_expiring()`. See PASETO Validators. #### `allow_non_expiring()` ```rust pub fn allow_non_expiring(&mut self) ``` Explicitly allow non-expiring tokens (i.e. the `exp` claim is missing). #### `validate_issuer_with()` ```rust pub fn validate_issuer_with(&mut self, valid_issuer: &str) ``` Set the `valid_issuer` the claims should be validated against. #### `validate_subject_with()` ```rust pub fn validate_subject_with(&mut self, valid_subject: &str) ``` Set the `valid_subject` the claims should be validated against. #### `validate_audience_with()` ```rust pub fn validate_audience_with(&mut self, valid_audience: &str) ``` Set the `valid_audience` the claims should be validated against. #### `validate_token_identifier_with()` ```rust pub fn validate_token_identifier_with(&mut self, valid_token_identifier: &str) ``` Set the `valid_token_identifier` the claims should be validated against. #### `validate_claims()` ```rust pub fn validate_claims(&self, claims: &Claims) -> Result<(), Error> ``` Validate the set of registered `claims` against the currently defined validation rules. If `claims` has defined the `exp` claim, this is validated regardless of whether the rules have allowed for non-expiring. Non-expiring means that there should be no `exp` in `claims`. **Errors:** * Token is expired * Token is not yet valid * Token was issued in the future * Token has no `exp` claim but the validation rules do not allow non-expiring tokens * The claims values cannot be converted to `str` * `iat`, `nbf` and `exp` fail `str -> DateTime` conversion * Claim `iss`, `sub`, `aud`, `jti` does not match the expected * `claims` has no `nbf` or `iat` (unless `Self::disable_valid_at()` has been set) * a claim was registered for validation in the rules but is missing from the actual `claims` **NOTE:** This **does not** validate any non-registered claims (see `Claims::REGISTERED_CLAIMS`). They must be validated separately. ### Trait Implementations #### `Clone` ```rust fn clone(&self) -> ClaimsValidationRules ``` Returns a duplicate of the value. #### `Default` ```rust fn default() -> Self ``` Returns the “default value” for a type. #### `Debug` ```rust fn fmt(&self, f: &mut Formatter<'_>) -> Result ``` Formats the value using the given formatter. #### `PartialEq` ```rust fn eq(&self, other: &ClaimsValidationRules) -> bool fn ne(&self, other: &Rhs) -> bool ``` Tests for equality and inequality between two `ClaimsValidationRules` instances. ### Auto Trait Implementations `Freeze`, `RefUnwindSafe`, `Send`, `Sync`, `Unpin`, `UnwindSafe` ### Blanket Implementations `Any`, `Borrow`, `BorrowMut`, `CloneToUninit`, `From` ``` -------------------------------- ### Create ClaimsValidationRules Instance Source: https://docs.rs/pasetors/latest/pasetors/claims/struct Provides a constructor to create a new `ClaimsValidationRules` instance. It automatically enables validation for 'iat' (issued at), 'nbf' (not before), and 'exp' (expiration) claims. ```rust pub fn new() -> Self ``` -------------------------------- ### Claim Management in Footer - Rust Source: https://docs.rs/pasetors/latest/pasetors/footer/struct Illustrates checking for the existence of a claim and retrieving its value from a `Footer`. The `contains_claim()` method returns a boolean, while `get_claim()` returns an `Option<&Value>` if the claim is found, allowing for easy access to footer data. ```rust pub fn contains_claim(&self, claim: &str) -> bool pub fn get_claim(&self, claim: &str) -> Option<&Value> ``` -------------------------------- ### Implement Borrow and BorrowMut for Generic Type T Source: https://docs.rs/pasetors/latest/pasetors/keys/struct Provides standard implementations for `Borrow` and `BorrowMut` for any type `T`. These traits allow borrowing references to `T` immutably and mutably, respectively. They are fundamental for enabling various standard library operations and generic programming patterns. ```rust impl Borrow for T where T: ?Sized, { fn borrow(&self) -> &T { self } } impl BorrowMut for T where T: ?Sized, { fn borrow_mut(&mut self) -> &mut T { self } } ``` -------------------------------- ### Implement Clone for PASETO V3 Struct Source: https://docs.rs/pasetors/latest/pasetors/version3/struct This section shows the implementation of the `Clone` trait for the `V3` struct, allowing instances of `V3` to be duplicated. It includes methods for both `clone` and `clone_from`. ```rust fn clone(&self) -> V3 fn clone_from(&mut self, source: &Self) ``` -------------------------------- ### Compare AsymmetricSecretKey for equality in Rust Source: https://docs.rs/pasetors/latest/pasetors/keys/struct Implements the PartialEq trait for AsymmetricSecretKey, enabling equality comparisons between keys. The `eq` method tests for equality, and `ne` tests for inequality. ```rust impl PartialEq for AsymmetricSecretKey fn eq(&self, other: &AsymmetricSecretKey) -> bool ``` ```rust fn ne(&self, other: &Rhs) -> bool ``` -------------------------------- ### Create AsymmetricSecretKey from bytes in Rust Source: https://docs.rs/pasetors/latest/pasetors/keys/struct Provides a function to create an AsymmetricSecretKey from a byte slice. It returns a Result which can be Ok(Self) or Err(Error). A panic occurs for V2 or V4 if an all-zero secret seed is used. ```rust pub fn from(bytes: &[u8]) -> Result ``` -------------------------------- ### Implement Generic Cloning for PASETO V3 Source: https://docs.rs/pasetors/latest/pasetors/version3/struct This section shows blanket implementations of `CloneToUninit` and `ToOwned` for types that implement `Clone`, including potentially the `V3` struct. These traits facilitate efficient copying and ownership management. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) fn to_owned(&self) -> T fn clone_into(&self, target: &mut T) ``` -------------------------------- ### Implement PartialEq for ClaimsValidationRules Source: https://docs.rs/pasetors/latest/pasetors/claims/struct Implements the `PartialEq` trait for `ClaimsValidationRules`, allowing instances to be compared for equality. This is useful for testing and verifying that two sets of validation rules are identical. ```rust fn eq(&self, other: &ClaimsValidationRules) -> bool ``` ```rust fn ne(&self, other: &Rhs) -> bool ``` -------------------------------- ### Rust Trait Implementation: FormatAsPaserk for Id Source: https://docs.rs/pasetors/latest/pasetors/paserk/struct Details the implementation of the FormatAsPaserk trait for the 'Id' struct, enabling the formatting of a key as a PASERK. ```rust impl FormatAsPaserk for Id { fn fmt(&self, write: &mut dyn Write) -> Result } ``` -------------------------------- ### Implement Debug for PASETO V3 Struct Source: https://docs.rs/pasetors/latest/pasetors/version3/struct This code snippet illustrates the implementation of the `Debug` trait for the `V3` struct, enabling formatted output for debugging purposes. ```rust fn fmt(&self, f: &mut Formatter<'_>) -> Result ``` -------------------------------- ### Implement From for T Source: https://docs.rs/pasetors/latest/pasetors/claims/struct Demonstrates the `From` trait implementation for any type `T`, including `ClaimsValidationRules`. This allows for conversion into itself, which is a standard practice for identity transformations. ```rust fn from(t: T) -> T ``` -------------------------------- ### Generate Symmetric Key for PASETO V4 Source: https://docs.rs/pasetors/latest/pasetors/version4/struct Implements the `Generate` trait for `SymmetricKey`, enabling the creation of a new symmetric key for PASETO Version 4. The function returns a `Result` with the generated key or an error. ```rust impl Generate, V4> for SymmetricKey fn generate() -> Result, Error> ``` -------------------------------- ### Rust Trait Implementation: PartialEq for Id Source: https://docs.rs/pasetors/latest/pasetors/paserk/struct Illustrates the implementation of the PartialEq trait for the 'Id' struct, enabling equality comparisons between 'Id' instances. ```rust impl PartialEq for Id { fn eq(&self, other: &Id) -> bool fn ne(&self, other: &Rhs) -> bool } ``` -------------------------------- ### Constants for PASETO Footer - Rust Source: https://docs.rs/pasetors/latest/pasetors/footer/struct Provides constants related to PASETO footer claims and security. `REGISTERED_CLAIMS` lists reserved claim keys, `DISALLOWED_FOOTER` lists unsafe PASERK types for footers, `DEFAULT_MAX_KEYS` and `DEFAULT_MAX_LEN` define limits for JSON objects, and `MAX_RECURSION_DEPTH` sets the maximum nesting level for JSON parsing. ```rust pub const REGISTERED_CLAIMS: [&'static str; 2] pub const DISALLOWED_FOOTER: [&'static str; 8] pub const DEFAULT_MAX_KEYS: usize = 512usize pub const DEFAULT_MAX_LEN: usize = 8_192usize pub const MAX_RECURSION_DEPTH: usize = 128usize ``` -------------------------------- ### Rust TryInto Trait Implementation Source: https://docs.rs/pasetors/latest/pasetors/paserk/struct This code block shows the implementation of the `TryInto` trait for a generic type `T`. This allows types that implement `TryFrom` to be converted into `U` using the `try_into` method. The `where` clause ensures that the conversion target `U` must have a `TryFrom` implementation. ```rust impl TryInto for T where U: TryFrom, ``` -------------------------------- ### Rust: Implement `TryInto` trait for `T` to `U` Source: https://docs.rs/pasetors/latest/pasetors/footer/struct Allows fallible conversion from type `T` to type `U` using the `try_into` method, provided `U` implements `TryFrom`. It returns a `Result` to accommodate potential conversion failures. ```rust impl TryInto for T where U: TryFrom, { type Error = >::Error; fn try_into(self) -> Result>::Error>; } ``` -------------------------------- ### Rust `TryInto` Trait Usage Source: https://docs.rs/pasetors/latest/pasetors/errors/enum Illustrates using the `TryInto` trait for fallible conversions, which is automatically implemented when `TryFrom` is implemented. It provides a convenient method to perform conversions that may fail. ```Rust use std::convert::TryInto; struct MyStruct { value: i32 } struct OtherStruct { data: String } impl TryFrom for MyStruct { type Error = &'static str; fn try_from(value: OtherStruct) -> Result { if value.data.starts_with("valid_") { Ok(MyStruct { value: value.data.len() as i32 }) } else { Err("Invalid data format") } } } fn main() { let valid_data = OtherStruct { data: "valid_string".to_string() }; let invalid_data = OtherStruct { data: "invalid_data".to_string() }; let my_struct_result: Result = valid_data.try_into(); match my_struct_result { Ok(s) => println!("Successfully converted: {}", s.value), Err(e) => println!("Conversion failed: {}", e), } let my_struct_result_fail: Result = invalid_data.try_into(); match my_struct_result_fail { Ok(s) => println!("Successfully converted: {}", s.value), Err(e) => println!("Conversion failed: {}", e), } } ``` -------------------------------- ### Debug AsymmetricSecretKey in Rust Source: https://docs.rs/pasetors/latest/pasetors/keys/struct Implements the Debug trait for AsymmetricSecretKey, enabling formatted output for debugging purposes. This allows the key to be printed using the `{:?}` format specifier. ```rust impl Debug for AsymmetricSecretKey fn fmt(&self, f: &mut Formatter<'_>) -> Result ``` -------------------------------- ### Generate SymmetricKey for V2 Source: https://docs.rs/pasetors/latest/pasetors/version2/struct Implements the Generate trait for SymmetricKey, enabling the creation of new symmetric keys for PASETO Version 2. This function returns a Result containing the generated symmetric key or an error. ```rust impl Generate, V2> for SymmetricKey fn generate() -> Result, Error> ``` -------------------------------- ### TryFrom String for UntrustedToken Source: https://docs.rs/pasetors/latest/pasetors/token/struct Enables conversion of a String reference into an 'UntrustedToken'. This conversion fails if the string is not a valid PASETO token or has invalid base64 encoding. Requires T and V to implement Purpose and Version traits respectively. ```rust impl, V: Version> TryFrom<&String> for UntrustedToken ``` -------------------------------- ### Convert AsymmetricSecretKey to AsymmetricPublicKey in Rust Source: https://docs.rs/pasetors/latest/pasetors/keys/struct Implements the TryFrom trait to attempt conversion of an AsymmetricSecretKey to an AsymmetricPublicKey for specific versions (V2, V3, V4). This operation can fail, returning a Result with an Error type. ```rust impl TryFrom<&AsymmetricSecretKey> for AsymmetricPublicKey where AsymmetricSecretKey: TryFrom<&'static str>, AsymmetricPublicKey: TryFrom<&'static str>, { type Error = Error fn try_from(value: &AsymmetricSecretKey) -> Result ``` ```rust impl TryFrom<&AsymmetricSecretKey> for AsymmetricPublicKey { type Error = Error fn try_from(value: &AsymmetricSecretKey) -> Result ``` ```rust impl TryFrom<&AsymmetricSecretKey> for AsymmetricPublicKey { type Error = Error fn try_from(value: &AsymmetricSecretKey) -> Result ``` -------------------------------- ### Verify PASETO v4 Public Token - Rust Source: https://docs.rs/pasetors/latest/pasetors/public/fn Verifies a PASETO v4 public token using a provided public key and validates its claims against specified rules. This function requires the `std` and `v4` crate features to be enabled. It returns a trusted token upon successful verification and validation, or an error otherwise. ```rust pub fn verify( public_key: &AsymmetricPublicKey, token: &UntrustedToken, validation_rules: &ClaimsValidationRules, footer: Option<&Footer>, implicit_assert: Option<&[u8]>, ) -> Result ``` -------------------------------- ### Trait FormatAsPaserk for PASERK Serialization (Rust) Source: https://docs.rs/pasetors/latest/pasetors/paserk/trait The `FormatAsPaserk` trait defines a method for serializing types into the PASERK format. It requires a `fmt` method that takes a mutable writer and returns a Result. This trait is essential for converting cryptographic keys into a standardized, portable format. ```rust pub trait FormatAsPaserk { // Required method fn fmt(&self, write: &mut dyn Write) -> Result; } ``` -------------------------------- ### Format AsymmetricSecretKey as PASERK in Rust Source: https://docs.rs/pasetors/latest/pasetors/keys/struct Implements the FormatAsPaserk trait for AsymmetricSecretKey for versions V2, V3, and V4. This allows the key to be formatted according to the PASERK specification, typically used for serialization and interoperability. ```rust impl FormatAsPaserk for AsymmetricSecretKey fn fmt(&self, write: &mut dyn Write) -> Result ``` ```rust impl FormatAsPaserk for AsymmetricSecretKey fn fmt(&self, write: &mut dyn Write) -> Result ``` ```rust impl FormatAsPaserk for AsymmetricSecretKey fn fmt(&self, write: &mut dyn Write) -> Result ``` -------------------------------- ### TryFrom str for UntrustedToken Source: https://docs.rs/pasetors/latest/pasetors/token/struct Enables conversion of a string slice into an 'UntrustedToken'. This conversion fails if the string is not a valid PASETO token or has invalid base64 encoding. Requires T and V to implement Purpose and Version traits respectively. ```rust impl, V: Version> TryFrom<&str> for UntrustedToken ``` -------------------------------- ### Implement Auto Traits for AsymmetricSecretKey Source: https://docs.rs/pasetors/latest/pasetors/keys/struct Demonstrates the implementation of several auto traits (`Freeze`, `RefUnwindSafe`, `Send`, `Sync`, `Unpin`, `UnwindSafe`) for `AsymmetricSecretKey`, where `V` is a generic type parameter. These implementations indicate thread safety and memory safety properties of the `AsymmetricSecretKey` type. ```rust impl Freeze for AsymmetricSecretKey {} impl RefUnwindSafe for AsymmetricSecretKey where V: RefUnwindSafe {} impl Send for AsymmetricSecretKey where V: Send {} impl Sync for AsymmetricSecretKey where V: Sync {} impl Unpin for AsymmetricSecretKey where V: Unpin {} impl UnwindSafe for AsymmetricSecretKey where V: UnwindSafe {} ``` -------------------------------- ### Serialize Footer to String - Rust Source: https://docs.rs/pasetors/latest/pasetors/footer/struct Provides a method to serialize a `Footer` instance into its JSON string representation. The `to_string()` function returns a `Result`, indicating success with the JSON string or failure if serialization is not possible. ```rust pub fn to_string(&self) -> Result ``` -------------------------------- ### Generate Asymmetric Key Pair for PASETO V4 Source: https://docs.rs/pasetors/latest/pasetors/version4/struct Implements the `Generate` trait for `AsymmetricKeyPair`, allowing the creation of a new asymmetric key pair specifically for PASETO Version 4. This function returns a `Result` containing the key pair or an error if generation fails. ```rust impl Generate, V4> for AsymmetricKeyPair fn generate() -> Result, Error> ``` -------------------------------- ### Implement Debug for ClaimsValidationRules Source: https://docs.rs/pasetors/latest/pasetors/claims/struct Implements the `Debug` trait for `ClaimsValidationRules`, enabling formatted output for debugging purposes. This helps in inspecting the state of validation rules. ```rust fn fmt(&self, f: &mut Formatter<'_>) -> Result ``` -------------------------------- ### Rust Trait Implementation: Clone for Id Source: https://docs.rs/pasetors/latest/pasetors/paserk/struct Demonstrates the implementation of the Clone trait for the 'Id' struct. This allows for creating duplicate instances of an 'Id'. Includes methods for cloning and clone_from. ```rust impl Clone for Id { fn clone(&self) -> Id fn clone_from(&mut self, source: &Self) } ``` -------------------------------- ### Generate AsymmetricKeyPair for V2 Source: https://docs.rs/pasetors/latest/pasetors/version2/struct Implements the Generate trait for AsymmetricKeyPair, allowing for the creation of new asymmetric key pairs specifically for PASETO Version 2. This function returns a Result containing the generated key pair or an error. ```rust impl Generate, V2> for AsymmetricKeyPair fn generate() -> Result, Error> ``` -------------------------------- ### Generate AsymmetricKeyPair for PASETO V3 Source: https://docs.rs/pasetors/latest/pasetors/version3/struct This implementation demonstrates how to generate an asymmetric key pair specifically for PASETO Version 3. This function is part of the 'Generate' trait for `AsymmetricKeyPair`. ```rust fn generate() -> Result, Error> ``` -------------------------------- ### Parse Footer from Bytes or String - Rust Source: https://docs.rs/pasetors/latest/pasetors/footer/struct Shows how to parse a `Footer` from raw bytes or a string. The `parse_bytes()` and `parse_string()` methods handle JSON decoding and validation against various constraints, including valid UTF-8, JSON structure, claim types, recursion depth, key count, and string length. Errors are returned if parsing fails. ```rust pub fn parse_bytes(&mut self, bytes: &[u8]) -> Result<(), Error> pub fn parse_string(&mut self, string: &str) -> Result<(), Error> ``` -------------------------------- ### Rust Trait Implementation: Serialize for Id Source: https://docs.rs/pasetors/latest/pasetors/paserk/struct Shows the implementation of the Serialize trait from the 'serde' crate for the 'Id' struct. This allows 'Id' instances to be serialized into various data formats. Requires the 'serde' feature. ```rust impl Serialize for Id { fn serialize(&self, serializer: S) -> Result where S: Serializer } ``` -------------------------------- ### Rust Trait Implementation: From<&AsymmetricSecretKey> for Id Source: https://docs.rs/pasetors/latest/pasetors/paserk/struct Shows implementations for converting 'Id' from various asymmetric secret key types (V2, V3, V4) using the From trait. ```rust impl From<&AsymmetricSecretKey> for Id { fn from(key: &AsymmetricSecretKey) -> Self } impl From<&AsymmetricSecretKey> for Id { fn from(key: &AsymmetricSecretKey) -> Self } impl From<&AsymmetricSecretKey> for Id { fn from(key: &AsymmetricSecretKey) -> Self } ``` -------------------------------- ### Rust Trait Implementation: From<&AsymmetricPublicKey> for Id Source: https://docs.rs/pasetors/latest/pasetors/paserk/struct Provides implementations for converting 'Id' from various asymmetric public key types (V2, V3, V4) using the From trait. ```rust impl From<&AsymmetricPublicKey> for Id { fn from(key: &AsymmetricPublicKey) -> Self } impl From<&AsymmetricPublicKey> for Id { fn from(key: &AsymmetricPublicKey) -> Self } impl From<&AsymmetricPublicKey> for Id { fn from(key: &AsymmetricPublicKey) -> Self } ``` -------------------------------- ### Implement Sync for UntrustedToken Source: https://docs.rs/pasetors/latest/pasetors/token/struct Marks 'UntrustedToken' as 'Sync', meaning it can be safely shared between threads via references. Requires generic types T and V to also be 'Sync'. ```rust impl Sync for UntrustedToken where T: Sync, V: Sync, ```