Struct Cat

Source
pub struct Cat { /* private fields */ }
Expand description

Common Access Token (CAT) validator and generator.

This is the main struct for working with CAT tokens. It provides methods for:

  • Generating tokens from claims
  • Validating tokens and extracting claims
  • Converting between JSON and CAT claims

§Examples

use common_access_token::{Cat, CatOptions, CatGenerateOptions, CatValidationOptions, CatValidationType, Claims};
use std::collections::HashMap;

// Create a CAT instance
let key = hex::decode("403697de87af64611c1d32a05dab0fe1fcb715a86ab435f1ec99192d79569388").unwrap();
let cat = Cat::new(CatOptions {
    keys: HashMap::from([("key-1".to_string(), key)]),
    expect_cwt_tag: true,
});

// Create and generate a token
let mut claims = Claims::new();
claims.set_issuer("example");
let token = cat.generate(claims, &CatGenerateOptions {
    validation_type: CatValidationType::Mac,
    alg: "HS256".to_string(),
    kid: "key-1".to_string(),
    generate_cwt_id: true,
}).unwrap();

// Validate the token
let validation_options = CatValidationOptions {
    issuer: "example".to_string(),
    audience: None,
};
let validated_claims = cat.validate(&token, CatValidationType::Mac, &validation_options).unwrap();

Implementations§

Source§

impl Cat

Source

pub fn new(opts: CatOptions) -> Self

Creates a new CAT instance with the specified options.

§Arguments
  • opts - Configuration options including cryptographic keys and format settings
§Examples
use common_access_token::{Cat, CatOptions};
use std::collections::HashMap;

let key = hex::decode("403697de87af64611c1d32a05dab0fe1fcb715a86ab435f1ec99192d79569388").unwrap();
let cat = Cat::new(CatOptions {
    keys: HashMap::from([("key-1".to_string(), key)]),
    expect_cwt_tag: true,
});
Source

pub fn validate( &self, token: &str, validation_type: CatValidationType, opts: &CatValidationOptions, ) -> Result<Claims, Error>

Validates a CAT token and returns the claims if valid.

This method performs several validation steps:

  1. Decodes the token from base64
  2. Verifies the cryptographic signature/MAC
  3. Validates the claims (issuer, expiration, audience)
§Arguments
  • token - The CAT token as a base64url-encoded string
  • validation_type - The type of validation to perform (Mac, Sign, or None)
  • opts - Options controlling validation behavior
§Returns
  • Ok(Claims) - The validated claims from the token
  • Err(Error) - An error indicating why validation failed
§Examples
// Validate a token
let token = "..."; // Base64url-encoded token
let validation_options = CatValidationOptions {
    issuer: "trusted-issuer".to_string(),
    audience: Some(vec!["my-app".to_string()]),
};

match cat.validate(token, CatValidationType::Mac, &validation_options) {
    Ok(claims) => {
        println!("Token is valid!");
        println!("Subject: {:?}", claims.get_subject());
    },
    Err(err) => {
        println!("Token validation failed: {}", err);
    }
}
Source

pub fn generate( &self, claims: Claims, opts: &CatGenerateOptions, ) -> Result<String, Error>

Generates a CAT token from the provided claims.

This method creates a token by:

  1. Optionally generating a CWT ID if requested
  2. Serializing the claims to CBOR
  3. Creating a cryptographic signature/MAC
  4. Encoding the result as a base64url string
§Arguments
  • claims - The claims to include in the token
  • opts - Options controlling token generation
§Returns
  • Ok(String) - The generated token as a base64url-encoded string
  • Err(Error) - An error indicating why token generation failed
§Examples
// Create claims
let mut claims = Claims::new();
claims.set_issuer("my-service");
claims.set_subject("user-123");
claims.set_audience("client-app");

// Set expiration time
let now = std::time::SystemTime::now()
    .duration_since(std::time::UNIX_EPOCH)
    .unwrap()
    .as_secs() as i64;
claims.set_expiration(now + 3600); // 1 hour from now

// Generate the token
let token = cat.generate(claims, &CatGenerateOptions {
    validation_type: CatValidationType::Mac,
    alg: "HS256".to_string(),
    kid: "key-1".to_string(),
    generate_cwt_id: true,
}).unwrap();

println!("Generated token: {}", token);
Source

pub fn generate_from_json( &self, json_claims: Value, opts: &CatGenerateOptions, ) -> Result<String, Error>

Generates a CAT token from a JSON object containing claims.

This is a convenience method that converts JSON claims to a Claims object and then generates a token. It’s useful when working with JSON data from external sources.

§Arguments
  • json_claims - JSON object containing claims (e.g., {"iss": "issuer", "sub": "subject"})
  • opts - Options controlling token generation
§Returns
  • Ok(String) - The generated token as a base64url-encoded string
  • Err(Error) - An error indicating why token generation failed
§Examples
// Create claims as JSON
let now = std::time::SystemTime::now()
    .duration_since(std::time::UNIX_EPOCH)
    .unwrap()
    .as_secs() as i64;

let json_claims = json!({
    "iss": "my-service",
    "sub": "user-123",
    "aud": "client-app",
    "exp": now + 3600, // 1 hour from now
    "iat": now
});

// Generate the token
let token = cat.generate_from_json(json_claims, &CatGenerateOptions {
    validation_type: CatValidationType::Mac,
    alg: "HS256".to_string(),
    kid: "key-1".to_string(),
    generate_cwt_id: true,
}).unwrap();
Source

pub fn resign_token( &self, token: &str, validation_opts: &CatValidationOptions, new_expiration: i64, generate_opts: &CatGenerateOptions, ) -> Result<String, Error>

Converts a JSON object to a Claims object.

This method maps standard JWT claim names to their CWT equivalents:

  • “iss” -> issuer
  • “sub” -> subject
  • “aud” -> audience
  • “exp” -> expiration
  • “nbf” -> not before
  • “iat” -> issued at
  • “cti” -> CWT ID
§Arguments
  • json_claims - JSON object containing claims
  • opts - Generation options (used for CWT ID generation)
§Returns
  • Ok(Claims) - The converted claims
  • Err(Error) - An error if conversion fails Re-signs an existing token with a new expiration time.

This method extends the lifetime of an existing token by:

  1. Validating the existing token
  2. Extracting the claims
  3. Updating the expiration time
  4. Generating a new token with the updated claims
§Arguments
  • token - The existing token to re-sign
  • validation_opts - Options for validating the existing token
  • new_expiration - The new expiration time (in seconds since UNIX epoch)
  • generate_opts - Options for generating the new token
§Returns
  • Ok(String) - The newly generated token with extended lifetime
  • Err(Error) - An error if token validation or generation fails
§Examples
// Validation options for the existing token
let validation_options = CatValidationOptions {
    issuer: "trusted-issuer".to_string(),
    audience: None,
};

// Calculate new expiration time (e.g., 1 hour from now)
let now = std::time::SystemTime::now()
    .duration_since(std::time::UNIX_EPOCH)
    .unwrap()
    .as_secs() as i64;
let new_expiration = now + 3600;

// Generation options for the new token
let generate_options = CatGenerateOptions {
    validation_type: CatValidationType::Mac,
    alg: "HS256".to_string(),
    kid: "key-1".to_string(),
    generate_cwt_id: true, // Generate a new CWT ID
};

// Re-sign the token with the new expiration
let new_token = cat.resign_token(
    &existing_token,
    &validation_options,
    new_expiration,
    &generate_options
).unwrap();

Trait Implementations§

Source§

impl Clone for Cat

Source§

fn clone(&self) -> Cat

Returns a copy 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 Cat

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Cat

§

impl RefUnwindSafe for Cat

§

impl Send for Cat

§

impl Sync for Cat

§

impl Unpin for Cat

§

impl UnwindSafe for Cat

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, 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> 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