# rusty_paseto
A type-driven, ergonomic implementation of the [PASETO](https://github.com/paseto-standard/paseto-spec) protocol for secure stateless tokens.
### PASETO: Platform-Agnostic Security Tokens
Paseto is everything you love about JOSE (JWT, JWE, JWS) without any of the
[many design deficits that plague the JOSE standards](https://paragonie.com/blog/2017/03/jwt-json-web-tokens-is-bad-standard-that-everyone-should-avoid).


## Roadmap and Current Feature Status
| PASETO Token Builder | :green_circle: | :green_circle: | :green_circle: | :green_circle: | :green_circle: | :black_circle: | :green_circle: | :green_circle: |
| PASETO Token Parser | :green_circle: | :green_circle: | :green_circle: | :green_circle: | :green_circle: | :black_circle: | :green_circle: | :green_circle: |
| Flexible Claim Validation | :green_circle: | :green_circle: | :green_circle: | :green_circle: | :green_circle: | :black_circle: | :green_circle: | :green_circle: |
| Generic Token Builder | :green_circle: | :green_circle: | :green_circle: | :green_circle: | :green_circle: | :black_circle: | :green_circle: | :green_circle: |
| Generic Token Parser | :green_circle: | :green_circle: | :green_circle: | :green_circle: | :green_circle: | :black_circle: | :green_circle: | :green_circle: |
| Encryption/Signing | :green_circle: | :green_circle: | :green_circle: | :green_circle: | :green_circle: | :black_circle: | :green_circle: | :green_circle: |
| Decryption/Verification | :green_circle: | :green_circle: | :green_circle: | :green_circle: | :green_circle: | :black_circle: | :green_circle: | :green_circle: |
| [PASETO Test vectors](https://github.com/paseto-standard/test-vectors) | :green_circle: | :green_circle: | :green_circle: | :green_circle: | :green_circle: | :black_circle: | :green_circle: | :green_circle: |
| Documentation | :black_circle: | :black_circle: | :orange_circle: | :black_circle: | :black_circle: | :black_circle: | :black_circle: | :black_circle: |
| Feature gates | :black_circle: |
| PASERK support | :black_circle: |
# Usage
```Rust
// at the top of your source file
use rusty_paseto::prelude::*;
```
# Examples: Building and parsing tokens
Here's a basic, default token:
```Rust
use rusty_paseto::prelude::*;
// create a key specifying the PASETO version and purpose
let key = PasetoSymmetricKey::<V4, Local>::from(Key::from(b"wubbalubbadubdubwubbalubbadubdub"));
// use a default token builder with the same PASETO version and purpose
let token = PasetoBuilder::<V4, Local>::default().build(&key)?;
// token is a String in the form: "v4.local.encoded-payload"
```
## A default token
* Has no [footer](https://github.com/paseto-standard/paseto-spec/tree/master/docs)
* Has no [implicit assertion](https://github.com/paseto-standard/paseto-spec/tree/master/docs)
for V3 or V4 versioned tokens
* Expires in **1 hour** after creation (due to an included default ExpirationClaim)
* Contains an IssuedAtClaim defaulting to the current utc time the token was created
* Contains a NotBeforeClaim defaulting to the current utc time the token was created
You can parse and validate an existing token with the following:
```Rust
let key = PasetoSymmetricKey::<V4, Local>::from(Key::from(b"wubbalubbadubdubwubbalubbadubdub"));
let json_value = PasetoParser::<V4, Local>::default().parse(&token, &key)?;
assert!(json_value["exp"].is_string());
assert!(json_value["iat"].is_string());
```
## A default parser
* Validates the token structure and decryptes the payload or verifies the signature of the content
* Validates the [footer](https://github.com/paseto-standard/paseto-spec/tree/master/docs) if
one was provided
* Validates the [implicit assertion](https://github.com/paseto-standard/paseto-spec/tree/master/docs) if one was provided (for V3 or V4 versioned tokens only)
## A token with a footer
PASETO tokens can have an [optional footer](https://github.com/paseto-standard/paseto-spec/tree/master/docs). In rusty_paseto we have strict types for most things.
So we can extend the previous example to add a footer to the token by using code like the
following:
```rust
use rusty_paseto::prelude::*;
let key = PasetoSymmetricKey::<V4, Local>::from(Key::from(b"wubbalubbadubdubwubbalubbadubdub"));
let token = PasetoBuilder::<V4, Local>::default()
.set_footer(Footer::from("Sometimes science is more art than science"))
.build(&key)?;
```
And parse it by passing in the same expected footer
```rust
let json_value = PasetoParser::<V4, Local>::default()
.set_footer(Footer::from("Sometimes science is more art than science"))
.parse(&token, &key)?;
assert!(json_value["exp"].is_string());
assert!(json_value["iat"].is_string());
```
## A token with an implicit assertion (V3 or V4 versioned tokens only)
Version 3 (V3) and Version 4 (V4) PASETO tokens can have an [optional implicit assertion](https://github.com/paseto-standard/paseto-spec/tree/master/docs).
So we can extend the previous example to add an implicit assertion to the token by using code like the
following:
```rust
use rusty_paseto::prelude::*;
let key = PasetoSymmetricKey::<V4, Local>::from(Key::from(b"wubbalubbadubdubwubbalubbadubdub"));
let token = PasetoBuilder::<V4, Local>::default()
.set_footer(Footer::from("Sometimes science is more art than science"))
.set_implicit_assertion(ImplicitAssertion::from("There’s a lesson here, and I’m not going to be the one to figure it out."))
.build(&key)?;
```
And parse it by passing in the same expected implicit assertion
```rust
let json_value = PasetoParser::<V4, Local>::default()
.set_footer(Footer::from("Sometimes science is more art than science"))
.set_implicit_assertion(ImplicitAssertion::from("There’s a lesson here, and I’m not going to be the one to figure it out."))
.parse(&token, &key)?;
```
## Setting a different expiration time
As mentioned, default tokens expire **1 hour** from creation time. You can set your own
expiration time by adding an ExpirationClaim which takes an ISO 8601 (Rfc3339) compliant datetime string.
#### Note: *claims taking an ISO 8601 (Rfc3339) string use the TryFrom trait and return a Result<(),PasetoClaimError>*
```rust
# use rusty_paseto::prelude::*;
use std::convert::TryFrom;
let key = PasetoSymmetricKey::<V4, Local>::from(Key::from(b"wubbalubbadubdubwubbalubbadubdub"));
let token = PasetoBuilder::<V4, Local>::default()
.set_claim(ExpirationClaim::try_from(in_5_minutes)?)
.set_footer(Footer::from("Sometimes science is more art than science"))
.build(&key)?;
```
## Tokens that never expire
A **1 hour** ExpirationClaim is set by default because the use case for non-expiring tokens in the world of security tokens is fairly limited.
Omitting an expiration claim or forgetting to require one when processing them
is almost certainly an oversight rather than a deliberate choice.
When it is a deliberate choice, you have the opportunity to deliberately remove this claim from the Builder.
The method call required to do so ensures readers of the code understand the implicit risk.
```rust
let token = PasetoBuilder::<V4, Local>::default()
.set_claim(ExpirationClaim::try_from(in_5_minutes)?)
.set_no_expiration_danger_acknowledged()
.build(&key)?;
```
## Setting PASETO Claims
The PASETO specification includes [seven reserved claims](https://github.com/paseto-standard/paseto-spec/blob/master/docs/02-Implementation-Guide/04-Claims.md) which you can set with their explicit types:
```rust
let in_2_minutes = (time::OffsetDateTime::now_utc() + time::Duration::minutes(2)).format(&Rfc3339)?;
let token = PasetoBuilder::<V4, Local>::default()
.set_claim(ExpirationClaim::try_from(in_5_minutes)?)
.set_claim(NotBeforeClaim::try_from(in_2_minutes)?)
.set_claim(AudienceClaim::from("Cromulons"))
.set_claim(SubjectClaim::from("Get schwifty"))
.set_claim(IssuerClaim::from("Earth Cesium-137"))
.set_claim(TokenIdentifierClaim::from("Planet Music - Season 988"))
.build(&key)?;
```
## Setting your own Custom Claims
The CustomClaim struct takes a tuple in the form of `(key: String, value: T)` where T is any
serializable type
#### Note: *CustomClaims use the TryFrom trait and return a Result<(), PasetoClaimError> if you attempt to use one of the [reserved PASETO keys](https://github.com/paseto-standard/paseto-spec/blob/master/docs/02-Implementation-Guide/04-Claims.md) in your CustomClaim*
```rust
let token = PasetoBuilder::<V4, Local>::default()
.set_claim(CustomClaim::try_from(("Co-star", "Morty Smith"))?)
.set_claim(CustomClaim::try_from(("Universe", 137))?)
.build(&key)?;
```
This throws an error:
```rust
let token = PasetoBuilder::<V4, Local>::default()
.set_claim(CustomClaim::try_from(("exp", "Some expiration value"))?)
.build(&key)?;
```
# Validating claims
rusty_paseto allows for flexible claim validation at parse time
## Checking claims
Let's see how we can check particular claims exist with expected values.
```rust
let token = PasetoBuilder::<V4, Local>::default()
.set_claim(SubjectClaim::from("Get schwifty"))
.set_claim(CustomClaim::try_from(("Contestant", "Earth"))?)
.set_claim(CustomClaim::try_from(("Universe", 137))?)
.build(&key)?;
PasetoParser::<V4, Local>::default()
.check_claim(SubjectClaim::from("Get schwifty"))
.check_claim(CustomClaim::try_from(("Contestant", "Earth"))?)
.check_claim(CustomClaim::try_from(("Universe", 137))?)
.parse(&token, &key)?;
```
# Custom validation
What if we have more complex validation requirements? You can pass in a reference to a closure which receives
the key and value of the claim you want to validate so you can implement any validation logic
you choose.
Let's see how we can validate our tokens only contain universes with prime numbers:
```rust
let token = PasetoBuilder::<V4, Local>::default()
.set_claim(SubjectClaim::from("Get schwifty"))
.set_claim(CustomClaim::try_from(("Contestant", "Earth"))?)
.set_claim(CustomClaim::try_from(("Universe", 137))?)
.build(&key)?;
PasetoParser::<V4, Local>::default()
.check_claim(SubjectClaim::from("Get schwifty"))
.check_claim(CustomClaim::try_from(("Contestant", "Earth"))?)
.validate_claim(CustomClaim::try_from("Universe")?, &|key, value| {
let universe = value
.as_u64()
.ok_or(PasetoClaimError::Unexpected(key.to_string()))?;
if primes::is_prime(universe) {
Ok(())
} else {
Err(PasetoClaimError::CustomValidation(key.to_string()))
}
})
.parse(&token, &key)?;
```
This token will fail to parse with the validation code above:
```rust
let token = PasetoBuilder::<V4, Local>::default()
.set_claim(CustomClaim::try_from(("Universe", 136))?)
.build(&key)?;
```
# Acknowledgments
If the API of this crate doesn't suit your tastes, check out the other PASETO implementations
in the Rust ecosystem which inspired rusty_paseto:
- [paseto](https://crates.io/crates/paseto) - by [Cynthia Coan](https://crates.io/users/Mythra)
- [pasetors](https://crates.io/crates/pasetors) - by [Johannes](https://crates.io/users/brycx)
# Questions?
File an issue or hit me up on [Twitter](https://twitter.com/rrrodzilla)!