spiffe/workload_api/
x509_source.rs

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
//! # X509Source Module
//!
//! This module provides a source of X.509 SVIDs and X.509 bundles, backed by a workload API client
//! that continuously fetches the X.509 context (SVIDs and bundles) behind the scenes.
//! This ensures that the `X509Source` is always up to date.
//!
//! It allows for fetching and managing X.509 SVIDs and bundles, and includes functionality for updating
//! the context and closing the source. Users can utilize the `X509Source` to obtain SVIDs and bundles,
//! listen for updates, and manage the lifecycle of the source.
//!
//! ## Usage
//!
//! The `X509Source` can be created and configured to fetch SVIDs and bundles, respond to updates, and
//! handle closing. It provides a seamless interface for working with X.509 SVIDs and bundles.
//!
//! ### Example
//!
//! ```no_run
//! use spiffe::{BundleSource, SvidSource, TrustDomain, X509Source};
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
//! let source = X509Source::default().await?;
//! let svid = source.get_svid()?;
//! let trust_domain = TrustDomain::new("example.org").unwrap();
//! let bundle = source
//!     .get_bundle_for_trust_domain(&trust_domain)
//!     .map_err(|e| {
//!         format!(
//!             "Failed to get bundle for trust domain {}: {}",
//!             trust_domain, e
//!         )
//!     })?;
//!
//! # Ok(())
//! # }
//! ```
//!
//! ## Error Handling
//!
//! The `X509SourceError` enum provides detailed error information, including errors related to GRPC client failures,
//! lock issues, and other non-specific errors.
//!
//! ## Update Handling
//!
//! The `X509Source` provides a method to listen for updates, allowing parts of your system to respond to changes.
//! The `updated` method returns a `watch::Receiver<()>` that can be used to listen for notifications when the `X509Source` is updated.
//!
//! ## Closing the Source
//!
//! The `close` method can be used to close the `X509Source`, canceling all spawned tasks and stopping updates.
use crate::error::GrpcClientError;
use crate::{
    BundleSource, SvidSource, TrustDomain, WorkloadApiClient, X509Bundle, X509BundleSet,
    X509Context, X509Svid,
};
use log::{debug, error, info};
use std::error::Error;
use std::fmt::Debug;
use std::sync::{Arc, PoisonError, RwLock};
use thiserror::Error;
use tokio::sync::watch;
use tokio_stream::StreamExt;
use tokio_util::sync::CancellationToken;

/// `SvidPicker` is a trait defining the behavior for selecting an `X509Svid`.
///
/// Implementors of this trait must provide a concrete implementation of the `pick_svid` method, which
/// takes a reference to a slice of `X509Svid` and returns an `Option<&X509Svid>`.
///
/// The trait requires that implementing types are both `Send` and `Sync`, ensuring that they can be
/// sent between threads and accessed concurrently.
///
/// # Example
///
/// ```
/// use spiffe::workload_api::x509_source::SvidPicker;
/// use spiffe::X509Svid;
///
/// #[derive(Debug)]
/// struct SecondSvidPicker;
///
/// impl SvidPicker for SecondSvidPicker {
///     fn pick_svid<'a>(&self, svids: &'a [X509Svid]) -> Option<&'a X509Svid> {
///         svids.get(1) // return second svid
///     }
/// }
/// ```
pub trait SvidPicker: Debug + Send + Sync {
    /// Selects an `X509Svid` from the provided slice of `X509Svid`.
    ///
    /// # Parameters
    /// * `svids`: A reference to a slice of `X509Svid` from which the `X509Svid` should be selected.
    ///
    /// # Returns
    /// * An `Option<&X509Svid>`, where a `None` value indicates that no suitable `X509Svid` was found.
    fn pick_svid<'a>(&self, svids: &'a [X509Svid]) -> Option<&'a X509Svid>;
}

/// Enumerates errors that can occur within the X509Source.
#[derive(Debug, Error)]
pub enum X509SourceError {
    /// Error when a GRPC client fails to fetch an X509Context.
    #[error("GRPC client error: {0}")]
    GrpcError(GrpcClientError),

    /// Error when no suitable SVID is found by the picker.
    #[error("No suitable SVID found by picker")]
    NoSuitableSvid,

    /// Error related to internal operations.
    #[error("Internal error while {0}: {1}")]
    InternalError(String, String),

    /// Other non-specific error.
    #[error("{0}")]
    Other(String),
}

impl X509SourceError {
    fn from_lock_err<T>(err: PoisonError<T>, action: &str) -> Self {
        X509SourceError::InternalError(action.to_string(), err.to_string())
    }
}

/// Represents a source of X.509 SVIDs and X.509 bundles.
///
///
/// `X509Source` implements the [`BundleSource`] and [`SvidSource`] traits.
///
/// The methods return cloned instances of the underlying objects.
#[derive(Debug)]
pub struct X509Source {
    svid: RwLock<Option<X509Svid>>,
    bundles: RwLock<Option<X509BundleSet>>,
    svid_picker: Option<Box<dyn SvidPicker>>,
    workload_api_client: WorkloadApiClient,
    closed: RwLock<bool>,
    cancellation_token: CancellationToken,
    update_notifier: watch::Sender<()>,
    updated: watch::Receiver<()>,
}

/// Builder for `X509Source`.
#[derive(Debug)]
pub struct X509SourceBuilder {
    client: Option<WorkloadApiClient>,
    svid_picker: Option<Box<dyn SvidPicker>>,
}

/// A builder for creating a new `X509Source` with optional client and svid_picker configurations.
///
/// Allows for customization by accepting a client and/or svid_picker.
///
/// # Example
///
/// ```no_run
/// use spiffe::workload_api::x509_source::{SvidPicker, X509SourceBuilder};
/// use spiffe::{WorkloadApiClient, X509Svid};
/// use std::error::Error;
///
/// #[derive(Debug)]
/// struct SecondSvidPicker;
///
/// impl SvidPicker for SecondSvidPicker {
///     fn pick_svid<'a>(&self, svids: &'a [X509Svid]) -> Option<&'a X509Svid> {
///         svids.get(1) // return second svid
///     }
/// }
///
/// # async fn example() -> Result<(), Box< dyn Error>> {
/// let client = WorkloadApiClient::default().await?;
/// let source = X509SourceBuilder::new()
///     .with_client(client)
///     .with_picker(Box::new(SecondSvidPicker))
///     .build()
///     .await?;
///
/// # Ok(())
/// # }
/// ```
///
/// # Returns
/// A `Result` containing an `Arc<X509Source>` or an `X509SourceError` if an error occurs.
impl X509SourceBuilder {
    /// Creates a new `X509SourceBuilder`.
    pub fn new() -> Self {
        Self {
            client: None,
            svid_picker: None,
        }
    }

    /// Sets the Workload API client to be used by the X509Source.
    pub fn with_client(mut self, client: WorkloadApiClient) -> Self {
        self.client = Some(client);
        self
    }

    /// Sets the svid_picker to be used by the X509Source.
    pub fn with_picker(mut self, svid_picker: Box<dyn SvidPicker>) -> Self {
        self.svid_picker = Some(svid_picker);
        self
    }

    /// Builds an `X509Source` using the provided configuration.
    pub async fn build(self) -> Result<Arc<X509Source>, X509SourceError> {
        let client = match self.client {
            Some(client) => client,
            None => WorkloadApiClient::default()
                .await
                .map_err(X509SourceError::GrpcError)?,
        };

        X509Source::new(client, self.svid_picker).await
    }
}

impl Default for X509SourceBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl SvidSource for X509Source {
    type Item = X509Svid;

    /// Retrieves the X.509 SVID from the source.
    ///
    /// # Returns
    ///
    /// An `Result<Option<X509Svid>, Box<dyn Error + Send + Sync + 'static>>` containing the X.509 SVID if available.
    /// Returns `Ok(None)` if no SVID is found.
    /// Returns an error if the source is closed or if there's an issue fetching the SVID.
    fn get_svid(&self) -> Result<Option<Self::Item>, Box<dyn Error + Send + Sync + 'static>> {
        self.assert_not_closed().map_err(Box::new)?;

        let svid_option = self
            .svid
            .read()
            .map_err(|e| X509SourceError::from_lock_err(e, "reading SVIDs from source"))?;

        Ok(svid_option.clone())
    }
}

impl BundleSource for X509Source {
    type Item = X509Bundle;

    /// Retrieves the X.509 bundle for the given trust domain.
    ///
    /// # Arguments
    /// * `trust_domain` - The trust domain for which the X.509 bundle is to be retrieved.
    ///
    /// # Returns
    /// A `Result` containing an `Option<X509Bundle>` for the given trust domain. If the bundle is not found, returns `Ok(None)`.
    ///
    /// # Errors
    /// Returns a boxed error if the source is closed or if there is an issue accessing the bundle.
    fn get_bundle_for_trust_domain(
        &self,
        trust_domain: &TrustDomain,
    ) -> Result<Option<Self::Item>, Box<dyn Error + Send + Sync + 'static>> {
        self.assert_not_closed().map_err(Box::new)?;

        // Read the bundles
        let bundles_option = self
            .bundles
            .read()
            .map_err(|e| X509SourceError::from_lock_err(e, "reading bundles from source"))?;
        let bundle_set = match bundles_option.as_ref() {
            Some(set) => set,
            None => return Ok(None),
        };

        // Get the bundle for the trust domain
        let bundle = bundle_set.get_bundle(trust_domain);

        // Return the bundle if found, or Ok(None) if not found
        Ok(bundle.cloned())
    }
}

// public methods
impl X509Source {
    /// Builds a new `X509Source` using a default [`WorkloadApiClient`] and no SVID picker.
    /// Since no SVID picker is provided, the `get_svid` method will return the default SVID.
    ///
    /// This method is asynchronous and may return an error if the initialization fails.
    pub async fn default() -> Result<Arc<Self>, X509SourceError> {
        X509SourceBuilder::new().build().await
    }

    /// Returns a `watch::Receiver<()>` that can be used to listen for notifications when the X509Source is updated.
    ///
    /// # Example
    ///
    /// ``no_run
    /// let mut update_channel = source.updated(); // Get the watch receiver for the source
    ///
    /// // Asynchronously handle updates in a loop
    /// tokio::spawn(async move {
    ///     loop {
    ///         match update_channel.changed().await {
    ///             Ok(_) => {
    ///                 println!("X509Source was updated!");
    ///             },
    ///             Err(_) => {
    ///                 println!("Watch channel closed; exiting update loop");
    ///                 break;
    ///             }
    ///         }
    ///     }
    /// });
    /// ```
    pub fn updated(&self) -> watch::Receiver<()> {
        self.updated.clone()
    }

    /// Closes the X509Source cancelling all spawned tasks.
    pub fn close(&self) -> Result<(), X509SourceError> {
        self.assert_not_closed()?;

        let mut closed = self
            .closed
            .write()
            .map_err(|e| X509SourceError::from_lock_err(e, "closing source"))?;
        *closed = true;

        self.cancellation_token.cancel();

        info!("X509Source has been closed.");
        Ok(())
    }
}

// private methods
impl X509Source {
    async fn new(
        client: WorkloadApiClient,
        svid_picker: Option<Box<dyn SvidPicker>>,
    ) -> Result<Arc<X509Source>, X509SourceError> {
        let (update_notifier, updated) = watch::channel(());
        let cancellation_token = CancellationToken::new();
        let cancellation_token_clone = cancellation_token.clone();

        let source = Arc::new(X509Source {
            svid: RwLock::new(None),
            bundles: RwLock::new(None),
            workload_api_client: client,
            closed: RwLock::new(false),
            svid_picker,
            cancellation_token,
            updated,
            update_notifier,
        });

        let source_clone = Arc::clone(&source);
        let mut client_clone = source_clone.workload_api_client.clone();
        let mut stream = client_clone
            .stream_x509_contexts()
            .await
            .map_err(X509SourceError::GrpcError)?;

        // Block until the first X509Context is fetched.
        if let Some(update) = stream.next().await {
            match update {
                Ok(x509_context) => source_clone.set_x509_context(x509_context).map_err(|e| {
                    X509SourceError::Other(format!("Failed to set X509Context: {}", e))
                })?,
                Err(e) => return Err(X509SourceError::GrpcError(e)),
            }
        } else {
            return Err(X509SourceError::Other(
                "Stream ended without an update".to_string(),
            ));
        }

        // Spawn a task to handle subsequent updates
        tokio::spawn(async move {
            loop {
                if cancellation_token_clone.is_cancelled() {
                    debug!("Cancellation signal received; stopping updates.");
                    break;
                }

                match stream.next().await {
                    Some(update) => match update {
                        Ok(x509_context) => {
                            if let Err(e) = source_clone.set_x509_context(x509_context) {
                                error!("Error updating X509 context: {}", e);
                            } else {
                                info!("X509 context updated successfully.");
                            }
                        }
                        Err(e) => error!("GRPC client error: {}", e),
                    },
                    None => {
                        error!("Stream ended; no more updates will be received.");
                        break;
                    }
                }
            }
        });

        Ok(source)
    }

    fn set_x509_context(&self, x509_context: X509Context) -> Result<(), X509SourceError> {
        let svid = if let Some(ref svid_picker) = self.svid_picker {
            svid_picker
                .pick_svid(x509_context.svids())
                .ok_or(X509SourceError::NoSuitableSvid)?
        } else {
            x509_context
                .default_svid()
                .ok_or(X509SourceError::NoSuitableSvid)?
        };

        self.set_svid(svid)?;

        self.bundles
            .write()
            .map_err(|e| {
                X509SourceError::InternalError(
                    "writing bundles to source".to_string(),
                    e.to_string(),
                )
            })?
            .replace(x509_context.bundle_set().clone());

        self.notify_update();
        Ok(())
    }

    fn set_svid(&self, svid: &X509Svid) -> Result<(), X509SourceError> {
        self.svid
            .write()
            .map_err(|e| {
                X509SourceError::InternalError("writing SVID to source".to_string(), e.to_string())
            })?
            .replace(svid.clone());
        Ok(())
    }

    fn notify_update(&self) {
        let _ = self.update_notifier.send(());
    }

    fn assert_not_closed(&self) -> Result<(), X509SourceError> {
        let closed = self.closed.read().map_err(|e| {
            X509SourceError::InternalError(
                "reading closed state from source".to_string(),
                e.to_string(),
            )
        })?;
        if *closed {
            return Err(X509SourceError::Other("X509Source is closed".into()));
        }
        Ok(())
    }
}