Skip to main content

bitwarden_core/client/
flags_client.rs

1//! Feature flag retrieval, persistence, and refresh from the server `/config` endpoint.
2
3use std::{collections::HashMap, sync::Arc};
4
5use bitwarden_state::PersistedValue;
6use chrono::{DateTime, Duration, Utc};
7
8use crate::{
9    Client,
10    client::{
11        flags::Flags,
12        internal::ApiConfigurations,
13        persisted_state::{FLAGS, FLAGS_FETCHED_AT},
14    },
15};
16
17const FLAGS_TTL: Duration = Duration::hours(1);
18
19/// Errors returned by [`FlagsClient::fetch`].
20#[derive(Debug, thiserror::Error)]
21pub enum FetchFlagsError {
22    /// Network or deserialization error when fetching `/config`.
23    #[error("failed to fetch /config: {0}")]
24    Api(#[from] bitwarden_api_api::ApiError),
25    /// Error persisting flags or fetched_at timestamp to state registry.
26    #[error("state access error: {0}")]
27    State(#[from] bitwarden_state::PersistedValueError),
28}
29
30/// A client for inspecting and refreshing feature flags.
31#[bitwarden_ffi::wasm_object]
32pub struct FlagsClient {
33    flags: PersistedValue<FLAGS>,
34    flags_fetched_at: PersistedValue<FLAGS_FETCHED_AT>,
35    api_configurations: Arc<ApiConfigurations>,
36}
37
38impl FlagsClient {
39    /// Persist a flag map (e.g. from `/config`) into the state registry.
40    pub async fn load(&self, flags: HashMap<String, bool>) {
41        let flags = Flags::load_from_map(flags);
42        let _ = self.flags.set(flags).await;
43    }
44
45    /// Retrieve the active feature flags from the state registry.
46    pub async fn get(&self) -> Flags {
47        self.flags
48            .try_get()
49            .await
50            .ok()
51            .flatten()
52            .unwrap_or_default()
53    }
54
55    /// Fetch flags from `/config` and persist both the flag values and a `fetched_at` timestamp.
56    ///
57    /// Pass `force = true` from `from_authenticated_data` (PM-27624) immediately before
58    /// `save_to_state`, so the initial flag fetch is part of the persisted login state.
59    /// [`Client::load_from_state`] calls this with `force = false` to honour the 1-hour TTL.
60    pub async fn fetch(&self, force: bool) -> Result<(), FetchFlagsError> {
61        if !force {
62            let last: Option<DateTime<Utc>> = self.flags_fetched_at.try_get().await?;
63            if let Some(fetched_at) = last
64                && Utc::now().signed_duration_since(fetched_at) < FLAGS_TTL
65            {
66                return Ok(());
67            }
68        }
69
70        let config = self
71            .api_configurations
72            .api_client
73            .config_api()
74            .get_configs()
75            .await?;
76        let feature_states = config.feature_states.unwrap_or_default();
77        // `/config` returns `serde_json::Value`; coerce to bool. Non-bool values are dropped
78        // because `Flags` only models boolean flags today.
79        let bool_map = feature_states
80            .into_iter()
81            .filter_map(|(k, v)| v.as_bool().map(|b| (k, b)))
82            .collect();
83        self.load(bool_map).await;
84        self.flags_fetched_at.set(Utc::now()).await?;
85        Ok(())
86    }
87}
88
89impl Client {
90    /// Access to feature flag retrieval, persistence, and refresh.
91    pub fn flags(&self) -> FlagsClient {
92        let registry = &self.internal.state_registry;
93        FlagsClient {
94            flags: registry.value::<FLAGS>(),
95            flags_fetched_at: registry.value::<FLAGS_FETCHED_AT>(),
96            api_configurations: self.internal.api_configurations.clone(),
97        }
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use serde_json::json;
104    use wiremock::{
105        Mock, MockServer, ResponseTemplate,
106        matchers::{method, path},
107    };
108
109    use super::*;
110    use crate::{ClientSettings, DeviceType};
111
112    fn settings_for(server: &MockServer) -> ClientSettings {
113        ClientSettings {
114            identity_url: format!("http://{}", server.address()),
115            api_url: format!("http://{}", server.address()),
116            user_agent: "flags-tests".to_string(),
117            device_type: DeviceType::SDK,
118            device_identifier: None,
119            bitwarden_client_version: None,
120            bitwarden_package_type: None,
121        }
122    }
123
124    async fn write_fetched_at(client: &Client, at: DateTime<Utc>) {
125        client
126            .internal
127            .state_registry
128            .value::<FLAGS_FETCHED_AT>()
129            .set(at)
130            .await
131            .unwrap();
132    }
133
134    async fn read_fetched_at(client: &Client) -> Option<DateTime<Utc>> {
135        client
136            .internal
137            .state_registry
138            .value::<FLAGS_FETCHED_AT>()
139            .try_get()
140            .await
141            .unwrap()
142    }
143
144    #[tokio::test]
145    async fn load_round_trips_through_persisted_value() {
146        let client = Client::new(None);
147
148        // With no flags loaded yet, get should return defaults.
149        let initial = client.flags().get().await;
150        assert!(!initial.strict_cipher_decryption);
151
152        // Loading flags should persist them via the FLAGS persisted value.
153        let mut map = HashMap::new();
154        map.insert("pm-34500-strict-cipher-decryption".to_string(), true);
155        client.flags().load(map).await;
156
157        // get should now return the loaded values.
158        let loaded = client.flags().get().await;
159        assert!(loaded.strict_cipher_decryption);
160
161        // The values should be readable directly from the persisted value too.
162        let persisted = client
163            .internal
164            .state_registry
165            .value::<FLAGS>()
166            .get()
167            .await
168            .expect("flags should be persisted after load");
169        assert!(persisted.strict_cipher_decryption);
170    }
171
172    #[tokio::test]
173    async fn fetch_force_persists_flags_and_timestamp() {
174        let server = MockServer::start().await;
175        Mock::given(method("GET"))
176            .and(path("/config"))
177            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
178                "featureStates": { "pm-34500-strict-cipher-decryption": true }
179            })))
180            .expect(1)
181            .mount(&server)
182            .await;
183
184        let client = Client::new(Some(settings_for(&server)));
185        let before = Utc::now();
186        client.flags().fetch(true).await.unwrap();
187
188        assert!(client.flags().get().await.strict_cipher_decryption);
189        let fetched_at = read_fetched_at(&client)
190            .await
191            .expect("fetched_at must be set after a successful fetch");
192        assert!(fetched_at >= before);
193    }
194
195    #[tokio::test]
196    async fn fetch_skips_when_fresh() {
197        let server = MockServer::start().await;
198        Mock::given(method("GET"))
199            .and(path("/config"))
200            .respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
201            .expect(0)
202            .mount(&server)
203            .await;
204
205        let client = Client::new(Some(settings_for(&server)));
206        write_fetched_at(&client, Utc::now() - Duration::minutes(5)).await;
207
208        client.flags().fetch(false).await.unwrap();
209    }
210
211    #[tokio::test]
212    async fn fetch_force_ignores_ttl() {
213        let server = MockServer::start().await;
214        Mock::given(method("GET"))
215            .and(path("/config"))
216            .respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
217            .expect(1)
218            .mount(&server)
219            .await;
220
221        let client = Client::new(Some(settings_for(&server)));
222        write_fetched_at(&client, Utc::now() - Duration::minutes(5)).await;
223
224        client.flags().fetch(true).await.unwrap();
225    }
226
227    #[tokio::test]
228    async fn fetch_refreshes_when_stale() {
229        let server = MockServer::start().await;
230        Mock::given(method("GET"))
231            .and(path("/config"))
232            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
233                "featureStates": { "pm-34500-strict-cipher-decryption": true }
234            })))
235            .expect(1)
236            .mount(&server)
237            .await;
238
239        let client = Client::new(Some(settings_for(&server)));
240        let stale = Utc::now() - Duration::hours(2);
241        write_fetched_at(&client, stale).await;
242
243        client.flags().fetch(false).await.unwrap();
244
245        assert!(client.flags().get().await.strict_cipher_decryption);
246        let fetched_at = read_fetched_at(&client).await.unwrap();
247        assert!(fetched_at > stale);
248    }
249
250    #[tokio::test]
251    async fn fetch_network_error_is_non_fatal_and_preserves_flags() {
252        let server = MockServer::start().await;
253        Mock::given(method("GET"))
254            .and(path("/config"))
255            .respond_with(ResponseTemplate::new(500))
256            .mount(&server)
257            .await;
258
259        let client = Client::new(Some(settings_for(&server)));
260        client
261            .flags()
262            .load(HashMap::from([(
263                "pm-34500-strict-cipher-decryption".to_string(),
264                true,
265            )]))
266            .await;
267
268        assert!(client.flags().fetch(true).await.is_err());
269        assert!(
270            client.flags().get().await.strict_cipher_decryption,
271            "previously persisted flags must survive a failed fetch"
272        );
273    }
274}