pdk-jwt-lib 1.9.0

PDK JWT Library
Documentation
// Copyright (c) 2026, Salesforce, Inc.,
// All rights reserved.
// For full license text, see the LICENSE.txt file

//! # Untrusted Token Handling
//!
//! This module provides utilities for handling untrusted JWT tokens before validation,
//! including extraction of key IDs and token metadata.

/// Trait to get the key ID from an untrusted token.
pub trait UntrustedToken {
    fn kid(&self) -> Option<&String>;
}

/// Module to handle untrusted JWT compact tokens.
pub mod untrusted_jwt_compact {
    use super::UntrustedToken;
    use crate::error::jwt_error::JWTError;

    /// Struct to handle untrusted JWT compact tokens.
    pub struct UntrustedJWT<'a> {
        untrusted_token: jwt_compact::UntrustedToken<'a>,
    }

    impl<'a> UntrustedJWT<'a> {
        /// Create a new [`UntrustedJWT`] from a token string.
        pub fn new<S: AsRef<str> + ?Sized>(token_string: &'a S) -> Result<Self, JWTError> {
            let untrusted = jwt_compact::UntrustedToken::new(token_string)?;
            Ok(UntrustedJWT {
                untrusted_token: untrusted,
            })
        }
    }

    impl UntrustedToken for UntrustedJWT<'_> {
        fn kid(&self) -> Option<&String> {
            self.untrusted_token.header().key_id.as_ref()
        }
    }

    impl<'a> From<UntrustedJWT<'a>> for jwt_compact::UntrustedToken<'a> {
        fn from(token: UntrustedJWT<'a>) -> Self {
            token.untrusted_token
        }
    }
}

/// Module to handle untrusted JWT tokens which provides a wrapper around
/// untrusted JWT tokens, extracting Key IDs and storing the original token.
pub mod untrusted_jwt {
    use super::UntrustedToken;
    use crate::error::jwt_error::JWTError;
    use jwt_simple::prelude::Token;
    use std::option::Option;

    /// Struct to handle untrusted JWT tokens.
    pub struct UntrustedJWT {
        kid: Option<String>,
        value: Option<String>,
    }

    impl UntrustedJWT {
        /// Create a new [`UntrustedJWT`] from a token string.
        pub fn new(token_string: &str) -> Result<Self, JWTError> {
            let untrusted = Token::decode_metadata(token_string)?;

            Ok(UntrustedJWT {
                kid: untrusted.key_id().map(String::from),
                value: Some(String::from(token_string)),
            })
        }

        /// Get the token value.
        pub fn value(&self) -> &String {
            self.value.as_ref().unwrap()
        }
    }

    impl UntrustedToken for UntrustedJWT {
        fn kid(&self) -> Option<&String> {
            self.kid.as_ref()
        }
    }
}