encore-reqauth 2.0.0-beta.9

The wire protocol of Encore's service-to-service request auth
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
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(())
    }
}

/// The secret an [`EncoreAuthKey`] signs with, resolved each time a call is
/// signed or verified — so a key that cannot be resolved fails the calls that
/// use it, not the process.
pub trait KeyData: Send + Sync {
    fn resolve(&self) -> Result<&[u8], Box<dyn std::error::Error + Send + Sync>>;
}

/// Key material that is already resolved.
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, // index into keys
    /// Whether a call signed for another app or environment is refused.
    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 {
    /// Signs calls as the environment `env_name` of the app `app_slug`, and
    /// accepts a call signed with any of `keys` whatever app and environment
    /// it was signed for, as the old runtimes do.
    pub fn new(app_slug: String, env_name: String, keys: Vec<EncoreAuthKey>) -> Self {
        Self::build(app_slug, env_name, keys, false)
    }

    /// Signs calls as the environment `env_name` of the app `app_slug`, and
    /// accepts only calls signed for it, so a key shared between environments
    /// does not let a call signed in one verify in another.
    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>),
    /// The call was signed for another app or environment than the
    /// verifier's, named here as the call names them.
    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);
        }

        // The signature below is rebuilt for the app and environment the call
        // names, so with a key shared between environments it verifies in
        // every one of them.
        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 {
    /// A deterministic hash of the call's metadata: `{header}={value}\n` for
    /// every value of every header covered, sorted by header name, then by
    /// value. A header name has no `=` and a value no newline, so no two sets
    /// of headers hash the same lines, and the order they came in does not
    /// matter. A call without Request Context fields hashes as the old
    /// runtimes hash it.
    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();
        // A relay's: only a gateway relaying a public request sends
        // `Gateway`, or `Frontend`, and with it what the receiving gateway
        // serves the request as. Any other call hashes as the old runtimes
        // hash it, which do not know them.
        let relay = keys.contains(&MetaKey::Gateway) || keys.contains(&MetaKey::Frontend);
        for key in keys {
            use MetaKey::*;
            match key {
                SvcAuthMethod | SvcAuthEncoreAuthHash | SvcAuthEncoreAuthDate => {
                    // Skip these headers, as they are part of the auth mechanism itself.
                }

                TraceParent | TraceState => {
                    // Skip these headers, as they are part of the tracing mechanism and could be changed
                    // by things like load balancers.
                }

                // `Service`, `Gateway` and `Frontend` are only on requests a
                // gateway forwards to another container. Covering them keeps a
                // captured request from being redirected to another service,
                // gateway or frontend.
                XCorrelationId | Version | UserId | UserData | Caller | Callee | Service
                | Gateway | Frontend => {
                    covered.extend(
                        req.meta_values(key)
                            .map(|v| (key.header_key(), v.as_bytes())),
                    );
                }

                // Who a relayed request is served as, the host it is for, and
                // which relay it is: covering them keeps a captured relay from
                // being served as another client's, for another host, or
                // twice.
                ClientIp | ForwardedHost | RelayId if relay => {
                    covered.extend(
                        req.meta_values(key)
                            .map(|v| (key.header_key(), v.as_bytes())),
                    );
                }
                ClientIp | ForwardedHost | RelayId => {}
            }
        }
        // Request Context (parser ADR 0014): set by a gateway or the calling
        // service, and trusted by the service called as the user is.
        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()),
            }],
        )
    }

    /// A call without `x-encore-service` — every call but a gateway's — is
    /// signed over its meta headers alone, as the old runtimes sign it.
    #[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"#
            )
        );
    }

    /// A relay's signature covers who it is served as, the host it is for
    /// and which relay it is, so none of them can be changed on the way.
    #[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()
            );
        }
    }

    /// Any other call hashes as the old runtimes hash it: they do not know the
    /// headers only a relay's signature covers.
    #[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"
        );
    }

    /// A frontend relay is a relay: its signature covers the frontend, and
    /// who it is served as, for which host.
    #[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"
        );
    }

    /// A call signed with `fields`, Request Context header names and values.
    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");
    }

    /// Fields are hashed sorted, so the order a call carries them in, and
    /// the order of a field's values, does not matter.
    #[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)
        );
        // Which is not how a call without them signs. That one signs as the
        // old runtimes sign it: see the fixed signatures above.
        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()),
            }],
        )
    }

    /// Environments may share a key; a call signed in one is still refused in
    /// another.
    #[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}"
            );
        }
    }

    /// `encore infra config generate` names no app, and calls the environment
    /// `self-hosted`.
    #[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());
    }

    /// The old runtimes accept a call signed for any app and environment.
    #[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());
    }

    /// A gateway signs over pingora's request headers, and the service it
    /// forwards to verifies over `http`'s. The crate's tests always build with
    /// `pingora` (see `[dev-dependencies]`), so this runs under a plain
    /// `cargo test -p encore-reqauth`.
    #[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")?;

        // The signature covers the caller identity.
        forwarded.insert(MetaKey::Caller.header_key(), "api:admin.Root".parse()?);
        assert!(matches!(
            auth.verify(&forwarded, now),
            Err(VerifyError::SignatureMismatch)
        ));
        Ok(())
    }
}