Struct rocket::mtls::Certificate[]

#[repr(transparent)]
pub struct Certificate<'a>(_);
This is supported on crate feature mtls only.
Expand description

A request guard for validated, verified client certificates.

This type is a wrapper over x509::TbsCertificate with convenient methods and complete documentation. Should the data exposed by the inherent methods not suffice, this type derefs to x509::TbsCertificate.

Request Guard

The request guard implementation succeeds if:

  • The client presents certificates.
  • The certificates are active and not yet expired.
  • The client’s certificate chain was signed by the CA identified by the configured ca_certs and with respect to SNI, if any. See module level docs for configuration details.

If the client does not present certificates, the guard forwards.

If the certificate chain fails to validate or verify, the guard fails with the respective Error.

Wrapping

To implement roles, the Certificate guard can be wrapped with a more semantically meaningful type with extra validation. For example, if a certificate with a specific serial number is known to belong to an administrator, a CertifiedAdmin type can authorize as follow:

use rocket::mtls::{self, bigint::BigUint, Certificate};
use rocket::request::{Request, FromRequest, Outcome};
use rocket::outcome::try_outcome;

// The serial number for the certificate issued to the admin.
const ADMIN_SERIAL: &str = "65828378108300243895479600452308786010218223563";

// A request guard that authenticates and authorizes an administrator.
struct CertifiedAdmin<'r>(Certificate<'r>);

#[rocket::async_trait]
impl<'r> FromRequest<'r> for CertifiedAdmin<'r> {
    type Error = mtls::Error;

    async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
        let cert = try_outcome!(req.guard::<Certificate<'r>>().await);
        if let Some(true) = cert.has_serial(ADMIN_SERIAL) {
            Outcome::Success(CertifiedAdmin(cert))
        } else {
            Outcome::Forward(())
        }
    }
}

#[get("/admin")]
fn admin(admin: CertifiedAdmin<'_>) {
    // This handler can only execute if an admin is authenticated.
}

#[get("/admin", rank = 2)]
fn unauthorized(user: Option<Certificate<'_>>) {
    // This handler always executes, whether there's a non-admin user that's
    // authenticated (user = Some()) or not (user = None).
}

Example

To retrieve certificate data in a route, use Certificate as a guard:

use rocket::mtls::{self, Certificate};

#[get("/auth")]
fn auth(cert: Certificate<'_>) {
    // This handler only runs when a valid certificate was presented.
}

#[get("/maybe")]
fn maybe_auth(cert: Option<Certificate<'_>>) {
    // This handler runs even if no certificate was presented or an invalid
    // certificate was presented.
}

#[get("/ok")]
fn ok_auth(cert: mtls::Result<Certificate<'_>>) {
    // This handler does not run if a certificate was not presented but
    // _does_ run if a valid (Ok) or invalid (Err) one was presented.
}

Implementations

Returns the serial number of the X.509 certificate.

Example

use rocket::mtls::Certificate;

#[get("/auth")]
fn auth(cert: Certificate<'_>) {
    let cert = cert.serial();
}

Returns the version of the X.509 certificate.

Example

use rocket::mtls::Certificate;

#[get("/auth")]
fn auth(cert: Certificate<'_>) {
    let cert = cert.version();
}

Returns the subject (a “DN” or “Distinguised Name”) of the X.509 certificate.

Example

use rocket::mtls::Certificate;

#[get("/auth")]
fn auth(cert: Certificate<'_>) {
    if let Some(name) = cert.subject().common_name() {
        println!("Hello, {}!", name);
    }
}

Returns the issuer (a “DN” or “Distinguised Name”) of the X.509 certificate.

Example

use rocket::mtls::Certificate;

#[get("/auth")]
fn auth(cert: Certificate<'_>) {
    if let Some(name) = cert.issuer().common_name() {
        println!("Issued by: {}", name);
    }
}

Returns a map of the extensions in the X.509 certificate.

Example

use rocket::mtls::{oid, x509, Certificate};

#[get("/auth")]
fn auth(cert: Certificate<'_>) {
    let subject_alt = cert.extensions()
        .get(&oid::OID_X509_EXT_SUBJECT_ALT_NAME)
        .and_then(|e| match e.parsed_extension() {
            x509::ParsedExtension::SubjectAlternativeName(s) => Some(s),
            _ => None
        });

    if let Some(subject_alt) = subject_alt {
        for name in &subject_alt.general_names {
            if let x509::GeneralName::RFC822Name(name) = name {
                println!("An email, perhaps? {}", name);
            }
        }
    }
}

Checks if the certificate has the serial number number.

If number is not a valid unsigned integer in base 10, returns None.

Otherwise, returns Some(true) if it does and Some(false) if it does not.

use rocket::mtls::Certificate;

const SERIAL: &str = "65828378108300243895479600452308786010218223563";

#[get("/auth")]
fn auth(cert: Certificate<'_>) {
    if cert.has_serial(SERIAL).unwrap_or(false) {
        println!("certificate has the expected serial number");
    }
}

Methods from Deref<Target = TbsCertificate<'a>>

Get a reference to the map of extensions.

Returns true if certificate has basicConstraints CA:true

Get the raw bytes of the certificate serial number

Get a formatted string of the certificate serial number, separated by ‘:’

Trait Implementations

Formats the value using the given formatter. Read more

The resulting type after dereferencing.

Dereferences the value.

The associated error to be returned if derivation fails.

Derives an instance of Self from the incoming request metadata. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Converts self into T using Into<T>. Read more

Converts self into a target type. Read more

Causes self to use its Binary implementation when Debug-formatted.

Causes self to use its Display implementation when Debug-formatted. Read more

Causes self to use its LowerExp implementation when Debug-formatted. Read more

Causes self to use its LowerHex implementation when Debug-formatted. Read more

Causes self to use its Octal implementation when Debug-formatted.

Causes self to use its Pointer implementation when Debug-formatted. Read more

Causes self to use its UpperExp implementation when Debug-formatted. Read more

Causes self to use its UpperHex implementation when Debug-formatted. Read more

Performs the conversion.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Performs the conversion.

Converts self into a collection.

Pipes by value. This is generally the method you want to use. Read more

Borrows self and passes that borrow into the pipe function. Read more

Mutably borrows self and passes that borrow into the pipe function. Read more

Borrows self, then passes self.borrow() into the pipe function. Read more

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more

Borrows self, then passes self.as_ref() into the pipe function.

Mutably borrows self, then passes self.as_mut() into the pipe function. Read more

Borrows self, then passes self.deref() into the pipe function.

Mutably borrows self, then passes self.deref_mut() into the pipe function. Read more

Pipes a value into a function that cannot ordinarily be called in suffix position. Read more

Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more

Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more

Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more

Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more

Pipes a dereference into a function that cannot normally be called in suffix position. Read more

Pipes a mutable dereference into a function that cannot normally be called in suffix position. Read more

Pipes a reference into a function that cannot ordinarily be called in suffix position. Read more

Pipes a mutable reference into a function that cannot ordinarily be called in suffix position. Read more

Should always be Self

Immutable access to a value. Read more

Mutable access to a value. Read more

Immutable access to the Borrow<B> of a value. Read more

Mutable access to the BorrowMut<B> of a value. Read more

Immutable access to the AsRef<R> view of a value. Read more

Mutable access to the AsMut<R> view of a value. Read more

Immutable access to the Deref::Target of a value. Read more

Mutable access to the Deref::Target of a value. Read more

Calls .tap() only in debug builds, and is erased in release builds.

Calls .tap_mut() only in debug builds, and is erased in release builds. Read more

Calls .tap_borrow() only in debug builds, and is erased in release builds. Read more

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds. Read more

Calls .tap_ref() only in debug builds, and is erased in release builds. Read more

Calls .tap_ref_mut() only in debug builds, and is erased in release builds. Read more

Calls .tap_deref() only in debug builds, and is erased in release builds. Read more

Calls .tap_deref_mut() only in debug builds, and is erased in release builds. Read more

Provides immutable access for inspection. Read more

Calls tap in debug builds, and does nothing in release builds.

Provides mutable access for modification. Read more

Calls tap_mut in debug builds, and does nothing in release builds.

Provides immutable access to the reference for inspection.

Calls tap_ref in debug builds, and does nothing in release builds.

Provides mutable access to the reference for modification.

Calls tap_ref_mut in debug builds, and does nothing in release builds.

Provides immutable access to the borrow for inspection. Read more

Calls tap_borrow in debug builds, and does nothing in release builds.

Provides mutable access to the borrow for modification.

Calls tap_borrow_mut in debug builds, and does nothing in release builds. Read more

Immutably dereferences self for inspection.

Calls tap_deref in debug builds, and does nothing in release builds.

Mutably dereferences self for modification.

Calls tap_deref_mut in debug builds, and does nothing in release builds. Read more

Attempts to convert self into T using TryInto<T>. Read more

Attempts to convert self into a target type. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.