hatchet-client 0.1.0

Rust SDK for Hatchet: run workers and trigger tasks
Documentation
//! Reads the claims the SDK needs out of a Hatchet API token.
//!
//! The token is a JWT, but the SDK is not the party that verifies it: like
//! the official SDKs, it only base64-decodes the payload to learn where the
//! engine lives. The engine verifies the signature on every call.

use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use serde::Deserialize;

use crate::{Error, Result};

#[derive(Debug, Deserialize)]
pub(crate) struct TokenClaims {
    /// Tenant ID.
    pub(crate) sub: Option<String>,
    pub(crate) server_url: Option<String>,
    pub(crate) grpc_broadcast_address: Option<String>,
}

pub(crate) fn decode_claims(token: &str) -> Result<TokenClaims> {
    let parts: Vec<&str> = token.split('.').collect();
    let [_, payload, _] = parts.as_slice() else {
        return Err(Error::InvalidToken(format!(
            "expected three dot-separated parts, found {}",
            parts.len()
        )));
    };
    let bytes = URL_SAFE_NO_PAD
        .decode(payload.trim_end_matches('='))
        .map_err(|e| Error::InvalidToken(format!("payload is not base64url: {e}")))?;
    serde_json::from_slice(&bytes)
        .map_err(|e| Error::InvalidToken(format!("payload is not a JSON object of claims: {e}")))
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use base64::Engine;
    use base64::engine::general_purpose::URL_SAFE_NO_PAD;

    /// Builds an unsigned JWT-shaped token around `claims`.
    pub(crate) fn token_with(claims: serde_json::Value) -> String {
        let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"ES256","typ":"JWT"}"#);
        let payload = URL_SAFE_NO_PAD.encode(claims.to_string());
        format!("{header}.{payload}.signature")
    }

    pub(crate) fn full_token() -> String {
        token_with(serde_json::json!({
            "sub": "707d0855-80ab-4e1f-a156-f1c4546cbf52",
            "server_url": "https://hatchet.example.com",
            "grpc_broadcast_address": "grpc.example.com:443",
            "exp": 1_900_000_000,
        }))
    }

    #[test]
    fn reads_the_three_claims() {
        let claims = decode_claims(&full_token()).unwrap();
        assert_eq!(
            claims.sub.as_deref(),
            Some("707d0855-80ab-4e1f-a156-f1c4546cbf52")
        );
        assert_eq!(
            claims.server_url.as_deref(),
            Some("https://hatchet.example.com")
        );
        assert_eq!(
            claims.grpc_broadcast_address.as_deref(),
            Some("grpc.example.com:443")
        );
    }

    #[test]
    fn accepts_padded_base64() {
        let payload = base64::engine::general_purpose::URL_SAFE.encode(r#"{"sub":"t"}"#);
        assert!(payload.ends_with('='), "test needs a payload that pads");
        let claims = decode_claims(&format!("h.{payload}.s")).unwrap();
        assert_eq!(claims.sub.as_deref(), Some("t"));
    }

    #[test]
    fn missing_claims_decode_as_none() {
        let claims = decode_claims(&token_with(serde_json::json!({"sub": "t"}))).unwrap();
        assert_eq!(claims.server_url, None);
        assert_eq!(claims.grpc_broadcast_address, None);
    }

    #[test]
    fn truncated_token_is_an_error() {
        let token = full_token();
        let truncated = &token[..token.rfind('.').unwrap()];
        let err = decode_claims(truncated).unwrap_err();
        assert!(matches!(err, Error::InvalidToken(_)), "{err:?}");
        assert!(err.to_string().contains("three"), "{err}");
    }

    #[test]
    fn garbage_payload_is_an_error_that_does_not_leak_the_token() {
        let token = "aaaa.!!!not-base64!!!.cccc";
        let err = decode_claims(token).unwrap_err();
        assert!(matches!(err, Error::InvalidToken(_)), "{err:?}");
        assert!(!err.to_string().contains("not-base64"), "{err}");

        let not_json = format!("h.{}.s", URL_SAFE_NO_PAD.encode("plain text"));
        assert!(matches!(
            decode_claims(&not_json),
            Err(Error::InvalidToken(_))
        ));
    }
}