use std::fmt::{Debug, Display};
use std::time::SystemTime;
use anyhow::Context;
use sha3::digest::Digest;
use subtle::ConstantTimeEq;
use crate::encoreauth;
use crate::encoreauth::{OperationHash, SignatureComponents};
use crate::meta::{MetaKey, MetaMap, MetaMapMut};
pub trait ServiceAuthMethod: Debug + Send + Sync + 'static {
fn name(&self) -> &'static str;
fn sign(&self, headers: &mut dyn MetaMapMut, now: SystemTime) -> anyhow::Result<()>;
fn verify(&self, headers: &dyn MetaMap, now: SystemTime) -> Result<(), VerifyError>;
}
#[derive(Debug)]
pub struct Noop;
impl ServiceAuthMethod for Noop {
fn name(&self) -> &'static str {
"noop"
}
fn sign(&self, _headers: &mut dyn MetaMapMut, _now: SystemTime) -> anyhow::Result<()> {
Ok(())
}
fn verify(&self, _headers: &dyn MetaMap, _now: SystemTime) -> Result<(), VerifyError> {
Ok(())
}
}
pub trait KeyData: Send + Sync {
fn resolve(&self) -> Result<&[u8], Box<dyn std::error::Error + Send + Sync>>;
}
impl KeyData for Vec<u8> {
fn resolve(&self) -> Result<&[u8], Box<dyn std::error::Error + Send + Sync>> {
Ok(self)
}
}
pub struct EncoreAuthKey {
pub key_id: u32,
pub data: Box<dyn KeyData>,
}
pub struct EncoreAuth {
app_slug: String,
env_name: String,
keys: Vec<EncoreAuthKey>,
latest_idx: usize, own_environment_only: bool,
}
impl Debug for EncoreAuth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EncoreAuth")
.field("app_slug", &self.app_slug)
.field("env_name", &self.env_name)
.field("own_environment_only", &self.own_environment_only)
.finish()
}
}
impl EncoreAuth {
pub fn new(app_slug: String, env_name: String, keys: Vec<EncoreAuthKey>) -> Self {
Self::build(app_slug, env_name, keys, false)
}
pub fn for_environment(app_slug: String, env_name: String, keys: Vec<EncoreAuthKey>) -> Self {
Self::build(app_slug, env_name, keys, true)
}
fn build(
app_slug: String,
env_name: String,
keys: Vec<EncoreAuthKey>,
own_environment_only: bool,
) -> Self {
if keys.is_empty() {
panic!("auth keys must not be empty");
}
let latest_idx = {
let mut max_id = keys[0].key_id;
let mut max_idx = 0;
for (idx, k) in keys.iter().enumerate() {
if k.key_id > max_id {
max_idx = idx;
max_id = k.key_id;
}
}
max_idx
};
Self {
app_slug,
env_name,
keys,
latest_idx,
own_environment_only,
}
}
}
#[derive(Debug)]
pub enum VerifyError {
NoAuthorizationHeader,
NoDateHeader,
InvalidHeader(encoreauth::InvalidSignature),
SignatureMismatch,
DateSkew,
UnknownKey,
ResolveKeyData(Box<dyn std::error::Error + Send + Sync>),
OtherEnvironment {
app_slug: String,
env_name: String,
},
}
impl Display for VerifyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use VerifyError::*;
match self {
NoAuthorizationHeader => write!(f, "no authorization header"),
NoDateHeader => write!(f, "no date header"),
InvalidHeader(e) => write!(f, "invalid header: {e}"),
SignatureMismatch => write!(f, "signature mismatch"),
DateSkew => write!(f, "date skew"),
UnknownKey => write!(f, "unknown key"),
ResolveKeyData(e) => write!(f, "unable to resolve secret key data: {e}"),
OtherEnvironment { app_slug, env_name } => write!(
f,
"signed for app {app_slug:?} environment {env_name:?}, not this one"
),
}
}
}
impl std::error::Error for VerifyError {}
impl ServiceAuthMethod for EncoreAuth {
fn name(&self) -> &'static str {
"encore-auth"
}
fn sign(&self, headers: &mut dyn MetaMapMut, now: SystemTime) -> anyhow::Result<()> {
let op_hash = self.build_op_hash(headers);
let key = &self.keys[self.latest_idx];
let key_data = key
.data
.resolve()
.map_err(|e| anyhow::anyhow!(e))
.context("unable to resolve auth key data")?;
let hash = encoreauth::sign(
(key.key_id, key_data),
&self.app_slug,
&self.env_name,
now,
&op_hash,
);
headers
.set(MetaKey::SvcAuthEncoreAuthHash, hash)
.context("set auth hash header")?;
headers
.set(MetaKey::SvcAuthEncoreAuthDate, httpdate::fmt_http_date(now))
.context("set auth date header")?;
Ok(())
}
fn verify(&self, headers: &dyn MetaMap, now: SystemTime) -> Result<(), VerifyError> {
let auth_header = headers
.get_meta(MetaKey::SvcAuthEncoreAuthHash)
.ok_or(VerifyError::NoAuthorizationHeader)?;
let date_header = headers
.get_meta(MetaKey::SvcAuthEncoreAuthDate)
.ok_or(VerifyError::NoDateHeader)?;
let components = SignatureComponents::parse(auth_header, date_header)
.map_err(VerifyError::InvalidHeader)?;
let diff = now
.duration_since(components.timestamp)
.unwrap_or_else(|e| e.duration());
if diff.as_secs() > 120 {
return Err(VerifyError::DateSkew);
}
if self.own_environment_only
&& (components.app_slug != self.app_slug || components.env_name != self.env_name)
{
return Err(VerifyError::OtherEnvironment {
app_slug: components.app_slug,
env_name: components.env_name,
});
}
let key = self
.keys
.iter()
.find(|k| k.key_id == components.key_id)
.ok_or(VerifyError::UnknownKey)?;
let key_data = key.data.resolve().map_err(VerifyError::ResolveKeyData)?;
let expected_signature = encoreauth::sign_for_verification(
(key.key_id, key_data),
&components.app_slug,
&components.env_name,
components.timestamp,
&components.operation_hash,
);
let signature_match: bool = expected_signature
.as_bytes()
.ct_eq(auth_header.as_bytes())
.into();
if !signature_match {
return Err(VerifyError::SignatureMismatch);
}
let expected_op_hash = self.build_op_hash(headers);
if !expected_op_hash.ct_eq(&components.operation_hash) {
return Err(VerifyError::SignatureMismatch);
}
Ok(())
}
}
impl EncoreAuth {
fn build_op_hash<R: MetaMap + ?Sized>(&self, req: &R) -> OperationHash {
let mut covered: Vec<(&str, &[u8])> = Vec::new();
let keys = req.sorted_meta_keys();
let relay = keys.contains(&MetaKey::Gateway) || keys.contains(&MetaKey::Frontend);
for key in keys {
use MetaKey::*;
match key {
SvcAuthMethod | SvcAuthEncoreAuthHash | SvcAuthEncoreAuthDate => {
}
TraceParent | TraceState => {
}
XCorrelationId | Version | UserId | UserData | Caller | Callee | Service
| Gateway | Frontend => {
covered.extend(
req.meta_values(key)
.map(|v| (key.header_key(), v.as_bytes())),
);
}
ClientIp | ForwardedHost | RelayId if relay => {
covered.extend(
req.meta_values(key)
.map(|v| (key.header_key(), v.as_bytes())),
);
}
ClientIp | ForwardedHost | RelayId => {}
}
}
covered.extend(req.ctx_fields());
covered.sort_unstable();
let mut hash = <sha3::Sha3_256 as Digest>::new();
for (name, value) in covered {
hash.update(name);
hash.update(b"=");
hash.update(value);
hash.update(b"\n");
}
let payload = hash.finalize();
OperationHash::new(
"internal-api".as_bytes(),
"call".as_bytes(),
Some(payload.as_slice()),
std::iter::empty(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn metas<R: MetaMap>(req: &R) -> Vec<(MetaKey, Vec<String>)> {
let keys = req.sorted_meta_keys();
keys.into_iter()
.map(|k| {
(
k,
req.meta_values(k)
.map(|s| s.to_string())
.collect::<Vec<_>>(),
)
})
.collect()
}
#[test]
fn test_encore_auth() -> anyhow::Result<()> {
let mut headers = http::HeaderMap::new();
let auth = EncoreAuth {
app_slug: "app".into(),
env_name: "env".into(),
keys: vec![EncoreAuthKey {
key_id: 123,
data: Box::new(b"secret data".to_vec()),
}],
latest_idx: 0,
own_environment_only: false,
};
let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
auth.sign(&mut headers, now)
.context("unable to sign request")?;
auth.verify(&headers, now)
.context("unable to verify request")?;
assert_eq!(
metas(&headers),
vec![
(
MetaKey::SvcAuthEncoreAuthDate,
vec!["Fri, 13 Feb 2009 23:31:30 GMT".to_string()]
),
(MetaKey::SvcAuthEncoreAuthHash, vec![r#"ENCORE1-HMAC-SHA3-256 cred="20090213/app/env/123", op=f3c70a419394ce9d56efafad2208154b92c8596d7396b3a2b4ea7fd925d28dc2, sig=fc0c88b47c13d999353ecc8681d91d9c03209a1f05583b92d84e429fedfe387a"#.to_string()]),
]
);
Ok(())
}
fn call(auth: &EncoreAuth, service: Option<&str>) -> http::HeaderMap {
let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
let mut headers = http::HeaderMap::new();
headers.set(MetaKey::Version, "1".into()).unwrap();
headers
.set(MetaKey::Caller, "api:checkout.Pay".into())
.unwrap();
headers
.set(MetaKey::Callee, "billing.Charge".into())
.unwrap();
if let Some(service) = service {
headers.set(MetaKey::Service, service.into()).unwrap();
}
auth.sign(&mut headers, now).unwrap();
headers
}
fn test_auth() -> EncoreAuth {
EncoreAuth::new(
"app".into(),
"env".into(),
vec![EncoreAuthKey {
key_id: 123,
data: Box::new(b"secret data".to_vec()),
}],
)
}
#[test]
fn a_call_without_a_service_header_is_signed_over_its_meta_alone() {
let headers = call(&test_auth(), None);
assert_eq!(
headers.get_meta(MetaKey::SvcAuthEncoreAuthHash),
Some(
r#"ENCORE1-HMAC-SHA3-256 cred="20090213/app/env/123", op=65d66c2cb4ed3d3b8906ddb00b06048a8ee53feef398fad74cc4e756ffa7ca1a, sig=67bed7676bbd90dc2e3b01c16a70b34b66d009b591fc2ed1631bf5fafb5991f0"#
)
);
}
#[test]
fn a_relays_signature_covers_its_client_host_and_id() {
let auth = test_auth();
let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
for (key, changed) in [
(MetaKey::ClientIp, "192.0.2.1"),
(MetaKey::ForwardedHost, "evil.example.com"),
(MetaKey::RelayId, "another"),
] {
let mut headers = call(&auth, None);
headers.set(MetaKey::Gateway, "api".into()).unwrap();
headers
.set(MetaKey::ClientIp, "203.0.113.9".into())
.unwrap();
headers
.set(MetaKey::ForwardedHost, "api.example.com".into())
.unwrap();
headers.set(MetaKey::RelayId, "relay-1".into()).unwrap();
auth.sign(&mut headers, now).unwrap();
assert!(auth.verify(&headers, now).is_ok());
headers.insert(key.header_key(), changed.parse().unwrap());
assert!(
matches!(
auth.verify(&headers, now),
Err(VerifyError::SignatureMismatch)
),
"{} changed on the way",
key.header_key()
);
}
}
#[test]
fn a_call_that_is_no_relay_is_not_signed_over_a_relays_headers() {
let auth = test_auth();
let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
let mut headers = call(&auth, Some("users"));
headers
.set(MetaKey::ForwardedHost, "api.example.com".into())
.unwrap();
auth.sign(&mut headers, now).unwrap();
let signed_with = headers
.get_meta(MetaKey::SvcAuthEncoreAuthHash)
.map(str::to_string);
let mut without = call(&auth, Some("users"));
auth.sign(&mut without, now).unwrap();
assert_eq!(
without
.get_meta(MetaKey::SvcAuthEncoreAuthHash)
.map(str::to_string),
signed_with
);
}
#[test]
fn the_signature_covers_the_gateway_a_request_is_relayed_to() {
let auth = test_auth();
let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
let mut headers = call(&auth, None);
headers.set(MetaKey::Gateway, "api".into()).unwrap();
auth.sign(&mut headers, now).unwrap();
assert!(auth.verify(&headers, now).is_ok());
headers.insert(MetaKey::Gateway.header_key(), "admin".parse().unwrap());
assert!(
matches!(
auth.verify(&headers, now),
Err(VerifyError::SignatureMismatch)
),
"redirected to another gateway"
);
let mut added = call(&auth, None);
added.insert(MetaKey::Gateway.header_key(), "api".parse().unwrap());
assert!(
matches!(
auth.verify(&added, now),
Err(VerifyError::SignatureMismatch)
),
"a gateway added to a call signed without one"
);
}
#[test]
fn the_signature_covers_the_frontend_a_request_is_relayed_to() {
let auth = test_auth();
let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
for (key, changed) in [
(MetaKey::Frontend, "admin"),
(MetaKey::ClientIp, "192.0.2.1"),
(MetaKey::ForwardedHost, "evil.example.com"),
(MetaKey::RelayId, "another"),
] {
let mut headers = call(&auth, None);
headers.set(MetaKey::Frontend, "web".into()).unwrap();
headers
.set(MetaKey::ClientIp, "203.0.113.9".into())
.unwrap();
headers
.set(MetaKey::ForwardedHost, "example.com".into())
.unwrap();
headers.set(MetaKey::RelayId, "relay-1".into()).unwrap();
auth.sign(&mut headers, now).unwrap();
assert!(auth.verify(&headers, now).is_ok());
headers.insert(key.header_key(), changed.parse().unwrap());
assert!(
matches!(
auth.verify(&headers, now),
Err(VerifyError::SignatureMismatch)
),
"{} changed on the way",
key.header_key()
);
}
}
#[test]
fn the_signature_covers_the_service_a_call_is_for() {
let auth = test_auth();
let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
let mut headers = call(&auth, Some("billing"));
assert!(auth.verify(&headers, now).is_ok());
headers.insert(MetaKey::Service.header_key(), "users".parse().unwrap());
assert!(
matches!(
auth.verify(&headers, now),
Err(VerifyError::SignatureMismatch)
),
"redirected to another service"
);
headers.remove(MetaKey::Service.header_key());
assert!(
matches!(
auth.verify(&headers, now),
Err(VerifyError::SignatureMismatch)
),
"the service removed"
);
let mut added = call(&auth, None);
added.insert(MetaKey::Service.header_key(), "billing".parse().unwrap());
assert!(
matches!(
auth.verify(&added, now),
Err(VerifyError::SignatureMismatch)
),
"a service added to a call signed without one"
);
}
fn call_with(auth: &EncoreAuth, fields: &[(&str, &str)]) -> http::HeaderMap {
let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
let mut headers = http::HeaderMap::new();
headers
.set(MetaKey::Caller, "api:checkout.Pay".into())
.unwrap();
for (name, value) in fields {
let name = http::HeaderName::from_bytes(name.as_bytes()).unwrap();
headers.append(name, value.parse().unwrap());
}
auth.sign(&mut headers, now).unwrap();
headers
}
fn mismatch(auth: &EncoreAuth, headers: &http::HeaderMap) -> bool {
let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
matches!(
auth.verify(headers, now),
Err(VerifyError::SignatureMismatch)
)
}
#[test]
fn the_signature_covers_request_context() {
let auth = test_auth();
let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
let user = ("x-encore-meta-ctx-user", "eyJpZCI6MX0");
let tenant = ("x-encore-meta-ctx-tenant", "ImFjbWUi");
let headers = call_with(&auth, &[user, tenant]);
assert!(auth.verify(&headers, now).is_ok());
let mut tampered = headers.clone();
tampered.insert(user.0, "eyJpZCI6Mn0".parse().unwrap());
assert!(mismatch(&auth, &tampered), "a field's value changed");
let mut removed = headers.clone();
removed.remove(tenant.0);
assert!(mismatch(&auth, &removed), "a field removed");
let mut added = headers.clone();
added.insert("x-encore-meta-ctx-plan", "InBybyI".parse().unwrap());
assert!(mismatch(&auth, &added), "a field added");
let mut repeated = headers.clone();
repeated.append(user.0, "eyJpZCI6Mn0".parse().unwrap());
assert!(mismatch(&auth, &repeated), "a second value added");
let mut renamed = headers.clone();
renamed.remove(tenant.0);
renamed.insert("x-encore-meta-ctx-tenant2", tenant.1.parse().unwrap());
assert!(mismatch(&auth, &renamed), "a field renamed");
}
#[test]
fn request_context_is_hashed_in_any_order() {
let auth = test_auth();
let one = call_with(
&auth,
&[
("x-encore-meta-ctx-user", "a"),
("x-encore-meta-ctx-tenant", "b"),
("x-encore-meta-ctx-user", "c"),
],
);
let other = call_with(
&auth,
&[
("x-encore-meta-ctx-tenant", "b"),
("x-encore-meta-ctx-user", "c"),
("x-encore-meta-ctx-user", "a"),
],
);
assert_eq!(
one.get_meta(MetaKey::SvcAuthEncoreAuthHash),
other.get_meta(MetaKey::SvcAuthEncoreAuthHash)
);
assert_ne!(
one.get_meta(MetaKey::SvcAuthEncoreAuthHash),
call_with(&auth, &[]).get_meta(MetaKey::SvcAuthEncoreAuthHash)
);
}
fn auth_for(app_slug: &str, env_name: &str) -> EncoreAuth {
EncoreAuth::for_environment(
app_slug.into(),
env_name.into(),
vec![EncoreAuthKey {
key_id: 123,
data: Box::new(b"secret data".to_vec()),
}],
)
}
#[test]
fn a_call_signed_for_another_environment_is_refused() {
let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
let prod = auth_for("app", "prod");
assert!(prod.verify(&call(&prod, None), now).is_ok());
for (app, env) in [("app", "staging"), ("other", "prod")] {
let headers = call(&auth_for(app, env), None);
assert!(
matches!(
prod.verify(&headers, now),
Err(VerifyError::OtherEnvironment { app_slug, env_name })
if app_slug == app && env_name == env
),
"signed for {app}/{env}"
);
}
}
#[test]
fn a_call_from_a_generated_config_verifies_in_it() {
let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
let auth = auth_for("", "self-hosted");
assert!(auth.verify(&call(&auth, Some("billing")), now).is_ok());
}
#[test]
fn new_accepts_a_call_signed_for_another_environment() {
let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
let staging = call(&auth_for("app", "staging"), None);
assert!(test_auth().verify(&staging, now).is_ok());
}
#[cfg(feature = "pingora")]
#[test]
fn a_signature_made_over_pingora_headers_verifies_over_http_headers() -> anyhow::Result<()> {
let auth = EncoreAuth::new(
"app".into(),
"env".into(),
vec![EncoreAuthKey {
key_id: 1,
data: Box::new(b"secret data".to_vec()),
}],
);
let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
let mut request = pingora_http::RequestHeader::build("POST", b"/orders.Create", None)?;
request.set(MetaKey::Caller, "api:checkout.Pay".into())?;
request.set(MetaKey::Version, "1".into())?;
auth.sign(&mut request, now)?;
let mut forwarded = request.headers.clone();
auth.verify(&forwarded, now)
.context("unable to verify forwarded request")?;
forwarded.insert(MetaKey::Caller.header_key(), "api:admin.Root".parse()?);
assert!(matches!(
auth.verify(&forwarded, now),
Err(VerifyError::SignatureMismatch)
));
Ok(())
}
}