## Compact

# Enum Compact

    pub enum Compact<T, H> {
        Decrypted {
            header: Header<H>,
            payload: T,
        },
        Encrypted(Compact),
    }

Expand description

Compact representation of a JWE, or an encrypted JWT

This representation contains a payload of type `T` with custom headers provided by type `H`. In general you should use a JWE with a JWS. That is, you should sign your JSON Web Token to create a JWS, and then encrypt the signed JWS.

## §Nonce/Initialization Vectors for AES GCM encryption

When encrypting tokens with AES GCM, you must take care not to reuse the nonce for the same key. You can keep track of this by simply treating the nonce as a 96 bit counter and incrementing it every time you encrypt something new.

## §Examples

### §Encrypting a JWS/JWT

See the example code in the `biscuit::JWE` type alias.

### §Encrypting a string payload with A256GCMKW and A256GCM

    use std::str;
    use biscuit::Empty;
    use biscuit::jwk::JWK;
    use biscuit::jwe;
    use biscuit::jwa::{EncryptionOptions, KeyManagementAlgorithm, ContentEncryptionAlgorithm};

    let payload = "The true sign of intelligence is not knowledge but imagination.";
    // You would usually have your own AES key for this, but we will use a zeroed key as an example
    let key: JWK<Empty> = JWK::new_octet_key(&vec![0; 256 / 8], Default::default());

    // Construct the JWE
    let jwe = jwe::Compact::new_decrypted(
        From::from(jwe::RegisteredHeader {
            cek_algorithm: KeyManagementAlgorithm::A256GCMKW,
            enc_algorithm: ContentEncryptionAlgorithm::A256GCM,
            ..Default::default()
        }),
        payload.as_bytes().to_vec(),
    );

    // We need to create an `EncryptionOptions` with a nonce for AES GCM encryption.
    // You must take care NOT to reuse the nonce. You can simply treat the nonce as a 96 bit
    // counter that is incremented after every use
    let mut nonce_counter = num_bigint::BigUint::from_bytes_le(&vec![0; 96 / 8]);
    // Make sure it's no more than 96 bits!
    assert!(nonce_counter.bits() <= 96);
    let mut nonce_bytes = nonce_counter.to_bytes_le();
    // We need to ensure it is exactly 96 bits
    nonce_bytes.resize(96/8, 0);
    let options = EncryptionOptions::AES_GCM { nonce: nonce_bytes };

    // Encrypt
    let encrypted_jwe = jwe.encrypt(&key, &options).unwrap();

    // Decrypt
    let decrypted_jwe = encrypted_jwe
        .decrypt(
            &key,
            KeyManagementAlgorithm::A256GCMKW,
            ContentEncryptionAlgorithm::A256GCM,
        )
        .unwrap();

    let decrypted_payload: &Vec<u8> = decrypted_jwe.payload().unwrap();
    let decrypted_str = str::from_utf8(&*decrypted_payload).unwrap();
    assert_eq!(decrypted_str, payload);

    // Don't forget to increment the nonce!
    nonce_counter = nonce_counter + 1u8;

## Variants§

§

### Decrypted

Decrypted form of the JWE. This variant cannot be serialized or deserialized and will return an error.

#### Fields

§`header: Header<H>`

Embedded header

§`payload: T`

Payload, usually a signed/unsigned JWT

§

### Encrypted(Compact)

Encrypted JWT. Use this form to send to your clients

## Implementations§

§

### impl<T, H> Compact<T, H>
where T: CompactPart, H: Serialize + DeserializeOwned + Clone,

#### pub fn new_decrypted(header: Header<H>, payload: T) -> Compact<T, H>

Create a new encrypted JWE

#### pub fn new_encrypted(token: &str) -> Compact<T, H>

Create a new encrypted JWE

#### pub fn into_encrypted<K>( self, key: &JWK<K>, options: &EncryptionOptions, ) -> Result<Compact<T, H>, Error>
where K: Serialize + DeserializeOwned,

Consumes self and encrypt it. If the token is already encrypted, this is a no-op.

You will need to provide a `jwa::EncryptionOptions` that will differ based on your chosen algorithms.

If your `cek_algorithm` is not `dir` or direct, the options provided will be used to encrypt your content encryption key.

If your `cek_algorithm` is `dir` or Direct, then the options will be used to encrypt your content directly.

#### pub fn encrypt<K>( &self, key: &JWK<K>, options: &EncryptionOptions, ) -> Result<Compact<T, H>, Error>
where K: Serialize + DeserializeOwned,

Encrypt an Decrypted JWE.

You will need to provide a `jwa::EncryptionOptions` that will differ based on your chosen algorithms.

If your `cek_algorithm` is not `dir` or direct, the options provided will be used to encrypt your content encryption key.

If your `cek_algorithm` is `dir` or Direct, then the options will be used to encrypt your content directly.

#### pub fn into_decrypted<K>( self, key: &JWK<K>, cek_alg: KeyManagementAlgorithm, enc_alg: ContentEncryptionAlgorithm, ) -> Result<Compact<T, H>, Error>
where K: Serialize + DeserializeOwned,

Consumes self and decrypt it. If the token is already decrypted, this is a no-op.

#### pub fn decrypt<K>( &self, key: &JWK<K>, cek_alg: KeyManagementAlgorithm, enc_alg: ContentEncryptionAlgorithm, ) -> Result<Compact<T, H>, Error>
where K: Serialize + DeserializeOwned,

Decrypt an encrypted JWE. Provide the expected algorithms to mitigate an attacker modifying the fields

#### pub fn encrypted(&self) -> Result<&Compact, Error>

Convenience method to get a reference to the encrypted payload

#### pub fn encrypted_mut(&mut self) -> Result<&mut Compact, Error>

Convenience method to get a mutable reference to the encrypted payload

#### pub fn payload(&self) -> Result<&T, Error>

Convenience method to get a reference to the payload from an Decrypted JWE

#### pub fn payload_mut(&mut self) -> Result<&mut T, Error>

Convenience method to get a mutable reference to the payload from an Decrypted JWE

#### pub fn header(&self) -> Result<&Header<H>, Error>

Convenience method to get a reference to the header from an Decrypted JWE

#### pub fn header_mut(&mut self) -> Result<&mut Header<H>, Error>

Convenience method to get a reference to the header from an Decrypted JWE

#### pub fn unwrap_decrypted(self) -> (Header<H>, T)

Consumes self, and move the payload and header out and return them as a tuple

##### §Panics

Panics if the JWE is not decrypted

#### pub fn unwrap_encrypted(self) -> Compact

Consumes self, and move the encrypted Compact serialization out and return it

##### §Panics

Panics if the JWE is not encrypted

§

### impl<P, H> Compact<ClaimsSet<P>, H>
where ClaimsSet<P>: CompactPart, H: Serialize + DeserializeOwned + Clone,

Convenience implementation for a Compact that contains a `ClaimsSet`

#### pub fn validate(&self, options: ValidationOptions) -> Result<(), Error>

Validate the temporal claims in the decoded token

If `None` is provided for options, the defaults will apply.

By default, no temporal claims (namely `iat`, `exp`, `nbf`) are required, and they will pass validation if they are missing.

## Trait Implementations§

§

### impl<T, H> Clone for Compact<T, H>
where T: Clone, H: Clone,

§

#### fn clone(&self) -> Compact<T, H>

Returns a duplicate of the value. Read more
1.0.0 · Source§

#### fn clone_from(&mut self, source: &Self)

Performs copy-assignment from `source`. Read more
§

### impl<T, H> Debug for Compact<T, H>
where T: Debug, H: Debug,

§

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

Formats the value using the given formatter. Read more
§

### impl<'de, T, H> Deserialize<'de> for Compact<T, H>

§

#### fn deserialize<__D>( __deserializer: __D, ) -> Result<Compact<T, H>, <__D as Deserializer<'de>>::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
§

### impl<T, H> PartialEq for Compact<T, H>
where T: PartialEq, H: PartialEq,

§

#### fn eq(&self, other: &Compact<T, H>) -> bool

Tests for `self` and `other` values to be equal, and is used by `==`.
1.0.0 · Source§

#### fn ne(&self, other: &Rhs) -> bool

Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason.
§

### impl<T, H> Serialize for Compact<T, H>

§

#### fn serialize<__S>( &self, __serializer: __S, ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
§

### impl<T, H> Eq for Compact<T, H>
where T: Eq, H: Eq,

§

### impl<T, H> StructuralPartialEq for Compact<T, H>

## Auto Trait Implementations§

§

### impl<T, H> Freeze for Compact<T, H>
where T: Freeze, H: Freeze,

§

### impl<T, H> RefUnwindSafe for Compact<T, H>
where T: RefUnwindSafe, H: RefUnwindSafe,

§

### impl<T, H> Send for Compact<T, H>
where T: Send, H: Send,

§

### impl<T, H> Sync for Compact<T, H>
where T: Sync, H: Sync,

§

### impl<T, H> Unpin for Compact<T, H>
where T: Unpin, H: Unpin,

§

### impl<T, H> UnwindSafe for Compact<T, H>
where T: UnwindSafe, H: UnwindSafe,

## 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
§

### impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

#### fn equivalent(&self, key: &K) -> bool

Compare self to `key` and return `true` if they are equal.
Source§

### impl<T> From<T> for T

Source§

#### fn from(t: T) -> T

Returns the argument unchanged.

§

### impl<T> Instrument for T

§

#### fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [`Span`], returning an `Instrumented` wrapper. Read more
§

#### fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more
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.

§

### impl<T> PolicyExt for T
where T: ?Sized,

§

#### fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new `Policy` that returns [`Action::Follow`] only if `self` and `other` return `Action::Follow`. Read more
§

#### fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new `Policy` that returns [`Action::Follow`] if either `self` or `other` returns `Action::Follow`. Read more
§

### impl<T> ServiceExt for T

§

#### fn map_response_body<F>(self, f: F) -> MapResponseBody<Self, F>
where Self: Sized,

Apply a transformation to the response body. Read more
§

#### fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using HTTP status codes. Read more
§

#### fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using gRPC headers. Read more
§

#### fn follow_redirects(self) -> FollowRedirect<Self>
where Self: Sized,

Follow redirect resposes using the `Standard` policy. Read more
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.
§

### impl<T> WithSubscriber for T

§

#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided `Subscriber` to this type, returning a [`WithDispatch`] wrapper. Read more
§

#### fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default `Subscriber` to this type, returning a [`WithDispatch`] wrapper. Read more
Source§

### impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,