1use std::fmt::{Debug, Display};
2use std::time::SystemTime;
3
4use anyhow::Context;
5use sha3::digest::Digest;
6use subtle::ConstantTimeEq;
7
8use crate::encoreauth;
9use crate::encoreauth::{OperationHash, SignatureComponents};
10use crate::meta::{MetaKey, MetaMap, MetaMapMut};
11
12pub trait ServiceAuthMethod: Debug + Send + Sync + 'static {
13 fn name(&self) -> &'static str;
14 fn sign(&self, headers: &mut dyn MetaMapMut, now: SystemTime) -> anyhow::Result<()>;
15 fn verify(&self, headers: &dyn MetaMap, now: SystemTime) -> Result<(), VerifyError>;
16}
17
18#[derive(Debug)]
19pub struct Noop;
20
21impl ServiceAuthMethod for Noop {
22 fn name(&self) -> &'static str {
23 "noop"
24 }
25
26 fn sign(&self, _headers: &mut dyn MetaMapMut, _now: SystemTime) -> anyhow::Result<()> {
27 Ok(())
28 }
29
30 fn verify(&self, _headers: &dyn MetaMap, _now: SystemTime) -> Result<(), VerifyError> {
31 Ok(())
32 }
33}
34
35pub trait KeyData: Send + Sync {
39 fn resolve(&self) -> Result<&[u8], Box<dyn std::error::Error + Send + Sync>>;
40}
41
42impl KeyData for Vec<u8> {
44 fn resolve(&self) -> Result<&[u8], Box<dyn std::error::Error + Send + Sync>> {
45 Ok(self)
46 }
47}
48
49pub struct EncoreAuthKey {
50 pub key_id: u32,
51 pub data: Box<dyn KeyData>,
52}
53
54pub struct EncoreAuth {
55 app_slug: String,
56 env_name: String,
57 keys: Vec<EncoreAuthKey>,
58 latest_idx: usize, own_environment_only: bool,
61}
62
63impl Debug for EncoreAuth {
64 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65 f.debug_struct("EncoreAuth")
66 .field("app_slug", &self.app_slug)
67 .field("env_name", &self.env_name)
68 .field("own_environment_only", &self.own_environment_only)
69 .finish()
70 }
71}
72
73impl EncoreAuth {
74 pub fn new(app_slug: String, env_name: String, keys: Vec<EncoreAuthKey>) -> Self {
78 Self::build(app_slug, env_name, keys, false)
79 }
80
81 pub fn for_environment(app_slug: String, env_name: String, keys: Vec<EncoreAuthKey>) -> Self {
85 Self::build(app_slug, env_name, keys, true)
86 }
87
88 fn build(
89 app_slug: String,
90 env_name: String,
91 keys: Vec<EncoreAuthKey>,
92 own_environment_only: bool,
93 ) -> Self {
94 if keys.is_empty() {
95 panic!("auth keys must not be empty");
96 }
97
98 let latest_idx = {
99 let mut max_id = keys[0].key_id;
100 let mut max_idx = 0;
101 for (idx, k) in keys.iter().enumerate() {
102 if k.key_id > max_id {
103 max_idx = idx;
104 max_id = k.key_id;
105 }
106 }
107 max_idx
108 };
109
110 Self {
111 app_slug,
112 env_name,
113 keys,
114 latest_idx,
115 own_environment_only,
116 }
117 }
118}
119
120#[derive(Debug)]
121pub enum VerifyError {
122 NoAuthorizationHeader,
123 NoDateHeader,
124 InvalidHeader(encoreauth::InvalidSignature),
125 SignatureMismatch,
126 DateSkew,
127 UnknownKey,
128 ResolveKeyData(Box<dyn std::error::Error + Send + Sync>),
129 OtherEnvironment {
132 app_slug: String,
133 env_name: String,
134 },
135}
136
137impl Display for VerifyError {
138 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139 use VerifyError::*;
140 match self {
141 NoAuthorizationHeader => write!(f, "no authorization header"),
142 NoDateHeader => write!(f, "no date header"),
143 InvalidHeader(e) => write!(f, "invalid header: {e}"),
144 SignatureMismatch => write!(f, "signature mismatch"),
145 DateSkew => write!(f, "date skew"),
146 UnknownKey => write!(f, "unknown key"),
147 ResolveKeyData(e) => write!(f, "unable to resolve secret key data: {e}"),
148 OtherEnvironment { app_slug, env_name } => write!(
149 f,
150 "signed for app {app_slug:?} environment {env_name:?}, not this one"
151 ),
152 }
153 }
154}
155
156impl std::error::Error for VerifyError {}
157
158impl ServiceAuthMethod for EncoreAuth {
159 fn name(&self) -> &'static str {
160 "encore-auth"
161 }
162
163 fn sign(&self, headers: &mut dyn MetaMapMut, now: SystemTime) -> anyhow::Result<()> {
164 let op_hash = self.build_op_hash(headers);
165
166 let key = &self.keys[self.latest_idx];
167 let key_data = key
168 .data
169 .resolve()
170 .map_err(|e| anyhow::anyhow!(e))
171 .context("unable to resolve auth key data")?;
172
173 let hash = encoreauth::sign(
174 (key.key_id, key_data),
175 &self.app_slug,
176 &self.env_name,
177 now,
178 &op_hash,
179 );
180
181 headers
182 .set(MetaKey::SvcAuthEncoreAuthHash, hash)
183 .context("set auth hash header")?;
184 headers
185 .set(MetaKey::SvcAuthEncoreAuthDate, httpdate::fmt_http_date(now))
186 .context("set auth date header")?;
187
188 Ok(())
189 }
190
191 fn verify(&self, headers: &dyn MetaMap, now: SystemTime) -> Result<(), VerifyError> {
192 let auth_header = headers
193 .get_meta(MetaKey::SvcAuthEncoreAuthHash)
194 .ok_or(VerifyError::NoAuthorizationHeader)?;
195 let date_header = headers
196 .get_meta(MetaKey::SvcAuthEncoreAuthDate)
197 .ok_or(VerifyError::NoDateHeader)?;
198
199 let components = SignatureComponents::parse(auth_header, date_header)
200 .map_err(VerifyError::InvalidHeader)?;
201
202 let diff = now
203 .duration_since(components.timestamp)
204 .unwrap_or_else(|e| e.duration());
205 if diff.as_secs() > 120 {
206 return Err(VerifyError::DateSkew);
207 }
208
209 if self.own_environment_only
213 && (components.app_slug != self.app_slug || components.env_name != self.env_name)
214 {
215 return Err(VerifyError::OtherEnvironment {
216 app_slug: components.app_slug,
217 env_name: components.env_name,
218 });
219 }
220
221 let key = self
222 .keys
223 .iter()
224 .find(|k| k.key_id == components.key_id)
225 .ok_or(VerifyError::UnknownKey)?;
226
227 let key_data = key.data.resolve().map_err(VerifyError::ResolveKeyData)?;
228 let expected_signature = encoreauth::sign_for_verification(
229 (key.key_id, key_data),
230 &components.app_slug,
231 &components.env_name,
232 components.timestamp,
233 &components.operation_hash,
234 );
235
236 let signature_match: bool = expected_signature
237 .as_bytes()
238 .ct_eq(auth_header.as_bytes())
239 .into();
240 if !signature_match {
241 return Err(VerifyError::SignatureMismatch);
242 }
243
244 let expected_op_hash = self.build_op_hash(headers);
245 if !expected_op_hash.ct_eq(&components.operation_hash) {
246 return Err(VerifyError::SignatureMismatch);
247 }
248
249 Ok(())
250 }
251}
252
253impl EncoreAuth {
254 fn build_op_hash<R: MetaMap + ?Sized>(&self, req: &R) -> OperationHash {
261 let mut covered: Vec<(&str, &[u8])> = Vec::new();
262 let keys = req.sorted_meta_keys();
263 let relay = keys.contains(&MetaKey::Gateway) || keys.contains(&MetaKey::Frontend);
268 for key in keys {
269 use MetaKey::*;
270 match key {
271 SvcAuthMethod | SvcAuthEncoreAuthHash | SvcAuthEncoreAuthDate => {
272 }
274
275 TraceParent | TraceState => {
276 }
279
280 XCorrelationId | Version | UserId | UserData | Caller | Callee | Service
285 | Gateway | Frontend => {
286 covered.extend(
287 req.meta_values(key)
288 .map(|v| (key.header_key(), v.as_bytes())),
289 );
290 }
291
292 ClientIp | ForwardedHost | RelayId if relay => {
297 covered.extend(
298 req.meta_values(key)
299 .map(|v| (key.header_key(), v.as_bytes())),
300 );
301 }
302 ClientIp | ForwardedHost | RelayId => {}
303 }
304 }
305 covered.extend(req.ctx_fields());
308 covered.sort_unstable();
309
310 let mut hash = <sha3::Sha3_256 as Digest>::new();
311 for (name, value) in covered {
312 hash.update(name);
313 hash.update(b"=");
314 hash.update(value);
315 hash.update(b"\n");
316 }
317
318 let payload = hash.finalize();
319 OperationHash::new(
320 "internal-api".as_bytes(),
321 "call".as_bytes(),
322 Some(payload.as_slice()),
323 std::iter::empty(),
324 )
325 }
326}
327
328#[cfg(test)]
329mod tests {
330 use super::*;
331
332 fn metas<R: MetaMap>(req: &R) -> Vec<(MetaKey, Vec<String>)> {
333 let keys = req.sorted_meta_keys();
334 keys.into_iter()
335 .map(|k| {
336 (
337 k,
338 req.meta_values(k)
339 .map(|s| s.to_string())
340 .collect::<Vec<_>>(),
341 )
342 })
343 .collect()
344 }
345
346 #[test]
347 fn test_encore_auth() -> anyhow::Result<()> {
348 let mut headers = http::HeaderMap::new();
349
350 let auth = EncoreAuth {
351 app_slug: "app".into(),
352 env_name: "env".into(),
353 keys: vec![EncoreAuthKey {
354 key_id: 123,
355 data: Box::new(b"secret data".to_vec()),
356 }],
357 latest_idx: 0,
358 own_environment_only: false,
359 };
360
361 let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
362 auth.sign(&mut headers, now)
363 .context("unable to sign request")?;
364
365 auth.verify(&headers, now)
366 .context("unable to verify request")?;
367
368 assert_eq!(
369 metas(&headers),
370 vec![
371 (
372 MetaKey::SvcAuthEncoreAuthDate,
373 vec!["Fri, 13 Feb 2009 23:31:30 GMT".to_string()]
374 ),
375 (MetaKey::SvcAuthEncoreAuthHash, vec![r#"ENCORE1-HMAC-SHA3-256 cred="20090213/app/env/123", op=f3c70a419394ce9d56efafad2208154b92c8596d7396b3a2b4ea7fd925d28dc2, sig=fc0c88b47c13d999353ecc8681d91d9c03209a1f05583b92d84e429fedfe387a"#.to_string()]),
376 ]
377 );
378
379 Ok(())
380 }
381
382 fn call(auth: &EncoreAuth, service: Option<&str>) -> http::HeaderMap {
383 let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
384 let mut headers = http::HeaderMap::new();
385 headers.set(MetaKey::Version, "1".into()).unwrap();
386 headers
387 .set(MetaKey::Caller, "api:checkout.Pay".into())
388 .unwrap();
389 headers
390 .set(MetaKey::Callee, "billing.Charge".into())
391 .unwrap();
392 if let Some(service) = service {
393 headers.set(MetaKey::Service, service.into()).unwrap();
394 }
395 auth.sign(&mut headers, now).unwrap();
396 headers
397 }
398
399 fn test_auth() -> EncoreAuth {
400 EncoreAuth::new(
401 "app".into(),
402 "env".into(),
403 vec![EncoreAuthKey {
404 key_id: 123,
405 data: Box::new(b"secret data".to_vec()),
406 }],
407 )
408 }
409
410 #[test]
413 fn a_call_without_a_service_header_is_signed_over_its_meta_alone() {
414 let headers = call(&test_auth(), None);
415 assert_eq!(
416 headers.get_meta(MetaKey::SvcAuthEncoreAuthHash),
417 Some(
418 r#"ENCORE1-HMAC-SHA3-256 cred="20090213/app/env/123", op=65d66c2cb4ed3d3b8906ddb00b06048a8ee53feef398fad74cc4e756ffa7ca1a, sig=67bed7676bbd90dc2e3b01c16a70b34b66d009b591fc2ed1631bf5fafb5991f0"#
419 )
420 );
421 }
422
423 #[test]
426 fn a_relays_signature_covers_its_client_host_and_id() {
427 let auth = test_auth();
428 let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
429 for (key, changed) in [
430 (MetaKey::ClientIp, "192.0.2.1"),
431 (MetaKey::ForwardedHost, "evil.example.com"),
432 (MetaKey::RelayId, "another"),
433 ] {
434 let mut headers = call(&auth, None);
435 headers.set(MetaKey::Gateway, "api".into()).unwrap();
436 headers
437 .set(MetaKey::ClientIp, "203.0.113.9".into())
438 .unwrap();
439 headers
440 .set(MetaKey::ForwardedHost, "api.example.com".into())
441 .unwrap();
442 headers.set(MetaKey::RelayId, "relay-1".into()).unwrap();
443 auth.sign(&mut headers, now).unwrap();
444 assert!(auth.verify(&headers, now).is_ok());
445
446 headers.insert(key.header_key(), changed.parse().unwrap());
447 assert!(
448 matches!(
449 auth.verify(&headers, now),
450 Err(VerifyError::SignatureMismatch)
451 ),
452 "{} changed on the way",
453 key.header_key()
454 );
455 }
456 }
457
458 #[test]
461 fn a_call_that_is_no_relay_is_not_signed_over_a_relays_headers() {
462 let auth = test_auth();
463 let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
464 let mut headers = call(&auth, Some("users"));
465 headers
466 .set(MetaKey::ForwardedHost, "api.example.com".into())
467 .unwrap();
468 auth.sign(&mut headers, now).unwrap();
469 let signed_with = headers
470 .get_meta(MetaKey::SvcAuthEncoreAuthHash)
471 .map(str::to_string);
472
473 let mut without = call(&auth, Some("users"));
474 auth.sign(&mut without, now).unwrap();
475 assert_eq!(
476 without
477 .get_meta(MetaKey::SvcAuthEncoreAuthHash)
478 .map(str::to_string),
479 signed_with
480 );
481 }
482
483 #[test]
484 fn the_signature_covers_the_gateway_a_request_is_relayed_to() {
485 let auth = test_auth();
486 let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
487 let mut headers = call(&auth, None);
488 headers.set(MetaKey::Gateway, "api".into()).unwrap();
489 auth.sign(&mut headers, now).unwrap();
490 assert!(auth.verify(&headers, now).is_ok());
491
492 headers.insert(MetaKey::Gateway.header_key(), "admin".parse().unwrap());
493 assert!(
494 matches!(
495 auth.verify(&headers, now),
496 Err(VerifyError::SignatureMismatch)
497 ),
498 "redirected to another gateway"
499 );
500
501 let mut added = call(&auth, None);
502 added.insert(MetaKey::Gateway.header_key(), "api".parse().unwrap());
503 assert!(
504 matches!(
505 auth.verify(&added, now),
506 Err(VerifyError::SignatureMismatch)
507 ),
508 "a gateway added to a call signed without one"
509 );
510 }
511
512 #[test]
515 fn the_signature_covers_the_frontend_a_request_is_relayed_to() {
516 let auth = test_auth();
517 let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
518 for (key, changed) in [
519 (MetaKey::Frontend, "admin"),
520 (MetaKey::ClientIp, "192.0.2.1"),
521 (MetaKey::ForwardedHost, "evil.example.com"),
522 (MetaKey::RelayId, "another"),
523 ] {
524 let mut headers = call(&auth, None);
525 headers.set(MetaKey::Frontend, "web".into()).unwrap();
526 headers
527 .set(MetaKey::ClientIp, "203.0.113.9".into())
528 .unwrap();
529 headers
530 .set(MetaKey::ForwardedHost, "example.com".into())
531 .unwrap();
532 headers.set(MetaKey::RelayId, "relay-1".into()).unwrap();
533 auth.sign(&mut headers, now).unwrap();
534 assert!(auth.verify(&headers, now).is_ok());
535
536 headers.insert(key.header_key(), changed.parse().unwrap());
537 assert!(
538 matches!(
539 auth.verify(&headers, now),
540 Err(VerifyError::SignatureMismatch)
541 ),
542 "{} changed on the way",
543 key.header_key()
544 );
545 }
546 }
547
548 #[test]
549 fn the_signature_covers_the_service_a_call_is_for() {
550 let auth = test_auth();
551 let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
552 let mut headers = call(&auth, Some("billing"));
553 assert!(auth.verify(&headers, now).is_ok());
554
555 headers.insert(MetaKey::Service.header_key(), "users".parse().unwrap());
556 assert!(
557 matches!(
558 auth.verify(&headers, now),
559 Err(VerifyError::SignatureMismatch)
560 ),
561 "redirected to another service"
562 );
563
564 headers.remove(MetaKey::Service.header_key());
565 assert!(
566 matches!(
567 auth.verify(&headers, now),
568 Err(VerifyError::SignatureMismatch)
569 ),
570 "the service removed"
571 );
572
573 let mut added = call(&auth, None);
574 added.insert(MetaKey::Service.header_key(), "billing".parse().unwrap());
575 assert!(
576 matches!(
577 auth.verify(&added, now),
578 Err(VerifyError::SignatureMismatch)
579 ),
580 "a service added to a call signed without one"
581 );
582 }
583
584 fn call_with(auth: &EncoreAuth, fields: &[(&str, &str)]) -> http::HeaderMap {
586 let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
587 let mut headers = http::HeaderMap::new();
588 headers
589 .set(MetaKey::Caller, "api:checkout.Pay".into())
590 .unwrap();
591 for (name, value) in fields {
592 let name = http::HeaderName::from_bytes(name.as_bytes()).unwrap();
593 headers.append(name, value.parse().unwrap());
594 }
595 auth.sign(&mut headers, now).unwrap();
596 headers
597 }
598
599 fn mismatch(auth: &EncoreAuth, headers: &http::HeaderMap) -> bool {
600 let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
601 matches!(
602 auth.verify(headers, now),
603 Err(VerifyError::SignatureMismatch)
604 )
605 }
606
607 #[test]
608 fn the_signature_covers_request_context() {
609 let auth = test_auth();
610 let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
611 let user = ("x-encore-meta-ctx-user", "eyJpZCI6MX0");
612 let tenant = ("x-encore-meta-ctx-tenant", "ImFjbWUi");
613 let headers = call_with(&auth, &[user, tenant]);
614 assert!(auth.verify(&headers, now).is_ok());
615
616 let mut tampered = headers.clone();
617 tampered.insert(user.0, "eyJpZCI6Mn0".parse().unwrap());
618 assert!(mismatch(&auth, &tampered), "a field's value changed");
619
620 let mut removed = headers.clone();
621 removed.remove(tenant.0);
622 assert!(mismatch(&auth, &removed), "a field removed");
623
624 let mut added = headers.clone();
625 added.insert("x-encore-meta-ctx-plan", "InBybyI".parse().unwrap());
626 assert!(mismatch(&auth, &added), "a field added");
627
628 let mut repeated = headers.clone();
629 repeated.append(user.0, "eyJpZCI6Mn0".parse().unwrap());
630 assert!(mismatch(&auth, &repeated), "a second value added");
631
632 let mut renamed = headers.clone();
633 renamed.remove(tenant.0);
634 renamed.insert("x-encore-meta-ctx-tenant2", tenant.1.parse().unwrap());
635 assert!(mismatch(&auth, &renamed), "a field renamed");
636 }
637
638 #[test]
641 fn request_context_is_hashed_in_any_order() {
642 let auth = test_auth();
643 let one = call_with(
644 &auth,
645 &[
646 ("x-encore-meta-ctx-user", "a"),
647 ("x-encore-meta-ctx-tenant", "b"),
648 ("x-encore-meta-ctx-user", "c"),
649 ],
650 );
651 let other = call_with(
652 &auth,
653 &[
654 ("x-encore-meta-ctx-tenant", "b"),
655 ("x-encore-meta-ctx-user", "c"),
656 ("x-encore-meta-ctx-user", "a"),
657 ],
658 );
659 assert_eq!(
660 one.get_meta(MetaKey::SvcAuthEncoreAuthHash),
661 other.get_meta(MetaKey::SvcAuthEncoreAuthHash)
662 );
663 assert_ne!(
666 one.get_meta(MetaKey::SvcAuthEncoreAuthHash),
667 call_with(&auth, &[]).get_meta(MetaKey::SvcAuthEncoreAuthHash)
668 );
669 }
670
671 fn auth_for(app_slug: &str, env_name: &str) -> EncoreAuth {
672 EncoreAuth::for_environment(
673 app_slug.into(),
674 env_name.into(),
675 vec![EncoreAuthKey {
676 key_id: 123,
677 data: Box::new(b"secret data".to_vec()),
678 }],
679 )
680 }
681
682 #[test]
685 fn a_call_signed_for_another_environment_is_refused() {
686 let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
687 let prod = auth_for("app", "prod");
688 assert!(prod.verify(&call(&prod, None), now).is_ok());
689
690 for (app, env) in [("app", "staging"), ("other", "prod")] {
691 let headers = call(&auth_for(app, env), None);
692 assert!(
693 matches!(
694 prod.verify(&headers, now),
695 Err(VerifyError::OtherEnvironment { app_slug, env_name })
696 if app_slug == app && env_name == env
697 ),
698 "signed for {app}/{env}"
699 );
700 }
701 }
702
703 #[test]
706 fn a_call_from_a_generated_config_verifies_in_it() {
707 let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
708 let auth = auth_for("", "self-hosted");
709 assert!(auth.verify(&call(&auth, Some("billing")), now).is_ok());
710 }
711
712 #[test]
714 fn new_accepts_a_call_signed_for_another_environment() {
715 let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
716 let staging = call(&auth_for("app", "staging"), None);
717 assert!(test_auth().verify(&staging, now).is_ok());
718 }
719
720 #[cfg(feature = "pingora")]
725 #[test]
726 fn a_signature_made_over_pingora_headers_verifies_over_http_headers() -> anyhow::Result<()> {
727 let auth = EncoreAuth::new(
728 "app".into(),
729 "env".into(),
730 vec![EncoreAuthKey {
731 key_id: 1,
732 data: Box::new(b"secret data".to_vec()),
733 }],
734 );
735 let now = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567890);
736
737 let mut request = pingora_http::RequestHeader::build("POST", b"/orders.Create", None)?;
738 request.set(MetaKey::Caller, "api:checkout.Pay".into())?;
739 request.set(MetaKey::Version, "1".into())?;
740 auth.sign(&mut request, now)?;
741
742 let mut forwarded = request.headers.clone();
743 auth.verify(&forwarded, now)
744 .context("unable to verify forwarded request")?;
745
746 forwarded.insert(MetaKey::Caller.header_key(), "api:admin.Root".parse()?);
748 assert!(matches!(
749 auth.verify(&forwarded, now),
750 Err(VerifyError::SignatureMismatch)
751 ));
752 Ok(())
753 }
754}