Skip to main content

flamingo_verifier_client/
client.rs

1//! Verification helpers for the Flamingo Verifier host, and the client that opens a session.
2
3use base64::{Engine as _, engine::general_purpose::STANDARD};
4
5use eddsa_babyjubjub::EdDSAPublicKey;
6use flamingo_verifier_api_types::{EnclaveAssignmentResponse, ErrorEnvelope};
7#[cfg(feature = "dev")]
8use flamingo_verifier_sealed_types::ByteBuf;
9use flamingo_verifier_sealed_types::{
10    CHANNEL_DOMAIN, DebugReport, FlamingoClaims, FlamingoToken, MatchResult, ReleaseManifest,
11};
12use pontifex::ChannelConsumer;
13use pontifex::attestation::{VerifiedAttestation, Verifier};
14use world_id_primitives::FieldElement;
15
16use crate::config::Config;
17use crate::error::Error;
18use crate::session::FlamingoVerifierSession;
19
20/// Error code the host uses for a request that did not open.
21const REASSIGN_REQUIRED: &str = "reassign_required";
22
23/// How the client verifies the enclave's attestations.
24#[derive(Debug)]
25pub enum Attestations {
26    /// Nitro documents, verified by Pontifex.
27    Nitro(Verifier),
28    /// The unsigned documents of a `dev` Verifier, no older than `max_age`.
29    #[cfg(feature = "dev")]
30    Dev {
31        /// How old a document's own timestamp may be.
32        max_age: std::time::Duration,
33    },
34}
35
36/// Verifies an assignment response's attestation, binds it to the supplied public key, and checks
37/// that it attests the release manifest sent with it (WIP-201 §4.6 step 1).
38pub fn verify_assignment(
39    attestations: &Attestations,
40    response: &EnclaveAssignmentResponse,
41) -> Result<VerifiedAssignment, Error> {
42    let document = STANDARD
43        .decode(&response.attestation)
44        .map_err(|_| Error::MalformedAssignment)?;
45    let public_key = STANDARD
46        .decode(&response.public_key)
47        .map_err(|_| Error::MalformedAssignment)?;
48    let (consumer, attestation, user_data) = match attestations {
49        Attestations::Nitro(verifier) => {
50            let (consumer, attestation) =
51                ChannelConsumer::from_attestation(CHANNEL_DOMAIN, verifier, &document, &public_key)
52                    .map_err(Error::Channel)?;
53            let user_data = attestation
54                .document()
55                .user_data
56                .as_ref()
57                .map(|data| data.to_vec());
58            (consumer, Some(attestation), user_data)
59        }
60        #[cfg(feature = "dev")]
61        Attestations::Dev { max_age } => {
62            let (consumer, user_data) = verify_dev_attestation(&document, &public_key, *max_age)?;
63            (consumer, None, user_data)
64        }
65    };
66    let release = attested_release(&response.release_manifest, user_data.as_deref())?;
67
68    Ok(VerifiedAssignment {
69        attestation,
70        consumer,
71        release,
72    })
73}
74
75/// Checks a `dev` channel document as Pontifex checks a Nitro one, except for the signature: it is
76/// fresh and commits to `public_key`. Returns the consumer and the document's `user_data`.
77#[cfg(feature = "dev")]
78fn verify_dev_attestation(
79    document: &[u8],
80    public_key: &[u8],
81    max_age: std::time::Duration,
82) -> Result<(ChannelConsumer, Option<Vec<u8>>), Error> {
83    use pontifex::ChannelError;
84
85    let document = fresh_dev_attestation(document, max_age)
86        .map_err(|error| Error::Channel(ChannelError::Attestation(error)))?;
87    if document.public_key.as_slice() != CHANNEL_DOMAIN.public_key_commitment(public_key) {
88        return Err(Error::Channel(ChannelError::KeyCommitmentMismatch));
89    }
90    let consumer = ChannelConsumer::from_unverified_public_key(CHANNEL_DOMAIN, public_key)
91        .map_err(Error::Channel)?;
92    Ok((consumer, document.user_data.map(ByteBuf::into_vec)))
93}
94
95/// Decodes a `dev` document and checks that it is no older than `max_age`.
96#[cfg(feature = "dev")]
97fn fresh_dev_attestation(
98    document: &[u8],
99    max_age: std::time::Duration,
100) -> Result<flamingo_verifier_sealed_types::dev::DevAttestation, pontifex::attestation::Error> {
101    use flamingo_verifier_sealed_types::dev::DevAttestation;
102    use pontifex::attestation;
103
104    let document = DevAttestation::from_cbor(document)
105        .map_err(|_| attestation::Error::ParseError("not a dev attestation".to_owned()))?;
106    let now_millis = std::time::SystemTime::now()
107        .duration_since(std::time::UNIX_EPOCH)
108        .map_or(0, |elapsed| {
109            u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX)
110        });
111    let age_millis = now_millis.saturating_sub(document.timestamp_millis);
112    let max_age = u64::try_from(max_age.as_millis()).unwrap_or(u64::MAX);
113    if age_millis > max_age {
114        return Err(attestation::Error::Stale {
115            age_millis,
116            max_age,
117        });
118    }
119    Ok(document)
120}
121
122/// The release manifest `jws`, if the channel attestation's `user_data` is its `release_hash`.
123fn attested_release(jws: &str, user_data: Option<&[u8]>) -> Result<ReleaseManifest, Error> {
124    let release = ReleaseManifest::from_jws(jws).map_err(|_| Error::MalformedAssignment)?;
125    if user_data != Some(release.release_hash().as_slice()) {
126        return Err(Error::ReleaseNotAttested);
127    }
128    Ok(release)
129}
130
131/// Opens a sealed match response and verifies the statement it carries, if any.
132pub fn open_verified_match(
133    attestations: &Attestations,
134    ciphertext: &[u8],
135    opener: pontifex::ResponseOpener,
136) -> Result<VerifiedMatchResult, Error> {
137    let plaintext = opener
138        .open_from_enclave(ciphertext)
139        .map_err(Error::Channel)?;
140    let response = MatchResult::from_padded_cbor(&plaintext).map_err(|_| Error::MalformedResult)?;
141
142    match response {
143        MatchResult::Success {
144            statement,
145            debug_report,
146        } => {
147            let signing_key =
148                attested_signing_key(attestations, &statement.signing_key_attestation)?;
149
150            let claims = FlamingoToken::from_cwt(&statement.token)
151                .and_then(|token| token.verify(&signing_key).copied())
152                .map_err(|_| Error::StatementInvalid)?;
153            Ok(VerifiedMatchResult::Success {
154                verified: Box::new(VerifiedMatch {
155                    statement,
156                    claims,
157                    verifier_key: signing_key,
158                }),
159                debug_report,
160            })
161        }
162        MatchResult::Failed {
163            reason,
164            debug_report,
165        } => Ok(VerifiedMatchResult::Failed {
166            reason,
167            debug_report,
168        }),
169    }
170}
171
172/// The signing key `document` attests.
173fn attested_signing_key(
174    attestations: &Attestations,
175    document: &[u8],
176) -> Result<EdDSAPublicKey, Error> {
177    let attested;
178    #[cfg(feature = "dev")]
179    let dev;
180    let key = match attestations {
181        Attestations::Nitro(verifier) => {
182            // Response encryption alone does not authenticate the signing key.
183            attested = verifier.verify_attestation_document(document)?;
184            attested
185                .document()
186                .public_key
187                .as_ref()
188                .ok_or(Error::InvalidSigningKey)?
189                .as_slice()
190        }
191        #[cfg(feature = "dev")]
192        Attestations::Dev { max_age } => {
193            dev = fresh_dev_attestation(document, *max_age)?;
194            // Only the channel key's document carries `user_data`.
195            if dev.user_data.is_some() {
196                return Err(Error::InvalidSigningKey);
197            }
198            dev.public_key.as_slice()
199        }
200    };
201    <[u8; 32]>::try_from(key)
202        .map_err(|_| Error::InvalidSigningKey)
203        .and_then(|bytes| {
204            EdDSAPublicKey::from_compressed_bytes(bytes).map_err(|_| Error::InvalidSigningKey)
205        })
206}
207
208/// Rejects a verified result whose claims differ from `expected`.
209///
210/// The Verifier sets `now` from its own clock, and signs either the `billing_nullifier` the request
211/// carried or `0` for an RP it does not bill (WIP-201 §4.5), so those two claims are checked apart.
212pub fn ensure_claims_match(
213    expected: &FlamingoClaims,
214    billing_nullifier: FieldElement,
215    result: &VerifiedMatchResult,
216) -> Result<(), Error> {
217    let VerifiedMatchResult::Success { verified, .. } = result else {
218        return Ok(());
219    };
220    let claims = &verified.claims;
221    let expected = FlamingoClaims {
222        now: claims.now,
223        billing_nullifier: claims.billing_nullifier,
224        ..*expected
225    };
226    let billing = claims.billing_nullifier == FieldElement::ZERO
227        || claims.billing_nullifier == billing_nullifier;
228    if *claims == expected && billing {
229        Ok(())
230    } else {
231        Err(Error::StatementInvalid)
232    }
233}
234
235/// Classifies an error envelope received over the WebSocket.
236pub fn classify_envelope(envelope: &ErrorEnvelope) -> Error {
237    if envelope.error.code == REASSIGN_REQUIRED {
238        return Error::ReassignRequired;
239    }
240
241    Error::ApiFrame {
242        code: envelope.error.code.clone(),
243        allow_retry: envelope.allow_retry,
244    }
245}
246
247/// An assignment whose attestation verified and whose encryption key is ready for sealing.
248#[derive(Debug, Clone)]
249pub struct VerifiedAssignment {
250    /// Metadata read from the signed attestation document; `None` for a `dev` Verifier's.
251    attestation: Option<VerifiedAttestation>,
252    consumer: ChannelConsumer,
253    /// The release whose `release_hash` the attestation carries.
254    release: ReleaseManifest,
255}
256
257impl VerifiedAssignment {
258    /// Metadata from the verified channel-key Nitro attestation; `None` for a `dev` Verifier's.
259    #[must_use]
260    pub const fn attestation(&self) -> Option<&VerifiedAttestation> {
261        self.attestation.as_ref()
262    }
263
264    /// The channel consumer bound to this assignment's verified key.
265    #[must_use]
266    pub const fn consumer(&self) -> &ChannelConsumer {
267        &self.consumer
268    }
269
270    /// The attested release the enclave runs. Its manifest signature is not verified here
271    /// (WIP-201 §4.3.4).
272    #[must_use]
273    pub const fn release(&self) -> &ReleaseManifest {
274        &self.release
275    }
276}
277
278/// Opens a WebSocket session with the Flamingo Verifier host.
279///
280/// Nothing is returned until the enclave that produced the assignment has been verified, so
281/// callers cannot accidentally use an unattested key.
282#[derive(Debug)]
283pub struct FlamingoVerifierClient {
284    config: Config,
285}
286
287impl FlamingoVerifierClient {
288    /// Builds a client from `config`.
289    ///
290    /// # Errors
291    ///
292    /// Returns [`Error`] if the configuration is invalid.
293    pub fn new(config: Config) -> Result<Self, Error> {
294        config.verifier()?;
295
296        Ok(Self { config })
297    }
298
299    /// Creates the WebSocket upgrade request without sending it.
300    ///
301    /// Callers may add headers before passing the builder to [`Self::connect_with`].
302    ///
303    /// # Errors
304    ///
305    /// Returns [`Error`] if the configured host URL cannot be used as a WebSocket endpoint.
306    pub fn build_request(
307        &self,
308    ) -> Result<tokio_tungstenite::tungstenite::ClientRequestBuilder, Error> {
309        crate::session::build_request(&self.config)
310    }
311
312    /// Opens the WebSocket, verifies the enclave assignment delivered on it, and returns a
313    /// session that runs exactly one match over that same socket.
314    ///
315    /// The session owns both the socket and the verified assignment, so its match cannot be sent
316    /// over a connection whose assignment was not verified.
317    ///
318    /// # Errors
319    ///
320    /// Returns [`Error`] if the handshake fails, the host rejects or closes the connection, the
321    /// assignment does not arrive or verify, or the exchange exceeds the configured deadline.
322    pub async fn connect(&self) -> Result<FlamingoVerifierSession, Error> {
323        self.connect_with(self.build_request()?).await
324    }
325
326    /// Opens a WebSocket with a caller-customized upgrade request.
327    ///
328    /// The `request` should be created from [`Self::build_request`] so it targets this client's
329    /// configured endpoint. The assignment is verified before the session is returned.
330    ///
331    /// # Errors
332    ///
333    /// Returns [`Error`] if the handshake fails, the host rejects or closes the connection, the
334    /// assignment does not arrive or verify, or the exchange exceeds the configured deadline.
335    pub async fn connect_with(
336        &self,
337        request: tokio_tungstenite::tungstenite::ClientRequestBuilder,
338    ) -> Result<FlamingoVerifierSession, Error> {
339        crate::session::connect(&self.config, self.config.attestations()?, request).await
340    }
341}
342
343/// A Flamingo Token whose attestation, signature and claims the client verified.
344#[derive(Debug, Clone, PartialEq, Eq)]
345pub struct VerifiedMatch {
346    /// Encoded token and attestation for proof consumers.
347    pub statement: flamingo_verifier_sealed_types::AttestedStatement,
348    /// The token's claims, equal to those the request implies.
349    pub claims: FlamingoClaims,
350    /// The Verifier's signing key, which `statement.signing_key_attestation` attests and the token
351    /// verifies under. A WIP-202 proof needs it.
352    pub verifier_key: EdDSAPublicKey,
353}
354
355/// Verified success or an encrypted unsigned rejection, with bounded worker diagnostics.
356#[derive(Debug, Clone, PartialEq, Eq)]
357pub enum VerifiedMatchResult {
358    /// Attested signed result and parsed claims.
359    Success {
360        /// Signature-verified statement and claims.
361        verified: Box<VerifiedMatch>,
362        /// Original worker diagnostics, not signed proof claims.
363        debug_report: DebugReport,
364    },
365    /// No statement issued.
366    Failed {
367        /// Input or biometric rejection.
368        reason: flamingo_verifier_sealed_types::FailureReason,
369        /// Original worker diagnostics, if produced.
370        debug_report: DebugReport,
371    },
372}
373
374#[cfg(test)]
375mod tests {
376    use super::{
377        Attestations, CHANNEL_DOMAIN, Error, FlamingoClaims, ReleaseManifest, STANDARD,
378        VerifiedMatch, VerifiedMatchResult, attested_release, attested_signing_key,
379        ensure_claims_match, verify_assignment,
380    };
381    use base64::Engine as _;
382    use flamingo_verifier_api_types::EnclaveAssignmentResponse;
383    use flamingo_verifier_sealed_types::{
384        AttestedStatement, ByteBuf, DebugReport, dev::DevAttestation, testing,
385    };
386    use world_id_primitives::FieldElement;
387
388    fn success(claims: &FlamingoClaims) -> VerifiedMatchResult {
389        VerifiedMatchResult::Success {
390            verified: Box::new(VerifiedMatch {
391                statement: AttestedStatement {
392                    token: vec![],
393                    signing_key_attestation: vec![],
394                },
395                claims: *claims,
396                verifier_key: eddsa_babyjubjub::EdDSAPrivateKey::from_bytes([7; 32]).public(),
397            }),
398            debug_report: DebugReport::NotProduced,
399        }
400    }
401
402    /// An assignment for a fresh channel key, attested by a `dev` document built by `attest` from
403    /// the key's commitment and the manifest's `release_hash`.
404    fn dev_assignment(
405        attest: impl FnOnce([u8; 32], Vec<u8>) -> DevAttestation,
406    ) -> EnclaveAssignmentResponse {
407        let enclave = pontifex::ChannelEnclave::generate(CHANNEL_DOMAIN).unwrap();
408        let manifest = testing::manifest(testing::TEST_ENGINE_HASH, 1);
409        let release_hash = ReleaseManifest::from_jws(&manifest).unwrap().release_hash();
410        let document = attest(enclave.public_key_commitment(), release_hash.to_vec());
411        EnclaveAssignmentResponse {
412            attestation: STANDARD.encode(document.to_cbor().unwrap()),
413            public_key: STANDARD.encode(enclave.public_key()),
414            release_manifest: manifest,
415        }
416    }
417
418    fn dev_document(commitment: [u8; 32], user_data: Vec<u8>) -> DevAttestation {
419        DevAttestation {
420            public_key: ByteBuf::from(commitment),
421            user_data: Some(ByteBuf::from(user_data)),
422            timestamp_millis: u64::try_from(
423                std::time::SystemTime::now()
424                    .duration_since(std::time::UNIX_EPOCH)
425                    .unwrap()
426                    .as_millis(),
427            )
428            .unwrap(),
429        }
430    }
431
432    #[test]
433    fn a_nitro_policy_rejects_dev_attestations() {
434        let nitro = Attestations::Nitro(
435            crate::Config::dangerously_skip_measurements("http://localhost:8000")
436                .unwrap()
437                .verifier()
438                .unwrap(),
439        );
440        assert!(matches!(
441            verify_assignment(&nitro, &dev_assignment(dev_document)),
442            Err(Error::Channel(_))
443        ));
444        let key = eddsa_babyjubjub::EdDSAPrivateKey::from_bytes([7; 32]).public();
445        assert!(matches!(
446            attested_signing_key(&nitro, &key.to_compressed_bytes().unwrap()),
447            Err(Error::Attestation(_))
448        ));
449    }
450
451    #[cfg(feature = "dev")]
452    #[test]
453    fn a_dev_policy_binds_the_channel_key_and_release() {
454        use pontifex::{ChannelError, attestation};
455
456        let Attestations::Dev { max_age } =
457            crate::Config::dangerously_accept_dev_attestation("http://localhost:8000")
458                .unwrap()
459                .attestations()
460                .unwrap()
461        else {
462            panic!("expected a dev policy")
463        };
464        let dev = Attestations::Dev { max_age };
465        let assignment = verify_assignment(&dev, &dev_assignment(dev_document)).unwrap();
466        assert!(assignment.attestation().is_none());
467
468        assert!(matches!(
469            verify_assignment(
470                &dev,
471                &dev_assignment(|_, release_hash| dev_document([0; 32], release_hash))
472            ),
473            Err(Error::Channel(ChannelError::KeyCommitmentMismatch))
474        ));
475        assert!(matches!(
476            verify_assignment(
477                &dev,
478                &dev_assignment(|commitment, _| dev_document(commitment, vec![0; 32]))
479            ),
480            Err(Error::ReleaseNotAttested)
481        ));
482        assert!(matches!(
483            verify_assignment(
484                &dev,
485                &dev_assignment(|commitment, _| DevAttestation {
486                    user_data: None,
487                    ..dev_document(commitment, vec![])
488                })
489            ),
490            Err(Error::ReleaseNotAttested)
491        ));
492        assert!(matches!(
493            verify_assignment(
494                &dev,
495                &dev_assignment(|commitment, release_hash| DevAttestation {
496                    timestamp_millis: 0,
497                    ..dev_document(commitment, release_hash)
498                })
499            ),
500            Err(Error::Channel(ChannelError::Attestation(
501                attestation::Error::Stale { .. }
502            )))
503        ));
504
505        let key = eddsa_babyjubjub::EdDSAPrivateKey::from_bytes([7; 32]).public();
506        let raw = key.to_compressed_bytes().unwrap();
507        let signing = |public_key: &[u8], user_data: Option<Vec<u8>>, timestamp_millis| {
508            DevAttestation {
509                public_key: ByteBuf::from(public_key),
510                user_data: user_data.map(ByteBuf::from),
511                timestamp_millis,
512            }
513            .to_cbor()
514            .unwrap()
515        };
516        let now = dev_document([0; 32], vec![]).timestamp_millis;
517        assert_eq!(
518            attested_signing_key(&dev, &signing(&raw, None, now)).unwrap(),
519            key
520        );
521        assert!(matches!(
522            attested_signing_key(&dev, &raw),
523            Err(Error::Attestation(attestation::Error::ParseError(_)))
524        ));
525        assert!(matches!(
526            attested_signing_key(&dev, &signing(&raw[1..], None, now)),
527            Err(Error::InvalidSigningKey)
528        ));
529        assert!(matches!(
530            attested_signing_key(&dev, &signing(&raw, Some(vec![0; 32]), now)),
531            Err(Error::InvalidSigningKey)
532        ));
533        assert!(matches!(
534            attested_signing_key(&dev, &signing(&raw, None, 0)),
535            Err(Error::Attestation(attestation::Error::Stale { .. }))
536        ));
537    }
538
539    #[test]
540    fn the_release_must_be_the_attested_one() {
541        use flamingo_verifier_sealed_types::{ReleaseManifest, testing};
542        let jws = testing::manifest(testing::TEST_ENGINE_HASH, 1);
543        let release_hash = ReleaseManifest::from_jws(&jws).unwrap().release_hash();
544        assert_eq!(
545            attested_release(&jws, Some(&release_hash))
546                .unwrap()
547                .release_hash(),
548            release_hash
549        );
550        let other = testing::manifest(testing::TEST_ENGINE_HASH, 2);
551        for (jws, user_data) in [
552            (&jws, None),
553            (&jws, Some(&[0u8; 32][..])),
554            (&other, Some(&release_hash[..])),
555        ] {
556            assert!(matches!(
557                attested_release(jws, user_data),
558                Err(Error::ReleaseNotAttested)
559            ));
560        }
561        assert!(matches!(
562            attested_release("not.a.jws", Some(&release_hash)),
563            Err(Error::MalformedAssignment)
564        ));
565    }
566
567    #[test]
568    fn claims_must_be_the_ones_the_request_implies() {
569        let expected = FlamingoClaims {
570            now: 1,
571            entry_hashes: [
572                1u64.into(),
573                2u64.into(),
574                FieldElement::ZERO,
575                FieldElement::ZERO,
576            ],
577            aud: 1u64.into(),
578            nonce: 2u64.into(),
579            aat: None,
580            engine_config_hash: 3u64.into(),
581            pipeline_type: 5u64.into(),
582            strictness: 2,
583            billing_nullifier: FieldElement::ZERO,
584        };
585        let billed = 7u64.into();
586        for accepted in [
587            expected,
588            FlamingoClaims { now: 9, ..expected },
589            FlamingoClaims {
590                billing_nullifier: billed,
591                ..expected
592            },
593        ] {
594            assert!(ensure_claims_match(&expected, billed, &success(&accepted)).is_ok());
595        }
596        for changed in [
597            FlamingoClaims {
598                nonce: 3u64.into(),
599                ..expected
600            },
601            FlamingoClaims {
602                engine_config_hash: 4u64.into(),
603                ..expected
604            },
605            FlamingoClaims {
606                entry_hashes: [3u64.into(); 4],
607                ..expected
608            },
609            FlamingoClaims {
610                pipeline_type: 6u64.into(),
611                ..expected
612            },
613            FlamingoClaims {
614                strictness: 3,
615                ..expected
616            },
617            FlamingoClaims {
618                billing_nullifier: 8u64.into(),
619                ..expected
620            },
621        ] {
622            assert!(matches!(
623                ensure_claims_match(&expected, billed, &success(&changed)),
624                Err(Error::StatementInvalid)
625            ));
626        }
627    }
628}