Skip to main content

toolkit_contract/runtime/
platform_credential.rs

1//! The **outbound** platform-plane credential, built from `internal_auth` config
2//! (`cpt-cf-adr-two-plane-auth`).
3//!
4//! This is the single config → credential mapping. It yields a transport-agnostic
5//! [`InternalTokenProvider`]; transports adapt it instead of resolving config on
6//! their own:
7//!
8//! - REST and generated gRPC clients take the provider as is (via `ClientTuning`
9//!   / `GearCtx`).
10//! - Hand-written tonic clients (the `DirectoryService` client, cluster-sdk) wrap
11//!   it with [`internal_auth_interceptor`].
12//!
13//! Every carrier therefore applies the same attach policy,
14//! [`InternalTokenProvider::resolve_for_attach`]: `Available` attaches, an
15//! `Unavailable` source warns, and `NotConfigured` is silent.
16
17use std::path::PathBuf;
18use std::time::Duration;
19
20use tokio_util::sync::CancellationToken;
21use toolkit_security::{InternalAuthConfig, InvalidOutboundAuth, OutboundSpec};
22use toolkit_transport_grpc::{
23    DEFAULT_REFRESH_INTERVAL, InternalAuthInterceptor, ServiceAccountTokenReader,
24};
25
26use crate::runtime::config::{CredentialState, InternalTokenProvider};
27
28/// Failure to build the outbound platform-plane credential from an
29/// [`InternalAuthConfig`].
30#[derive(Debug, thiserror::Error)]
31#[non_exhaustive]
32pub enum OutboundCredentialError {
33    /// The config cannot supply an outbound credential (no kube `present`
34    /// block, an empty token path, or an unusable shared secret), per
35    /// [`InternalAuthConfig::outbound`].
36    #[error(transparent)]
37    Config(#[from] InvalidOutboundAuth),
38    /// The projected service-account token could not be read (or was empty) on
39    /// the initial load.
40    #[error("cannot read projected service-account token at {}: {source}", path.display())]
41    TokenUnreadable {
42        /// The configured `present.token_path`.
43        path: PathBuf,
44        /// The underlying I/O failure.
45        #[source]
46        source: std::io::Error,
47    },
48}
49
50/// Build the outbound platform-plane [`InternalTokenProvider`] from `cfg`. Call
51/// it only from code that sends platform-plane calls: it always yields a
52/// credential, or an error.
53///
54/// - `shared_secret` → a provider that always yields the secret.
55/// - `kube` with a `present` block → a provider backed by a
56///   [`ServiceAccountTokenReader`]: the token at `present.token_path` is read
57///   once, then re-read every [`DEFAULT_REFRESH_INTERVAL`] until a child of
58///   `cancel` is cancelled (or every clone of the provider is dropped). A failed
59///   or empty re-read keeps the previous token.
60/// - `kube` without a `present` block → an error.
61///
62/// # Errors
63/// - [`OutboundCredentialError::Config`] when [`InternalAuthConfig::outbound`]
64///   refuses the config: a `shared_secret` that is empty or the redaction
65///   placeholder, or `kube` without a `present` block or with an empty path.
66/// - [`OutboundCredentialError::TokenUnreadable`] when `present.token_path`
67///   cannot be read, or is empty, on the initial load.
68pub async fn build_internal_token_provider(
69    cfg: &InternalAuthConfig,
70    cancel: &CancellationToken,
71) -> Result<InternalTokenProvider, OutboundCredentialError> {
72    build_with_interval(cfg, cancel, DEFAULT_REFRESH_INTERVAL).await
73}
74
75/// [`build_internal_token_provider`] with a custom refresh `interval` (for tests).
76async fn build_with_interval(
77    cfg: &InternalAuthConfig,
78    cancel: &CancellationToken,
79    interval: Duration,
80) -> Result<InternalTokenProvider, OutboundCredentialError> {
81    // `OutboundSpec` is exhaustive, so a new provider variant fails to compile
82    // here rather than silently fall through to "no outbound credential".
83    match cfg.outbound()? {
84        OutboundSpec::SharedSecret(secret) => Ok(InternalTokenProvider::from_token(secret.clone())),
85        OutboundSpec::ProjectedToken(token_path) => {
86            let reader = ServiceAccountTokenReader::with_cancellation(
87                token_path,
88                interval,
89                cancel.child_token(),
90            )
91            .await
92            .map_err(|source| OutboundCredentialError::TokenUnreadable {
93                path: token_path.to_path_buf(),
94                source,
95            })?;
96            // The initial read succeeded and re-reads keep the previous value on
97            // failure, so the reader should never yield `None` here. If it ever
98            // does, that is a broken source (`Unavailable`, warned), not an
99            // opt-out (`NotConfigured`, silent).
100            let token_fn = reader.token_provider();
101            Ok(InternalTokenProvider::new(move || match token_fn() {
102                Some(token) => CredentialState::Available(token),
103                None => CredentialState::Unavailable(
104                    "projected service-account token is currently unavailable \
105                     (file empty or not yet read)"
106                        .into(),
107                ),
108            }))
109        }
110    }
111}
112
113/// Adapt `provider` to a tonic client interceptor that attaches the credential
114/// to every outgoing request, under the shared attach policy
115/// ([`InternalTokenProvider::resolve_for_attach`]):
116///
117/// - `None` / `NotConfigured` → attach nothing, silently (Profile 1).
118/// - `Available` → attach the token.
119/// - `Unavailable` → attach nothing but warn, naming `client`. A broken
120///   credential source is not an intentional opt-out, and failing the call
121///   instead would take the fleet down when a token file goes briefly empty.
122///
123/// The provider is invoked per request, so a rotating token is picked up
124/// without rebuilding the channel. `client` names the caller in the warning:
125/// the interceptor runs before the method is known, so there is no per-RPC
126/// label.
127#[must_use]
128pub fn internal_auth_interceptor(
129    provider: Option<&InternalTokenProvider>,
130    client: &'static str,
131) -> InternalAuthInterceptor {
132    match provider {
133        Some(provider) => {
134            let provider = provider.clone();
135            InternalAuthInterceptor::new(move || {
136                InternalTokenProvider::resolve_for_attach(Some(&provider), client)
137            })
138        }
139        None => InternalAuthInterceptor::disabled(),
140    }
141}
142
143#[cfg(test)]
144#[cfg_attr(coverage_nightly, coverage(off))]
145mod tests {
146    use super::*;
147    use secrecy::{ExposeSecret, SecretString};
148    use tonic::service::Interceptor as _;
149    use toolkit_security::{InvalidSharedSecret, KubePresent, KubeVerify};
150
151    fn unique_dir(tag: &str) -> PathBuf {
152        use std::sync::atomic::{AtomicU64, Ordering};
153        static COUNTER: AtomicU64 = AtomicU64::new(0);
154        let n = COUNTER.fetch_add(1, Ordering::Relaxed);
155        std::env::temp_dir().join(format!("pc-{tag}-{}-{n}", std::process::id()))
156    }
157
158    fn kube(token_path: Option<PathBuf>) -> InternalAuthConfig {
159        InternalAuthConfig::Kube {
160            verify: Some(KubeVerify {
161                audiences: vec!["toolkit-internal".to_owned()],
162            }),
163            present: token_path.map(|token_path| KubePresent { token_path }),
164        }
165    }
166
167    fn shared_secret(secret: &str) -> InternalAuthConfig {
168        InternalAuthConfig::SharedSecret {
169            secret: secret.to_owned().into(),
170            peer_name: "toolkit-internal".to_owned(),
171        }
172    }
173
174    /// The token `provider` currently hands out, if `Available`.
175    fn available(provider: &InternalTokenProvider) -> Option<String> {
176        match provider.current() {
177            CredentialState::Available(token) => Some(token.expose_secret().to_owned()),
178            CredentialState::NotConfigured | CredentialState::Unavailable(_) => None,
179        }
180    }
181
182    /// The token `interceptor` attaches to a request, if any.
183    fn attached(interceptor: &mut InternalAuthInterceptor) -> Option<String> {
184        let request = interceptor
185            .call(tonic::Request::new(()))
186            .expect("interceptor runs");
187        toolkit_transport_grpc::extract_internal_token_grpc(request.metadata())
188            .ok()
189            .map(|t| t.expose_secret().to_owned())
190    }
191
192    #[tokio::test]
193    async fn shared_secret_yields_the_secret() {
194        let provider =
195            build_internal_token_provider(&shared_secret("shared-tok"), &CancellationToken::new())
196                .await
197                .expect("shared secret builds");
198        assert_eq!(available(&provider).as_deref(), Some("shared-tok"));
199    }
200
201    #[tokio::test]
202    async fn unusable_shared_secret_is_refused() {
203        for (secret, expected) in [
204            ("", InvalidSharedSecret::Empty),
205            (
206                toolkit_security::REDACTED_PLACEHOLDER,
207                InvalidSharedSecret::RedactedPlaceholder,
208            ),
209        ] {
210            let err =
211                build_internal_token_provider(&shared_secret(secret), &CancellationToken::new())
212                    .await
213                    .expect_err("an unusable secret must not become a credential");
214            match err {
215                OutboundCredentialError::Config(InvalidOutboundAuth::SharedSecret(got)) => {
216                    assert_eq!(got, expected);
217                }
218                other => panic!("expected an invalid shared secret, got {other:?}"),
219            }
220        }
221    }
222
223    #[tokio::test]
224    async fn kube_without_present_block_is_refused() {
225        let err = build_internal_token_provider(&kube(None), &CancellationToken::new())
226            .await
227            .expect_err("a caller that sends platform calls must not get an empty credential");
228        assert!(
229            matches!(
230                err,
231                OutboundCredentialError::Config(InvalidOutboundAuth::MissingKubePresent)
232            ),
233            "got {err:?}"
234        );
235        assert!(err.to_string().contains("present"), "got: {err}");
236    }
237
238    #[tokio::test]
239    async fn kube_with_present_block_reads_the_projected_token() {
240        let dir = unique_dir("kube");
241        tokio::fs::create_dir_all(&dir).await.expect("mkdir");
242        let path = dir.join("token");
243        tokio::fs::write(&path, "kube.sa.jwt").await.expect("write");
244
245        let provider = build_internal_token_provider(&kube(Some(path)), &CancellationToken::new())
246            .await
247            .expect("builds rotating provider");
248        assert_eq!(available(&provider).as_deref(), Some("kube.sa.jwt"));
249
250        tokio::fs::remove_dir_all(&dir).await.ok();
251    }
252
253    #[tokio::test]
254    async fn unreadable_token_path_is_named_in_the_error() {
255        let path = unique_dir("kube-missing").join("token");
256        let err =
257            build_internal_token_provider(&kube(Some(path.clone())), &CancellationToken::new())
258                .await
259                .expect_err("a missing token file must error");
260        match &err {
261            OutboundCredentialError::TokenUnreadable { path: p, source } => {
262                assert_eq!(p, &path);
263                assert_eq!(source.kind(), std::io::ErrorKind::NotFound);
264            }
265            other => panic!("expected TokenUnreadable, got {other:?}"),
266        }
267        assert!(
268            err.to_string().contains(&path.display().to_string()),
269            "error must name the token file: {err}"
270        );
271    }
272
273    #[tokio::test]
274    async fn refresh_task_stops_rereading_after_cancellation() {
275        const INTERVAL: Duration = Duration::from_millis(20);
276
277        let dir = unique_dir("kube-cancel");
278        tokio::fs::create_dir_all(&dir).await.expect("mkdir");
279        let path = dir.join("token");
280        tokio::fs::write(&path, "token-v1").await.expect("write");
281
282        let cancel = CancellationToken::new();
283        let provider = build_with_interval(&kube(Some(path.clone())), &cancel, INTERVAL)
284            .await
285            .expect("builds rotating provider");
286
287        // Before cancellation the task re-reads the file (rotation is seen).
288        tokio::fs::write(&path, "token-v2").await.expect("rotate");
289        let mut observed = None;
290        for _ in 0..100 {
291            tokio::time::sleep(INTERVAL).await;
292            observed = available(&provider);
293            if observed.as_deref() == Some("token-v2") {
294                break;
295            }
296        }
297        assert_eq!(observed.as_deref(), Some("token-v2"), "rotation observed");
298
299        // After cancellation it never re-reads, even though the provider (the
300        // only strong holder) is still alive.
301        cancel.cancel();
302        // Let an in-flight read (if any) finish so the task observes the cancel.
303        tokio::time::sleep(INTERVAL * 3).await;
304        tokio::fs::write(&path, "token-v3").await.expect("rotate");
305        tokio::time::sleep(INTERVAL * 10).await;
306        assert_eq!(
307            available(&provider).as_deref(),
308            Some("token-v2"),
309            "the file must not be re-read after cancellation"
310        );
311
312        tokio::fs::remove_dir_all(&dir).await.ok();
313    }
314
315    /// The interceptor is a thin adapter: it attaches exactly what the provider
316    /// hands out, so the gRPC carrier and the provider never disagree.
317    #[tokio::test]
318    async fn interceptor_attaches_the_providers_token() {
319        let provider =
320            build_internal_token_provider(&shared_secret("shared-tok"), &CancellationToken::new())
321                .await
322                .expect("shared secret builds");
323        let mut interceptor = internal_auth_interceptor(Some(&provider), "test");
324        assert_eq!(attached(&mut interceptor).as_deref(), Some("shared-tok"));
325    }
326
327    #[test]
328    fn interceptor_follows_the_attach_policy() {
329        let mut none = internal_auth_interceptor(None, "test");
330        assert_eq!(attached(&mut none), None, "no provider attaches nothing");
331
332        let not_configured = InternalTokenProvider::new(|| CredentialState::NotConfigured);
333        let mut interceptor = internal_auth_interceptor(Some(&not_configured), "test");
334        assert_eq!(attached(&mut interceptor), None);
335
336        let unavailable =
337            InternalTokenProvider::new(|| CredentialState::Unavailable("file empty".into()));
338        let mut interceptor = internal_auth_interceptor(Some(&unavailable), "test");
339        assert_eq!(
340            attached(&mut interceptor),
341            None,
342            "unavailable sends no token"
343        );
344
345        let rotating = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
346        let counter = std::sync::Arc::clone(&rotating);
347        let rotating = InternalTokenProvider::new(move || {
348            let n = counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
349            CredentialState::Available(SecretString::from(format!("token-{n}")))
350        });
351        let mut interceptor = internal_auth_interceptor(Some(&rotating), "test");
352        assert_eq!(attached(&mut interceptor).as_deref(), Some("token-0"));
353        assert_eq!(
354            attached(&mut interceptor).as_deref(),
355            Some("token-1"),
356            "the provider is resolved per request"
357        );
358    }
359}