Skip to main content

flamingo_verifier_client/
config.rs

1//! Configuration for the verifier client.
2//!
3//! Follows the shape `world-id-protocol` uses for authenticator configuration. Configuration
4//! is explicit — nothing is read from the environment.
5
6use std::time::Duration;
7
8use serde::{Deserialize, Serialize};
9
10use crate::client::Attestations;
11use crate::error::Error;
12use url::Url;
13
14use flamingo_verifier_sealed_types::MAX_ATTESTATION_AGE;
15use pontifex::attestation::{PcrConfig, PcrMeasurement, Verifier};
16
17/// Default freshness bound, matching the few-hour lifetime of a Nitro certificate.
18const fn default_max_attestation_age_millis() -> u64 {
19    60 * 60 * 1000
20}
21
22const fn default_connect_timeout_millis() -> u64 {
23    5_000
24}
25
26const fn default_request_timeout_millis() -> u64 {
27    60_000
28}
29
30/// WIP-201 §4.6 step 3: at most 8 slots, so a response's timing reveals at most 3 bits.
31const fn default_max_response_slots() -> usize {
32    8
33}
34
35/// Configuration to interact with a Flamingo Verifier host.
36#[derive(Clone, Debug, Serialize, Deserialize)]
37#[serde(deny_unknown_fields)]
38pub struct Config {
39    /// Base URL of the host, e.g. `https://verifier.example.com`.
40    host_url: Url,
41    /// Measurements to trust. A document is accepted if it matches any one configuration in
42    /// full, which lets several enclave versions be trusted at once during a rollout.
43    #[serde(default, with = "pcr_configs")]
44    allowed_pcr_configs: Vec<Vec<PcrMeasurement>>,
45    /// Explicit development-only bypass of all PCR measurement checks.
46    #[serde(default)]
47    dangerously_skip_measurements: bool,
48    /// Test-only acceptance of the unsigned attestations of a `dev` Verifier instead of Nitro's.
49    #[cfg(feature = "dev")]
50    #[serde(default)]
51    dangerously_accept_dev_attestation: bool,
52    /// How old an attestation document's own timestamp may be.
53    #[serde(default = "default_max_attestation_age_millis")]
54    max_attestation_age_millis: u64,
55    /// Bound on establishing a connection.
56    #[serde(default = "default_connect_timeout_millis")]
57    connect_timeout_millis: u64,
58    /// Bound on a whole exchange.
59    #[serde(default = "default_request_timeout_millis")]
60    request_timeout_millis: u64,
61    /// Most response slots a pipeline may list before the client sends biometrics to it.
62    #[serde(default = "default_max_response_slots")]
63    max_response_slots: usize,
64}
65
66impl Config {
67    /// Instantiates a configuration with the default bounds.
68    ///
69    /// # Errors
70    ///
71    /// Returns an error if `host_url` is not a valid URL or the measurement policy fails
72    /// the requirements of [`Self::verifier`].
73    pub fn new(
74        host_url: &str,
75        allowed_pcr_configs: Vec<Vec<PcrMeasurement>>,
76    ) -> Result<Self, Error> {
77        Self::new_inner(host_url, allowed_pcr_configs, false)
78    }
79
80    /// Creates a configuration that bypasses all PCR measurement checks.
81    ///
82    /// No measurements are required. Certificate chain, signature, freshness, and
83    /// channel public-key commitment verification remain enabled.
84    ///
85    /// # Warning
86    /// Accepts any enclave code with otherwise valid attestation, including Nitro
87    /// debug enclaves. Use only for development, never in production.
88    ///
89    /// # Errors
90    ///
91    /// Returns an error if `host_url` is not a valid URL.
92    pub fn dangerously_skip_measurements(host_url: &str) -> Result<Self, Error> {
93        Self::new_inner(host_url, vec![], true)
94    }
95
96    /// Creates a configuration that accepts only the unsigned attestations of an in-process `dev`
97    /// Verifier, with the channel key commitment and `release_hash` bound as for Nitro documents.
98    ///
99    /// # Warning
100    /// Nothing proves the Verifier runs in an enclave. Use only in tests, never in production.
101    ///
102    /// # Errors
103    ///
104    /// Returns an error if `host_url` is not a valid URL.
105    #[cfg(feature = "dev")]
106    pub fn dangerously_accept_dev_attestation(host_url: &str) -> Result<Self, Error> {
107        let mut config = Self::new_inner(host_url, vec![], true)?;
108        config.dangerously_accept_dev_attestation = true;
109        Ok(config)
110    }
111
112    fn new_inner(
113        host_url: &str,
114        allowed_pcr_configs: Vec<Vec<PcrMeasurement>>,
115        dangerously_skip_measurements: bool,
116    ) -> Result<Self, Error> {
117        let host_url = Url::parse(host_url).map_err(|error| Error::InvalidConfig {
118            attribute: "host_url".to_string(),
119            reason: error.to_string(),
120        })?;
121
122        let config = Self {
123            host_url,
124            allowed_pcr_configs,
125            dangerously_skip_measurements,
126            #[cfg(feature = "dev")]
127            dangerously_accept_dev_attestation: false,
128            max_attestation_age_millis: default_max_attestation_age_millis(),
129            connect_timeout_millis: default_connect_timeout_millis(),
130            request_timeout_millis: default_request_timeout_millis(),
131            max_response_slots: default_max_response_slots(),
132        };
133        config.validate()?;
134
135        Ok(config)
136    }
137
138    /// Bounds how old an attestation document's own timestamp may be.
139    #[must_use]
140    pub fn with_max_attestation_age(mut self, max_age: Duration) -> Self {
141        self.max_attestation_age_millis = u64::try_from(max_age.as_millis()).unwrap_or(u64::MAX);
142        self
143    }
144
145    /// Bounds each WebSocket exchange phase. Connecting uses `connect_timeout_millis` instead.
146    #[must_use]
147    pub fn with_request_timeout(mut self, timeout: Duration) -> Self {
148        self.request_timeout_millis = u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX);
149        self
150    }
151
152    /// Bounds how many response slots a pipeline may list (WIP-201 §4.6 step 3).
153    #[must_use]
154    pub const fn with_max_response_slots(mut self, max_slots: usize) -> Self {
155        self.max_response_slots = max_slots;
156        self
157    }
158
159    /// Loads a configuration from JSON.
160    ///
161    /// # Errors
162    ///
163    /// Returns an error if the JSON is invalid or the resulting configuration is not usable.
164    pub fn from_json(json: &str) -> Result<Self, Error> {
165        let config: Self = serde_json::from_str(json)
166            .map_err(|error| Error::MalformedConfig(error.to_string()))?;
167        config.validate()?;
168
169        Ok(config)
170    }
171
172    /// Validates the measurement policy before constructing the verifier.
173    fn validate(&self) -> Result<(), Error> {
174        #[cfg(feature = "dev")]
175        if self.dangerously_accept_dev_attestation && !self.dangerously_skip_measurements {
176            return Err(Error::InvalidConfig {
177                attribute: "dangerously_accept_dev_attestation".to_owned(),
178                reason: "requires dangerously_skip_measurements".to_owned(),
179            });
180        }
181        self.verifier().map(|_| ())
182    }
183
184    /// Builds a Pontifex verifier applying the configured measurements and freshness bound.
185    ///
186    /// # Errors
187    ///
188    /// Rejects a zero `max_response_slots`, and a zero age or one above WIP-201
189    /// `MAX_ATTESTATION_AGE`. Without the explicit measurement bypass, also rejects an empty
190    /// policy, missing or zero PCR0–2, duplicate indices, or malformed measurements.
191    pub fn verifier(&self) -> Result<Verifier, Error> {
192        // Checked here, not only in `validate`, so the builder methods cannot bypass it.
193        if self.max_response_slots == 0 {
194            return Err(Error::InvalidConfig {
195                attribute: "max_response_slots".to_owned(),
196                reason: "must be nonzero".to_owned(),
197            });
198        }
199        let max_age = Duration::from_millis(self.max_attestation_age_millis);
200        if max_age.is_zero() || max_age > MAX_ATTESTATION_AGE {
201            return Err(Error::InvalidConfig {
202                attribute: "max_attestation_age_millis".to_owned(),
203                reason: "must be nonzero and at most WIP-201 MAX_ATTESTATION_AGE (3 hours)"
204                    .to_owned(),
205            });
206        }
207        if self.dangerously_skip_measurements {
208            return Ok(Verifier::new(vec![], max_age).dangerously_skip_measurements());
209        }
210        let invalid = || Error::InvalidConfig {
211            attribute: "allowed_pcr_configs".to_owned(),
212            reason: "each configuration must pin nonzero 48-byte PCR0, PCR1 and PCR2; \
213                     all measurements must be 48 bytes with unique indices"
214                .to_owned(),
215        };
216        if self.allowed_pcr_configs.is_empty() {
217            return Err(invalid());
218        }
219        let mut configs = Vec::new();
220        for measurements in &self.allowed_pcr_configs {
221            let mut indices = std::collections::BTreeSet::new();
222            if measurements
223                .iter()
224                .any(|pcr| pcr.value.len() != 48 || !indices.insert(pcr.index))
225            {
226                return Err(invalid());
227            }
228            // WIP-201 §3.7: PCR0–2 together are the Verifier's measurement.
229            let pinned = |index| {
230                measurements
231                    .iter()
232                    .any(|pcr| pcr.index == index && pcr.value.iter().any(|&byte| byte != 0))
233            };
234            if !(0..=2).all(pinned) {
235                return Err(invalid());
236            }
237            let pcr0 = measurements
238                .iter()
239                .find(|pcr| pcr.index == 0)
240                .ok_or_else(invalid)?;
241            let image = <[u8; 48]>::try_from(pcr0.value.as_slice()).map_err(|_| invalid())?;
242            if image == [0; 48] {
243                return Err(invalid());
244            }
245            let mut config = PcrConfig::new(image);
246            for pcr in measurements.iter().filter(|pcr| pcr.index != 0) {
247                config = config.with_pcr(pcr.index, pcr.value.clone());
248            }
249            configs.push(config);
250        }
251        Ok(Verifier::new(configs, max_age))
252    }
253
254    /// How the client verifies the enclave's attestations, after [`Self::verifier`] validated the
255    /// configuration.
256    pub(crate) fn attestations(&self) -> Result<Attestations, Error> {
257        let verifier = self.verifier()?;
258        #[cfg(feature = "dev")]
259        if self.dangerously_accept_dev_attestation {
260            return Ok(Attestations::Dev {
261                max_age: Duration::from_millis(self.max_attestation_age_millis),
262            });
263        }
264        Ok(Attestations::Nitro(verifier))
265    }
266
267    /// The host to call.
268    #[must_use]
269    pub const fn host_url(&self) -> &Url {
270        &self.host_url
271    }
272
273    /// Bound on establishing a connection.
274    #[must_use]
275    pub const fn connect_timeout(&self) -> Duration {
276        Duration::from_millis(self.connect_timeout_millis)
277    }
278
279    /// Bound on a whole exchange.
280    #[must_use]
281    pub const fn request_timeout(&self) -> Duration {
282        Duration::from_millis(self.request_timeout_millis)
283    }
284
285    /// Most response slots a pipeline may list before the client sends biometrics to it.
286    #[must_use]
287    pub const fn max_response_slots(&self) -> usize {
288        self.max_response_slots
289    }
290}
291
292mod pcr_configs {
293    use pontifex::PcrMeasurement;
294    use serde::{Deserialize, Serialize};
295
296    #[derive(Serialize, Deserialize)]
297    struct Measurement {
298        index: u32,
299        #[serde(
300            serialize_with = "hex::serde::serialize",
301            deserialize_with = "deserialize_pcr"
302        )]
303        value: Vec<u8>,
304    }
305
306    fn deserialize_pcr<'de, D: serde::Deserializer<'de>>(
307        deserializer: D,
308    ) -> Result<Vec<u8>, D::Error> {
309        let value = String::deserialize(deserializer)?;
310        hex::decode(value.strip_prefix("0x").unwrap_or(&value)).map_err(serde::de::Error::custom)
311    }
312
313    pub(super) fn serialize<S: serde::Serializer>(
314        configs: &[Vec<PcrMeasurement>],
315        serializer: S,
316    ) -> Result<S::Ok, S::Error> {
317        let configs: Vec<Vec<Measurement>> = configs
318            .iter()
319            .map(|measurements| {
320                measurements
321                    .iter()
322                    .map(|pcr| Measurement {
323                        index: pcr.index,
324                        value: pcr.value.clone(),
325                    })
326                    .collect()
327            })
328            .collect();
329        configs.serialize(serializer)
330    }
331
332    pub(super) fn deserialize<'de, D: serde::Deserializer<'de>>(
333        deserializer: D,
334    ) -> Result<Vec<Vec<PcrMeasurement>>, D::Error> {
335        let configs = Vec::<Vec<Measurement>>::deserialize(deserializer)?;
336        Ok(configs
337            .into_iter()
338            .map(|measurements| {
339                measurements
340                    .into_iter()
341                    .map(|pcr| PcrMeasurement::new(pcr.index, pcr.value))
342                    .collect()
343            })
344            .collect())
345    }
346}
347
348#[cfg(test)]
349mod tests {
350    use std::time::Duration;
351
352    use super::PcrMeasurement;
353    use super::{Config, MAX_ATTESTATION_AGE};
354    use crate::error::Error;
355
356    fn pcrs() -> Vec<Vec<PcrMeasurement>> {
357        vec![
358            (0..=2)
359                .map(|index| PcrMeasurement::new(index, [0xab; 48]))
360                .collect(),
361        ]
362    }
363
364    #[test]
365    fn rejects_a_configuration_that_pins_nothing() {
366        let error = Config::new("http://localhost:8000", Vec::new())
367            .expect_err("an empty policy must fail closed");
368
369        assert!(matches!(error, Error::InvalidConfig { .. }));
370    }
371
372    #[test]
373    fn attestation_age_is_bounded_by_wip_201() {
374        let config = Config::new("http://localhost:8000", pcrs()).unwrap();
375        assert!(
376            config
377                .clone()
378                .with_max_attestation_age(MAX_ATTESTATION_AGE)
379                .verifier()
380                .is_ok()
381        );
382        for age in [
383            Duration::ZERO,
384            Duration::from_secs(10_800) + Duration::from_millis(1),
385            Duration::from_hours(24),
386        ] {
387            assert!(matches!(
388                config.clone().with_max_attestation_age(age).verifier(),
389                Err(Error::InvalidConfig { .. })
390            ));
391        }
392    }
393
394    #[test]
395    fn a_zero_slot_budget_is_rejected_whichever_way_it_is_set() {
396        let config = Config::new("http://localhost:8000", pcrs()).unwrap();
397        assert!(matches!(
398            config.clone().with_max_response_slots(0).verifier(),
399            Err(Error::InvalidConfig { .. })
400        ));
401        assert!(matches!(
402            crate::FlamingoVerifierClient::new(config.clone().with_max_response_slots(0)),
403            Err(Error::InvalidConfig { .. })
404        ));
405        let mut json = serde_json::to_value(&config).unwrap();
406        json["max_response_slots"] = 0.into();
407        assert!(Config::from_json(&json.to_string()).is_err());
408    }
409
410    #[test]
411    fn requires_each_release_measurement_even_when_pcr0_is_pinned() {
412        for missing in 0..=2 {
413            let mut policy = pcrs().pop().unwrap();
414            policy.retain(|pcr| pcr.index != missing);
415            assert!(Config::new("http://localhost:8000", vec![policy]).is_err());
416            let mut policy = pcrs().pop().unwrap();
417            policy
418                .iter_mut()
419                .find(|pcr| pcr.index == missing)
420                .unwrap()
421                .value
422                .fill(0);
423            assert!(Config::new("http://localhost:8000", vec![policy]).is_err());
424        }
425    }
426
427    #[test]
428    fn rejects_an_invalid_host_url() {
429        let error =
430            Config::new("not a url", pcrs()).expect_err("an unparseable URL must be rejected");
431
432        assert!(matches!(error, Error::InvalidConfig { .. }));
433    }
434
435    #[test]
436    fn rejects_missing_zero_malformed_and_duplicate_measurements() {
437        let policies = [
438            vec![],
439            vec![PcrMeasurement::new(1, [0xab; 48])],
440            vec![PcrMeasurement::new(0, [0; 48])],
441            vec![PcrMeasurement::new(0, [0xab; 32])],
442            vec![
443                PcrMeasurement::new(0, [0xab; 48]),
444                PcrMeasurement::new(1, [0xab; 32]),
445            ],
446            vec![
447                PcrMeasurement::new(0, [0xab; 48]),
448                PcrMeasurement::new(0, [0xcd; 48]),
449            ],
450        ];
451        for policy in policies {
452            let error = Config::new("http://localhost:8000", vec![policy]).unwrap_err();
453            assert!(matches!(error, Error::InvalidConfig { .. }));
454        }
455    }
456
457    #[test]
458    fn deserialization_cannot_bypass_client_policy_validation() {
459        let config: Config = serde_json::from_value(serde_json::json!({
460            "host_url": "http://localhost:8000",
461            "allowed_pcr_configs": []
462        }))
463        .unwrap();
464        assert!(matches!(
465            crate::FlamingoVerifierClient::new(config),
466            Err(Error::InvalidConfig { .. })
467        ));
468    }
469
470    #[test]
471    fn measurement_skip_is_explicit_and_survives_json_round_trip() {
472        assert!(Config::dangerously_skip_measurements("not a URL").is_err());
473        let config = Config::dangerously_skip_measurements("http://localhost:8000").unwrap();
474        assert!(config.verifier().is_ok());
475        let mut json = serde_json::to_value(config).unwrap();
476        assert_eq!(json["dangerously_skip_measurements"], true);
477        assert_eq!(json["allowed_pcr_configs"], serde_json::json!([]));
478        assert!(
479            Config::from_json(&json.to_string())
480                .unwrap()
481                .verifier()
482                .is_ok()
483        );
484        json.as_object_mut().unwrap().remove("allowed_pcr_configs");
485        assert!(
486            Config::from_json(&json.to_string())
487                .unwrap()
488                .verifier()
489                .is_ok()
490        );
491        json.as_object_mut()
492            .unwrap()
493            .remove("dangerously_skip_measurements");
494        assert!(Config::from_json(&json.to_string()).is_err());
495        json["dangerously_skip_measurements"] = serde_json::json!(false);
496        assert!(Config::from_json(&json.to_string()).is_err());
497        json.as_object_mut()
498            .unwrap()
499            .remove("dangerously_skip_measurements");
500        json["allow_debug_measurements"] = serde_json::json!(true);
501        assert!(Config::from_json(&json.to_string()).is_err());
502    }
503
504    #[cfg(not(feature = "dev"))]
505    #[test]
506    fn dev_attestations_need_the_dev_feature() {
507        let mut json = serde_json::to_value(
508            Config::dangerously_skip_measurements("http://localhost:8000").unwrap(),
509        )
510        .unwrap();
511        json["dangerously_accept_dev_attestation"] = serde_json::json!(true);
512        assert!(Config::from_json(&json.to_string()).is_err());
513    }
514
515    #[cfg(feature = "dev")]
516    #[test]
517    fn dev_attestations_are_explicit_and_survive_json_round_trip() {
518        use crate::client::Attestations;
519
520        let nitro = Config::dangerously_skip_measurements("http://localhost:8000").unwrap();
521        assert!(matches!(nitro.attestations(), Ok(Attestations::Nitro(_))));
522        let config = Config::dangerously_accept_dev_attestation("http://localhost:8000").unwrap();
523        let json = serde_json::to_value(config).unwrap();
524        assert_eq!(json["dangerously_accept_dev_attestation"], true);
525        assert!(matches!(
526            Config::from_json(&json.to_string()).unwrap().attestations(),
527            Ok(Attestations::Dev { .. })
528        ));
529    }
530
531    #[cfg(feature = "dev")]
532    #[test]
533    fn dev_attestations_require_skipping_measurements() {
534        let mut json =
535            serde_json::to_value(Config::new("http://localhost:8000", pcrs()).unwrap()).unwrap();
536        json["dangerously_accept_dev_attestation"] = serde_json::json!(true);
537        assert!(matches!(
538            Config::from_json(&json.to_string()),
539            Err(Error::InvalidConfig { .. })
540        ));
541        json["dangerously_skip_measurements"] = serde_json::json!(true);
542        json["allowed_pcr_configs"] = serde_json::json!([]);
543        assert!(matches!(
544            Config::from_json(&json.to_string()).unwrap().attestations(),
545            Ok(crate::client::Attestations::Dev { .. })
546        ));
547    }
548
549    #[test]
550    fn measurement_skip_ignores_supplied_pins() {
551        for pins in [
552            vec![],
553            vec![PcrMeasurement::new(1, [0; 48])],
554            vec![PcrMeasurement::new(0, [0; 48])],
555            vec![PcrMeasurement::new(0, [0; 47])],
556            vec![
557                PcrMeasurement::new(0, [1; 48]),
558                PcrMeasurement::new(1, [0; 49]),
559            ],
560            vec![
561                PcrMeasurement::new(0, [1; 48]),
562                PcrMeasurement::new(0, [1; 48]),
563            ],
564        ] {
565            let mut config =
566                Config::dangerously_skip_measurements("http://localhost:8000").unwrap();
567            config.allowed_pcr_configs = vec![pins];
568            let mut json = serde_json::to_value(config).unwrap();
569            assert!(
570                Config::from_json(&json.to_string())
571                    .unwrap()
572                    .verifier()
573                    .is_ok()
574            );
575            json["dangerously_skip_measurements"] = serde_json::json!(false);
576            assert!(Config::from_json(&json.to_string()).is_err());
577        }
578    }
579
580    #[test]
581    fn accepts_pcr_values_with_and_without_the_0x_prefix() {
582        // Release metadata records PCRs 0x-prefixed; both spellings should be accepted.
583        let json = r#"{
584            "host_url": "http://localhost:8000",
585            "allowed_pcr_configs": [[
586                { "index": 0, "value": "0xab01" },
587                { "index": 1, "value": "ab01" },
588                { "index": 2, "value": "ab01" }
589            ]]
590        }"#;
591
592        let json = json
593            .replace("0xab01", &format!("0x{}", "ab".repeat(48)))
594            .replace("ab01", &"ab".repeat(48));
595        let config = Config::from_json(&json).expect("both spellings should parse");
596
597        let pcrs = &config.allowed_pcr_configs[0];
598        assert_eq!(pcrs[0].value, pcrs[1].value);
599
600        Config::from_json(
601            r#"{
602            "host_url": "http://localhost:8000",
603            "allowed_pcr_configs": [[{ "index": 0, "value": "0xzz" }]]
604        }"#,
605        )
606        .expect_err("non-hex must still be rejected");
607    }
608
609    #[test]
610    fn round_trips_through_json_with_defaults_applied() {
611        let config = Config::new(
612            "http://localhost:8000",
613            vec![
614                vec![
615                    pontifex::PcrMeasurement::new(0, [0xab; 48]),
616                    pontifex::PcrMeasurement::new(1, [0xcd; 48]),
617                    pontifex::PcrMeasurement::new(2, [0xde; 48]),
618                ],
619                (0..=2)
620                    .map(|index| PcrMeasurement::new(index, [0xef; 48]))
621                    .collect(),
622            ],
623        )
624        .expect("Pontifex measurements should be accepted");
625        let json = serde_json::to_value(&config).expect("config should serialize");
626        assert_eq!(json["dangerously_skip_measurements"], false);
627        assert_eq!(
628            json["allowed_pcr_configs"],
629            serde_json::json!([
630                [
631                    { "index": 0, "value": "ab".repeat(48) },
632                    { "index": 1, "value": "cd".repeat(48) },
633                    { "index": 2, "value": "de".repeat(48) }
634                ],
635                [
636                    { "index": 0, "value": "ef".repeat(48) },
637                    { "index": 1, "value": "ef".repeat(48) },
638                    { "index": 2, "value": "ef".repeat(48) }
639                ]
640            ])
641        );
642
643        let decoded = Config::from_json(&json.to_string()).expect("config should parse");
644        assert_eq!(decoded.request_timeout(), Duration::from_mins(1));
645        assert_eq!(decoded.max_response_slots(), 8);
646        assert_eq!(serde_json::to_value(decoded).unwrap(), json);
647    }
648}