A Rust implementation of the Common Access Token (CAT) specification, which is based on CBOR Object Signing and Encryption (COSE). Common Access Tokens are compact, secure tokens designed for efficient transmission in resource-constrained environments.
Common Access Tokens provide a more compact alternative to JSON Web Tokens (JWT) by using CBOR encoding instead of JSON. This makes them ideal for IoT devices, embedded systems, and other environments where bandwidth and processing power are limited.
This library uses the minicbor crate for CBOR serialization and deserialization, and supports both COSE_Sign1 and COSE_Mac0 structures for token verification.
- Compact Representation: CBOR-encoded tokens are significantly smaller than equivalent JWT tokens
- Flexible Token Structure: Support for both protected and unprotected headers
- Multiple Token Formats: Compatible with both COSE_Sign1 and COSE_Mac0 structures
- Standard Claims: Support for all standard CWT claims (iss, sub, aud, exp, nbf, iat, cti)
- Custom Claims: Support for application-specific claims with string, binary, integer, and nested map values
- CAT-specific Claims: Support for CAT-specific claims like CATU (URI restrictions), CATR (token renewal), CATM (HTTP methods), and more
- Key Identifiers: Support for both binary and string key identifiers (kid)
- Multiple Signing Algorithms: HMAC-SHA256 (HS256) MACs, plus ECDSA P-256 (ES256) and RSASSA-PSS (PS256) asymmetric signatures
- Comprehensive Verification: Validate signatures, expiration times, and other claims
- CAT-specific Validation: Validate URI restrictions, HTTP method constraints, and replay protection
- Media over QUIC (MoQ): Issue and validate
moqt/moqt-revalscopes from draft-ietf-moq-c4m for MoQT relays, publishers, and clients
Add this to your Cargo.toml:
[dependencies]
common-access-token = "0.7"wasm32-wasip1 (for example Fastly Compute) works with no extra setup.
For browsers and Node.js (wasm32-unknown-unknown with wasm-bindgen), enable
the js feature (new in 0.6):
[dependencies]
common-access-token = { version = "0.7", features = ["js"] }It takes randomness (for the PS256 salt) from crypto.getRandomValues and the
current time from Date.now(). Node.js 19 or later is needed for
crypto.getRandomValues. Without the feature, the wasm32-unknown-unknown
build fails in getrandom. The feature is off by default because wasm-bindgen
breaks non-JavaScript WASM hosts, and it does nothing on other targets.
npm/ packages this crate for JavaScript and TypeScript, in browsers
and Node.js, as @fastly/common-access-token. Its bindings are in
bindings/wasm/. See npm/README.md.
You can create tokens with various claims and headers using the builder pattern:
use common_access_token::{
Algorithm, CborValue, KeyId, RegisteredClaims, TokenBuilder, current_timestamp,
};
use std::collections::BTreeMap;
// Secret key for signing
let key = b"my-secret-key-for-hmac-sha256";
let now = current_timestamp();
// Create a token with string key ID
let token = TokenBuilder::new()
.algorithm(Algorithm::HmacSha256)
.protected_key_id(KeyId::string("my-key-id"))
.registered_claims(
RegisteredClaims::new()
.with_issuer("example-issuer")
.with_subject("example-subject")
.with_audience("example-audience")
.with_expiration(now + 3600) // 1 hour from now
.with_not_before(now)
.with_issued_at(now)
.with_cti(b"token-id-1234".to_vec())
)
.custom_string(100, "custom-string-value")
.custom_binary(101, b"custom-binary-value".to_vec())
.custom_int(102, 12345)
// You can also add nested maps as claims
.custom_map(103, {
let mut map = std::collections::BTreeMap::new();
map.insert(1, CborValue::Text("nested-value".to_string()));
map.insert(2, CborValue::Integer(42));
map
})
.sign(key)
.expect("Failed to sign token");
// Encode token to bytes
let token_bytes = token.to_bytes().expect("Failed to encode token");use common_access_token::{Token, VerificationOptions, VerifyingKey};
// Decode the token
let token = Token::from_bytes(&token_bytes).expect("Failed to decode token");
// Verify the signature
token
.verify_with_key(VerifyingKey::HmacSha256(key))
.expect("Failed to verify signature");
// Verify the claims
let options = VerificationOptions::new()
.verify_exp(true)
.verify_nbf(true)
.expected_issuer("example-issuer")
.expected_audience("example-audience");
token.verify_claims(&options).expect("Failed to verify claims");
// Access token data
if let Some(kid) = token.header.key_id_text() {
println!("Key ID: {}", kid);
}
if let Some(iss) = &token.claims.registered.iss {
println!("Issuer: {}", iss);
}
// Access custom claims
if let Some(text) = token.get_custom_string(100) {
println!("Custom string: {}", text);
}
// Access nested map claims
if let Some(nested @ CborValue::Map(map)) = token.get_custom_claim(103) {
println!("Found nested map with {} entries", map.len());
if let Some(CborValue::Text(text)) = nested.get(1) {
println!("Nested text: {}", text);
}
}CTA-5007-B §4.6.1 requires a recipient to reject a token that isn't signed by
an issuer it accepts, with a key associated with that issuer.
verify_with_key checks the signature against the key you pass, and
verify_claims compares iss only when expected_issuer is set, so binding
issuers to keys is up to you: pick the verification key by issuer (or by a key
ID that belongs to one issuer). If one key serves several issuers, or you pick
keys by key ID alone, set expected_issuer so a token from another issuer
signed with that key is rejected.
The library supports both binary and string key identifiers:
// String key ID
let string_kid = KeyId::string("my-key-id");
// Binary key ID
let binary_kid = KeyId::binary(vec![0x01, 0x02, 0x03, 0x04, 0x05]);A kid is always a byte string in the token (RFC 9052 §3.1), so a string key
ID is written as its UTF-8 bytes and decodes as KeyId::Binary. Key IDs with
the same bytes are equal whichever variant they are, so
token.header.key_id() == Some(KeyId::string("my-key-id")) still holds, and
token.header.key_id_text() reads it back as a string. A text kid from an
older token still decodes, as KeyId::String.
Common Access Tokens are encoded as CBOR objects following the COSE (CBOR Object Signing and Encryption) specification. When using HMAC algorithms (like HmacSha256), tokens are created as COSE_Mac0 structures with CWT (tag 61) and COSE_Mac0 (tag 17) CBOR tags for compatibility with other CAT implementations.
The token structure is:
COSE_Mac0 = [
protected: bstr .cbor header_map,
unprotected: header_map,
payload: bstr .cbor claims,
signature: bstr
]
Asymmetric signature algorithms (ES256, PS256) instead use the COSE_Sign1 structure with CWT (tag 61) and COSE_Sign1 (tag 18) CBOR tags. The array layout is identical; only the final element is a signature rather than a MAC.
An HMAC token's MAC is verified over the COSE_Mac0 MAC_structure (context "MAC0", RFC 9052 §6.3) only. For tokens from an issuer that MACs over the COSE_Sign1 structure (context "Signature1") instead, token.verify_hmac_allowing_legacy_sign1(key) also accepts that form; it isn't RFC 9052 or CTA-5007-B conformant.
The library supports three algorithms, selected via Algorithm on the builder. The sign() key bytes and the VerifyingKey passed to verify_with_key() are interpreted according to the algorithm:
| Algorithm | COSE id | Structure | sign() key |
verify_with_key() key |
|---|---|---|---|---|
Algorithm::HmacSha256 |
5 | COSE_Mac0 | raw symmetric key bytes | VerifyingKey::HmacSha256 (raw bytes) |
Algorithm::Es256 |
-7 | COSE_Sign1 | PKCS#8 DER P-256 private key | VerifyingKey::Es256 (SPKI DER public key) |
Algorithm::Ps256 |
-37 | COSE_Sign1 | PKCS#8 DER RSA private key | VerifyingKey::Ps256 (SPKI DER public key) |
ES256 is ECDSA over the NIST P-256 curve with SHA-256; signatures are the fixed 64-byte COSE r || s form. PS256 is RSASSA-PSS with SHA-256 and MGF1-SHA-256. PSS uses a random salt, so each signature over the same input differs while all remain valid.
Verify with a typed
VerifyingKey.verify_with_key()rejects any token whose headeralgdoesn't match the key's algorithm, which prevents algorithm-confusion forgery (anHmacSha256token MACed with your public key). The deprecatedverify(&[u8])only accepts HMAC-SHA256 and must never be given a public key.
use common_access_token::{Algorithm, KeyId, RegisteredClaims, TokenBuilder, VerifyingKey, current_timestamp};
// `private_key` is PKCS#8 DER; `public_key` is SPKI DER.
let token = TokenBuilder::new()
.algorithm(Algorithm::Es256)
.protected_key_id(KeyId::string("my-ec-key"))
.registered_claims(
RegisteredClaims::new()
.with_issuer("example-issuer")
.with_expiration(current_timestamp() + 3600),
)
.sign(private_key)
.expect("Failed to sign token");
let token_bytes = token.to_bytes().expect("Failed to encode token");
let decoded = common_access_token::Token::from_bytes(&token_bytes).expect("decode");
decoded
.verify_with_key(VerifyingKey::Es256(public_key))
.expect("Failed to verify ES256 signature");You can include complex structured data in tokens using nested maps. Map keys
are MapKeys: integers, text, or arrays of those. CWT and COSE labels can be
integers or text (RFC 8392, RFC 9052), cath (CTA-5007-B §4.6.13) is keyed
by header names, and catif (§4.9.1) by text and arrays. Claim labels can be
text too, though the registered and CAT claims all
use integers.
use common_access_token::{CborValue, MapKey, TokenBuilder};
// Create a nested map
let location_data = CborValue::map([
(MapKey::from(1), CborValue::Text("coordinates".to_string())),
(MapKey::from("lat"), CborValue::Integer(40)),
(MapKey::from("lon"), CborValue::Integer(-74)),
]);
// Add it to a token
let token = TokenBuilder::new()
// ... other token configuration ...
.custom_cbor(200, location_data)
.sign(key)
.expect("Failed to sign token");
// Read it back
let location = token.get_custom_claim(200).unwrap();
assert_eq!(location.get("lat"), Some(&CborValue::Integer(40)));Maps encode with integer keys first, then text keys, then array keys. Lookups
on the maps themselves (claims.custom, header.protected, a
CborValue::Map) take a MapKey: claims.custom.get(&MapKey::from(100)).
Claims with text labels are never registered claims (a text "aud" isn't
aud), and verification ignores them like any unknown claim.
You can customize token verification with various options:
use common_access_token::VerificationOptions;
// Standard verification options
let options = VerificationOptions::new()
.verify_exp(true) // Verify expiration time
.require_exp(true) // Require expiration claim to be present
.verify_nbf(true) // Verify not-before time
.expected_issuer("trusted-issuer") // Require iss, and check it
.expected_audience("my-service"); // Require aud, and check it
// .require_iss(true) / .require_aud(true) require the claim without
// checking its value
// CAT-specific verification options
let cat_options = VerificationOptions::new()
// Standard verification
.verify_exp(true)
.expected_issuer("trusted-issuer")
// CAT-specific verification
.verify_catu(true) // Verify URI restrictions
.uri("https://api.example.com/users/123") // URI to verify against
.verify_catm(true) // Verify HTTP method restrictions
.http_method("GET") // HTTP method to verify against
.verify_catreplay(true) // Verify replay protection
.token_seen_before(false); // Whether token has been seen before
token.verify_claims(&options).expect("Failed to verify claims");
token.verify_claims(&cat_options).expect("Failed to verify CAT-specific claims");A token's catu, catm, cath, catnip and catnetprint claims restrict the request
it can be used for, and this library can't see the request. So verify_claims
checks each one against the context you pass, and rejects a token carrying one
whose context you didn't pass (UnverifiedClaim): CTA-5007-B §4.3.1.2 accepts a
claim only if what it asserts is "true or not relevant to the recipient".
| Claim | Context to pass |
|---|---|
catu |
uri |
catm |
http_method |
cath |
request_header (once per field line) or request_headers |
catnip |
client_ip and/or client_asn |
catnetprint |
fingerprint_type and fingerprint_value |
If the token travels in the request URI, remove it from the URI before passing
uri (CTA-5007-B §4.6.10).
Passing the context runs the check; the verify_catu-style flags are no longer
needed (they still work, and still require their context). Pass every piece of
request context you have. A claim that genuinely can't apply to this recipient
can be declared with not_relevant, by claim key:
let options = VerificationOptions::new()
.uri("https://cdn.example.com/video.m3u8")
.client_ip("203.0.113.7".parse().unwrap())
// This recipient serves a protocol with no HTTP methods.
.not_relevant([cat_keys::CATM]);Missing context isn't the same as a claim not applying: a recipient that doesn't know the client's IP should still reject a token restricted to some networks, which is the default.
Declaring a claim that does apply not relevant isn't CTA-5007-B conformant. Only
those five claims can be listed, and not while their context is also passed
(InvalidOptions). Under verify_moqt, catm is treated as not relevant,
since a MoQ action has no HTTP method; pass the connection URI for catu (for
WebTransport, the session URL).
catreplay is checked only with verify_catreplay(true) and
token_seen_before(..) together, since CTA-5007-B makes rejecting a replay a
MAY; token_seen_before alone does nothing. Claims this library
doesn't implement are ignored, as CTA-5007-B §4.3.1.5 requires of claims a
recipient doesn't understand: catpor, catgeocoord, catgeoalt, cattpk,
catif, catifdata and catr (which a renewal service, not a verifier, acts
on).
catalpn, catgeoiso3166 and geohash, which recipients MAY support, are
checked when you pass their context and ignored otherwise. They aren't
restrictive claims in the sense above: without the context, a token carrying
one isn't rejected.
| Claim | Context to pass | Rejected (error) when |
|---|---|---|
catalpn (§4.6.12) |
tls_alpn(id), tls_alpn_unknown() or not_over_tls() |
the ALPN isn't listed (compared byte for byte), isn't known, or the request isn't over TLS (InvalidAlpnClaim) |
catgeoiso3166 (§4.6.14) |
client_country("US"), and client_region("CA") if known |
no listed code matches: a country code matches any of its regions, a region code needs that region (InvalidGeoClaim) |
geohash (§4.6.16) |
client_geohash("9q8yyk") |
the client's geohash doesn't start with a listed one (InvalidGeoClaim) |
Once checked, a malformed claim is rejected too, including a catgeoiso3166
code that isn't an ISO 3166 code, and a geohash longer than 4 characters
(it must be encrypted, §4.6.16) or wrapped in a CRS tag (279), as only WGS84
is supported. Codes and geohashes compare case-insensitively. How the
recipient locates the client is up to it.
CTA-5007-B §4.6.2 requires every recipient to check aud: a token that has an
aud is rejected unless it lists one of the audiences the recipient answers
to. Name them with expected_audience (call it again for more) or
expected_audiences:
let options = VerificationOptions::new()
.expected_audiences(["cdn.example.com", "edge.example.com"]);Token's aud |
No expected audiences set | Set, and the aud lists one |
Set, and it lists none |
|---|---|---|---|
| absent | accepted (MissingClaim with require_aud) |
— | MissingClaim |
| present | UnverifiedClaim |
accepted | InvalidAudience |
[] |
UnverifiedClaim |
— | InvalidAudience |
Matching is exact and case-sensitive. A recipient that has agreed with its
issuers, out of band, not to enforce aud can opt out with
skip_audience_check(true). That isn't CTA-5007-B conformant: it accepts
tokens issued for other recipients.
verify_claims always checks catv, before any other claim. CTA-5007-B
§4.6.8 defines only version 1 and says "A recipient MUST reject a token with an
unsupported version number":
Token's catv |
Result |
|---|---|
| absent | accepted (a token without catv is version 1) |
the unsigned integer 1 |
accepted |
another unsigned integer, such as 2 |
UnsupportedVersion |
any other value, such as "1", 1.0 or -1 |
InvalidClaimValue |
A recipient whose issuers emit a catv other than 1 for tokens that otherwise
follow version 1 can opt out with skip_catv_check(true), which ignores catv
entirely. Like skip_audience_check, that isn't CTA-5007-B conformant.
catv versions CTA-5007-B itself, so claims defined outside it, such as
catnetprint and the MoQ moqt claims, don't change it. Tokens that carry
them still use catv 1, or omit it. Such claims extend a token through their
own claim keys instead. A recipient that doesn't understand a claim ignores it
(CTA-5007-B 4.3.1.5), so it doesn't enforce the restriction either: send these
tokens only to recipients that support the claims, and enable their checks
(verify_catnetprint, verify_moqt) on the recipient.
A token with a cnf claim (RFC 8747) is bound to a key, and is valid only when
the request proves possession of it. For the jkt method that's a DPoP proof
(RFC 9449), which CTA-5007-B §4.8.1 requires recipients to check. This library
doesn't verify proofs of possession, so verify_claims rejects every token
with a cnf claim (UnverifiedClaim, or MoqtDpopRequired under
verify_moqt) until you verify the proof yourself and say so:
// After checking the request's DPoP proof against the token's cnf jkt:
let options = VerificationOptions::new().dpop_verified(true);A malformed cnf (not a map, no method, or a jkt that isn't a 32-byte
thumbprint) is rejected with InvalidClaimValue either way. Tokens without
cnf are unaffected.
verify_claims checks a catdpop claim whenever it's present (CTA-5007-B
§4.8.2). It's rejected (InvalidClaimValue) if it isn't a map, if its crit
setting lists a setting this crate doesn't understand (it understands only
window and jti, which crit must not list), or if window or jti isn't
an unsigned integer. Their values are never a reason to reject. The DPoP proof
is verified by the caller, so token.dpop_settings() returns the settings for
it to apply: the proof's time window, which it must use when present, and
the jti mode (a missing or unrecognised jti means the proof's jti is
ignored).
By default, signing and verification follow CTA-5007-B. Each of these relaxes one rule, isn't conformant, and is for a deployment whose issuers and recipients have agreed the exception:
| Option | Use when |
|---|---|
skip_audience_check(true) |
the recipient deliberately doesn't enforce aud (Audience) |
skip_catv_check(true) |
issuers emit a catv other than 1 for tokens that otherwise follow version 1 (Version) |
allow_unencrypted_precise_catnip(true), catnip::create_allowing_precise, TokenBuilder::allow_unencrypted_precise_catnip(true) |
tokens are bound to an exact client address (CATNIP) |
TokenBuilder::allow_unencrypted_catgeocoord(true) |
an issuer signs a catgeocoord claim, which CTA-5007-B §4.6.15 requires to be encrypted |
allow_unencrypted_precise_geohash(true), geohash::create_allowing_precise, TokenBuilder::allow_unencrypted_precise_geohash(true) |
tokens carry geohashes longer than 4 characters, which §4.6.16 requires to be encrypted |
verify_hmac_allowing_legacy_sign1(key) |
an HMAC issuer MACs over the COSE_Sign1 structure (Multiple Token Formats Support) |
not_relevant([...]) isn't one of these: declaring a restrictive claim that
genuinely can't apply to the recipient is conformant (CTA-5007-B §4.3.1.2).
Only declaring one that does apply isn't (Restrictive claims).
This library creates HMAC tokens using the COSE_Mac0 structure with proper CBOR tags for compatibility with other CAT implementations, and verifies their MAC over the COSE_Mac0 structure, as RFC 9052 defines:
token
.verify_with_key(VerifyingKey::HmacSha256(key))
.expect("Failed to verify signature");For an issuer known to MAC over the COSE_Sign1 structure instead, verify with this in place of verify_with_key. It accepts either form, but isn't RFC 9052 or CTA-5007-B conformant:
token
.verify_hmac_allowing_legacy_sign1(key)
.expect("Failed to verify signature");Each CAT claim with an assigned key has a builder. Most builders refuse
values the specification doesn't allow; catu::*, catv::create and
catnetprint::create build values from their arguments without checking
them (CatuClaim checks catu). TokenBuilder::validate_claims, which is
off by default, applies the checks to claims however they were built, for
the claims marked below. The composition claims (and, or, nor and
others, proposed in draft-lemmons-composite-claims, which CTA-5007-B
references but doesn't define) aren't supported, as they have no assigned
keys.
| Claim | Key | Builder | validate_claims |
Verification |
|---|---|---|---|---|
catreplay |
308 | catreplay::* |
yes | with verify_catreplay and token_seen_before; required under MoQ for value 1 |
catpor |
309 | catpor::create |
yes | ignored (MAY) |
catv |
310 | catv::create |
no | always: a version other than 1 is rejected |
catnip |
311 | catnip::create |
yes | restrictive: client_ip / client_asn |
catu |
312 | catu::*, CatuClaim |
no | restrictive: uri |
catm |
313 | catm::create |
yes | restrictive: http_method (not under MoQ) |
catalpn |
314 | catalpn::create |
yes | opt-in: tls_alpn, tls_alpn_unknown, not_over_tls |
cath |
315 | cath::create |
yes | restrictive: request_header |
catgeoiso3166 |
316 | catgeoiso3166::create |
yes | opt-in: client_country, client_region |
catgeocoord |
317 | catgeocoord::create |
refused, unless allow_unencrypted_catgeocoord (not conformant: it must be encrypted) |
ignored (MAY) |
catgeoalt |
318 | catgeoalt::create |
yes | ignored (MAY) |
cattpk |
319 | cattpk::create |
yes | ignored (MAY) |
catifdata |
320 | catifdata::* |
refused outside a catif template, unless catif_response |
ignored |
catdpop |
321 | catdpop::create |
yes | parsed: a critical setting it doesn't understand rejects the token; Token::dpop_settings for the rest |
catif |
322 | catif::create |
yes | not acted on: a recipient that supports it reads it after rejecting a token |
catr |
323 | catr::* |
yes | not acted on: a renewal service reads it |
geohash |
282 | geohash::create |
yes; longer than 4 characters only with allow_unencrypted_precise_geohash |
opt-in: client_geohash |
catnetprint |
-66000 (provisional) | catnetprint::create |
no | restrictive: fingerprint_type and fingerprint_value |
cnf |
8 | custom_cbor |
no | rejected unless dpop_verified (see Proof of possession) |
moqt, moqt-reval |
-65537, -65538 (provisional) | MoqtClaim, TokenBuilder::moqt |
catreplay 1 needs cti and exp |
with verify_moqt (see Media over QUIC) |
composition (and, or, ...) |
not assigned | none | no | not supported; ignored as unknown claims |
Without validate_claims, sign checks only the registered claims and the
nesting depth, so custom_cbor can build any claim, as negative tests need.
The JavaScript signToken always validates.
"Restrictive" claims reject a token when their context isn't passed, unless
declared not_relevant (see Restrictive claims).
"Opt-in" claims are checked when their context is passed and ignored
otherwise.
The cat_claims module has the builders, among them:
- CATU (Common Access Token URI) - limits the URI to which the token can provide access
- CATM (Common Access Token Methods) - restricts HTTP methods
- CATREPLAY - controls token replay behavior
- CATR (Common Access Token Renewal) - instructions for token renewal
- CATNIP (Common Access Token Network IP) - IP address restrictions
- CATGEOISO3166 - geographic country/region restrictions (ISO 3166 codes)
- CATV (Common Access Token Version) - CAT specification version
- CATDPOP (Common Access Token DPoP Settings) - DPoP configuration (
catdpop::create) - CATNETPRINT - network fingerprint restrictions (not part of CTA-5007-B; see below)
The builders refuse values verifiers would reject. Claims written by hand
with custom_cbor, custom_int or custom_array are signed as given, so
tests can build malformed tokens; call TokenBuilder::validate_claims to
apply the same checks to them at sign:
use common_access_token::{cat_keys, Algorithm, CborValue, Error, TokenBuilder};
let result = TokenBuilder::new()
.algorithm(Algorithm::HmacSha256)
.custom_cbor(cat_keys::CATREPLAY, CborValue::Integer(7)) // not 0, 1 or 2
.validate_claims()
.sign(b"my-secret-key-of-at-least-32-bytes");
assert!(matches!(result, Err(Error::InvalidClaimValue(_))));It checks catreplay, catm, cath, catr, catif, the MAY claims below, catdpop and catnip (refusing
precise entries, as this crate's tokens are unencrypted, unless
allow_unencrypted_precise_catnip(true) is set, which isn't conformant) and,
in a token with a moqt claim, that catreplay 1 comes with cti and exp.
A moqt claim under a label other than the default counts when written with
moqt_at, or named with moqt_label. The JavaScript signToken always
applies these checks.
The claims recipients MAY support have builders too. Verification ignores
them, as CTA-5007-B allows; the builders and validate_claims check their
shape.
| Builder | Claim | CTA-5007-B | Checks |
|---|---|---|---|
catpor::create |
probability of rejection (309) | §4.6.7 | probability 0 to 1; an id that's bytes or names a byte-string claim (checked at sign time); a NumericDate expiration |
catalpn::create |
TLS ALPN (314) | §4.6.12 | 1 to 50 distinct protocol IDs of 1 to 255 bytes |
catgeocoord::create |
coordinates (317) | §4.6.15 | latitude, longitude and radius ranges. It must be conveyed encrypted, which this crate can't do, so validate_claims refuses it unless allow_unencrypted_catgeocoord(true) is set (not conformant) |
catgeoalt::create |
altitude (318) | §4.6.17 | a finite altitude and a non-negative deviation |
cattpk::create |
TLS public key (319) | §4.6.18 | a DER SubjectPublicKeyInfo |
catifdata::text, list, template |
if data (320) | §4.7.3 | text or text arrays; in a catif token template, also replacers. §4.7.3 forbids it outside the context of a catif claim, so validate_claims refuses it except in a template or a token marked catif_response(true), the one a recipient issues in response to a catif claim |
geohash::create |
geohash (282) | §4.6.16 | at least one geohash, each in the geohash alphabet and at most 4 characters (create_allowing_precise and allow_unencrypted_precise_geohash(true) for longer, which isn't conformant) |
The geo builders emit WGS84 coordinates without a CRS wrapper (tag 279), as CTA-5007-B requires for WGS84.
The CATU claim allows you to restrict the URI to which the token can provide access. You can specify restrictions on different components of the URI, such as scheme, host, path, etc.
use common_access_token::{cat_keys, uri_components, catu, TokenBuilder};
use std::collections::BTreeMap;
// Create a CATU claim
let mut catu_components = BTreeMap::new();
// Restrict to https scheme
catu_components.insert(uri_components::SCHEME, catu::exact_match("https"));
// Restrict to example.com host
catu_components.insert(uri_components::HOST, catu::suffix_match(".example.com"));
// Restrict to paths starting with /content
catu_components.insert(uri_components::PATH, catu::prefix_match("/content"));
// Add the CATU claim to the token
let token_builder = TokenBuilder::new()
// ... other token configuration ...
.custom_cbor(cat_keys::CATU, catu::create(catu_components));The typed CatuClaim builds the same claim, and reads one back from a token. A component can hold several matches of different types, which must all hold:
use common_access_token::{CatuClaim, TokenBuilder, UriComponent, UriMatch};
// A component holds one match of each type: a second one is an error
let claim = CatuClaim::new()
.with(UriComponent::Scheme, UriMatch::Exact("https".into()))?
.with(UriComponent::Host, UriMatch::Suffix(".example.com".into()))?
.with(UriComponent::Path, UriMatch::Prefix("/content".into()))?
.with(UriComponent::Path, UriMatch::Suffix(".m3u8".into()))?;
let token_builder = TokenBuilder::new()
// ... other token configuration ...
.catu(claim);
// Reading it back: Ok(None) without the claim, an error if it's malformed
// let claim = token.catu_claim()?;The CATU module provides several match types (UriMatch has one variant for each):
exact_match- exact text matchprefix_match- prefix matchsuffix_match- suffix matchcontains_match- contains matchregex_match- regular expression match (claims requiring capture-group values are rejected; see the CHANGELOG). Patterns are POSIX extended regular expressions, as CTA-5007-B §4.6.10 specifies. Syntax that POSIX and the Rust regex engine read differently is rejected rather than reinterpreted: a backslash inside[...], escapes such as\d,\wand\b,(?groups and flags,{,n}, and non-POSIX bracket syntax. Escaped punctuation (\.,\/) and POSIX classes ([[:digit:]]) are accepted. Patterns are compiled within resource limits (MAX_CATU_REGEX_LEN,MAX_CATU_REGEX_SIZE,MAX_CATU_REGEX_NEST), and one over them is rejected.sha256_match- SHA-256 matchsha512_256_match- SHA-512/256 match
The CATR claim provides instructions for token renewal. You can specify different renewal types, such as automatic, cookie, header, or redirect.
use common_access_token::{cat_keys, catr, TokenBuilder, current_timestamp};
let now = current_timestamp();
// Create an automatic renewal claim
let renewal_params = catr::automatic_renewal(3600, Some((now + 3000) as i64));
// Add the CATR claim to the token
let token_builder = TokenBuilder::new()
// ... other token configuration ...
.custom_cbor(cat_keys::CATR, catr::create(renewal_params).unwrap());The CATR module provides several renewal types:
automatic_renewal- automatic renewal: the renewed token goes back the way it cameautomatic_renewal_with- automatic renewal with a cookie name, header name and redirect status code, each used when the token arrived that way (CTA-5007-B §4.9.2.1)cookie_renewal- cookie renewalheader_renewal- header renewalredirect_renewal- redirect renewal
The CATIF claim (CTA-5007-B §4.9.1) tells a recipient how to respond when it
rejects a request because of the token: for each claim key, or array of claim
keys, whose failure caused the rejection, a status code, headers to add, and
optionally the ID of a key to sign tokens embedded in those headers. This
library builds the claim; acting on it is up to the recipient, and
verify_claims ignores it.
use common_access_token::{cat_keys, catif, cwt_keys, CborValue, TokenBuilder};
// CTA-5007-B §4.9.1.2: once exp has passed, redirect to an auth service
// with a fresh token, which the recipient completes and signs with "abc123".
let claim = catif::create([(
cwt_keys::EXP,
catif::Action::new(307)
.header(
"Location",
vec![
catif::Part::text("https://auth.example.net/?CAT="),
catif::Part::token([
(cwt_keys::ISS, CborValue::Null), // filled in by the recipient
(cwt_keys::IAT, CborValue::Null), // likewise
]),
],
)
.kid("abc123"),
)])
.unwrap();
let token_builder = TokenBuilder::new()
// ... other token configuration ...
.custom_cbor(cat_keys::CATIF, claim);A header value is text, or parts the recipient processes and concatenates:
Part::Text, a Part::Replace integer (catif::URI, URI_WITHOUT_TOKEN,
REJECTED_LABELS, or a negative one for private use), and Part::Token
claim sets, which it signs into tokens. create refuses a status outside
100-599, a header name that isn't an RFC 9110 token or that repeats ignoring
case, a control character other than tab in a header value (which could
inject a header line), an empty array of parts, more than 49 array elements in
one action's headers, counting arrays inside token claim sets (recipients need
only process fewer than 50), a key ID with a control character, a null in a
token's claims other than iss or iat, and a token claim set whose claims
sign-time validation would refuse. REJECTED_LABELS tells the client
which claims failed; CTA-5007-B §4.9.1 warns that this can disclose
information.
The CATM claim limits the HTTP methods that can be used with the token.
Methods are compared exactly, as CTA-5007-B §4.6.11 and HTTP (RFC 9110 §9.1)
require, so a claim listing GET doesn't match a request method get. The
claim must be a non-empty array of text, and a claim with more than
MAX_CATM_METHODS (64) members makes the token invalid.
use common_access_token::{cat_keys, catm, TokenBuilder};
// Create a CATM claim with allowed methods
let allowed_methods = vec!["GET", "HEAD"];
// Add the CATM claim to the token
let token_builder = TokenBuilder::new()
// ... other token configuration ...
.custom_array(cat_keys::CATM, catm::create(allowed_methods).unwrap());The CATH claim (CTA-5007-B §4.6.13) restricts the request headers: a map from
header names to the same match conditions catu uses. Every member must be
satisfied by a header of that name, compared case-insensitively. Pass the
request's header field lines, once per line:
use common_access_token::VerificationOptions;
let options = VerificationOptions::new()
.request_header("User-Agent", "Mozilla/5.0")
.request_header("Accept", "text/html")
.request_header("Accept", "*/*"); // combined as "text/html, */*"Field lines with the same name are combined before matching (RFC 9110 §5.3),
joined with ", " in the order given. Cookie lines are joined with "; ", as
HTTP/2 and HTTP/3 split cookies are (RFC 9113 §8.2.3, RFC 9114 §4.2.1). Each
value is trimmed of surrounding spaces and tabs; empty lines aren't dropped
(a, ``, b combine to `a, , b`). A member is never satisfied by a missing
header, nor by one whose combined value is empty, even for an exact match on
`""`. If any line of a header isn't valid UTF-8, leave out every line with
that name rather than converting it lossily or dropping only that line, so a
member for it fails instead of matching part of the value.
A request with no headers is still context: pass request_headers with
nothing in it. not_relevant is for a recipient with no HTTP request at all,
such as MoQ over native QUIC.
Values are matched exactly as catu matches URI components, including its
regular-expression rules and limits. Messages name the header but quote
neither its value nor the claim's values and patterns, since either can be a
credential (Authorization, Cookie). A claim that isn't a map of text keys to
match conditions, or that lists a header twice (compared case-insensitively),
is rejected with Error::InvalidHeaderClaim, as are failed matches.
cath::create builds the claim from header names and the catu match
helpers. It refuses a claim the verifier would reject, and what CTA-5007-B
§4.6.13 forbids issuing: no headers, names that aren't RFC 9110 tokens or that
repeat ignoring case, and invalid regexes or hashes.
use common_access_token::{cat_keys, cath, catu, TokenBuilder};
let claim = cath::create([
("User-Agent", catu::contains_match("Mozilla")),
("My-Example-Header", catu::exact_match("CustomValue")),
])
.unwrap();
let token_builder = TokenBuilder::new()
// ... other token configuration ...
.custom_cbor(cat_keys::CATH, claim);The CATNIP claim limits the client networks that can use the token: RFC 9164
IP prefixes and autonomous system numbers. With verify_catnip(true), the
token is accepted if the client's IP is in one of its prefixes or its ASN is
listed. This crate can't look up ASNs, so pass the client's ASN if you know it.
use common_access_token::{cat_claims::catnip, cat_keys, TokenBuilder, VerificationOptions};
let token_builder = TokenBuilder::new()
// ... other token configuration ...
.custom_array(cat_keys::CATNIP, catnip::create(vec!["203.0.113.0/24", "64512"]).unwrap());
let options = VerificationOptions::new()
.verify_catnip(true)
.client_ip("203.0.113.7".parse().unwrap())
.client_asn(64512);A client in none of the listed networks is rejected with InvalidNetworkClaim.
If it matches nothing that could be checked, but the claim lists ASNs and no
client_asn was given (or prefixes and no client_ip), it's rejected with
UnverifiedClaim. As CTA-5007-B §4.6.9 requires of an unencrypted token, a
claim listing a full IP address, an IPv4 prefix longer than /24, an IPv6 prefix
longer than /56, an ASN range or ASN 0 makes the token invalid
(InvalidNetworkClaim). catnip::parse still decodes those forms, for
inspection.
That rule keeps precise client addresses out of tokens that often travel in
URLs and logs; it doesn't affect security, since a precise entry only narrows
which clients a token allows. A deployment that binds tokens to an exact
client address can opt out with allow_unencrypted_precise_catnip(true), which
accepts full addresses and longer prefixes and matches them normally. Like
skip_audience_check, that isn't CTA-5007-B conformant. A prefix whose address bytes end in zero bytes, which RFC 9164
has encoders omit, is accepted as long as no bit past the prefix length is set,
for interoperability with CTA-5007-B's own example.
The CATV claim specifies the version of the CAT specification. Version 1 is
the only one defined, and a token without catv is version 1, so issuers can
leave it out. Recipients reject any other version (see
Version).
use common_access_token::{cat_keys, catv, TokenBuilder};
// Add the CATV claim to the token
let token_builder = TokenBuilder::new()
// ... other token configuration ...
.custom_cbor(cat_keys::CATV, catv::create()); // Version 1The cat_keys module provides constants for all CAT-specific claim keys:
GEOHASH- Geohash (geohash) claim key, defined by CTA-5009CATREPLAY- Common Access Token Replay (catreplay) claim keyCATPOR- Common Access Token Probability of Rejection (catpor) claim keyCATV- Common Access Token Version (catv) claim keyCATNIP- Common Access Token Network IP (catnip) claim keyCATU- Common Access Token URI (catu) claim keyCATM- Common Access Token Methods (catm) claim keyCATALPN- Common Access Token ALPN (catalpn) claim keyCATH- Common Access Token Header (cath) claim keyCATGEOISO3166- Common Access Token Geographic ISO3166 (catgeoiso3166) claim keyCATGEOCOORD- Common Access Token Geographic Coordinate (catgeocoord) claim keyCATGEOALT- Common Access Token Geographic Altitude (catgeoalt) claim keyCATTPK- Common Access Token TLS Public Key (cattpk) claim keyCATIFDATA- Common Access Token If Data (catifdata) claim keyCATDPOP- Common Access Token DPoP Settings (catdpop) claim keyCATIF- Common Access Token If (catif) claim keyCATR- Common Access Token Renewal (catr) claim keyCATNETPRINT- Common Access Token Network Fingerprint (catnetprint) claim key; provisional, see below
cat_keys::name and cat_keys::from_name map these keys to their names and
back (cat_keys::name(cat_keys::CATU) is Some("catu")). cwt_keys,
moqt_keys, cose_labels and replay_values have the same pair, and
claim_name / claim_label cover every claim key in cwt_keys, cat_keys
and moqt_keys. Names are matched exactly (case-sensitive), and the names of
provisional keys (catnetprint, moqt, moqt-reval) describe their default
keys.
catnetprint restricts a token to a client with a given network fingerprint:
JA3 or JA4 for TLS, or another JA4-family fingerprint such as JA4H (HTTP), JA4T
(TCP) or JA4D (DHCP). It isn't part of CTA-5007-B and is intended to be proposed
for a future revision. Until a key is registered, cat_keys::CATNETPRINT is
-66000, from the RFC 8392 Private Use range, and may change.
use common_access_token::{cat_keys, catnetprint, FingerprintType, TokenBuilder, VerificationOptions};
let token_builder = TokenBuilder::new()
// ... other token configuration ...
.custom_cbor(
cat_keys::CATNETPRINT,
catnetprint::create(FingerprintType::JA4, "t13d1516h2_8daaf6152771_b186095e22b6"),
);
let options = VerificationOptions::new()
.verify_catnetprint(true)
.fingerprint_type(FingerprintType::JA4)
.fingerprint_value("t13d1516h2_8daaf6152771_b186095e22b6");
// A deployment that agrees on another key can read the claim there:
// .catnetprint_label(-66001)The moqt and moqt-reval claims from
draft-ietf-moq-c4m-02
authorize MoQ Transport actions on specific Full Track Names (namespace tuple +
track name). Only draft -02 is supported. A moqt claim in draft -01's
bare-array form is rejected, because -01 numbered its actions differently.
The claim keys are provisional. IANA has not assigned them, so the library
defaults to -65537 and -65538, the Private Use placeholders from the draft's
test vectors. They're exposed as moqt_keys::MOQT and moqt_keys::MOQT_REVAL.
To interoperate with an issuer that uses other labels before IANA assignment,
set VerificationOptions::moqt_claim_labels, or read a claim with
Token::moqt_claim_at / moqt_reval_at. Issuers write one under another
label with TokenBuilder::moqt_at. A scope's actions are encoded sorted and
without duplicates.
use common_access_token::{
current_timestamp, Algorithm, MoqtAction, MoqtClaim, MoqtRequest, MoqtRevalidation,
MoqtScope, RegisteredClaims, Token, TokenBuilder, VerificationOptions, VerifyingKey,
};
let key = b"shared-secret";
// Issuer: a publisher may announce example.com/alice and publish "video-*" tracks
let token = TokenBuilder::new()
.algorithm(Algorithm::HmacSha256)
.registered_claims(
RegisteredClaims::new().with_expiration(current_timestamp() + 3600),
)
.moqt(MoqtClaim::new(vec![MoqtScope::new([
MoqtAction::PublishNamespace,
MoqtAction::Publish,
])
.namespace_exact("example.com")
.namespace_exact("alice")
.track_prefix("video-")]))
.moqt_reval(300)
.sign(key)
.unwrap();
// Validator (relay, origin, or publisher): signature first, then the request
let token = Token::from_bytes(&token.to_bytes().unwrap()).unwrap();
token.verify_with_key(VerifyingKey::HmacSha256(key)).unwrap();
let options = VerificationOptions::new()
.verify_moqt(true)
.moqt_revalidation(MoqtRevalidation::MinInterval(60))
.moqt_request(MoqtRequest::track(
MoqtAction::Publish,
["example.com", "alice"],
"video-hd",
));
token.verify_claims(&options).unwrap();Notes for validators:
- Same check for every role. Edge relays validating subscribers or
publishers, origins validating relays, and publishers validating a relay's
SUBSCRIBE all use
MoqtRequest+verify_claims. Publishers and origins should verify with an ES256/PS256 public key rather than holding an HMAC secret. Always useverify_with_keywith a typedVerifyingKey, which rejects HMAC forgeries computed over a public key. - Which matches apply.
SETUPonly checks that the action is listed. Namespace actions (PUBLISH_NAMESPACE,SUBSCRIBE_NAMESPACE,SUBSCRIBE_TRACKS) also check the namespace. Track actions also check the track, and are denied if no track is given. A request namespace shorter than the scope's is denied. - Filter what namespace actions deliver. Permitting a namespace action
checks only the namespace in the request. It doesn't limit what the action
then delivers. With the scope
[[9], ["live"], "public"],SUBSCRIBE_TRACKS ["live"]is permitted, and it would deliver every track underlive, includingprivate. With[[3], ["example", "com", nil]],SUBSCRIBE_NAMESPACE ["example", "com"]is permitted, and it coversexample/com/secret. Before delivering each namespace or track, check it withMoqtScope::matches_nameon the scopes whoseaction_codes()list the action. Re-checking withpermitsdoesn't work: the action decides what is matched, soMoqtRequest::track(MoqtAction::SubscribeTracks, ns, track)still ignores the track. - Strict parsing. A malformed
moqtclaim fails verification withError::InvalidMoqtClaim. It's never ignored. This includes a claim map with any key other than 0, which the draft reserves for future scope restrictions. - Default-deny. With
verify_moqt(true), a token with nomoqtclaim authorizes no MoQ action, as draft-ietf-moq-c4m §2 requires. - Session-held tokens. To check later actions (such as
REQUEST_UPDATE) against a token from setup, keep theTokenand callverify_claimsagain, or callMoqtClaim::permitson the result oftoken.moqt_claim(). The latter skips theexp/nbfchecks. - Revalidation. If
moqt-revalis present and non-zero, re-runverify_claimsat least everytoken.moqt_reval()seconds for ongoing actions. Recipients that can't revalidate leavemoqt_revalidationat its default,Unsupported, and such tokens are rejected, as the draft requires. - DPoP-bound tokens. This library does not verify DPoP proofs yet. A token
that has a
cnfclaim is rejected (withError::MoqtDpopRequiredunderverify_moqt(true)) unless you have verified the proof yourself (draft -02 §4.3) and setdpop_verified(true). See Proof of possession. - Replay (
catreplay1). For MoQ, value 1 means single-connection use, and the token must carryctiandexp. The draft says the relay "MUST reject the token on any other connection", so withverify_moqt(true)such a token is rejected (UnverifiedClaim) unless you also setverify_catreplay(true)andtoken_seen_before. Settoken_seen_before(true)only when the token'sctiwas already accepted on a different connection; reuse on the same connection is allowed. - Other restrictive claims.
catmis treated as not relevant underverify_moqt, since a MoQ action has no HTTP method.cathisn't: a WebTransport session is opened by an HTTP request, whose headers (Origin, for example) acathclaim can restrict, so pass them withrequest_header. Over native QUIC there are no request headers, so listcathinnot_relevantthere. Either way, a token withcathis rejected (UnverifiedClaim) until you've said which. - Forwarding upstream. Forward the raw token bytes you received.
to_bytes()re-encodes the outer COSE structure.
See examples/moqt.rs for edge relay, ingest relay, and publisher validation.
See the examples directory for complete usage examples:
basic_usage.rs: Demonstrates basic token creation and verificationcat_specific_claims.rs: Demonstrates how to use CAT-specific claims (CATU, CATM, CATR, CATREPLAY)cat_validation.rs: Shows how to validate CAT-specific claimsextended_cat_claims.rs: CATNIP, CATGEOISO3166 and CATV, and the claims that have no builder (built by hand withcustom_cbor)asymmetric_signing.rsandsample_es256_ps256_tokens.rs: ES256 and PS256 signing and verificationmoqt.rs: Media over QUIC tokens validated by an edge relay, an ingest relay, and a publisher
The crate ships Criterion benchmarks measuring signing time, verification time, and signature/token size for every supported algorithm (HS256, ES256, PS256).
Run them the native Rust way:
cargo bench --bench catTo produce a shareable report with graphs, run the benchmarks and then the report generator. The markdown report and SVG charts need no third-party Python packages:
cargo bench --bench cat
python3 scripts/bench_report.py # add --pdf to also render a PDF
# or do both at once:
scripts/run_benchmarks.sh # --quick for a fast run, --pdf for a PDFOutputs are written to target/bench/:
report.md— markdown summary table, graphs, and notesreport.pdf— printable PDF (only with--pdf)signing_time.svg,verification_time.svg,signature_size.svg,token_size.svg
The PDF is rendered with fpdf2, a pure-Python
package with no native dependencies and no browser. Without --pdf, fpdf2 is
not needed at all.
scripts/run_benchmarks.sh --pdf bootstraps a local virtualenv at .venv and
installs fpdf2 into it automatically (Homebrew's system Python is externally
managed, so it can't be installed into directly). In CI, where Python isn't
externally managed, you can skip the venv and just pip3 install fpdf2 before
running python3 scripts/bench_report.py --pdf.
Indicative results (Apple Silicon, release build — your numbers will vary):
| Algorithm | Signing time | Verification time | Signature size | Token size |
|---|---|---|---|---|
| HS256 | ~1.8 µs | ~3.4 µs | 32 B | 150 B |
| ES256 | ~350 µs | ~220 µs | 64 B | 182 B |
| PS256 | ~1.16 ms | ~140 µs | 256 B | 376 B |
Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the MIT License - see the LICENSE file for details.