useceleris_client/credentials.rs
1use std::fmt;
2use std::future::Future;
3use std::pin::Pin;
4use std::sync::Arc;
5use std::time::{Duration, SystemTime};
6
7use crate::errors::{CelerisError, configuration_error, failure};
8
9/// Authorizes one connection attempt. Both values are opaque: the SDK never
10/// parses, re-serializes or generates them. A trusted server signs them; a
11/// client only passes them on.
12///
13/// `Debug` shows them as redacted, so they never reach a log by accident.
14#[derive(Clone, PartialEq, Eq)]
15pub struct Credentials {
16 pub payload: String,
17 pub signature: String,
18} // end struct Credentials
19
20impl fmt::Debug for Credentials {
21 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
22 formatter.write_str("Credentials { redacted }")
23 } // end method fmt
24} // end impl Debug for Credentials
25
26/// Why credentials are requested.
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub enum CredentialReason {
29 /// The attempt that [`Channel::connect`](crate::Channel::connect) starts.
30 Initial,
31
32 /// An automatic reconnect.
33 Reconnect {
34 /// When the connection dropped.
35 disconnected_at: SystemTime,
36
37 /// A suggestion for how much history to replay: the outage so far plus
38 /// five seconds of overlap. The signing server decides if it signs any
39 /// replay into the credentials.
40 replay_lookback: Duration,
41 },
42} // end enum CredentialReason
43
44/// Describes the attempt that credentials are requested for. Credentials are
45/// requested fresh for every attempt, reconnects included (D-001).
46#[derive(Clone, Debug, PartialEq, Eq)]
47pub struct CredentialRequest {
48 pub channel_reference: String,
49 pub reason: CredentialReason,
50} // end struct CredentialRequest
51
52/// Any error that a credential provider returns. The SDK never inspects it or
53/// passes it on.
54pub type ProviderError = Box<dyn std::error::Error + Send + Sync>;
55
56/// The future that a credential provider returns.
57pub type CredentialFuture =
58 Pin<Box<dyn Future<Output = Result<Credentials, ProviderError>> + Send>>;
59
60/// Fetches credentials for one attempt, typically from your own credential
61/// endpoint.
62///
63/// The SDK drops the provider's future when the attempt's deadline passes or
64/// the channel closes, and discards anything that it would return afterwards.
65/// An error or a panic is reported as [`CelerisError::Transport`]; the SDK
66/// never inspects or passes on its detail.
67#[derive(Clone)]
68pub struct CredentialProvider {
69 provide: Arc<dyn Fn(CredentialRequest) -> CredentialFuture + Send + Sync>,
70} // end struct CredentialProvider
71
72impl CredentialProvider {
73 /// Wraps an async function or closure:
74 ///
75 /// ```
76 /// use useceleris_client::{CredentialProvider, Credentials};
77 ///
78 /// let provider = CredentialProvider::new(|_request| async {
79 /// // Fetch these from your own credential endpoint.
80 /// Ok(Credentials {
81 /// payload: "payload".to_owned(),
82 /// signature: "signature".to_owned(),
83 /// })
84 /// });
85 /// ```
86 pub fn new<Provide, Provided>(provide: Provide) -> CredentialProvider
87 where
88 Provide: Fn(CredentialRequest) -> Provided + Send + Sync + 'static,
89 Provided: Future<Output = Result<Credentials, ProviderError>> + Send + 'static,
90 {
91 CredentialProvider {
92 provide: Arc::new(move |request| Box::pin(provide(request))),
93 }
94 } // end fn new
95
96 /// Calls the provider.
97 pub fn provide(&self, request: CredentialRequest) -> CredentialFuture {
98 (self.provide)(request)
99 } // end method provide
100} // end impl CredentialProvider
101
102impl fmt::Debug for CredentialProvider {
103 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
104 formatter.write_str("CredentialProvider")
105 } // end method fmt
106} // end impl Debug for CredentialProvider
107
108/// Checks what a provider returned, naming the field that failed but never its
109/// value. Rust text is always valid UTF-8, so only emptiness remains to check
110/// (D-003).
111pub(crate) fn validate_credentials(credentials: &Credentials) -> Result<(), CelerisError> {
112 let mut failures = Vec::new();
113
114 if credentials.payload.is_empty() {
115 failures.push(failure("payload", "Must not be empty"));
116 }
117
118 if credentials.signature.is_empty() {
119 failures.push(failure("signature", "Must not be empty"));
120 }
121
122 if !failures.is_empty() {
123 return Err(configuration_error("credentials", &failures));
124 }
125
126 Ok(())
127} // end fn validate_credentials