1use crate::config::BaseUrl;
6use crate::error::{debug, trace, Error, Result};
7use crate::jexl_filter::JexlFilter;
8#[cfg(feature = "signatures")]
9use crate::signatures;
10use crate::storage::Storage;
11use crate::RemoteSettingsContext;
12use crate::{packaged_attachments, packaged_collections, RemoteSettingsServer};
13use parking_lot::{Mutex, MutexGuard};
14use serde::{Deserialize, Serialize};
15use sha2::{Digest, Sha256};
16use std::time::{Duration, Instant};
17use url::Url;
18use viaduct::{Request, Response};
19
20#[cfg(feature = "signatures")]
21#[cfg(not(test))]
22use std::time::{SystemTime, UNIX_EPOCH};
23
24#[cfg(feature = "signatures")]
25#[cfg(not(test))]
26fn epoch_seconds() -> u64 {
27 SystemTime::now()
28 .duration_since(UNIX_EPOCH)
29 .unwrap() .as_secs()
31}
32
33#[cfg(feature = "signatures")]
34#[cfg(test)]
35thread_local! {
36 static MOCK_TIME: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) }
37}
38
39#[cfg(feature = "signatures")]
40#[cfg(test)]
41fn epoch_seconds() -> u64 {
42 MOCK_TIME.with(|mock_time| mock_time.get().unwrap_or(0))
43}
44
45const HEADER_BACKOFF: &str = "Backoff";
46const HEADER_RETRY_AFTER: &str = "Retry-After";
47
48#[cfg(feature = "signatures")]
52const ROOT_CERT_SHA256_HASH_PROD: &str = "C8:A8:0E:9A:FA:EF:4E:21:9B:6F:B5:D7:A7:1D:0F:10:12:23:BA:C5:00:1A:C2:8F:9B:0D:43:DC:59:A1:06:DB";
53#[cfg(feature = "signatures")]
54const ROOT_CERT_SHA256_HASH_NONPROD: &str = "3C:01:44:6A:BE:90:36:CE:A9:A0:9A:CA:A3:A5:20:AC:62:8F:20:A7:AE:32:CE:86:1C:B2:EF:B7:0F:A0:C7:45";
55
56#[derive(Debug, Clone, Deserialize)]
57struct CollectionData {
58 data: Vec<RemoteSettingsRecord>,
59 timestamp: u64,
60}
61
62pub struct RemoteSettingsClient<C = ViaductApiClient> {
67 collection_name: String,
69 inner: Mutex<RemoteSettingsClientInner<C>>,
70 pending_config: Mutex<Option<RemoteSettingsClientConfig>>,
73}
74
75struct RemoteSettingsClientInner<C> {
76 storage: Storage,
77 api_client: C,
78 jexl_filter: JexlFilter,
79}
80
81struct RemoteSettingsClientConfig {
82 server_url: BaseUrl,
83 bucket_name: String,
84 context: Option<RemoteSettingsContext>,
85}
86
87impl<C: ApiClient> RemoteSettingsClient<C> {
94 packaged_collections! {
96 ("main", "regions"),
97 ("main", "search-config-icons"),
98 ("main", "search-config-v2"),
99 ("main", "search-telemetry-v2"),
100 ("main", "summarizer-models-config"),
101 ("main", "translations-models"),
102 ("main", "translations-wasm"),
103 }
104
105 packaged_attachments! {
116 ("main", "regions") => [
117 "world",
118 "world-buffered",
119 ],
120 ("main", "search-config-icons") => [
121 "001500a9-1a6c-3f5a-ba15-a5f5a075d256",
122 "06cf7432-efd7-f244-927b-5e423005e1ea",
123 "0a57b0cf-34f0-4d09-96e4-dbd6e3355410",
124 "0d7668a8-c3f4-cfee-cbc8-536511528937",
125 "0eec5640-6fde-d6fe-322a-c72c6d5bd5a2",
126 "101ce01d-2691-b729-7f16-9d389803384b",
127 "177aba42-9bed-4078-e36b-580e8794cd7f",
128 "25de0352-aabb-d31f-15f7-bf9299fb004c",
129 "2bbe48f4-d3b8-c9e0-86e3-a54c37ec3335",
130 "2e835b0e-9709-d1bb-9725-87f59f3445ca",
131 "2ecca3f8-c1ef-43cc-b053-886d1ae46c36",
132 "32d26d19-aeb0-5c01-32e8-f8970be9246f",
133 "39d0b17d-c020-4890-932f-83c0f6ed130b",
134 "41135a88-093d-4077-873b-9de1ae133427",
135 "41f0d805-3775-4988-8d8c-5ad8ccd86d1c",
136 "47da97b5-600f-c450-fd15-a52bb2169c11",
137 "48c72361-cd67-412e-bd7f-f81a43c10791",
138 "4e271681-3e0f-91ac-9750-03f665efc171",
139 "50f6171f-8e7a-b41b-862e-f97397038fb2",
140 "5203dd03-2c55-4b53-9c60-58258d587be1",
141 "5914932e-66ba-4126-8be5-d37beadd9532",
142 "5ded611d-44b2-dc46-fd67-fb116888d75d",
143 "5e03d6f4-6ee9-8bc8-cf22-7a5f2cf55c41",
144 "6644f26f-28ea-4222-929d-5d43a02dae05",
145 "6d10d702-7bd6-1452-90a5-3df665a38f66",
146 "6e36a151-e4f4-4117-9067-1ca82c47d01a",
147 "6f4da442-d31e-28f8-03af-797d16bbdd27",
148 "7072564d-a573-4750-bf33-f0a07631c9eb",
149 "70fdd651-6c50-b7bb-09ec-7e85da259173",
150 "71f41a0c-5b70-4116-b30f-e62089083522",
151 "74793ce1-a918-a5eb-d3c0-2aadaff3c88c",
152 "74f94dc2-caf6-4b90-b3d2-f3e2f7714d88",
153 "764e3b14-fe16-4feb-8384-124c516a5afa",
154 "7bf4ca37-e2b8-4d31-a1c3-979bc0e85131",
155 "7c81cf98-7c11-4afd-8279-db89118a6dfb",
156 "7cb4d88a-d4df-45b2-87e4-f896eaf1bbdb",
157 "7edaf4fe-a8a0-432b-86d2-bf75ebe80851",
158 "7efbed51-813c-581d-d8d3-f8758434e451",
159 "84bb4962-e571-227a-9ef6-2ac5f2aac361",
160 "87ac4cde-f581-398b-1e32-eb4079183b36",
161 "8831ce10-b1e4-6eb4-4975-83c67457288e",
162 "890de5c4-0941-a116-473a-5d240e79497a",
163 "8abb10a7-212f-46b5-a7b4-244f414e3810",
164 "91a9672d-e945-8e1e-0996-aefdb0190716",
165 "94a84724-c30f-4767-ba42-01cc37fc31a4",
166 "96327a73-c433-5eb4-a16d-b090cadfb80b",
167 "9802e63d-05ec-48ba-93f9-746e0981ad98",
168 "9d96547d-7575-49ca-8908-1e046b8ea90e",
169 "a06db97d-1210-ea2e-5474-0e2f7d295bfd",
170 "a06dc3fd-4bdb-41f3-2ebc-4cbed06a9bd3",
171 "a2c7d4e9-f770-51e1-0963-3c2c8401631d",
172 "a83f24e4-602c-47bd-930c-ad0947ee1adf",
173 "b50c3e3d-7bd0-4118-856f-19b26b21d01f",
174 "b64f09fd-52d1-c48e-af23-4ce918e7bf3b",
175 "b882b24d-1776-4ef9-9016-0bdbd935eda3",
176 "b8ca5a94-8fff-27ad-6e00-96e244a32e21",
177 "b9424309-f601-4a69-98ca-ca68e65633e6",
178 "c411adc1-9661-4fb5-a4c1-8cfe74911943",
179 "cbf9e891-d079-2b28-5617-283450d463dd",
180 "d87f251c-3e12-a8bf-e2d0-afd43d36c5f9",
181 "db0e1627-ae89-4c25-8944-a9481d8512d9",
182 "e02f23df-8d48-2b1b-3b5c-6dd27302c61c",
183 "e718e983-09aa-e8f6-b25f-cd4b395d4785",
184 "e7547f62-187b-b641-d462-e54a3f813d9a",
185 "eb62e768-151b-45d1-9fe5-9e1d2a5991c5",
186 "f312610a-ebfb-a106-ea92-fd643c5d3636",
187 "f943d7bc-872e-4a81-810f-94d26465da69",
188 "fa0fc42c-d91d-fca7-34eb-806ff46062dc",
189 "fca3e3ee-56cd-f474-dc31-307fd24a891d",
190 "fe75ce3f-1545-400c-b28c-ad771054e69f",
191 "fed4f021-ff3e-942a-010e-afa43fda2136",
192 ],
193 ("main", "translations-wasm") => [
194 "4fd32605-9889-4dd9-9fc7-577ad1136746",
195 ]
196 }
197}
198
199impl<C: ApiClient> RemoteSettingsClient<C> {
200 pub fn new_from_parts(
201 collection_name: String,
202 storage: Storage,
203 jexl_filter: JexlFilter,
204 api_client: C,
205 ) -> Self {
206 Self {
207 collection_name,
208 inner: Mutex::new(RemoteSettingsClientInner {
209 storage,
210 api_client,
211 jexl_filter,
212 }),
213 pending_config: Mutex::new(None),
214 }
215 }
216
217 fn lock_inner(&self) -> Result<MutexGuard<'_, RemoteSettingsClientInner<C>>> {
221 let pending_config = self.get_pending_config();
222 let mut inner = self.inner.lock();
223 if let Some(config) = pending_config {
224 inner.api_client =
225 C::create(config.server_url, config.bucket_name, &self.collection_name);
226 inner.jexl_filter = JexlFilter::new(config.context);
227 inner.storage.empty()?;
228 }
229 Ok(inner)
230 }
231
232 fn get_pending_config(&self) -> Option<RemoteSettingsClientConfig> {
233 self.pending_config.lock().take()
234 }
235
236 pub fn collection_name(&self) -> &str {
237 &self.collection_name
238 }
239
240 fn load_packaged_timestamp(&self) -> Option<u64> {
241 Self::get_packaged_timestamp(&self.collection_name)
243 }
244
245 fn load_packaged_data(&self) -> Option<CollectionData> {
246 let str_data = Self::get_packaged_data(&self.collection_name)?;
248 let data: CollectionData = serde_json::from_str(str_data).ok()?;
249 debug_assert_eq!(data.timestamp, self.load_packaged_timestamp().unwrap());
250 Some(data)
251 }
252
253 fn load_packaged_attachment(&self, filename: &str) -> Option<(&'static [u8], &'static str)> {
254 Self::get_packaged_attachment(&self.collection_name, filename)
256 }
257
258 fn filter_records(
260 &self,
261 records: Vec<RemoteSettingsRecord>,
262 inner: &RemoteSettingsClientInner<C>,
263 ) -> Vec<RemoteSettingsRecord> {
264 records
265 .into_iter()
266 .filter(|record| match record.fields.get("filter_expression") {
267 Some(serde_json::Value::String(filter_expr)) => {
268 inner.jexl_filter.evaluate(filter_expr).unwrap_or(false)
269 }
270 _ => true, })
272 .collect()
273 }
274
275 fn get_packaged_data_if_newer(
278 &self,
279 storage: &mut Storage,
280 collection_url: &str,
281 ) -> Result<Option<CollectionData>> {
282 let packaged_ts = self.load_packaged_timestamp();
283 let storage_ts = storage.get_last_modified_timestamp(collection_url)?;
284 let packaged_is_newer = match (packaged_ts, storage_ts) {
285 (Some(packaged_ts), Some(storage_ts)) => packaged_ts > storage_ts,
286 (Some(_), None) => true, (None, _) => false, };
289
290 if packaged_is_newer {
291 Ok(self.load_packaged_data())
292 } else {
293 Ok(None)
294 }
295 }
296
297 pub fn get_records(&self, sync_if_empty: bool) -> Result<Option<Vec<RemoteSettingsRecord>>> {
302 let mut inner = self.lock_inner()?;
303 let collection_url = inner.api_client.collection_url();
304
305 if inner.api_client.is_prod_server()? {
310 if let Some(packaged_data) =
311 self.get_packaged_data_if_newer(&mut inner.storage, &collection_url)?
312 {
313 inner.storage.empty()?;
315 inner.storage.insert_collection_content(
317 &collection_url,
318 &packaged_data.data,
319 packaged_data.timestamp,
320 CollectionMetadata::default(),
321 )?;
322 return Ok(Some(self.filter_records(packaged_data.data, &inner)));
323 }
324 }
325
326 let cached_records = inner.storage.get_records(&collection_url)?;
327
328 match (cached_records, sync_if_empty) {
329 (Some(cached_records), _) => Ok(Some(self.filter_records(cached_records, &inner))),
334 (None, true) => {
336 drop(inner);
338 self.sync()?;
340 let mut inner = self.lock_inner()?;
342 Ok(inner
343 .storage
344 .get_records(&collection_url)?
345 .map(|records| self.filter_records(records, &inner)))
346 }
347 (None, false) => Ok(None),
349 }
350 }
351
352 pub fn get_last_modified_timestamp(&self) -> Result<Option<u64>> {
354 let mut inner = self.lock_inner()?;
355 let collection_url = inner.api_client.collection_url();
356 inner.storage.get_last_modified_timestamp(&collection_url)
357 }
358
359 fn perform_sync_operation(&self) -> Result<()> {
364 let mut inner = self.lock_inner()?;
365 let collection_url = inner.api_client.collection_url();
366 let timestamp = inner.storage.get_last_modified_timestamp(&collection_url)?;
367 let changeset = inner.api_client.fetch_changeset(timestamp)?;
368 debug!(
369 "{0}: apply {1} change(s) locally.",
370 self.collection_name,
371 changeset.changes.len()
372 );
373 inner.storage.insert_collection_content(
374 &collection_url,
375 &changeset.changes,
376 changeset.timestamp,
377 changeset.metadata,
378 )
379 }
380
381 pub fn sync(&self) -> Result<()> {
382 self.perform_sync_operation()?;
384 if self.verify_signature().is_err() {
386 debug!(
387 "{0}: signature verification failed. Reset and retry.",
388 self.collection_name
389 );
390 self.reset_storage()?;
392 self.perform_sync_operation()?;
393 self.verify_signature().inspect_err(|_| {
395 self.reset_storage()
397 .expect("Failed to reset storage after verification failure");
398 })?;
399 }
400 trace!("{0}: sync done.", self.collection_name);
401 Ok(())
402 }
403
404 pub fn run_maintenance(&self) -> Result<()> {
405 let mut inner = self.lock_inner()?;
406 inner.storage.run_maintenance()
407 }
408
409 pub fn reset_storage(&self) -> Result<()> {
410 trace!("{0}: reset local storage.", self.collection_name);
411 let mut inner = self.lock_inner()?;
412 let collection_url = inner.api_client.collection_url();
413 inner.storage.empty()?;
415 if inner.api_client.is_prod_server()? {
417 if let Some(packaged_data) = self.load_packaged_data() {
418 trace!("{0}: restore packaged dump.", self.collection_name);
419 inner.storage.insert_collection_content(
420 &collection_url,
421 &packaged_data.data,
422 packaged_data.timestamp,
423 CollectionMetadata::default(),
424 )?;
425 }
426 }
427 Ok(())
428 }
429
430 pub fn shutdown(&self) {
431 self.inner.lock().storage.close();
432 }
433
434 #[cfg(not(feature = "signatures"))]
435 fn verify_signature(&self) -> Result<()> {
436 debug!("{0}: signature verification skipped.", self.collection_name);
437 Ok(())
438 }
439
440 #[cfg(feature = "signatures")]
441 fn verify_signature(&self) -> Result<()> {
442 let mut inner = self.lock_inner()?;
443 let collection_url = inner.api_client.collection_url();
444 let timestamp = inner.storage.get_last_modified_timestamp(&collection_url)?;
445 let records = inner.storage.get_records(&collection_url)?;
446 let metadata = inner.storage.get_collection_metadata(&collection_url)?;
447 match (timestamp, &records, metadata) {
448 (Some(timestamp), Some(records), Some(metadata)) => {
449 let expected_root_hash = if inner.api_client.is_prod_server()? {
451 ROOT_CERT_SHA256_HASH_PROD
452 } else {
453 ROOT_CERT_SHA256_HASH_NONPROD
454 };
455 let mut result = Err(Error::IncompleteSignatureDataError(
458 "No valid signatures found".into(),
459 ));
460 for signature in &metadata.signatures {
461 if signature.mode != "p384ecdsa" {
462 continue;
465 }
466
467 let cert_chain_bytes = inner.api_client.fetch_cert(&signature.x5u)?;
468
469 let expected_leaf_cname = format!(
474 "{}.content-signature.mozilla.org",
475 if metadata.bucket.contains("security-state") {
476 "onecrl"
477 } else {
478 "remote-settings"
479 }
480 );
481
482 result = signatures::verify_signature(
483 timestamp,
484 records,
485 signature.signature.as_bytes(),
486 &cert_chain_bytes,
487 epoch_seconds(),
488 expected_root_hash,
489 &expected_leaf_cname,
490 )
491 .inspect_err(|err| {
492 debug!(
493 "{0}: bad signature ({1:?}) using certificate {2} and signer '{3}'",
494 self.collection_name, err, &signature.x5u, expected_leaf_cname
495 );
496 });
497 if result.is_ok() {
499 trace!("{0}: signature verification success.", self.collection_name);
500 return Ok(());
501 }
502 }
503 result
505 }
506 _ => {
507 let missing_field = if timestamp.is_none() {
508 "timestamp"
509 } else if records.is_none() {
510 "records"
511 } else {
512 "metadata"
513 };
514 Err(Error::IncompleteSignatureDataError(missing_field.into()))
515 }
516 }
517 }
518
519 pub fn get_attachment(&self, record: &RemoteSettingsRecord) -> Result<Vec<u8>> {
522 let metadata = record
523 .attachment
524 .as_ref()
525 .ok_or_else(|| Error::RecordAttachmentMismatchError("No attachment metadata".into()))?;
526
527 let mut inner = self.lock_inner()?;
528 let collection_url = inner.api_client.collection_url();
529
530 if let Some(data) = inner
532 .storage
533 .get_attachment(&collection_url, metadata.clone())?
534 {
535 return Ok(data);
536 }
537
538 if inner.api_client.is_prod_server()? {
540 if let Some((data, manifest)) = self.load_packaged_attachment(&record.id) {
541 if let Ok(manifest_data) = serde_json::from_str::<serde_json::Value>(manifest) {
542 if metadata.hash == manifest_data["hash"].as_str().unwrap_or_default()
543 && metadata.size == manifest_data["size"].as_u64().unwrap_or_default()
544 {
545 inner
547 .storage
548 .set_attachment(&collection_url, &metadata.location, data)?;
549 return Ok(data.to_vec());
550 }
551 }
552 }
553 }
554
555 let attachment = inner.api_client.fetch_attachment(&metadata.location)?;
557
558 if attachment.len() as u64 != metadata.size {
560 return Err(Error::RecordAttachmentMismatchError(
561 "Downloaded attachment size mismatch".into(),
562 ));
563 }
564 let hash = format!("{:x}", Sha256::digest(&attachment));
565 if hash != metadata.hash {
566 return Err(Error::RecordAttachmentMismatchError(
567 "Downloaded attachment hash mismatch".into(),
568 ));
569 }
570
571 inner
573 .storage
574 .set_attachment(&collection_url, &metadata.location, &attachment)?;
575 Ok(attachment)
576 }
577
578 pub fn update_config(
579 &self,
580 server_url: BaseUrl,
581 bucket_name: String,
582 context: Option<RemoteSettingsContext>,
583 ) {
584 let mut pending_config = self.pending_config.lock();
585 *pending_config = Some(RemoteSettingsClientConfig {
586 server_url,
587 bucket_name,
588 context,
589 })
590 }
591}
592
593impl RemoteSettingsClient<ViaductApiClient> {
594 pub fn new(
595 server_url: BaseUrl,
596 bucket_name: String,
597 collection_name: String,
598 context: Option<RemoteSettingsContext>,
599 storage: Storage,
600 ) -> Self {
601 let api_client = ViaductApiClient::new(server_url, &bucket_name, &collection_name);
602 let jexl_filter = JexlFilter::new(context);
603
604 Self::new_from_parts(collection_name, storage, jexl_filter, api_client)
605 }
606}
607
608#[cfg_attr(test, mockall::automock)]
609pub trait ApiClient {
610 fn create(server_url: BaseUrl, bucket_name: String, collection_name: &str) -> Self;
612
613 fn collection_url(&self) -> String;
621
622 fn fetch_changeset(&mut self, timestamp: Option<u64>) -> Result<ChangesetResponse>;
624
625 fn fetch_attachment(&mut self, attachment_location: &str) -> Result<Vec<u8>>;
627
628 fn fetch_cert(&mut self, x5u: &str) -> Result<Vec<u8>>;
630
631 fn is_prod_server(&self) -> Result<bool>;
633}
634
635pub struct ViaductApiClient {
637 endpoints: RemoteSettingsEndpoints,
638 remote_state: RemoteState,
639}
640
641impl ViaductApiClient {
642 fn new(base_url: BaseUrl, bucket_name: &str, collection_name: &str) -> Self {
643 Self {
644 endpoints: RemoteSettingsEndpoints::new(&base_url, bucket_name, collection_name),
645 remote_state: RemoteState::default(),
646 }
647 }
648
649 fn make_request(&mut self, url: Url) -> Result<Response> {
650 trace!("make_request: {url}");
651 self.remote_state.ensure_no_backoff()?;
652
653 let req = Request::get(url);
654 let resp = req.send()?;
655
656 self.remote_state.handle_backoff_hint(&resp)?;
657
658 if resp.is_success() {
659 Ok(resp)
660 } else {
661 Err(Error::response_error(
662 &resp.url,
663 format!("status code: {}", resp.status),
664 ))
665 }
666 }
667}
668
669impl ApiClient for ViaductApiClient {
670 fn create(server_url: BaseUrl, bucket_name: String, collection_name: &str) -> Self {
671 Self::new(server_url, &bucket_name, collection_name)
672 }
673
674 fn collection_url(&self) -> String {
675 self.endpoints.collection_url.to_string()
676 }
677
678 fn fetch_changeset(&mut self, timestamp: Option<u64>) -> Result<ChangesetResponse> {
679 let mut url = self.endpoints.changeset_url.clone();
680 url.query_pairs_mut().append_pair("_expected", "0");
686 if let Some(timestamp) = timestamp {
687 url.query_pairs_mut()
688 .append_pair("_since", &format!("{}", timestamp));
689 }
690
691 let resp = self.make_request(url)?;
692
693 if resp.is_success() {
694 Ok(resp.json::<ChangesetResponse>()?)
695 } else {
696 Err(Error::response_error(
697 &resp.url,
698 format!("status code: {}", resp.status),
699 ))
700 }
701 }
702
703 fn fetch_attachment(&mut self, attachment_location: &str) -> Result<Vec<u8>> {
704 let attachments_base_url = match &self.remote_state.attachments_base_url {
705 Some(attachments_base_url) => attachments_base_url.to_owned(),
706 None => {
707 let server_info = self
708 .make_request(self.endpoints.root_url.clone())?
709 .json::<ServerInfo>()?;
710 let attachments_base_url = match server_info.capabilities.attachments {
711 Some(capability) => Url::parse(&capability.base_url)?,
712 None => Err(Error::AttachmentsUnsupportedError)?,
713 };
714 self.remote_state.attachments_base_url = Some(attachments_base_url.clone());
715 attachments_base_url
716 }
717 };
718
719 let resp = self.make_request(attachments_base_url.join(attachment_location)?)?;
720 Ok(resp.body)
721 }
722
723 fn is_prod_server(&self) -> Result<bool> {
724 Ok(self
725 .endpoints
726 .root_url
727 .as_str()
728 .starts_with(RemoteSettingsServer::Prod.get_url()?.as_str()))
729 }
730
731 fn fetch_cert(&mut self, x5u: &str) -> Result<Vec<u8>> {
732 let resp = self.make_request(Url::parse(x5u)?)?;
733 Ok(resp.body)
734 }
735}
736
737struct RemoteSettingsEndpoints {
741 root_url: Url,
745 collection_url: Url,
755 changeset_url: Url,
762}
763
764impl RemoteSettingsEndpoints {
765 fn new(base_url: &BaseUrl, bucket_name: &str, collection_name: &str) -> Self {
769 let mut root_url = base_url.clone();
770 root_url.path_segments_mut().push("");
772
773 let mut collection_url = base_url.clone();
774 collection_url
775 .path_segments_mut()
776 .push("buckets")
777 .push(bucket_name)
778 .push("collections")
779 .push(collection_name);
780
781 let mut changeset_url = collection_url.clone();
782 changeset_url.path_segments_mut().push("changeset");
783
784 Self {
785 root_url: root_url.into_inner(),
786 collection_url: collection_url.into_inner(),
787 changeset_url: changeset_url.into_inner(),
788 }
789 }
790}
791
792#[derive(Clone, Deserialize, Serialize)]
793pub struct ChangesetResponse {
794 changes: Vec<RemoteSettingsRecord>,
795 timestamp: u64,
796 metadata: CollectionMetadata,
797}
798
799#[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
800pub struct CollectionMetadata {
801 pub bucket: String,
802 pub signatures: Vec<CollectionSignature>,
803}
804
805#[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
806pub struct CollectionSignature {
807 pub signature: String,
808 pub x5u: String,
810 pub mode: String,
812}
813
814#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq, uniffi::Record)]
817pub struct RemoteSettingsRecord {
818 pub id: String,
819 pub last_modified: u64,
820 #[serde(default)]
822 pub deleted: bool,
823 pub attachment: Option<Attachment>,
824 #[serde(flatten)]
825 pub fields: RsJsonObject,
826}
827
828#[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq, uniffi::Record)]
831pub struct Attachment {
832 pub filename: String,
833 pub mimetype: String,
834 pub location: String,
835 pub hash: String,
836 pub size: u64,
837}
838
839pub type RsJsonObject = serde_json::Map<String, serde_json::Value>;
845uniffi::custom_type!(RsJsonObject, String, {
846 remote,
847 try_lift: |val| {
848 let json: serde_json::Value = serde_json::from_str(&val)?;
849
850 match json {
851 serde_json::Value::Object(obj) => Ok(obj),
852 _ => Err(uniffi::deps::anyhow::anyhow!(
853 "Unexpected JSON-non-object in the bagging area"
854 )),
855 }
856 },
857 lower: |obj| serde_json::Value::Object(obj).to_string(),
858});
859
860#[derive(Clone, Debug)]
861pub(crate) struct RemoteState {
862 attachments_base_url: Option<Url>,
863 backoff: BackoffState,
864}
865
866impl Default for RemoteState {
867 fn default() -> Self {
868 Self {
869 attachments_base_url: None,
870 backoff: BackoffState::Ok,
871 }
872 }
873}
874
875impl RemoteState {
876 pub fn handle_backoff_hint(&mut self, response: &Response) -> Result<()> {
877 let extract_backoff_header = |header| -> Result<u64> {
878 Ok(response
879 .headers
880 .get_as::<u64, _>(header)
881 .transpose()
882 .unwrap_or_default() .unwrap_or(0))
884 };
885 let backoff = extract_backoff_header(HEADER_BACKOFF)?;
887 let retry_after = extract_backoff_header(HEADER_RETRY_AFTER)?;
888 let max_backoff = backoff.max(retry_after);
889
890 if max_backoff > 0 {
891 self.backoff = BackoffState::Backoff {
892 observed_at: Instant::now(),
893 duration: Duration::from_secs(max_backoff),
894 };
895 }
896 Ok(())
897 }
898
899 pub fn ensure_no_backoff(&mut self) -> Result<()> {
900 if let BackoffState::Backoff {
901 observed_at,
902 duration,
903 } = self.backoff
904 {
905 let elapsed_time = observed_at.elapsed();
906 if elapsed_time >= duration {
907 self.backoff = BackoffState::Ok;
908 } else {
909 let remaining = duration - elapsed_time;
910 return Err(Error::BackoffError(remaining.as_secs()));
911 }
912 }
913 Ok(())
914 }
915}
916
917#[derive(Clone, Copy, Debug)]
919pub(crate) enum BackoffState {
920 Ok,
921 Backoff {
922 observed_at: Instant,
923 duration: Duration,
924 },
925}
926
927#[derive(Deserialize)]
928struct ServerInfo {
929 capabilities: Capabilities,
930}
931
932#[derive(Deserialize)]
933struct Capabilities {
934 attachments: Option<AttachmentsCapability>,
935}
936
937#[derive(Deserialize)]
938struct AttachmentsCapability {
939 base_url: String,
940}
941
942#[cfg(test)]
943mod test_new_client {
944 use super::*;
945
946 #[test]
947 fn test_endpoints() {
948 let endpoints = RemoteSettingsEndpoints::new(
949 &BaseUrl::parse("http://rs.example.com/v2").unwrap(),
950 "main",
951 "test-collection",
952 );
953 assert_eq!(endpoints.root_url.to_string(), "http://rs.example.com/v2/");
954 assert_eq!(
955 endpoints.collection_url.to_string(),
956 "http://rs.example.com/v2/buckets/main/collections/test-collection",
957 );
958 assert_eq!(
959 endpoints.changeset_url.to_string(),
960 "http://rs.example.com/v2/buckets/main/collections/test-collection/changeset",
961 );
962 }
963}
964
965#[cfg(test)]
966mod viaduct_client_tests {
967 use super::*;
968
969 #[test]
970 fn test_fetch_uses_local_timestamp_as_unquoted_since() {
971 viaduct_dev::init_backend_dev();
972 let changeset = mockito::mock(
973 "GET",
974 "/v2/buckets/main/collections/test-collection/changeset",
975 )
976 .match_query(mockito::Matcher::AllOf(vec![
978 mockito::Matcher::UrlEncoded("_expected".into(), "0".into()),
979 mockito::Matcher::UrlEncoded("_since".into(), "42".into()),
980 ]))
981 .with_status(200)
982 .with_header("content-type", "application/json")
983 .with_body(
984 r#"{"changes": [], "timestamp": 42, "metadata": {"bucket": "main", "signatures": []}}"#,
985 )
986 .create();
987
988 let mut api_client = ViaductApiClient::new(
989 BaseUrl::parse(&format!("{}/v2", mockito::server_url())).unwrap(),
990 "main",
991 "test-collection",
992 );
993 api_client.fetch_changeset(Some(42)).unwrap();
994
995 changeset.assert();
996 }
997}
998
999#[cfg(test)]
1000mod jexl_tests {
1001 use super::*;
1002 use std::sync::{Arc, Weak};
1003
1004 #[test]
1005 fn test_get_records_filtered_app_version_pass() {
1006 let mut api_client = MockApiClient::new();
1007 let records = vec![RemoteSettingsRecord {
1008 id: "record-0001".into(),
1009 last_modified: 100,
1010 deleted: false,
1011 attachment: None,
1012 fields: serde_json::json!({
1013 "filter_expression": "env.version|versionCompare(\"128.0a1\") > 0"
1014 })
1015 .as_object()
1016 .unwrap()
1017 .clone(),
1018 }];
1019 let changeset = ChangesetResponse {
1020 changes: records.clone(),
1021 timestamp: 42,
1022 metadata: CollectionMetadata::default(),
1023 };
1024 api_client.expect_collection_url().returning(|| {
1025 "http://rs.example.com/v2/buckets/main/collections/test-collection".into()
1026 });
1027 api_client.expect_fetch_changeset().returning({
1028 let changeset = changeset.clone();
1029 move |timestamp| {
1030 assert_eq!(timestamp, None);
1031 Ok(changeset.clone())
1032 }
1033 });
1034 api_client.expect_is_prod_server().returning(|| Ok(false));
1035
1036 let context = RemoteSettingsContext {
1037 app_version: Some("129.0.0".to_string()),
1038 ..Default::default()
1039 };
1040
1041 let mut storage = Storage::new(":memory:".into());
1042 let _ = storage.insert_collection_content(
1043 "http://rs.example.com/v2/buckets/main/collections/test-collection",
1044 &records,
1045 42,
1046 CollectionMetadata::default(),
1047 );
1048
1049 let rs_client = RemoteSettingsClient::new_from_parts(
1050 "test-collection".into(),
1051 storage,
1052 JexlFilter::new(Some(context)),
1053 api_client,
1054 );
1055
1056 assert_eq!(
1057 rs_client.get_records(false).expect("Error getting records"),
1058 Some(records)
1059 );
1060 }
1061
1062 #[test]
1063 fn test_get_records_filtered_app_version_too_low() {
1064 let mut api_client = MockApiClient::new();
1065 let records = vec![RemoteSettingsRecord {
1066 id: "record-0001".into(),
1067 last_modified: 100,
1068 deleted: false,
1069 attachment: None,
1070 fields: serde_json::json!({
1071 "filter_expression": "env.version|versionCompare(\"128.0a1\") > 0"
1072 })
1073 .as_object()
1074 .unwrap()
1075 .clone(),
1076 }];
1077 let changeset = ChangesetResponse {
1078 changes: records.clone(),
1079 timestamp: 42,
1080 metadata: CollectionMetadata::default(),
1081 };
1082 api_client.expect_collection_url().returning(|| {
1083 "http://rs.example.com/v2/buckets/main/collections/test-collection".into()
1084 });
1085 api_client.expect_fetch_changeset().returning({
1086 let changeset = changeset.clone();
1087 move |timestamp| {
1088 assert_eq!(timestamp, None);
1089 Ok(changeset.clone())
1090 }
1091 });
1092 api_client.expect_is_prod_server().returning(|| Ok(false));
1093
1094 let context = RemoteSettingsContext {
1095 app_version: Some("127.0.0.".to_string()),
1096 ..Default::default()
1097 };
1098
1099 let mut storage = Storage::new(":memory:".into());
1100 let _ = storage.insert_collection_content(
1101 "http://rs.example.com/v2/buckets/main/collections/test-collection",
1102 &records,
1103 42,
1104 CollectionMetadata::default(),
1105 );
1106
1107 let rs_client = RemoteSettingsClient::new_from_parts(
1108 "test-collection".into(),
1109 storage,
1110 JexlFilter::new(Some(context)),
1111 api_client,
1112 );
1113
1114 assert_eq!(
1115 rs_client.get_records(false).expect("Error getting records"),
1116 Some(vec![])
1117 );
1118 }
1119
1120 #[test]
1121 fn test_update_jexl_context() {
1122 let mut api_client = MockApiClient::new();
1123 let records = vec![RemoteSettingsRecord {
1124 id: "record-0001".into(),
1125 last_modified: 100,
1126 deleted: false,
1127 attachment: None,
1128 fields: serde_json::json!({
1129 "filter_expression": "env.country == \"US\""
1130 })
1131 .as_object()
1132 .unwrap()
1133 .clone(),
1134 }];
1135 let changeset = ChangesetResponse {
1136 changes: records.clone(),
1137 timestamp: 42,
1138 metadata: CollectionMetadata::default(),
1139 };
1140 api_client.expect_collection_url().returning(|| {
1141 "http://rs.example.com/v2/buckets/main/collections/test-collection".into()
1142 });
1143 api_client.expect_fetch_changeset().returning({
1144 let changeset = changeset.clone();
1145 move |timestamp| {
1146 assert_eq!(timestamp, None);
1147 Ok(changeset.clone())
1148 }
1149 });
1150 api_client.expect_is_prod_server().returning(|| Ok(false));
1151
1152 let context = RemoteSettingsContext {
1153 country: Some("US".to_string()),
1154 ..Default::default()
1155 };
1156
1157 let mut storage = Storage::new(":memory:".into());
1158 let _ = storage.insert_collection_content(
1159 "http://rs.example.com/v2/buckets/main/collections/test-collection",
1160 &records,
1161 42,
1162 CollectionMetadata::default(),
1163 );
1164
1165 let rs_client = RemoteSettingsClient::new_from_parts(
1166 "test-collection".into(),
1167 storage,
1168 JexlFilter::new(Some(context)),
1169 api_client,
1170 );
1171
1172 assert_eq!(
1173 rs_client.get_records(false).expect("Error getting records"),
1174 Some(records)
1175 );
1176
1177 rs_client.inner.lock().jexl_filter = JexlFilter::new(Some(RemoteSettingsContext {
1180 country: Some("UK".to_string()),
1181 ..Default::default()
1182 }));
1183
1184 assert_eq!(
1185 rs_client.get_records(false).expect("Error getting records"),
1186 Some(vec![])
1187 );
1188 }
1189
1190 #[test]
1193 fn test_update_config_deadlock() {
1194 let mut api_client = MockApiClient::new();
1195 let rs_client_ref: Arc<Mutex<Weak<RemoteSettingsClient<MockApiClient>>>> =
1196 Arc::new(Mutex::new(Weak::new()));
1197 let rs_client_ref2 = rs_client_ref.clone();
1198
1199 api_client.expect_collection_url().returning(move || {
1200 rs_client_ref2
1211 .lock()
1212 .upgrade()
1213 .expect("rs_client_ref not set")
1214 .update_config(
1215 BaseUrl::parse("https://example.com/").unwrap(),
1216 "test-collection".to_string(),
1217 None,
1218 );
1219 "http://rs.example.com/v2/buckets/main/collections/test-collection".into()
1220 });
1221 api_client.expect_is_prod_server().returning(|| Ok(false));
1222
1223 let context = RemoteSettingsContext {
1224 app_version: Some("129.0.0".to_string()),
1225 ..Default::default()
1226 };
1227 let storage = Storage::new(":memory:".into());
1228
1229 let rs_client = Arc::new(RemoteSettingsClient::new_from_parts(
1230 "test-collection".into(),
1231 storage,
1232 JexlFilter::new(Some(context)),
1233 api_client,
1234 ));
1235 *rs_client_ref.lock() = Arc::downgrade(&rs_client);
1236
1237 assert_eq!(
1238 rs_client.get_records(false).expect("Error getting records"),
1239 None,
1240 );
1241 }
1242}
1243
1244#[cfg(feature = "signatures")]
1245#[cfg(test)]
1246mod test_signatures {
1247 use core::assert_eq;
1248
1249 use crate::RemoteSettingsContext;
1250
1251 use super::*;
1252 use nss_as::ensure_initialized;
1253
1254 const VALID_CERTIFICATE: &str = "\
1255-----BEGIN CERTIFICATE-----
1256MIIDBjCCAougAwIBAgIIFml6g0ldRGowCgYIKoZIzj0EAwMwgaMxCzAJBgNVBAYT
1257AlVTMRwwGgYDVQQKExNNb3ppbGxhIENvcnBvcmF0aW9uMS8wLQYDVQQLEyZNb3pp
1258bGxhIEFNTyBQcm9kdWN0aW9uIFNpZ25pbmcgU2VydmljZTFFMEMGA1UEAww8Q29u
1259dGVudCBTaWduaW5nIEludGVybWVkaWF0ZS9lbWFpbEFkZHJlc3M9Zm94c2VjQG1v
1260emlsbGEuY29tMB4XDTIxMDIwMzE1MDQwNVoXDTIxMDQyNDE1MDQwNVowgakxCzAJ
1261BgNVBAYTAlVTMRMwEQYDVQ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
13455xZxahHoTFGS0mDRfXqzKH5uD578GgjOZp0fULmzkcjWsgzdpDhadGjExRZFKlAy
1346iKv8cXTONrGY0fyBDKennuX0uAca3V0Qm6v2VRp+7wG/pywWwc5n+04qgxTQPxgO
13476pPB9UUsNbaLMDR5QPYAWrNhqJ7B07XqIYJZSwGP5xB9NqUZLF4z+AOMYgWtDpmg
1348IKdcFKAt3fFrpyMhlfIKkLfmm0iDjmfmIXbDGBJw9SE=
1349-----END CERTIFICATE-----";
1350 const VALID_SIGNATURE: &str = r#"fJJcOpwdnkjEWFeHXfdOJN6GaGLuDTPGzQOxA2jn6ldIleIk6KqMhZcy2GZv2uYiGwl6DERWwpaoUfQFLyCAOcVjck1qlaaEFZGY1BQba9p99xEc9FNQ3YPPfvSSZqsw"#;
1351 const VALID_CERT_EPOCH_SECONDS: u64 = 1615559719;
1352
1353 fn build_client(
1354 diff_records: &[RemoteSettingsRecord],
1355 full_records: &[RemoteSettingsRecord],
1356 certificate: &str,
1357 signatures: &[CollectionSignature],
1358 epoch_secs: u64,
1359 bucket: &str,
1360 ) -> RemoteSettingsClient<MockApiClient> {
1361 let collection_name = "pioneer-study-addons";
1362
1363 MOCK_TIME.with(|cell| cell.set(Some(epoch_secs)));
1364
1365 let some_metadata = CollectionMetadata {
1366 bucket: bucket.into(),
1367 signatures: signatures.to_vec(),
1368 };
1369 let diff_changeset = ChangesetResponse {
1371 changes: diff_records.to_vec(),
1372 timestamp: 1603992731957,
1373 metadata: some_metadata.clone(),
1374 };
1375 let full_changeset = ChangesetResponse {
1377 changes: full_records.to_vec(),
1378 timestamp: 1603992731957,
1379 metadata: some_metadata.clone(),
1380 };
1381
1382 let mut api_client = MockApiClient::new();
1383 api_client
1384 .expect_collection_url()
1385 .returning(move || format!("http://server/{}", collection_name));
1386 api_client.expect_is_prod_server().returning(|| Ok(false));
1387 api_client.expect_fetch_changeset().returning(move |since| {
1388 Ok(if since.is_some() {
1389 diff_changeset.clone()
1390 } else {
1391 full_changeset.clone()
1392 })
1393 });
1394
1395 let certificate = certificate.to_string();
1396 api_client
1397 .expect_fetch_cert()
1398 .returning(move |_| Ok(certificate.clone().into_bytes()));
1399
1400 let storage = Storage::new(":memory:".into());
1401 let jexl_filter = JexlFilter::new(Some(RemoteSettingsContext::default()));
1402 RemoteSettingsClient::new_from_parts(
1403 collection_name.to_string(),
1404 storage,
1405 jexl_filter,
1406 api_client,
1407 )
1408 }
1409
1410 fn run_client_sync(
1411 diff_records: &[RemoteSettingsRecord],
1412 full_records: &[RemoteSettingsRecord],
1413 certificate: &str,
1414 signatures: &[CollectionSignature],
1415 epoch_secs: u64,
1416 bucket: &str,
1417 ) -> Result<()> {
1418 build_client(
1419 diff_records,
1420 full_records,
1421 certificate,
1422 signatures,
1423 epoch_secs,
1424 bucket,
1425 )
1426 .sync()
1427 }
1428
1429 #[test]
1430 fn test_valid_signature() -> Result<()> {
1431 ensure_initialized();
1432 run_client_sync(
1433 &[],
1434 &[],
1435 VALID_CERTIFICATE,
1436 &[CollectionSignature {
1437 signature: VALID_SIGNATURE.to_string(),
1438 x5u: "http://mocked".into(),
1439 mode: "p384ecdsa".into(),
1440 }],
1441 VALID_CERT_EPOCH_SECONDS,
1442 "main",
1443 )
1444 .expect("Valid signature");
1445 Ok(())
1446 }
1447
1448 #[test]
1449 fn test_second_signature_is_valid() -> Result<()> {
1450 ensure_initialized();
1451 run_client_sync(
1452 &[],
1453 &[],
1454 VALID_CERTIFICATE,
1455 &[
1456 CollectionSignature {
1457 signature: "invalid signature".to_string(),
1458 x5u: "http://mocked".into(),
1459 mode: "p384ecdsa".into(),
1460 },
1461 CollectionSignature {
1462 signature: VALID_SIGNATURE.to_string(),
1463 x5u: "http://mocked".into(),
1464 mode: "p384ecdsa".into(),
1465 },
1466 ],
1467 VALID_CERT_EPOCH_SECONDS,
1468 "main",
1469 )
1470 .expect("Valid signature");
1471 Ok(())
1472 }
1473
1474 #[test]
1475 fn test_first_signature_has_unknown_type() -> Result<()> {
1476 ensure_initialized();
1477 run_client_sync(
1478 &[],
1479 &[],
1480 VALID_CERTIFICATE,
1481 &[
1482 CollectionSignature {
1483 signature: "unkown signature".to_string(),
1484 x5u: "http://mocked".into(),
1485 mode: "mldsa".into(),
1487 },
1488 CollectionSignature {
1489 signature: VALID_SIGNATURE.to_string(),
1490 x5u: "http://mocked".into(),
1491 mode: "p384ecdsa".into(),
1492 },
1493 ],
1494 VALID_CERT_EPOCH_SECONDS,
1495 "main",
1496 )
1497 .expect("Valid signature");
1498 Ok(())
1499 }
1500
1501 #[test]
1502 fn test_valid_signature_after_retry() -> Result<()> {
1503 ensure_initialized();
1504 run_client_sync(
1505 &[RemoteSettingsRecord {
1506 id: "bad-record".to_string(),
1507 last_modified: 9999,
1508 deleted: true,
1509 attachment: None,
1510 fields: serde_json::Map::new(),
1511 }],
1512 &[],
1513 VALID_CERTIFICATE,
1514 &[CollectionSignature {
1515 signature: VALID_SIGNATURE.to_string(),
1516 x5u: "http://mocked".into(),
1517 mode: "p384ecdsa".into(),
1518 }],
1519 VALID_CERT_EPOCH_SECONDS,
1520 "main",
1521 )
1522 .expect("Valid signature");
1523 Ok(())
1524 }
1525
1526 #[test]
1527 fn test_invalid_signature_value() -> Result<()> {
1528 ensure_initialized();
1529 let err = run_client_sync(
1530 &[],
1531 &[],
1532 VALID_CERTIFICATE,
1533 &[CollectionSignature {
1534 signature: "invalid signature".to_string(),
1535 x5u: "http://mocked".into(),
1536 mode: "p384ecdsa".into(),
1537 }],
1538 VALID_CERT_EPOCH_SECONDS,
1539 "main",
1540 )
1541 .unwrap_err();
1542 assert!(matches!(err, Error::SignatureError(_)));
1543 assert_eq!(format!("{}", err), "Signature could not be verified: Signature content error: Encoded text cannot have a 6-bit remainder.");
1544
1545 Ok(())
1546 }
1547
1548 #[test]
1549 fn test_invalid_certificate_value() -> Result<()> {
1550 ensure_initialized();
1551 let err = run_client_sync(
1552 &[],
1553 &[],
1554 "some bad PEM content",
1555 &[CollectionSignature {
1556 signature: VALID_SIGNATURE.to_string(),
1557 x5u: "http://mocked".into(),
1558 mode: "p384ecdsa".into(),
1559 }],
1560 VALID_CERT_EPOCH_SECONDS,
1561 "main",
1562 )
1563 .unwrap_err();
1564
1565 assert!(matches!(err, Error::SignatureError(_)));
1566 assert_eq!(
1567 format!("{}", err),
1568 "Signature could not be verified: PEM content format error: Missing PEM data"
1569 );
1570
1571 Ok(())
1572 }
1573
1574 #[test]
1575 fn test_invalid_signature_expired_cert() -> Result<()> {
1576 ensure_initialized();
1577 let december_20_2024 = 1734651582;
1578
1579 let err = run_client_sync(
1580 &[],
1581 &[],
1582 VALID_CERTIFICATE,
1583 &[CollectionSignature {
1584 signature: VALID_SIGNATURE.to_string(),
1585 x5u: "http://mocked".into(),
1586 mode: "p384ecdsa".into(),
1587 }],
1588 december_20_2024,
1589 "main",
1590 )
1591 .unwrap_err();
1592
1593 assert!(matches!(err, Error::SignatureError(_)));
1594 assert_eq!(
1595 format!("{}", err),
1596 "Signature could not be verified: Certificate not yet valid or expired"
1597 );
1598
1599 Ok(())
1600 }
1601
1602 #[test]
1603 fn test_invalid_signature_invalid_data() -> Result<()> {
1604 ensure_initialized();
1605 let records = vec![RemoteSettingsRecord {
1607 id: "unexpected-data".to_string(),
1608 last_modified: 42,
1609 deleted: false,
1610 attachment: None,
1611 fields: serde_json::Map::new(),
1612 }];
1613 let err = run_client_sync(
1614 &records,
1615 &records,
1616 VALID_CERTIFICATE,
1617 &[CollectionSignature {
1618 signature: VALID_SIGNATURE.to_string(),
1619 x5u: "http://mocked".into(),
1620 mode: "p384ecdsa".into(),
1621 }],
1622 VALID_CERT_EPOCH_SECONDS,
1623 "main",
1624 )
1625 .unwrap_err();
1626
1627 assert!(matches!(err, Error::SignatureError(_)));
1628 assert_eq!(format!("{}", err), "Signature could not be verified: Content signature mismatch error: NSS error: NSS error: -8182 ");
1629
1630 Ok(())
1631 }
1632
1633 #[test]
1634 fn test_invalid_signature_invalid_signer_name() -> Result<()> {
1635 ensure_initialized();
1636 let err = run_client_sync(
1637 &[],
1638 &[],
1639 VALID_CERTIFICATE,
1640 &[CollectionSignature {
1641 signature: VALID_SIGNATURE.to_string(),
1642 x5u: "http://mocked".into(),
1643 mode: "p384ecdsa".into(),
1644 }],
1645 VALID_CERT_EPOCH_SECONDS,
1646 "security-state",
1647 )
1648 .unwrap_err();
1649 assert!(matches!(err, Error::SignatureError(_)));
1650 assert_eq!(
1651 format!("{}", err),
1652 "Signature could not be verified: Certificate subject mismatch"
1653 );
1654
1655 Ok(())
1656 }
1657
1658 #[test]
1659 fn test_get_records_sync_if_empty_verifies_signature() -> Result<()> {
1660 ensure_initialized();
1661 let rs_client = build_client(
1662 &[],
1663 &[],
1664 VALID_CERTIFICATE,
1665 &[CollectionSignature {
1666 signature: "invalid signature".to_string(),
1667 x5u: "http://mocked".into(),
1668 mode: "p384ecdsa".into(),
1669 }],
1670 VALID_CERT_EPOCH_SECONDS,
1671 "main",
1672 );
1673
1674 let err = rs_client.get_records(true).unwrap_err();
1675
1676 assert!(matches!(err, Error::SignatureError(_)));
1677 assert_eq!(format!("{}", err), "Signature could not be verified: Signature content error: Encoded text cannot have a 6-bit remainder.");
1678
1679 let mut inner = rs_client.lock_inner()?;
1681 let collection_url = inner.api_client.collection_url();
1682 assert_eq!(inner.storage.get_records(&collection_url)?, None);
1683
1684 Ok(())
1685 }
1686
1687 #[test]
1688 fn test_get_records_sync_if_empty_with_valid_signature() -> Result<()> {
1689 ensure_initialized();
1690 let rs_client = build_client(
1691 &[],
1692 &[],
1693 VALID_CERTIFICATE,
1694 &[CollectionSignature {
1695 signature: VALID_SIGNATURE.to_string(),
1696 x5u: "http://mocked".into(),
1697 mode: "p384ecdsa".into(),
1698 }],
1699 VALID_CERT_EPOCH_SECONDS,
1700 "main",
1701 );
1702
1703 assert_eq!(rs_client.get_records(true)?, Some(vec![]));
1705
1706 Ok(())
1707 }
1708}
1709
1710#[cfg(test)]
1711mod test_reset_storage {
1712 use super::*;
1713
1714 #[test]
1715 fn test_reset_storage_deletes_records_and_attachments() {
1716 let collection_url = "http://rs.example.com/v2/buckets/main/collections/test-collection";
1717
1718 let mut api_client = MockApiClient::new();
1719 api_client
1720 .expect_collection_url()
1721 .returning(|| collection_url.into());
1722 api_client.expect_is_prod_server().returning(|| Ok(false));
1723
1724 let records = vec![RemoteSettingsRecord {
1725 id: "record-0001".into(),
1726 last_modified: 100,
1727 deleted: false,
1728 attachment: Some(Attachment {
1729 filename: "test-file.bin".into(),
1730 mimetype: "application/octet-stream".into(),
1731 location: "attachments/test-file.bin".into(),
1732 hash: "3a6eb0790f39ac87c94f3856b2dd2c5d110e6811602261a9a923d3bb23adc8b7".into(),
1733 size: 4,
1734 }),
1735 fields: serde_json::Map::new(),
1736 }];
1737
1738 let mut storage = Storage::new(":memory:".into());
1739 storage
1740 .insert_collection_content(collection_url, &records, 100, CollectionMetadata::default())
1741 .expect("Failed to insert records");
1742
1743 storage
1744 .set_attachment(collection_url, "attachments/test-file.bin", b"data")
1745 .expect("Failed to insert attachment");
1746
1747 assert!(storage.get_records(collection_url).unwrap().is_some());
1749 assert!(storage
1750 .get_attachment(collection_url, records[0].attachment.clone().unwrap())
1751 .unwrap()
1752 .is_some());
1753
1754 let rs_client = RemoteSettingsClient::new_from_parts(
1755 "test-collection".into(),
1756 storage,
1757 JexlFilter::new(None),
1758 api_client,
1759 );
1760
1761 rs_client.reset_storage().expect("Failed to reset storage");
1762
1763 let mut inner = rs_client.inner.lock();
1765 assert_eq!(
1766 inner.storage.get_records(collection_url).unwrap(),
1767 None,
1768 "Records should be deleted after reset_storage"
1769 );
1770 assert_eq!(
1771 inner
1772 .storage
1773 .get_attachment(collection_url, records[0].attachment.clone().unwrap(),)
1774 .unwrap(),
1775 None,
1776 "Attachments should be deleted after reset_storage"
1777 );
1778 }
1779
1780 #[test]
1781 fn test_reset_storage_reverts_to_packaged_data() {
1782 let collection_url = "http://rs.example.com/v2/buckets/main/collections/regions";
1783
1784 let mut api_client = MockApiClient::new();
1785 api_client
1786 .expect_collection_url()
1787 .returning(|| collection_url.into());
1788 api_client.expect_is_prod_server().returning(|| Ok(true));
1790
1791 let synced_records = vec![RemoteSettingsRecord {
1792 id: "custom-synced-record".into(),
1793 last_modified: 99999,
1794 deleted: false,
1795 attachment: None,
1796 fields: serde_json::json!({"key": "synced-value"})
1797 .as_object()
1798 .unwrap()
1799 .clone(),
1800 }];
1801
1802 let mut storage = Storage::new(":memory:".into());
1803 storage
1804 .insert_collection_content(
1805 collection_url,
1806 &synced_records,
1807 99999,
1808 CollectionMetadata::default(),
1809 )
1810 .expect("Failed to insert synced records");
1811
1812 let records_before = storage.get_records(collection_url).unwrap().unwrap();
1814 assert_eq!(records_before[0].id, "custom-synced-record");
1815
1816 let rs_client = RemoteSettingsClient::new_from_parts(
1817 "regions".into(),
1818 storage,
1819 JexlFilter::new(None),
1820 api_client,
1821 );
1822
1823 rs_client.reset_storage().expect("Failed to reset storage");
1824
1825 let mut inner = rs_client.inner.lock();
1826 let records = inner.storage.get_records(collection_url).unwrap();
1827 assert!(
1828 records.is_some(),
1829 "Packaged data should be restored after reset_storage on prod"
1830 );
1831 let records = records.unwrap();
1832 assert!(
1833 !records.is_empty(),
1834 "Packaged regions data should not be empty"
1835 );
1836 assert!(
1837 !records.iter().any(|r| r.id == "custom-synced-record"),
1838 "Synced data should be replaced by packaged data after reset"
1839 );
1840 }
1841}