encore-reqauth 2.0.0-beta.9

The wire protocol of Encore's service-to-service request auth
Documentation
use std::str::{self, FromStr};

use http::HeaderValue;

pub trait HeaderValueExt {
    fn to_utf8_str(&self) -> Result<&str, std::str::Utf8Error>;
}

impl HeaderValueExt for HeaderValue {
    // Some header values may contain utf8 characters (e.g authdata) so we use `str::from_utf8`
    // rather than using `HeaderValues::to_str` which errors on non-visible ASCII characters.
    fn to_utf8_str(&self) -> Result<&str, std::str::Utf8Error> {
        std::str::from_utf8(self.as_bytes())
    }
}

#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
pub enum MetaKey {
    TraceParent,
    TraceState,
    XCorrelationId,
    Version,
    UserId,
    UserData,
    Caller,
    Callee,
    SvcAuthMethod,
    SvcAuthEncoreAuthHash,
    SvcAuthEncoreAuthDate,
    /// The service a call between containers is for, which the receiving
    /// gateway routes on. Only a gateway sends it.
    Service,
    /// The gateway a public request another container's gateway relayed is
    /// for, which the receiving gateway serves it through. Only a gateway
    /// sends it.
    Gateway,
    /// The frontend a public request another container's gateway relayed is
    /// for: one a service there hosts, which the receiving gateway passes it
    /// to. Only a gateway sends it.
    Frontend,
    /// The address of the client a relayed public request came from, which
    /// the receiving gateway serves it as. Covered by a relay's signature
    /// alone.
    ClientIp,
    /// The host a relayed public request was first sent to, which the
    /// receiving gateway serves it for. Covered by a relay's signature alone.
    ForwardedHost,
    /// What tells one relay from every other, so the receiving gateway serves
    /// each once. Covered by a relay's signature alone.
    RelayId,
}

impl MetaKey {
    pub fn header_key(&self) -> &'static str {
        use MetaKey::*;
        match self {
            TraceParent => "traceparent",
            TraceState => "tracestate",
            XCorrelationId => "x-correlation-id",
            Version => "x-encore-meta-version",
            UserId => "x-encore-meta-userid",
            UserData => "x-encore-meta-authdata",
            Caller => "x-encore-meta-caller",
            Callee => "x-encore-meta-callee",
            SvcAuthMethod => "x-encore-meta-svc-auth-method",
            SvcAuthEncoreAuthHash => "x-encore-meta-svc-auth",
            SvcAuthEncoreAuthDate => "x-encore-meta-date",
            Service => "x-encore-service",
            Gateway => "x-encore-gateway",
            Frontend => "x-encore-frontend",
            ClientIp => "x-encore-client-ip",
            ForwardedHost => "x-forwarded-host",
            RelayId => "x-encore-relay-id",
        }
    }
}

pub struct NotMetaKey;

impl FromStr for MetaKey {
    type Err = NotMetaKey;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        use MetaKey::*;
        Ok(match value {
            "traceparent" => TraceParent,
            "tracestate" => TraceState,
            "x-correlation-id" => XCorrelationId,
            "x-encore-meta-version" => Version,
            "x-encore-meta-userid" => UserId,
            "x-encore-meta-authdata" => UserData,
            "x-encore-meta-caller" => Caller,
            "x-encore-meta-callee" => Callee,
            "x-encore-meta-svc-auth-method" => SvcAuthMethod,
            "x-encore-meta-svc-auth" => SvcAuthEncoreAuthHash,
            "x-encore-meta-date" => SvcAuthEncoreAuthDate,
            "x-encore-service" => Service,
            "x-encore-gateway" => Gateway,
            "x-encore-frontend" => Frontend,
            "x-encore-client-ip" => ClientIp,
            "x-forwarded-host" => ForwardedHost,
            "x-encore-relay-id" => RelayId,
            _ => return Err(NotMetaKey),
        })
    }
}
pub trait MetaMapMut: MetaMap {
    fn set(&mut self, key: MetaKey, value: String) -> anyhow::Result<()>;
}

pub trait MetaMap {
    fn get_meta(&self, key: MetaKey) -> Option<&str>;
    fn meta_values<'a>(&'a self, key: MetaKey) -> Box<dyn Iterator<Item = &'a str> + 'a>;

    /// Returns all meta keys, sorted alphabetically based on MetaKey::header_key.
    fn sorted_meta_keys(&self) -> Vec<MetaKey>;

    /// Every value of every Request Context header
    /// ([`crate::reqctx::HEADER_PREFIX`]), with its header's name, in no
    /// particular order. Values are bytes, so one that is not UTF-8 is still
    /// covered by a call's signature.
    fn ctx_fields(&self) -> Vec<(&str, &[u8])>;
}

/// The Request Context headers of `headers`, with each of their values.
fn ctx_fields_of(headers: &http::HeaderMap) -> Vec<(&str, &[u8])> {
    headers
        .iter()
        .filter(|(name, _)| crate::reqctx::is_field_header(name.as_str()))
        .map(|(name, value)| (name.as_str(), value.as_bytes()))
        .collect()
}

impl MetaMapMut for http::HeaderMap {
    fn set(&mut self, key: MetaKey, value: String) -> anyhow::Result<()> {
        self.insert(key.header_key(), value.parse()?);
        Ok(())
    }
}

impl MetaMap for http::HeaderMap {
    fn get_meta(&self, key: MetaKey) -> Option<&str> {
        self.get(key.header_key())
            .and_then(|val| val.to_utf8_str().ok())
    }

    fn meta_values<'a>(&'a self, key: MetaKey) -> Box<dyn Iterator<Item = &'a str> + 'a> {
        Box::new(
            self.get_all(key.header_key())
                .iter()
                .filter_map(|v| v.to_utf8_str().ok()),
        )
    }

    fn sorted_meta_keys(&self) -> Vec<MetaKey> {
        let mut keys: Vec<_> = self
            .keys()
            .filter_map(|k| MetaKey::from_str(k.as_str()).ok())
            .collect();
        keys.sort_by_key(|k| k.header_key());
        keys
    }

    fn ctx_fields(&self) -> Vec<(&str, &[u8])> {
        ctx_fields_of(self)
    }
}

#[cfg(feature = "pingora")]
impl MetaMapMut for pingora_http::RequestHeader {
    fn set(&mut self, key: MetaKey, value: String) -> anyhow::Result<()> {
        self.insert_header(key.header_key(), value)?;
        Ok(())
    }
}

#[cfg(feature = "pingora")]
impl MetaMap for pingora_http::RequestHeader {
    fn get_meta(&self, key: MetaKey) -> Option<&str> {
        self.headers
            .get(key.header_key())
            .and_then(|v| v.to_utf8_str().ok())
    }

    fn meta_values<'a>(&'a self, key: MetaKey) -> Box<dyn Iterator<Item = &'a str> + 'a> {
        Box::new(
            self.headers
                .get_all(key.header_key())
                .iter()
                .filter_map(|v| v.to_utf8_str().ok()),
        )
    }

    fn sorted_meta_keys(&self) -> Vec<MetaKey> {
        let mut keys: Vec<_> = self
            .headers
            .keys()
            .filter_map(|k| MetaKey::from_str(k.as_str()).ok())
            .collect();
        keys.sort_by_key(|k| k.header_key());
        keys
    }

    fn ctx_fields(&self) -> Vec<(&str, &[u8])> {
        ctx_fields_of(&self.headers)
    }
}