Struct rocket::mtls::Certificate
[−]#[repr(transparent)]pub struct Certificate<'a>(_);
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
impl<'a> Certificate<'a>
impl<'a> Certificate<'a>
pub fn serial(&self) -> &BigUint
pub fn serial(&self) -> &BigUint
Returns the serial number of the X.509 certificate.
Example
use rocket::mtls::Certificate;
#[get("/auth")]
fn auth(cert: Certificate<'_>) {
let cert = cert.serial();
}
pub fn version(&self) -> u32
pub fn version(&self) -> u32
Returns the version of the X.509 certificate.
Example
use rocket::mtls::Certificate;
#[get("/auth")]
fn auth(cert: Certificate<'_>) {
let cert = cert.version();
}
pub fn subject(&self) -> &Name<'a>
pub fn subject(&self) -> &Name<'a>
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);
}
}
pub fn issuer(&self) -> &Name<'a>
pub fn issuer(&self) -> &Name<'a>
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);
}
}
pub fn extensions(&self) -> &[X509Extension<'a>]
pub fn extensions(&self) -> &[X509Extension<'a>]
Returns a slice 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().iter()
.find(|e| e.oid == 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);
}
}
}
}
pub fn has_serial(&self, number: &str) -> Option<bool>
pub fn has_serial(&self, number: &str) -> Option<bool>
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>>
pub fn version(&self) -> X509Version
pub fn version(&self) -> X509Version
Get the version of the encoded certificate
pub fn public_key(&self) -> &SubjectPublicKeyInfo<'_>
pub fn public_key(&self) -> &SubjectPublicKeyInfo<'_>
Get the certificate public key information.
pub fn extensions(&self) -> &[X509Extension<'a>]
pub fn extensions(&self) -> &[X509Extension<'a>]
Returns the certificate extensions
pub fn iter_extensions(&self) -> impl Iterator<Item = &X509Extension<'a>>
pub fn iter_extensions(&self) -> impl Iterator<Item = &X509Extension<'a>>
Returns an iterator over the certificate extensions
pub fn get_extension_unique(
&self,
oid: &Oid<'_>
) -> Result<Option<&X509Extension<'a>>, X509Error>
pub fn get_extension_unique(
&self,
oid: &Oid<'_>
) -> Result<Option<&X509Extension<'a>>, X509Error>
Searches for an extension with the given Oid
.
Return Ok(Some(extension))
if exactly one was found, Ok(None)
if none was found,
or an error DuplicateExtensions
if the extension is present twice or more.
pub fn find_extension(&self, oid: &Oid<'_>) -> Option<&X509Extension<'a>>
👎 Deprecated since 0.13.0: Do not use this function (duplicate extensions are not checked), use get_extension_unique
pub fn find_extension(&self, oid: &Oid<'_>) -> Option<&X509Extension<'a>>
Do not use this function (duplicate extensions are not checked), use get_extension_unique
Searches for an extension with the given Oid
.
Duplicate extensions
Note: if there are several extensions with the same Oid
, the first one is returned, masking other values.
RFC5280 forbids having duplicate extensions, but does not specify how errors should be handled.
Because of this, the find_extension
method is not safe and should not be used!
The get_extension_unique
method checks for duplicate extensions and should be
preferred.
pub fn extensions_map(
&self
) -> Result<HashMap<Oid<'_>, &X509Extension<'a>, RandomState>, X509Error>
pub fn extensions_map(
&self
) -> Result<HashMap<Oid<'_>, &X509Extension<'a>, RandomState>, X509Error>
Builds and returns a map of extensions.
If an extension is present twice, this will fail and return DuplicateExtensions
.
pub fn basic_constraints(
&self
) -> Result<Option<BasicExtension<&BasicConstraints>>, X509Error>
pub fn basic_constraints(
&self
) -> Result<Option<BasicExtension<&BasicConstraints>>, X509Error>
Attempt to get the certificate Basic Constraints extension
Return Ok(Some(extension))
if exactly one was found, Ok(None)
if none was found,
or an error if the extension is present twice or more.
pub fn key_usage(&self) -> Result<Option<BasicExtension<&KeyUsage>>, X509Error>
pub fn key_usage(&self) -> Result<Option<BasicExtension<&KeyUsage>>, X509Error>
Attempt to get the certificate Key Usage extension
Return Ok(Some(extension))
if exactly one was found, Ok(None)
if none was found,
or an error if the extension is invalid, or is present twice or more.
pub fn extended_key_usage(
&self
) -> Result<Option<BasicExtension<&ExtendedKeyUsage<'_>>>, X509Error>
pub fn extended_key_usage(
&self
) -> Result<Option<BasicExtension<&ExtendedKeyUsage<'_>>>, X509Error>
Attempt to get the certificate Extended Key Usage extension
Return Ok(Some(extension))
if exactly one was found, Ok(None)
if none was found,
or an error if the extension is invalid, or is present twice or more.
pub fn policy_constraints(
&self
) -> Result<Option<BasicExtension<&PolicyConstraints>>, X509Error>
pub fn policy_constraints(
&self
) -> Result<Option<BasicExtension<&PolicyConstraints>>, X509Error>
Attempt to get the certificate Policy Constraints extension
Return Ok(Some(extension))
if exactly one was found, Ok(None)
if none was found,
or an error if the extension is invalid, or is present twice or more.
pub fn inhibit_anypolicy(
&self
) -> Result<Option<BasicExtension<&InhibitAnyPolicy>>, X509Error>
pub fn inhibit_anypolicy(
&self
) -> Result<Option<BasicExtension<&InhibitAnyPolicy>>, X509Error>
Attempt to get the certificate Policy Constraints extension
Return Ok(Some(extension))
if exactly one was found, Ok(None)
if none was found,
or an error if the extension is invalid, or is present twice or more.
pub fn policy_mappings(
&self
) -> Result<Option<BasicExtension<&PolicyMappings<'_>>>, X509Error>
pub fn policy_mappings(
&self
) -> Result<Option<BasicExtension<&PolicyMappings<'_>>>, X509Error>
Attempt to get the certificate Policy Mappings extension
Return Ok(Some(extension))
if exactly one was found, Ok(None)
if none was found,
or an error if the extension is invalid, or is present twice or more.
pub fn subject_alternative_name(
&self
) -> Result<Option<BasicExtension<&SubjectAlternativeName<'_>>>, X509Error>
pub fn subject_alternative_name(
&self
) -> Result<Option<BasicExtension<&SubjectAlternativeName<'_>>>, X509Error>
Attempt to get the certificate Subject Alternative Name extension
Return Ok(Some(extension))
if exactly one was found, Ok(None)
if none was found,
or an error if the extension is invalid, or is present twice or more.
pub fn name_constraints(
&self
) -> Result<Option<BasicExtension<&NameConstraints<'_>>>, X509Error>
pub fn name_constraints(
&self
) -> Result<Option<BasicExtension<&NameConstraints<'_>>>, X509Error>
Attempt to get the certificate Name Constraints extension
Return Ok(Some(extension))
if exactly one was found, Ok(None)
if none was found,
or an error if the extension is invalid, or is present twice or more.
pub fn raw_serial(&self) -> &'a [u8]ⓘNotable traits for &'_ [u8]impl<'_> Read for &'_ [u8]impl<'_> Write for &'_ mut [u8]
pub fn raw_serial(&self) -> &'a [u8]ⓘNotable traits for &'_ [u8]impl<'_> Read for &'_ [u8]impl<'_> Write for &'_ mut [u8]
Get the raw bytes of the certificate serial number
pub fn raw_serial_as_string(&self) -> String
pub fn raw_serial_as_string(&self) -> String
Get a formatted string of the certificate serial number, separated by ‘:’
Trait Implementations
impl<'a> Debug for Certificate<'a>
impl<'a> Debug for Certificate<'a>
impl<'a> Deref for Certificate<'a>
impl<'a> Deref for Certificate<'a>
type Target = TbsCertificate<'a>
type Target = TbsCertificate<'a>
The resulting type after dereferencing.
fn deref(&self) -> &<Certificate<'a> as Deref>::Target
fn deref(&self) -> &<Certificate<'a> as Deref>::Target
Dereferences the value.
sourceimpl<'r> FromRequest<'r> for Certificate<'r>
impl<'r> FromRequest<'r> for Certificate<'r>
impl<'a> PartialEq<Certificate<'a>> for Certificate<'a>
impl<'a> PartialEq<Certificate<'a>> for Certificate<'a>
fn eq(&self, other: &Certificate<'a>) -> bool
fn eq(&self, other: &Certificate<'a>) -> bool
This method tests for self
and other
values to be equal, and is used
by ==
. Read more
fn ne(&self, other: &Certificate<'a>) -> bool
fn ne(&self, other: &Certificate<'a>) -> bool
This method tests for !=
.
impl<'a> StructuralPartialEq for Certificate<'a>
Auto Trait Implementations
impl<'a> RefUnwindSafe for Certificate<'a>
impl<'a> Send for Certificate<'a>
impl<'a> Sync for Certificate<'a>
impl<'a> Unpin for Certificate<'a>
impl<'a> UnwindSafe for Certificate<'a>
Blanket Implementations
impl<'a, T> AsTaggedExplicit<'a> for T where
T: 'a,
impl<'a, T> AsTaggedExplicit<'a> for T where
T: 'a,
fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self>
impl<'a, T> AsTaggedImplicit<'a> for T where
T: 'a,
impl<'a, T> AsTaggedImplicit<'a> for T where
T: 'a,
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<T> Instrument for T
impl<T> Instrument for T
sourcefn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
sourcefn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
impl<T> IntoCollection<T> for T
impl<T> IntoCollection<T> for T
fn into_collection<A>(self) -> SmallVec<A> where
A: Array<Item = T>,
fn into_collection<A>(self) -> SmallVec<A> where
A: Array<Item = T>,
Converts self
into a collection.
fn mapped<U, F, A>(self, f: F) -> SmallVec<A> where
F: FnMut(T) -> U,
A: Array<Item = U>,
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
fn vzip(self) -> V
sourceimpl<T> WithSubscriber for T
impl<T> WithSubscriber for T
sourcefn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
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
sourcefn with_current_subscriber(self) -> WithDispatch<Self>
fn with_current_subscriber(self) -> WithDispatch<Self>
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more