firebase_admin/auth/
mode.rs1use crate::auth::identity_toolkit::IdentityToolkitEndpoints;
10
11pub const EMULATOR_HOST_ENV_VAR: &str = "FIREBASE_AUTH_EMULATOR_HOST";
14
15#[derive(Debug, Clone)]
18pub enum ClientMode {
19 Live,
21 Emulator {
23 host: String,
25 },
26}
27
28impl ClientMode {
29 pub fn resolve(explicit_emulator_host: Option<String>) -> Self {
33 if let Some(host) = explicit_emulator_host {
34 return ClientMode::Emulator { host };
35 }
36 if let Ok(host) = std::env::var(EMULATOR_HOST_ENV_VAR) {
37 if !host.trim().is_empty() {
38 return ClientMode::Emulator { host };
39 }
40 }
41 ClientMode::Live
42 }
43
44 pub fn endpoints(&self) -> IdentityToolkitEndpoints {
46 match self {
47 ClientMode::Live => IdentityToolkitEndpoints::live(),
48 ClientMode::Emulator { host } => IdentityToolkitEndpoints::emulator(host),
49 }
50 }
51
52 pub fn requires_bearer_token(&self) -> bool {
56 matches!(self, ClientMode::Live)
57 }
58}
59
60#[cfg(test)]
61mod tests {
62 use super::*;
63 use std::sync::Mutex;
64
65 static ENV_VAR_TEST_LOCK: Mutex<()> = Mutex::new(());
69
70 fn with_emulator_env_var<T>(value: Option<&str>, f: impl FnOnce() -> T) -> T {
71 let _guard = ENV_VAR_TEST_LOCK.lock().unwrap();
72 let previous = std::env::var(EMULATOR_HOST_ENV_VAR).ok();
73 match value {
74 Some(v) => std::env::set_var(EMULATOR_HOST_ENV_VAR, v),
75 None => std::env::remove_var(EMULATOR_HOST_ENV_VAR),
76 }
77
78 let result = f();
79
80 match previous {
81 Some(v) => std::env::set_var(EMULATOR_HOST_ENV_VAR, v),
82 None => std::env::remove_var(EMULATOR_HOST_ENV_VAR),
83 }
84 result
85 }
86
87 #[test]
88 fn explicit_host_wins_over_env_var() {
89 with_emulator_env_var(Some("env-host:9099"), || {
90 let mode = ClientMode::resolve(Some("explicit-host:9099".to_string()));
91 assert!(matches!(mode, ClientMode::Emulator { host } if host == "explicit-host:9099"));
92 });
93 }
94
95 #[test]
96 fn env_var_is_used_when_no_explicit_host_given() {
97 with_emulator_env_var(Some("env-host:9099"), || {
98 let mode = ClientMode::resolve(None);
99 assert!(matches!(mode, ClientMode::Emulator { host } if host == "env-host:9099"));
100 });
101 }
102
103 #[test]
104 fn whitespace_only_env_var_is_treated_as_unset() {
105 with_emulator_env_var(Some(" "), || {
106 let mode = ClientMode::resolve(None);
107 assert!(matches!(mode, ClientMode::Live));
108 });
109 }
110
111 #[test]
112 fn defaults_to_live_with_nothing_set() {
113 with_emulator_env_var(None, || {
114 let mode = ClientMode::resolve(None);
115 assert!(matches!(mode, ClientMode::Live));
116 });
117 }
118
119 #[test]
120 fn requires_bearer_token_only_in_live_mode() {
121 assert!(ClientMode::Live.requires_bearer_token());
122 assert!(!ClientMode::Emulator {
123 host: "localhost:9099".to_string()
124 }
125 .requires_bearer_token());
126 }
127}