faucet_core/auth.rs
1//! Shared, connector-agnostic authentication abstraction.
2//!
3//! Multiple connectors that authenticate against the **same** system (e.g. four
4//! matrix rows reading from one Snowflake account, or four endpoints of one REST
5//! API) can share a single [`AuthProvider`]. A provider is a live entity that
6//! owns the token cache and refresh lifecycle; connectors hold an [`Arc`] to it
7//! and ask for the current [`Credential`] per request, so N connectors share one
8//! token with single-flight refresh instead of racing to refresh it.
9//!
10//! - [`Credential`] — a resolved credential (bearer token, header, basic auth).
11//! - [`AuthProvider`] — an object-safe trait yielding credentials, with
12//! single-flight refresh implemented by the provider.
13//! - [`AuthSpec`] — a connector config field that is **either** inline auth
14//! `{ type, config }` **or** a `{ ref: <name> }` pointer to a shared provider.
15//!
16//! The HTTP-based provider implementations (OAuth2, token-endpoint) live in the
17//! separate `faucet-auth` crate so `faucet-core` stays free of an HTTP-client
18//! dependency.
19
20use crate::FaucetError;
21use async_trait::async_trait;
22use schemars::JsonSchema;
23use serde::{Deserialize, Deserializer, Serialize};
24use std::sync::Arc;
25
26/// A resolved credential produced by an [`AuthProvider`] or built from inline
27/// auth config. Connectors map this onto their wire protocol (HTTP header, gRPC
28/// metadata, …).
29///
30/// Intentionally **not** `#[non_exhaustive]`: connectors must map every variant,
31/// so adding one should be a compile error that forces correct handling rather
32/// than a silently-ignored fallback.
33#[derive(Clone, PartialEq, Eq)]
34pub enum Credential {
35 /// `Authorization: Bearer <token>`.
36 Bearer(String),
37 /// An explicit header name + value.
38 Header {
39 /// Header name (e.g. `Authorization`, `X-Api-Key`).
40 name: String,
41 /// Header value.
42 value: String,
43 },
44 /// HTTP Basic credentials.
45 Basic {
46 /// Username.
47 username: String,
48 /// Password.
49 password: String,
50 },
51 /// A raw token for connector-specific assembly (e.g. gRPC `authorization`
52 /// metadata, Snowflake's `Authorization` with a token-type header).
53 Token(String),
54}
55
56// `Debug` is hand-written (not derived) so a `{:?}` of a credential — or of any
57// struct that embeds one, e.g. a logged connector config or a `StaticProvider` —
58// never prints the secret in clear. The secret-bearing fields render as `"***"`;
59// the non-secret identifiers (header name, basic-auth username) stay visible so
60// the output is still useful for diagnostics. `Credential` is a 1.0-frozen public
61// type, so this redaction is part of its contract.
62impl std::fmt::Debug for Credential {
63 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64 match self {
65 Credential::Bearer(_) => f.debug_tuple("Bearer").field(&"***").finish(),
66 Credential::Header { name, .. } => f
67 .debug_struct("Header")
68 .field("name", name)
69 .field("value", &"***")
70 .finish(),
71 Credential::Basic { username, .. } => f
72 .debug_struct("Basic")
73 .field("username", username)
74 .field("password", &"***")
75 .finish(),
76 Credential::Token(_) => f.debug_tuple("Token").field(&"***").finish(),
77 }
78 }
79}
80
81impl Credential {
82 /// The value to use for an `Authorization` header, when this credential maps
83 /// to one. Returns `None` for credentials that are applied differently
84 /// (e.g. [`Credential::Basic`], which connectors apply via basic-auth, or
85 /// [`Credential::Header`], which carries its own name).
86 pub fn authorization_value(&self) -> Option<String> {
87 match self {
88 Credential::Bearer(t) => Some(format!("Bearer {t}")),
89 Credential::Token(t) => Some(t.clone()),
90 Credential::Header { .. } | Credential::Basic { .. } => None,
91 }
92 }
93}
94
95/// One placement of a captured credential into an outgoing HTTP request,
96/// produced by [`AuthProvider::request_auth`]. Unlike [`Credential`] (which is
97/// header/bearer-shaped), a placement can target a query parameter, cookie, or
98/// JSON body field — the shapes multi-step auth flows (#511) need.
99///
100/// `#[non_exhaustive]` so new placement kinds can be added as a minor change.
101#[derive(Clone, PartialEq, Eq)]
102#[non_exhaustive]
103pub enum CredentialPlacement {
104 /// An HTTP header `name: value`.
105 Header {
106 /// Header name.
107 name: String,
108 /// Header value.
109 value: String,
110 },
111 /// A query-string parameter `?name=value`.
112 Query {
113 /// Parameter name.
114 name: String,
115 /// Parameter value.
116 value: String,
117 },
118 /// A cookie `name=value` (sent via the `Cookie` header).
119 Cookie {
120 /// Cookie name.
121 name: String,
122 /// Cookie value.
123 value: String,
124 },
125 /// A top-level field of the JSON request body.
126 BodyField {
127 /// Field name.
128 name: String,
129 /// Field value (string).
130 value: String,
131 },
132}
133
134// Hand-written `Debug` redacts the secret-bearing `value` while keeping the
135// non-secret `name` visible — same contract as `Credential`.
136impl std::fmt::Debug for CredentialPlacement {
137 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138 let (kind, name) = match self {
139 CredentialPlacement::Header { name, .. } => ("Header", name),
140 CredentialPlacement::Query { name, .. } => ("Query", name),
141 CredentialPlacement::Cookie { name, .. } => ("Cookie", name),
142 CredentialPlacement::BodyField { name, .. } => ("BodyField", name),
143 };
144 f.debug_struct(kind)
145 .field("name", name)
146 .field("value", &"***")
147 .finish()
148 }
149}
150
151/// The per-request auth a provider contributes beyond a single [`Credential`]:
152/// zero or more [`CredentialPlacement`]s plus an optional dynamic base-URL that
153/// overrides the connector's configured one (captured from a login response —
154/// Bullhorn `restUrl`, Zoho region host, #511).
155///
156/// A connector that receives a non-[`is_empty`](RequestAuth::is_empty)
157/// `RequestAuth` uses it **instead of** the plain [`credential`](AuthProvider::credential)
158/// path for that request. `#[non_exhaustive]`: construct via [`RequestAuth::new`]
159/// and the builder methods so fields can be added as a minor change.
160#[derive(Clone, Default)]
161#[non_exhaustive]
162pub struct RequestAuth {
163 /// Credential placements to apply to the request.
164 pub placements: Vec<CredentialPlacement>,
165 /// Optional per-session base-URL override.
166 pub base_url: Option<String>,
167}
168
169impl RequestAuth {
170 /// An empty `RequestAuth` (no placements, no base-URL override).
171 pub fn new() -> Self {
172 Self::default()
173 }
174
175 /// Add a credential placement (builder).
176 #[must_use]
177 pub fn with_placement(mut self, placement: CredentialPlacement) -> Self {
178 self.placements.push(placement);
179 self
180 }
181
182 /// Set the dynamic base-URL override (builder).
183 #[must_use]
184 pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
185 self.base_url = Some(base_url.into());
186 self
187 }
188
189 /// True when the provider contributed nothing (the connector then falls back
190 /// to the plain [`credential`](AuthProvider::credential) path).
191 pub fn is_empty(&self) -> bool {
192 self.placements.is_empty() && self.base_url.is_none()
193 }
194}
195
196// Redacting `Debug`: placements redact their own values; the base-URL is passed
197// through `redact_uri_credentials` so any embedded userinfo is scrubbed.
198impl std::fmt::Debug for RequestAuth {
199 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200 f.debug_struct("RequestAuth")
201 .field("placements", &self.placements)
202 .field(
203 "base_url",
204 &self
205 .base_url
206 .as_deref()
207 .map(crate::util::redact_uri_credentials),
208 )
209 .finish()
210 }
211}
212
213/// A live, shareable source of credentials.
214///
215/// One instance is shared (via [`Arc`]) across all connectors that reference it,
216/// giving single-flight refresh: concurrent callers during a refresh await the
217/// one in-flight fetch rather than each refreshing independently.
218///
219/// Object-safe — no generics or associated types, so it can be held as
220/// `Arc<dyn AuthProvider>` ([`SharedAuthProvider`]).
221#[async_trait]
222pub trait AuthProvider: Send + Sync + std::fmt::Debug {
223 /// Return a currently-valid credential, refreshing if needed.
224 async fn credential(&self) -> Result<Credential, FaucetError>;
225
226 /// Force a refresh **iff** the cached credential still equals `stale`
227 /// (compare-and-swap). Multiple connectors that hit a `401` with the same
228 /// token collapse into a single refresh; callers holding an already-rotated
229 /// token get the new one without triggering another fetch.
230 ///
231 /// The default delegates to [`AuthProvider::credential`]; providers that
232 /// support refresh override it.
233 async fn invalidate(&self, _stale: &Credential) -> Result<Credential, FaucetError> {
234 self.credential().await
235 }
236
237 /// Per-request signing hook (OAuth1 and similar, #496).
238 ///
239 /// Most providers issue a **reusable** credential via [`credential`](Self::credential);
240 /// they return `Ok(None)` here (the default) and the connector applies the
241 /// cached credential. A provider that must sign **each request individually**
242 /// (e.g. OAuth1, whose signature covers the HTTP method, URL, and query
243 /// parameters) overrides this to compute a fresh [`Credential`] — typically a
244 /// [`Credential::Header`] carrying the `Authorization` signature — from the
245 /// request. When it returns `Some`, the connector uses it **instead of**
246 /// `credential()` for that request.
247 ///
248 /// `query` is the request's query parameters (the connector's, before the
249 /// HTTP client appends them), which OAuth1 folds into its signature base
250 /// string. Object-safe: no generics, all args are borrowed primitives.
251 async fn sign_request(
252 &self,
253 _method: &str,
254 _url: &str,
255 _query: &std::collections::BTreeMap<String, String>,
256 ) -> Result<Option<Credential>, FaucetError> {
257 Ok(None)
258 }
259
260 /// Richer per-request auth for multi-step flows (#511): credential
261 /// placements across header / query / cookie / body plus an optional
262 /// dynamic base-URL override.
263 ///
264 /// Most providers issue a single [`Credential`] and return an empty
265 /// [`RequestAuth`] here (the default); the connector then applies the plain
266 /// [`credential`](Self::credential) path. A provider that must place a
267 /// captured value somewhere other than a header, place several values at
268 /// once, or redirect the request to a captured base-URL overrides this. When
269 /// it returns a non-[`is_empty`](RequestAuth::is_empty) value, the connector
270 /// applies the placements **instead of** `credential()` for that request.
271 ///
272 /// `query` is the request's query parameters before the HTTP client appends
273 /// them (some flows fold them into a signature). Object-safe: no generics,
274 /// all args are borrowed primitives.
275 async fn request_auth(
276 &self,
277 _method: &str,
278 _url: &str,
279 _query: &std::collections::BTreeMap<String, String>,
280 ) -> Result<RequestAuth, FaucetError> {
281 Ok(RequestAuth::new())
282 }
283
284 /// HTTP status codes on which the connector should force a re-auth
285 /// (via [`invalidate`](Self::invalidate)) and retry the request once.
286 ///
287 /// The default is empty — connectors keep their built-in `401` handling.
288 /// A multi-step flow (#511) whose session cookie/token can expire mid-run
289 /// returns the statuses (e.g. `[401]`, `[401, 403]`) that mean "log in again".
290 fn reauth_statuses(&self) -> &[u16] {
291 &[]
292 }
293
294 /// Stable, non-empty name for diagnostics and metrics.
295 fn provider_name(&self) -> &'static str;
296}
297
298/// A shared [`AuthProvider`] handle. Cloning it shares the one live provider
299/// (and its single token cache) across connectors.
300pub type SharedAuthProvider = Arc<dyn AuthProvider>;
301
302/// A `{ ref: <name> }` pointer to a named provider in the top-level `auth:`
303/// catalog. The only permitted key is `ref`.
304#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
305#[serde(deny_unknown_fields)]
306pub struct AuthReference {
307 /// Name of the provider in the top-level `auth:` catalog.
308 #[serde(rename = "ref")]
309 pub name: String,
310}
311
312/// A connector's `auth:` field: **either** an inline auth definition `A`
313/// (the `{ type, config }` shape), **or** a `{ ref: <name> }` reference to a
314/// shared provider defined in the top-level `auth:` catalog.
315///
316/// `ref` is mutually exclusive with inline fields — supplying both is a
317/// deserialization error.
318#[derive(Debug, Clone, Serialize, JsonSchema)]
319#[serde(untagged)]
320pub enum AuthSpec<A> {
321 /// Inline auth, spelled out on the connector.
322 Inline(A),
323 /// A reference to a shared provider in the top-level `auth:` catalog.
324 Reference(AuthReference),
325}
326
327impl<A: Default> Default for AuthSpec<A> {
328 fn default() -> Self {
329 AuthSpec::Inline(A::default())
330 }
331}
332
333impl<A> AuthSpec<A> {
334 /// The inline auth, if this is not a reference.
335 pub fn inline(&self) -> Option<&A> {
336 match self {
337 AuthSpec::Inline(a) => Some(a),
338 AuthSpec::Reference(_) => None,
339 }
340 }
341
342 /// The referenced provider name, if this is a reference.
343 pub fn reference_name(&self) -> Option<&str> {
344 match self {
345 AuthSpec::Reference(r) => Some(&r.name),
346 AuthSpec::Inline(_) => None,
347 }
348 }
349}
350
351// Manual `Deserialize` enforces the `ref`-XOR-inline rule, which a plain
352// `#[serde(untagged)]` derive cannot (it would silently ignore extra keys).
353impl<'de, A> Deserialize<'de> for AuthSpec<A>
354where
355 A: serde::de::DeserializeOwned,
356{
357 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
358 where
359 D: Deserializer<'de>,
360 {
361 let value = serde_json::Value::deserialize(deserializer)?;
362 let has_ref = value.get("ref").is_some();
363 if has_ref {
364 let has_other = value
365 .as_object()
366 .map(|o| o.keys().any(|k| k != "ref"))
367 .unwrap_or(false);
368 if has_other {
369 return Err(serde::de::Error::custom(
370 "auth: `ref` cannot be combined with inline auth fields (type/config)",
371 ));
372 }
373 let r: AuthReference =
374 serde_json::from_value(value).map_err(serde::de::Error::custom)?;
375 return Ok(AuthSpec::Reference(r));
376 }
377 let inner: A = serde_json::from_value(value).map_err(serde::de::Error::custom)?;
378 Ok(AuthSpec::Inline(inner))
379 }
380}
381
382#[cfg(test)]
383mod tests {
384 use super::*;
385
386 #[derive(Debug, Deserialize, PartialEq)]
387 #[serde(tag = "type", content = "config", rename_all = "snake_case")]
388 enum StubAuth {
389 None,
390 Bearer { token: String },
391 }
392
393 #[derive(Debug)]
394 struct MinimalProvider;
395
396 #[async_trait]
397 impl AuthProvider for MinimalProvider {
398 async fn credential(&self) -> Result<Credential, FaucetError> {
399 Ok(Credential::Bearer("t".into()))
400 }
401 fn provider_name(&self) -> &'static str {
402 "minimal"
403 }
404 }
405
406 #[test]
407 fn credential_placement_debug_redacts_value_keeps_name() {
408 let cases = [
409 CredentialPlacement::Header {
410 name: "X-Tok".into(),
411 value: "secret".into(),
412 },
413 CredentialPlacement::Query {
414 name: "access_token".into(),
415 value: "secret".into(),
416 },
417 CredentialPlacement::Cookie {
418 name: "sid".into(),
419 value: "secret".into(),
420 },
421 CredentialPlacement::BodyField {
422 name: "auth".into(),
423 value: "secret".into(),
424 },
425 ];
426 for p in cases {
427 let s = format!("{p:?}");
428 assert!(s.contains("***"), "value must be redacted: {s}");
429 assert!(!s.contains("secret"), "secret leaked: {s}");
430 }
431 }
432
433 #[test]
434 fn request_auth_builders_and_is_empty() {
435 let empty = RequestAuth::new();
436 assert!(empty.is_empty());
437
438 let ra = RequestAuth::new()
439 .with_placement(CredentialPlacement::Query {
440 name: "t".into(),
441 value: "v".into(),
442 })
443 .with_base_url("https://host");
444 assert!(!ra.is_empty());
445 assert_eq!(ra.placements.len(), 1);
446 assert_eq!(ra.base_url.as_deref(), Some("https://host"));
447
448 // base-URL alone (no placements) is still non-empty.
449 assert!(!RequestAuth::new().with_base_url("https://h").is_empty());
450 assert!(RequestAuth::default().is_empty());
451 }
452
453 #[test]
454 fn request_auth_debug_redacts_placements_and_base_url() {
455 let ra = RequestAuth::new()
456 .with_placement(CredentialPlacement::Header {
457 name: "Authorization".into(),
458 value: "topsecret".into(),
459 })
460 .with_base_url("https://user:pw@host/path");
461 let s = format!("{ra:?}");
462 assert!(!s.contains("topsecret"), "placement value leaked: {s}");
463 assert!(!s.contains("pw"), "base-url userinfo leaked: {s}");
464 }
465
466 #[tokio::test]
467 async fn default_request_auth_is_empty_and_reauth_is_empty() {
468 let p = MinimalProvider;
469 assert!(matches!(
470 p.credential().await.unwrap(),
471 Credential::Bearer(_)
472 ));
473 assert_eq!(p.provider_name(), "minimal");
474 let ra = p
475 .request_auth("GET", "https://x", &std::collections::BTreeMap::new())
476 .await
477 .unwrap();
478 assert!(ra.is_empty());
479 assert!(p.reauth_statuses().is_empty());
480 // The default sign_request also contributes nothing.
481 assert!(
482 p.sign_request("GET", "https://x", &std::collections::BTreeMap::new())
483 .await
484 .unwrap()
485 .is_none()
486 );
487 }
488
489 #[test]
490 fn credential_authorization_value() {
491 assert_eq!(
492 Credential::Bearer("abc".into()).authorization_value(),
493 Some("Bearer abc".to_string())
494 );
495 assert_eq!(
496 Credential::Token("Custom xyz".into()).authorization_value(),
497 Some("Custom xyz".to_string())
498 );
499 assert_eq!(
500 Credential::Basic {
501 username: "u".into(),
502 password: "p".into()
503 }
504 .authorization_value(),
505 None
506 );
507 assert_eq!(
508 Credential::Header {
509 name: "X-Api-Key".into(),
510 value: "k".into()
511 }
512 .authorization_value(),
513 None
514 );
515 }
516
517 #[test]
518 fn authspec_parses_inline() {
519 let j = serde_json::json!({"type": "bearer", "config": {"token": "t"}});
520 let s: AuthSpec<StubAuth> = serde_json::from_value(j).unwrap();
521 match s {
522 AuthSpec::Inline(StubAuth::Bearer { token }) => assert_eq!(token, "t"),
523 other => panic!("expected inline bearer, got {other:?}"),
524 }
525 }
526
527 #[test]
528 fn authspec_parses_inline_unit_variant() {
529 let j = serde_json::json!({"type": "none"});
530 let s: AuthSpec<StubAuth> = serde_json::from_value(j).unwrap();
531 assert!(matches!(s, AuthSpec::Inline(StubAuth::None)));
532 }
533
534 #[test]
535 fn authspec_parses_ref() {
536 let j = serde_json::json!({"ref": "sf"});
537 let s: AuthSpec<StubAuth> = serde_json::from_value(j).unwrap();
538 assert_eq!(s.reference_name(), Some("sf"));
539 }
540
541 #[test]
542 fn authspec_rejects_ref_plus_inline() {
543 let j = serde_json::json!({"ref": "sf", "type": "bearer"});
544 let r: Result<AuthSpec<StubAuth>, _> = serde_json::from_value(j);
545 assert!(r.is_err(), "ref + inline must be rejected");
546 }
547
548 #[derive(Debug)]
549 struct Fixed(Credential);
550
551 #[async_trait]
552 impl AuthProvider for Fixed {
553 async fn credential(&self) -> Result<Credential, FaucetError> {
554 Ok(self.0.clone())
555 }
556 fn provider_name(&self) -> &'static str {
557 "fixed"
558 }
559 }
560
561 #[test]
562 fn credential_debug_redacts_secrets() {
563 // Bearer / Token fully redact the secret value.
564 let b = format!("{:?}", Credential::Bearer("supersecrettoken".into()));
565 assert!(!b.contains("supersecrettoken"), "bearer token leaked: {b}");
566 assert!(b.contains("***"), "bearer token not masked: {b}");
567
568 let t = format!("{:?}", Credential::Token("tok-supersecretxyz".into()));
569 assert!(!t.contains("tok-supersecretxyz"), "raw token leaked: {t}");
570 assert!(t.contains("***"), "raw token not masked: {t}");
571
572 // Basic redacts the password but keeps the (non-secret) username.
573 let basic = format!(
574 "{:?}",
575 Credential::Basic {
576 username: "alice".into(),
577 password: "hunter2secret".into(),
578 }
579 );
580 assert!(!basic.contains("hunter2secret"), "password leaked: {basic}");
581 assert!(
582 basic.contains("alice"),
583 "username should stay visible for diagnostics: {basic}"
584 );
585
586 // Header redacts the value but keeps the (non-secret) header name.
587 let header = format!(
588 "{:?}",
589 Credential::Header {
590 name: "X-Api-Key".into(),
591 value: "secretkeyvalue".into(),
592 }
593 );
594 assert!(
595 !header.contains("secretkeyvalue"),
596 "header value leaked: {header}"
597 );
598 assert!(
599 header.contains("X-Api-Key"),
600 "header name should stay visible for diagnostics: {header}"
601 );
602 }
603
604 #[tokio::test]
605 async fn auth_provider_default_invalidate_returns_current() {
606 let p = Fixed(Credential::Bearer("x".into()));
607 assert_eq!(
608 p.credential().await.unwrap(),
609 Credential::Bearer("x".into())
610 );
611 // Default invalidate just returns the current credential.
612 assert_eq!(
613 p.invalidate(&Credential::Bearer("old".into()))
614 .await
615 .unwrap(),
616 Credential::Bearer("x".into())
617 );
618 }
619}