flamingo-verifier-client 0.7.0

Attestation-verifying client for the Flamingo verifier
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
//! The WebSocket session for the Flamingo Verifier host.
//!
//! A session performs exactly one exchange: the assignment request is answered with the
//! enclave's attested key, and then the match request is sealed to that key and sent as a
//! single binary frame. The socket and the verified assignment are held together, so a match
//! cannot be sent over a connection whose assignment was never verified.

use std::sync::Arc;
use std::time::Duration;

use flamingo_verifier_api_types::{
    ClientMessage, EnclaveAssignmentResponse, ErrorEnvelope, HostMessage, MAX_MATCH_BODY_BYTES,
    MAX_MATCH_RESPONSE_BYTES,
};
use flamingo_verifier_sealed_types::MatchInputs;
use futures_util::{SinkExt, StreamExt};
use pontifex::attestation::Verifier;
use tokio::net::TcpStream;
use tokio::time::Instant;
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
use tokio_tungstenite::tungstenite::{ClientRequestBuilder, Message};
use tokio_tungstenite::{
    Connector, MaybeTlsStream, WebSocketStream, connect_async_tls_with_config,
};
use url::Url;

use crate::client::{
    VerifiedAssignment, VerifiedMatchResult, classify_envelope, ensure_claims_match,
    open_verified_match, verify_assignment,
};
use crate::config::Config;
use crate::error::Error;

/// The WebSocket the session owns, over plain TCP or TLS.
type Socket = WebSocketStream<MaybeTlsStream<TcpStream>>;

/// One verified exchange: a WebSocket bound to the enclave assignment delivered on it.
///
/// Created by [`crate::FlamingoVerifierClient::connect`].
#[derive(Debug)]
pub struct FlamingoVerifierSession {
    socket: Socket,
    assignment: VerifiedAssignment,
    verifier: Verifier,
    request_timeout: Duration,
}

impl FlamingoVerifierSession {
    /// The verified assignment delivered on this session's socket.
    #[must_use]
    pub const fn assignment(&self) -> &VerifiedAssignment {
        &self.assignment
    }

    /// Seals `inputs` to this session's verified enclave key, sends them as the one binary match
    /// frame, and returns the verified result or the sealed rejection.
    ///
    /// Consumes the session: one socket carries exactly one match, and it is closed after the
    /// exchange, including on failure.
    ///
    /// # Errors
    ///
    /// Returns [`Error`] if sealing or transport fails, the host answers with an error envelope,
    /// the response is oversized, or the result or its claims do not verify.
    pub async fn request_match(
        mut self,
        inputs: &MatchInputs,
    ) -> Result<VerifiedMatchResult, Error> {
        let result = exchange_match(
            &mut self.socket,
            self.assignment.consumer(),
            inputs,
            &self.verifier,
            self.request_timeout,
        )
        .await;

        let _ = tokio::time::timeout(self.request_timeout, self.socket.close(None)).await;

        result
    }
}

/// Creates the WebSocket upgrade request.
pub fn build_request(config: &Config) -> Result<ClientRequestBuilder, Error> {
    let url = websocket_url(config.host_url())?;
    let uri = url
        .as_str()
        .parse::<tokio_tungstenite::tungstenite::http::Uri>()
        .map_err(|error| Error::WebSocket(error.into()))?;
    Ok(ClientRequestBuilder::new(uri))
}

/// Opens the WebSocket and verifies the assignment the host delivers on it.
pub async fn connect(
    config: &Config,
    verifier: Verifier,
    request: ClientRequestBuilder,
) -> Result<FlamingoVerifierSession, Error> {
    let socket_config = WebSocketConfig::default()
        .max_message_size(Some(MAX_MATCH_BODY_BYTES))
        .max_frame_size(Some(MAX_MATCH_BODY_BYTES));
    let (mut socket, _response) = tokio::time::timeout(
        config.connect_timeout(),
        connect_async_tls_with_config(request, Some(socket_config), false, Some(tls_connector()?)),
    )
    .await
    .map_err(|_| Error::Timeout)?
    .map_err(|error| match error {
        tokio_tungstenite::tungstenite::Error::Http(response) => response
            .body()
            .as_deref()
            .and_then(|body| serde_json::from_slice::<ErrorEnvelope>(body).ok())
            .map_or_else(
                || Error::WebSocket(tokio_tungstenite::tungstenite::Error::Http(response)),
                |envelope| classify_envelope(&envelope),
            ),
        other => Error::WebSocket(other),
    })?;

    let assignment = request_assignment(&mut socket, &verifier, config.request_timeout()).await?;

    Ok(FlamingoVerifierSession {
        socket,
        assignment,
        verifier,
        request_timeout: config.request_timeout(),
    })
}

/// The TLS connector for `wss` hosts, trusting the webpki roots.
///
/// The crypto provider is chosen explicitly: rustls otherwise panics when no provider, or more
/// than one, is enabled through crate features across the dependency graph.
fn tls_connector() -> Result<Connector, Error> {
    let mut roots = rustls::RootCertStore::empty();
    roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
    let config = rustls::ClientConfig::builder_with_provider(Arc::new(
        rustls::crypto::ring::default_provider(),
    ))
    .with_safe_default_protocol_versions()
    .map_err(|error| Error::WebSocket(tokio_tungstenite::tungstenite::Error::Tls(error.into())))?
    .with_root_certificates(roots)
    .with_no_client_auth();
    Ok(Connector::Rustls(Arc::new(config)))
}

/// Maps the configured HTTP base URL onto its WebSocket endpoint.
fn websocket_url(host: &Url) -> Result<Url, Error> {
    let mut url = host.clone();
    let mapped = match host.scheme() {
        "http" => url.set_scheme("ws"),
        "https" => url.set_scheme("wss"),
        _ => {
            return Err(Error::InvalidConfig {
                attribute: "host_url".to_owned(),
                reason: "the base URL scheme must be http or https to map to a WebSocket"
                    .to_owned(),
            });
        }
    };
    mapped.map_err(|()| Error::InvalidConfig {
        attribute: "host_url".to_owned(),
        reason: "the base URL scheme could not be mapped to a WebSocket".to_owned(),
    })?;
    url.set_path(&format!("{}/v1/matches", host.path().trim_end_matches('/')));

    Ok(url)
}

/// Sends the assignment request and returns the verified assignment.
async fn request_assignment(
    socket: &mut Socket,
    verifier: &Verifier,
    request_timeout: Duration,
) -> Result<VerifiedAssignment, Error> {
    // One absolute deadline bounds the whole phase: ignored pings and the send do not extend it.
    let deadline = Instant::now() + request_timeout;
    let request = serde_json::to_string(&ClientMessage::AssignmentRequest)
        .map_err(|_| Error::MalformedMessage)?;
    send_message(socket, Message::Text(request.into()), deadline).await?;

    loop {
        match read_message(socket, deadline).await? {
            Message::Text(text) => {
                let response = decode_assignment(text.as_str())?;
                return verify_assignment(verifier, &response);
            }
            Message::Binary(_) => return Err(Error::MalformedMessage),
            Message::Close(_) => return Err(Error::ConnectionClosed),
            Message::Ping(_) | Message::Pong(_) | Message::Frame(_) => {}
        }
    }
}

/// Seals the inputs, sends the one binary frame, and verifies the one binary response.
async fn exchange_match(
    socket: &mut Socket,
    consumer: &pontifex::ChannelConsumer,
    inputs: &MatchInputs,
    verifier: &Verifier,
    request_timeout: Duration,
) -> Result<VerifiedMatchResult, Error> {
    let plaintext = inputs.to_cbor().map_err(|_| Error::MalformedResult)?;
    let (sealed, opener) = consumer
        .seal_to_enclave(&plaintext)
        .map_err(Error::Channel)?;
    if sealed.len() > MAX_MATCH_BODY_BYTES {
        return Err(Error::MalformedResult);
    }

    // One absolute deadline bounds the whole phase: ignored pings and the send do not extend it.
    let deadline = Instant::now() + request_timeout;
    send_message(socket, Message::Binary(sealed.into()), deadline).await?;

    loop {
        match read_message(socket, deadline).await? {
            Message::Binary(ciphertext) => {
                if ciphertext.len() > MAX_MATCH_RESPONSE_BYTES {
                    return Err(Error::MalformedResult);
                }
                let result = open_verified_match(verifier, &ciphertext, opener)?;
                ensure_claims_match(inputs, &result)?;
                return Ok(result);
            }
            Message::Text(text) => return Err(error_from_text(text.as_str())),
            Message::Close(_) => return Err(Error::ConnectionClosed),
            Message::Ping(_) | Message::Pong(_) | Message::Frame(_) => {}
        }
    }
}

/// Parses the host's assignment text frame, or returns the error envelope it carries.
fn decode_assignment(text: &str) -> Result<EnclaveAssignmentResponse, Error> {
    if let Ok(HostMessage::Assignment(response)) = serde_json::from_str::<HostMessage>(text) {
        return Ok(response);
    }

    Err(error_from_text(text))
}

/// Reads a host text frame as an error envelope, falling back to a malformed-message error.
fn error_from_text(text: &str) -> Error {
    serde_json::from_str::<ErrorEnvelope>(text).map_or(Error::MalformedMessage, |envelope| {
        classify_envelope(&envelope)
    })
}

/// Reads the next frame, bounded by the phase's absolute deadline.
async fn read_message(socket: &mut Socket, deadline: Instant) -> Result<Message, Error> {
    match tokio::time::timeout_at(deadline, socket.next()).await {
        Err(_) => Err(Error::Timeout),
        Ok(None) => Err(Error::ConnectionClosed),
        Ok(Some(Err(error))) => Err(Error::WebSocket(error)),
        Ok(Some(Ok(message))) => Ok(message),
    }
}

/// Sends a frame, bounded by the phase's absolute deadline.
async fn send_message(
    socket: &mut Socket,
    message: Message,
    deadline: Instant,
) -> Result<(), Error> {
    match tokio::time::timeout_at(deadline, socket.send(message)).await {
        Err(_) => Err(Error::Timeout),
        Ok(Err(error)) => Err(Error::WebSocket(error)),
        Ok(Ok(())) => Ok(()),
    }
}

#[cfg(test)]
mod tests {
    use std::future::Future;
    use std::net::Ipv4Addr;
    use std::sync::Arc;
    use std::time::Duration;

    use flamingo_verifier_api_types::MAX_MATCH_RESPONSE_BYTES;
    use flamingo_verifier_protocol::match_token::MatchToken;
    use flamingo_verifier_sealed_types::{
        AttestedStatement, FailureReason, MATCH_CHANNEL_DOMAIN, MatchInputs, MatchResult,
    };
    use futures_util::{SinkExt, StreamExt};
    use pontifex::attestation::PcrConfig;
    use pontifex::{ChannelConsumer, ChannelDomain, ChannelEnclave};
    use tokio::net::{TcpListener, TcpStream};
    use tokio_tungstenite::tungstenite::Message;
    use tokio_tungstenite::{WebSocketStream, accept_async, connect_async};

    use super::{Socket, exchange_match, websocket_url};
    use crate::VerifiedMatchResult;
    use crate::error::Error;

    const TIMEOUT: Duration = Duration::from_secs(5);

    fn verifier() -> super::Verifier {
        super::Verifier::new(vec![PcrConfig::new([0xab; 48])], Duration::from_mins(1))
    }

    fn inputs() -> MatchInputs {
        MatchInputs::GrayBadge(flamingo_verifier_sealed_types::GrayBadgeInputs {
            live: flamingo_verifier_sealed_types::LiveCapture::Vanilla(b"live".to_vec().into()),
            rtms_challenge: b"challenge".to_vec().into(),
            match_threshold: 0.5,
        })
    }

    fn consumer_for(enclave: &ChannelEnclave) -> ChannelConsumer {
        ChannelConsumer::from_unverified_public_key(
            ChannelDomain::new(MATCH_CHANNEL_DOMAIN),
            &enclave.public_key(),
        )
        .expect("valid key")
    }

    /// Answers the client's binary frame with whatever `handler` sends back.
    async fn connect_to_stub<F, Fut>(handler: F) -> Socket
    where
        F: FnOnce(WebSocketStream<TcpStream>) -> Fut + Send + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
            .await
            .expect("should bind an ephemeral port");
        let address = listener
            .local_addr()
            .expect("listener should have an address");

        tokio::spawn(async move {
            let (stream, _) = listener.accept().await.expect("should accept");
            let socket = accept_async(stream).await.expect("should upgrade");
            handler(socket).await;
        });

        let (client, _) = connect_async(format!("ws://{address}"))
            .await
            .expect("client should upgrade");
        client
    }

    /// Reads one binary request frame and returns the responder sealed to the enclave.
    async fn open_request(socket: &mut WebSocketStream<TcpStream>) -> Arc<ChannelEnclave> {
        let request = socket
            .next()
            .await
            .expect("a frame")
            .expect("a valid frame");
        let Message::Binary(_) = request else {
            panic!("expected a binary match frame");
        };
        Arc::new(
            ChannelEnclave::generate(ChannelDomain::new(MATCH_CHANNEL_DOMAIN))
                .expect("channel key"),
        )
    }

    fn responder() -> Arc<ChannelEnclave> {
        Arc::new(
            ChannelEnclave::generate(ChannelDomain::new(MATCH_CHANNEL_DOMAIN))
                .expect("channel key"),
        )
    }

    async fn rejection_round_trip(foreign_reply: bool) -> Result<VerifiedMatchResult, Error> {
        let responder = responder();
        let answer = MatchResult::Failed(FailureReason::MalformedInputs);
        let server = Arc::clone(&responder);

        let mut socket = connect_to_stub(move |mut socket| async move {
            let request = socket
                .next()
                .await
                .expect("a frame")
                .expect("a valid frame");
            let Message::Binary(ciphertext) = request else {
                panic!("expected a binary match frame");
            };
            let (_, own_sealer) = server.open(&ciphertext).expect("opens its own request");
            let sealer = if foreign_reply {
                let stranger = consumer_for(&server);
                let (other, _) = stranger.seal_to_enclave(b"unrelated").expect("seal");
                server.open(&other).expect("opens its own").1
            } else {
                own_sealer
            };
            let encoded = answer.to_padded_cbor().expect("fits the envelope");
            socket
                .send(Message::Binary(sealer.seal(&encoded).unwrap().into()))
                .await
                .expect("should send");
        })
        .await;

        exchange_match(
            &mut socket,
            &consumer_for(&responder),
            &inputs(),
            &verifier(),
            TIMEOUT,
        )
        .await
    }

    #[tokio::test]
    async fn a_sealed_rejection_round_trips_over_the_socket() {
        let result = rejection_round_trip(false)
            .await
            .expect("a rejection is a normal return");

        assert!(matches!(
            result,
            VerifiedMatchResult::Failed(FailureReason::MalformedInputs)
        ));
    }

    #[tokio::test]
    async fn a_reply_from_another_exchange_cannot_be_opened() {
        let error = rejection_round_trip(true)
            .await
            .expect_err("a reply sealed on another exchange must not open");

        assert!(matches!(error, Error::Channel(_)), "got {error:?}");
    }

    #[tokio::test]
    async fn a_ping_storm_does_not_extend_the_phase_deadline() {
        let mut socket = connect_to_stub(|mut socket| async move {
            let _ = open_request(&mut socket).await;
            let ping = Message::Ping(Vec::new().into());
            // Keeps pinging well past the client's deadline: a per-read timeout would be reset
            // by each frame and never elapse.
            for _ in 0..500 {
                if socket.send(ping.clone()).await.is_err() {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await;

        let started = std::time::Instant::now();
        let error = exchange_match(
            &mut socket,
            &consumer_for(&responder()),
            &inputs(),
            &verifier(),
            Duration::from_millis(100),
        )
        .await
        .expect_err("a stream of pings must not keep the phase alive");

        assert!(matches!(error, Error::Timeout), "got {error:?}");
        assert!(
            started.elapsed() < Duration::from_secs(1),
            "the deadline was restarted by pings"
        );
    }

    #[tokio::test]
    async fn an_oversized_binary_response_is_rejected() {
        let mut socket = connect_to_stub(|mut socket| async move {
            let _ = open_request(&mut socket).await;
            let oversized = vec![0u8; MAX_MATCH_RESPONSE_BYTES + 1];
            socket
                .send(Message::Binary(oversized.into()))
                .await
                .expect("should send");
        })
        .await;

        let error = exchange_match(
            &mut socket,
            &consumer_for(&responder()),
            &inputs(),
            &verifier(),
            TIMEOUT,
        )
        .await
        .expect_err("an oversized response must be rejected");

        assert!(matches!(error, Error::MalformedResult), "got {error:?}");
    }

    #[tokio::test]
    async fn an_empty_binary_response_is_rejected() {
        let mut socket = connect_to_stub(|mut socket| async move {
            let _ = open_request(&mut socket).await;
            socket
                .send(Message::Binary(Vec::new().into()))
                .await
                .expect("should send");
        })
        .await;

        let error = exchange_match(
            &mut socket,
            &consumer_for(&responder()),
            &inputs(),
            &verifier(),
            TIMEOUT,
        )
        .await
        .expect_err("an empty response must be rejected");

        assert!(matches!(error, Error::Channel(_)), "got {error:?}");
    }

    #[tokio::test]
    async fn an_error_envelope_before_the_result_surfaces() {
        let mut socket = connect_to_stub(|mut socket| async move {
            let _ = open_request(&mut socket).await;
            let envelope =
                r#"{"allowRetry":true,"error":{"code":"reassign_required","message":"stale"}}"#;
            socket
                .send(Message::Text(envelope.into()))
                .await
                .expect("should send");
        })
        .await;

        let error = exchange_match(
            &mut socket,
            &consumer_for(&responder()),
            &inputs(),
            &verifier(),
            TIMEOUT,
        )
        .await
        .expect_err("an envelope is an error");

        assert!(matches!(error, Error::ReassignRequired), "got {error:?}");
    }

    #[tokio::test]
    async fn unexpected_text_before_the_result_is_rejected() {
        let mut socket = connect_to_stub(|mut socket| async move {
            let _ = open_request(&mut socket).await;
            socket
                .send(Message::Text("not json".into()))
                .await
                .expect("should send");
        })
        .await;

        let error = exchange_match(
            &mut socket,
            &consumer_for(&responder()),
            &inputs(),
            &verifier(),
            TIMEOUT,
        )
        .await
        .expect_err("stray text must be rejected");

        assert!(matches!(error, Error::MalformedMessage), "got {error:?}");
    }

    #[tokio::test]
    async fn a_statement_whose_attestation_does_not_verify_is_rejected_over_the_socket() {
        let responder = responder();
        let answer = MatchResult::Success(AttestedStatement {
            token: MatchToken::from_bytes(b"cose-sign1".to_vec()),
            signing_key_attestation: b"not a COSE attestation document".to_vec(),
        });
        let server = Arc::clone(&responder);

        let mut socket = connect_to_stub(move |mut socket| async move {
            let request = socket
                .next()
                .await
                .expect("a frame")
                .expect("a valid frame");
            let Message::Binary(ciphertext) = request else {
                panic!("expected a binary match frame");
            };
            let (_, sealer) = server.open(&ciphertext).expect("opens its own request");
            let encoded = answer.to_padded_cbor().expect("fits the envelope");
            socket
                .send(Message::Binary(sealer.seal(&encoded).unwrap().into()))
                .await
                .expect("should send");
        })
        .await;

        let error = exchange_match(
            &mut socket,
            &consumer_for(&responder),
            &inputs(),
            &verifier(),
            TIMEOUT,
        )
        .await
        .expect_err("an unverifiable attestation must not yield a statement");

        assert!(matches!(error, Error::Attestation(_)), "got {error:?}");
    }

    #[test]
    fn base_urls_map_onto_the_matches_endpoint() {
        let secure = websocket_url(&url::Url::parse("https://verifier.example.com").unwrap())
            .expect("https should map");
        assert_eq!(secure.as_str(), "wss://verifier.example.com/v1/matches");

        let plain = websocket_url(&url::Url::parse("http://127.0.0.1:8080").unwrap())
            .expect("http should map");
        assert_eq!(plain.as_str(), "ws://127.0.0.1:8080/v1/matches");

        let prefixed =
            websocket_url(&url::Url::parse("https://verifier.example.com/verifier/").unwrap())
                .expect("a prefixed base URL should map");
        assert_eq!(
            prefixed.as_str(),
            "wss://verifier.example.com/verifier/v1/matches"
        );
    }

    #[test]
    fn a_non_http_base_url_scheme_is_rejected() {
        let error = websocket_url(&url::Url::parse("ftp://verifier.example.com").unwrap())
            .expect_err("a non-http scheme has no WebSocket mapping");

        assert!(
            matches!(error, Error::InvalidConfig { .. }),
            "got {error:?}"
        );
    }
}