Debian Codegraph @

third_party/rust/remote_settings/src/client.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 use crate::config::{BaseUrl, RemoteSettingsConfig};
6 use crate::error::{debug, trace, Error, Result};
7 use crate::jexl_filter::JexlFilter;
8 #[cfg(feature = "signatures")]
9 use crate::signatures;
10 use crate::storage::Storage;
11 use crate::RemoteSettingsContext;
12 use crate::{packaged_attachments, packaged_collections, RemoteSettingsServer};
13 use parking_lot::Mutex;
14 use serde::{Deserialize, Serialize};
15 use sha2::{Digest, Sha256};
16 use std::{
17 borrow::Cow,
18 time::{Duration, Instant},
19 };
20 use url::Url;
21 use viaduct::{Request, Response};
22
23 #[cfg(feature = "signatures")]
24 #[cfg(not(test))]
25 use std::time::{SystemTime, UNIX_EPOCH};
26
27 #[cfg(feature = "signatures")]
28 #[cfg(not(test))]
29 fn epoch_seconds() -> u64 {
30 SystemTime::now()
31 .duration_since(UNIX_EPOCH)
32 .unwrap() // Time won't go backwards.
33 .as_secs()
34 }
35
36 #[cfg(feature = "signatures")]
37 #[cfg(test)]
38 thread_local! {
39 static MOCK_TIME: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) }
40 }
41
42 #[cfg(feature = "signatures")]
43 #[cfg(test)]
44 fn epoch_seconds() -> u64 {
45 MOCK_TIME.with(|mock_time| mock_time.get().unwrap_or(0))
46 }
47
48 const HEADER_BACKOFF: &str = "Backoff";
49 const HEADER_ETAG: &str = "ETag";
50 const HEADER_RETRY_AFTER: &str = "Retry-After";
51
52 /// Hard-coded SHA256 of our root certificates. This is used by rc_crypto/pkixc to verify that the
53 /// certificates chains used in content signatures verification were produced from our root certificate.
54 /// See https://bugzilla.mozilla.org/show_bug.cgi?id=1940903 to align with desktop implementation.
55 #[cfg(feature = "signatures")]
56 const 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";
57 #[cfg(feature = "signatures")]
58 const 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";
59
60 #[derive(Debug, Clone, Deserialize)]
61 struct CollectionData {
62 data: Vec<RemoteSettingsRecord>,
63 timestamp: u64,
64 }
65
66 /// Internal Remote settings client API
67 ///
68 /// This stores an ApiClient implementation. In the real-world, this is always ViaductApiClient,
69 /// but the tests use a mock client.
70 pub struct RemoteSettingsClient<C = ViaductApiClient> {
71 // This is immutable, so it can be outside the mutex
72 collection_name: String,
73 inner: Mutex<RemoteSettingsClientInner<C>>,
74 }
75
76 struct RemoteSettingsClientInner<C> {
77 storage: Storage,
78 api_client: C,
79 jexl_filter: JexlFilter,
80 }
81
82 // To initially download the dump (and attachments, if any), run:
83 // $ cargo remote-settings dump-get --bucket main --collection-name <collection name>
84 //
85 // Then add the entry here.
86 //
87 // For subsequent updates, run the command above again.
88 impl<C: ApiClient> RemoteSettingsClient<C> {
89 // One line per bucket + collection
90 packaged_collections! {
91 ("main", "search-config-icons"),
92 ("main", "search-config-v2"),
93 ("main", "search-telemetry-v2"),
94 ("main", "regions"),
95 }
96
97 // You have to specify
98 // - bucket + collection_name: ("main", "regions")
99 // - One line per file you want to add (e.g. "world")
100 //
101 // This will automatically also include the NAME.meta.json file
102 // for internal validation against hash and size
103 //
104 // The entries line up with the `Attachment::filename` field,
105 // and check for the folder + name in
106 // `remote_settings/dumps/{bucket}/attachments/{collection}/{filename}
107 packaged_attachments! {
108 ("main", "regions") => [
109 "world",
110 "world-buffered",
111 ],
112 ("main", "search-config-icons") => [
113 "001500a9-1a6c-3f5a-ba15-a5f5a075d256",
114 "06cf7432-efd7-f244-927b-5e423005e1ea",
115 "0a57b0cf-34f0-4d09-96e4-dbd6e3355410",
116 "0d7668a8-c3f4-cfee-cbc8-536511528937",
117 "0eec5640-6fde-d6fe-322a-c72c6d5bd5a2",
118 "101ce01d-2691-b729-7f16-9d389803384b",
119 "177aba42-9bed-4078-e36b-580e8794cd7f",
120 "25de0352-aabb-d31f-15f7-bf9299fb004c",
121 "2bbe48f4-d3b8-c9e0-86e3-a54c37ec3335",
122 "2e835b0e-9709-d1bb-9725-87f59f3445ca",
123 "2ecca3f8-c1ef-43cc-b053-886d1ae46c36",
124 "32d26d19-aeb0-5c01-32e8-f8970be9246f",
125 "39d0b17d-c020-4890-932f-83c0f6ed130b",
126 "41135a88-093d-4077-873b-9de1ae133427",
127 "41f0d805-3775-4988-8d8c-5ad8ccd86d1c",
128 "47da97b5-600f-c450-fd15-a52bb2169c11",
129 "48c72361-cd67-412e-bd7f-f81a43c10791",
130 "4e271681-3e0f-91ac-9750-03f665efc171",
131 "50f6171f-8e7a-b41b-862e-f97397038fb2",
132 "5203dd03-2c55-4b53-9c60-58258d587be1",
133 "5914932e-66ba-4126-8be5-d37beadd9532",
134 "5ded611d-44b2-dc46-fd67-fb116888d75d",
135 "5e03d6f4-6ee9-8bc8-cf22-7a5f2cf55c41",
136 "6644f26f-28ea-4222-929d-5d43a02dae05",
137 "6d10d702-7bd6-1452-90a5-3df665a38f66",
138 "6e36a151-e4f4-4117-9067-1ca82c47d01a",
139 "6f4da442-d31e-28f8-03af-797d16bbdd27",
140 "7072564d-a573-4750-bf33-f0a07631c9eb",
141 "70fdd651-6c50-b7bb-09ec-7e85da259173",
142 "71f41a0c-5b70-4116-b30f-e62089083522",
143 "74793ce1-a918-a5eb-d3c0-2aadaff3c88c",
144 "74f94dc2-caf6-4b90-b3d2-f3e2f7714d88",
145 "764e3b14-fe16-4feb-8384-124c516a5afa",
146 "7bbe6c5c-fdb8-2845-a4f4-e1382e708a0e",
147 "7bf4ca37-e2b8-4d31-a1c3-979bc0e85131",
148 "7c81cf98-7c11-4afd-8279-db89118a6dfb",
149 "7cb4d88a-d4df-45b2-87e4-f896eaf1bbdb",
150 "7edaf4fe-a8a0-432b-86d2-bf75ebe80851",
151 "7efbed51-813c-581d-d8d3-f8758434e451",
152 "84bb4962-e571-227a-9ef6-2ac5f2aac361",
153 "87ac4cde-f581-398b-1e32-eb4079183b36",
154 "8831ce10-b1e4-6eb4-4975-83c67457288e",
155 "890de5c4-0941-a116-473a-5d240e79497a",
156 "8abb10a7-212f-46b5-a7b4-244f414e3810",
157 "91a9672d-e945-8e1e-0996-aefdb0190716",
158 "94a84724-c30f-4767-ba42-01cc37fc31a4",
159 "95ed201d-4ab8-4cb8-831d-454f53cab0f8",
160 "96327a73-c433-5eb4-a16d-b090cadfb80b",
161 "9802e63d-05ec-48ba-93f9-746e0981ad98",
162 "a06db97d-1210-ea2e-5474-0e2f7d295bfd",
163 "a06dc3fd-4bdb-41f3-2ebc-4cbed06a9bd3",
164 "a2c7d4e9-f770-51e1-0963-3c2c8401631d",
165 "a83f24e4-602c-47bd-930c-ad0947ee1adf",
166 "b64f09fd-52d1-c48e-af23-4ce918e7bf3b",
167 "b882b24d-1776-4ef9-9016-0bdbd935eda3",
168 "b8ca5a94-8fff-27ad-6e00-96e244a32e21",
169 "b9424309-f601-4a69-98ca-ca68e65633e6",
170 "c411adc1-9661-4fb5-a4c1-8cfe74911943",
171 "cbf9e891-d079-2b28-5617-283450d463dd",
172 "d87f251c-3e12-a8bf-e2d0-afd43d36c5f9",
173 "db0e1627-ae89-4c25-8944-a9481d8512d9",
174 "e02f23df-8d48-2b1b-3b5c-6dd27302c61c",
175 "e718e983-09aa-e8f6-b25f-cd4b395d4785",
176 "e7547f62-187b-b641-d462-e54a3f813d9a",
177 "eb62e768-151b-45d1-9fe5-9e1d2a5991c5",
178 "f312610a-ebfb-a106-ea92-fd643c5d3636",
179 "fa0fc42c-d91d-fca7-34eb-806ff46062dc",
180 "fca3e3ee-56cd-f474-dc31-307fd24a891d",
181 "fe75ce3f-1545-400c-b28c-ad771054e69f",
182 "fed4f021-ff3e-942a-010e-afa43fda2136",
183 ]
184 }
185 }
186
187 impl<C: ApiClient> RemoteSettingsClient<C> {
188 pub fn new_from_parts(
189 collection_name: String,
190 storage: Storage,
191 jexl_filter: JexlFilter,
192 api_client: C,
193 ) -> Self {
194 Self {
195 collection_name,
196 inner: Mutex::new(RemoteSettingsClientInner {
197 storage,
198 api_client,
199 jexl_filter,
200 }),
201 }
202 }
203
204 pub fn collection_name(&self) -> &str {
205 &self.collection_name
206 }
207
208 fn load_packaged_data(&self) -> Option<CollectionData> {
209 // Using the macro generated `get_packaged_data` in macros.rs
210 Self::get_packaged_data(&self.collection_name)
211 .and_then(|data| serde_json::from_str(data).ok())
212 }
213
214 fn load_packaged_attachment(&self, filename: &str) -> Option<(&'static [u8], &'static str)> {
215 // Using the macro generated `get_packaged_attachment` in macros.rs
216 Self::get_packaged_attachment(&self.collection_name, filename)
217 }
218
219 /// Filters records based on the presence and evaluation of `filter_expression`.
220 fn filter_records(
221 &self,
222 records: Vec<RemoteSettingsRecord>,
223 inner: &RemoteSettingsClientInner<C>,
224 ) -> Vec<RemoteSettingsRecord> {
225 records
226 .into_iter()
227 .filter(|record| match record.fields.get("filter_expression") {
228 Some(serde_json::Value::String(filter_expr)) => {
229 inner.jexl_filter.evaluate(filter_expr).unwrap_or(false)
230 }
231 _ => true, // Include records without a valid filter expression by default
232 })
233 .collect()
234 }
235
236 /// Get the current set of records.
237 ///
238 /// If records are not present in storage this will normally return None. Use `sync_if_empty =
239 /// true` to change this behavior and perform a network request in this case.
240 pub fn get_records(&self, sync_if_empty: bool) -> Result<Option<Vec<RemoteSettingsRecord>>> {
241 let mut inner = self.inner.lock();
242 let collection_url = inner.api_client.collection_url();
243 let is_prod = inner.api_client.is_prod_server()?;
244 let packaged_data = if is_prod {
245 self.load_packaged_data()
246 } else {
247 None
248 };
249
250 // Case 1: The packaged data is more recent than the cache
251 //
252 // This happens when there's no cached data or when we get new packaged data because of a
253 // product update
254 if let Some(packaged_data) = packaged_data {
255 let cached_timestamp = inner
256 .storage
257 .get_last_modified_timestamp(&collection_url)?
258 .unwrap_or(0);
259 if packaged_data.timestamp > cached_timestamp {
260 // Remove previously cached data (packaged data does not have tombstones like diff responses do).
261 inner.storage.empty()?;
262 // Insert new packaged data.
263 inner.storage.insert_collection_content(
264 &collection_url,
265 &packaged_data.data,
266 packaged_data.timestamp,
267 CollectionMetadata::default(),
268 )?;
269 return Ok(Some(self.filter_records(packaged_data.data, &inner)));
270 }
271 }
272
273 let cached_records = inner.storage.get_records(&collection_url)?;
274
275 Ok(match (cached_records, sync_if_empty) {
276 // Case 2: We have cached records
277 //
278 // Note: we should return these even if it's an empty list and `sync_if_empty=true`.
279 // The "if empty" part refers to the cache being empty, not the list.
280 (Some(cached_records), _) => Some(self.filter_records(cached_records, &inner)),
281 // Case 3: sync_if_empty=true
282 (None, true) => {
283 let changeset = inner.api_client.fetch_changeset(None)?;
284 inner.storage.insert_collection_content(
285 &collection_url,
286 &changeset.changes,
287 changeset.timestamp,
288 changeset.metadata,
289 )?;
290 Some(self.filter_records(changeset.changes, &inner))
291 }
292 // Case 4: Nothing to return
293 (None, false) => None,
294 })
295 }
296
297 pub fn get_last_modified_timestamp(&self) -> Result<Option<u64>> {
298 let mut inner = self.inner.lock();
299 let collection_url = inner.api_client.collection_url();
300 inner.storage.get_last_modified_timestamp(&collection_url)
301 }
302
303 /// Synchronizes the local collection with the remote server by performing the following steps:
304 /// 1. Fetches the last modified timestamp of the collection from local storage.
305 /// 2. Fetches the changeset from the remote server based on the last modified timestamp.
306 /// 3. Inserts the fetched changeset into local storage.
307 fn perform_sync_operation(&self) -> Result<()> {
308 let mut inner = self.inner.lock();
309 let collection_url = inner.api_client.collection_url();
310 let timestamp = inner.storage.get_last_modified_timestamp(&collection_url)?;
311 let changeset = inner.api_client.fetch_changeset(timestamp)?;
312 debug!(
313 "{0}: apply {1} change(s) locally.",
314 self.collection_name,
315 changeset.changes.len()
316 );
317 inner.storage.insert_collection_content(
318 &collection_url,
319 &changeset.changes,
320 changeset.timestamp,
321 changeset.metadata,
322 )
323 }
324
325 pub fn sync(&self) -> Result<()> {
326 // First attempt
327 self.perform_sync_operation()?;
328 // Verify that inserted data has valid signature
329 if self.verify_signature().is_err() {
330 debug!(
331 "{0}: signature verification failed. Reset and retry.",
332 self.collection_name
333 );
334 // Retry with packaged dataset as base
335 self.reset_storage()?;
336 self.perform_sync_operation()?;
337 // Verify signature again
338 self.verify_signature().inspect_err(|_| {
339 // And reset with packaged data if it fails again.
340 self.reset_storage()
341 .expect("Failed to reset storage after verification failure");
342 })?;
343 }
344 trace!("{0}: sync done.", self.collection_name);
345 Ok(())
346 }
347
348 fn reset_storage(&self) -> Result<()> {
349 trace!("{0}: reset local storage.", self.collection_name);
350 let mut inner = self.inner.lock();
351 let collection_url = inner.api_client.collection_url();
352 // Clear existing storage
353 inner.storage.empty()?;
354 // Load packaged data only for production
355 if inner.api_client.is_prod_server()? {
356 if let Some(packaged_data) = self.load_packaged_data() {
357 trace!("{0}: restore packaged dump.", self.collection_name);
358 inner.storage.insert_collection_content(
359 &collection_url,
360 &packaged_data.data,
361 packaged_data.timestamp,
362 CollectionMetadata::default(),
363 )?;
364 }
365 }
366 Ok(())
367 }
368
369 pub fn shutdown(&self) {
370 self.inner.lock().storage.close();
371 }
372
373 #[cfg(not(feature = "signatures"))]
374 fn verify_signature(&self) -> Result<()> {
375 debug!("{0}: signature verification skipped.", self.collection_name);
376 Ok(())
377 }
378
379 #[cfg(feature = "signatures")]
380 fn verify_signature(&self) -> Result<()> {
381 let mut inner = self.inner.lock();
382 let collection_url = inner.api_client.collection_url();
383 let timestamp = inner.storage.get_last_modified_timestamp(&collection_url)?;
384 let records = inner.storage.get_records(&collection_url)?;
385 let metadata = inner.storage.get_collection_metadata(&collection_url)?;
386 match (timestamp, &records, metadata) {
387 (Some(timestamp), Some(records), Some(metadata)) => {
388 let cert_chain_bytes = inner.api_client.fetch_cert(&metadata.signature.x5u)?;
389 // rc_crypto verifies that the provided certificates chain leads to our root certificate.
390 let expected_root_hash = if inner.api_client.is_prod_server()? {
391 ROOT_CERT_SHA256_HASH_PROD
392 } else {
393 ROOT_CERT_SHA256_HASH_NONPROD
394 };
395
396 // The signer name is hard-coded. This would have to be modified in the very (very)
397 // unlikely situation where we would add a new collection signer.
398 // And clients code would have to be modified to handle this new collection anyway.
399 // https://searchfox.org/mozilla-central/rev/df850fa290fe962c2c5ae8b63d0943ce768e3cc4/services/settings/remote-settings.sys.mjs#40-48
400 let expected_leaf_cname = format!(
401 "{}.content-signature.mozilla.org",
402 if metadata.bucket.contains("security-state") {
403 "onecrl"
404 } else {
405 "remote-settings"
406 }
407 );
408 signatures::verify_signature(
409 timestamp,
410 records,
411 metadata.signature.signature.as_bytes(),
412 &cert_chain_bytes,
413 epoch_seconds(),
414 expected_root_hash,
415 &expected_leaf_cname,
416 )
417 .inspect_err(|err| {
418 debug!(
419 "{0}: bad signature ({1:?}) using certificate {2} and signer '{3}'",
420 self.collection_name, err, &metadata.signature.x5u, expected_leaf_cname
421 );
422 })?;
423 trace!("{0}: signature verification success.", self.collection_name);
424 Ok(())
425 }
426 _ => {
427 let missing_field = if timestamp.is_none() {
428 "timestamp"
429 } else if records.is_none() {
430 "records"
431 } else {
432 "metadata"
433 };
434 Err(Error::IncompleteSignatureDataError(missing_field.into()))
435 }
436 }
437 }
438
439 /// Downloads an attachment from [attachment_location]. NOTE: there are no guarantees about a
440 /// maximum size, so use care when fetching potentially large attachments.
441 pub fn get_attachment(&self, record: &RemoteSettingsRecord) -> Result<Vec<u8>> {
442 let metadata = record
443 .attachment
444 .as_ref()
445 .ok_or_else(|| Error::RecordAttachmentMismatchError("No attachment metadata".into()))?;
446
447 let mut inner = self.inner.lock();
448 let collection_url = inner.api_client.collection_url();
449
450 // First try storage - it will only return data that matches our metadata
451 if let Some(data) = inner
452 .storage
453 .get_attachment(&collection_url, metadata.clone())?
454 {
455 return Ok(data);
456 }
457
458 // Then try packaged data if we're in prod
459 if inner.api_client.is_prod_server()? {
460 if let Some((data, manifest)) = self.load_packaged_attachment(&record.id) {
461 if let Ok(manifest_data) = serde_json::from_str::<serde_json::Value>(manifest) {
462 if metadata.hash == manifest_data["hash"].as_str().unwrap_or_default()
463 && metadata.size == manifest_data["size"].as_u64().unwrap_or_default()
464 {
465 // Store valid packaged data in storage because it was either empty or outdated
466 inner
467 .storage
468 .set_attachment(&collection_url, &metadata.location, data)?;
469 return Ok(data.to_vec());
470 }
471 }
472 }
473 }
474
475 // Try to download the attachment because neither the storage nor the local data had it
476 let attachment = inner.api_client.fetch_attachment(&metadata.location)?;
477
478 // Verify downloaded data
479 if attachment.len() as u64 != metadata.size {
480 return Err(Error::RecordAttachmentMismatchError(
481 "Downloaded attachment size mismatch".into(),
482 ));
483 }
484 let hash = format!("{:x}", Sha256::digest(&attachment));
485 if hash != metadata.hash {
486 return Err(Error::RecordAttachmentMismatchError(
487 "Downloaded attachment hash mismatch".into(),
488 ));
489 }
490
491 // Store verified download in storage
492 inner
493 .storage
494 .set_attachment(&collection_url, &metadata.location, &attachment)?;
495 Ok(attachment)
496 }
497 }
498
499 impl RemoteSettingsClient<ViaductApiClient> {
500 pub fn new(
501 server_url: BaseUrl,
502 bucket_name: String,
503 collection_name: String,
504 context: Option<RemoteSettingsContext>,
505 storage: Storage,
506 ) -> Self {
507 let api_client = ViaductApiClient::new(server_url, &bucket_name, &collection_name);
508 let jexl_filter = JexlFilter::new(context);
509
510 Self::new_from_parts(collection_name, storage, jexl_filter, api_client)
511 }
512
513 pub fn update_config(
514 &self,
515 server_url: BaseUrl,
516 bucket_name: String,
517 context: Option<RemoteSettingsContext>,
518 ) -> Result<()> {
519 let mut inner = self.inner.lock();
520 inner.api_client = ViaductApiClient::new(server_url, &bucket_name, &self.collection_name);
521 inner.jexl_filter = JexlFilter::new(context);
522 inner.storage.empty()
523 }
524 }
525
526 #[cfg_attr(test, mockall::automock)]
527 pub trait ApiClient {
528 /// Get the Bucket URL for this client.
529 ///
530 /// This is a URL that includes the server URL, bucket name, and collection name. This is used
531 /// to check if the application has switched the remote settings config and therefore we should
532 /// throw away any cached data
533 ///
534 /// Returns it as a String, since that's what the storage expects
535 fn collection_url(&self) -> String;
536
537 /// Fetch records from the server
538 fn fetch_changeset(&mut self, timestamp: Option<u64>) -> Result<ChangesetResponse>;
539
540 /// Fetch an attachment from the server
541 fn fetch_attachment(&mut self, attachment_location: &str) -> Result<Vec<u8>>;
542
543 /// Fetch a server certificate
544 fn fetch_cert(&mut self, x5u: &str) -> Result<Vec<u8>>;
545
546 /// Check if this client is pointing to the production server
547 fn is_prod_server(&self) -> Result<bool>;
548 }
549
550 /// Client for Remote settings API requests
551 pub struct ViaductApiClient {
552 endpoints: RemoteSettingsEndpoints,
553 remote_state: RemoteState,
554 }
555
556 impl ViaductApiClient {
557 fn new(base_url: BaseUrl, bucket_name: &str, collection_name: &str) -> Self {
558 Self {
559 endpoints: RemoteSettingsEndpoints::new(&base_url, bucket_name, collection_name),
560 remote_state: RemoteState::default(),
561 }
562 }
563
564 fn make_request(&mut self, url: Url) -> Result<Response> {
565 trace!("make_request: {url}");
566 self.remote_state.ensure_no_backoff()?;
567
568 let req = Request::get(url);
569 let resp = req.send()?;
570
571 self.remote_state.handle_backoff_hint(&resp)?;
572
573 if resp.is_success() {
574 Ok(resp)
575 } else {
576 Err(Error::ResponseError(format!(
577 "status code: {}",
578 resp.status
579 )))
580 }
581 }
582 }
583
584 impl ApiClient for ViaductApiClient {
585 fn collection_url(&self) -> String {
586 self.endpoints.collection_url.to_string()
587 }
588
589 fn fetch_changeset(&mut self, timestamp: Option<u64>) -> Result<ChangesetResponse> {
590 let mut url = self.endpoints.changeset_url.clone();
591 // 0 is used as an arbitrary value for `_expected` because the current implementation does
592 // not leverage push timestamps or polling from the monitor/changes endpoint. More
593 // details:
594 //
595 // https://remote-settings.readthedocs.io/en/latest/client-specifications.html#cache-busting
596 url.query_pairs_mut().append_pair("_expected", "0");
597 if let Some(timestamp) = timestamp {
598 url.query_pairs_mut()
599 .append_pair("_since", &format!("\"{}\"", timestamp));
600 }
601
602 let resp = self.make_request(url)?;
603
604 if resp.is_success() {
605 Ok(resp.json::<ChangesetResponse>()?)
606 } else {
607 Err(Error::ResponseError(format!(
608 "status code: {}",
609 resp.status
610 )))
611 }
612 }
613
614 fn fetch_attachment(&mut self, attachment_location: &str) -> Result<Vec<u8>> {
615 let attachments_base_url = match &self.remote_state.attachments_base_url {
616 Some(attachments_base_url) => attachments_base_url.to_owned(),
617 None => {
618 let server_info = self
619 .make_request(self.endpoints.root_url.clone())?
620 .json::<ServerInfo>()?;
621 let attachments_base_url = match server_info.capabilities.attachments {
622 Some(capability) => Url::parse(&capability.base_url)?,
623 None => Err(Error::AttachmentsUnsupportedError)?,
624 };
625 self.remote_state.attachments_base_url = Some(attachments_base_url.clone());
626 attachments_base_url
627 }
628 };
629
630 let resp = self.make_request(attachments_base_url.join(attachment_location)?)?;
631 Ok(resp.body)
632 }
633
634 fn is_prod_server(&self) -> Result<bool> {
635 Ok(self
636 .endpoints
637 .root_url
638 .as_str()
639 .starts_with(RemoteSettingsServer::Prod.get_url()?.as_str()))
640 }
641
642 fn fetch_cert(&mut self, x5u: &str) -> Result<Vec<u8>> {
643 let resp = self.make_request(Url::parse(x5u)?)?;
644 Ok(resp.body)
645 }
646 }
647
648 /// A simple HTTP client that can retrieve Remote Settings data using the properties by [ClientConfig].
649 /// Methods defined on this will fetch data from
650 /// <base_url>/buckets/<bucket_name>/collections/<collection_name>/
651 pub struct Client {
652 endpoints: RemoteSettingsEndpoints,
653 pub(crate) remote_state: Mutex<RemoteState>,
654 }
655
656 impl Client {
657 /// Create a new [Client] with properties matching config.
658 pub fn new(config: RemoteSettingsConfig) -> Result<Self> {
659 let server = match (config.server, config.server_url) {
660 (Some(server), None) => server,
661 (None, Some(server_url)) => RemoteSettingsServer::Custom { url: server_url },
662 (None, None) => RemoteSettingsServer::Prod,
663 (Some(_), Some(_)) => Err(Error::ConfigError(
664 "`RemoteSettingsConfig` takes either `server` or `server_url`, not both".into(),
665 ))?,
666 };
667
668 let bucket_name = config.bucket_name.unwrap_or_else(|| String::from("main"));
669 let endpoints = RemoteSettingsEndpoints::new(
670 &server.get_base_url()?,
671 &bucket_name,
672 &config.collection_name,
673 );
674
675 Ok(Self {
676 endpoints,
677 remote_state: Default::default(),
678 })
679 }
680
681 /// Fetches all records for a collection that can be found in the server,
682 /// bucket, and collection defined by the [ClientConfig] used to generate
683 /// this [Client].
684 pub fn get_records(&self) -> Result<RemoteSettingsResponse> {
685 self.get_records_with_options(&GetItemsOptions::new())
686 }
687
688 /// Fetches all records for a collection that can be found in the server,
689 /// bucket, and collection defined by the [ClientConfig] used to generate
690 /// this [Client]. This function will return the raw network [Response].
691 pub fn get_records_raw(&self) -> Result<Response> {
692 self.get_records_raw_with_options(&GetItemsOptions::new())
693 }
694
695 /// Fetches all records that have been published since provided timestamp
696 /// for a collection that can be found in the server, bucket, and
697 /// collection defined by the [ClientConfig] used to generate this [Client].
698 pub fn get_records_since(&self, timestamp: u64) -> Result<RemoteSettingsResponse> {
699 self.get_records_with_options(
700 GetItemsOptions::new().filter_gt("last_modified", timestamp.to_string()),
701 )
702 }
703
704 /// Fetches records from this client's collection with the given options.
705 pub fn get_records_with_options(
706 &self,
707 options: &GetItemsOptions,
708 ) -> Result<RemoteSettingsResponse> {
709 let resp = self.get_records_raw_with_options(options)?;
710 let records = resp.json::<RecordsResponse>()?.data;
711 let etag = resp
712 .headers
713 .get(HEADER_ETAG)
714 .ok_or_else(|| Error::ResponseError("no etag header".into()))?;
715 // Per https://docs.kinto-storage.org/en/stable/api/1.x/timestamps.html,
716 // the `ETag` header value is a quoted integer. Trim the quotes before
717 // parsing.
718 let last_modified = etag.trim_matches('"').parse().map_err(|_| {
719 Error::ResponseError(format!(
720 "expected quoted integer in etag header; got `{}`",
721 etag
722 ))
723 })?;
724 Ok(RemoteSettingsResponse {
725 records,
726 last_modified,
727 })
728 }
729
730 /// Fetches a raw network [Response] for records from this client's
731 /// collection with the given options.
732 pub fn get_records_raw_with_options(&self, options: &GetItemsOptions) -> Result<Response> {
733 let mut url = self.endpoints.records_url.clone();
734 for (name, value) in options.iter_query_pairs() {
735 url.query_pairs_mut().append_pair(&name, &value);
736 }
737 self.make_request(url)
738 }
739
740 /// Downloads an attachment from [attachment_location]. NOTE: there are no
741 /// guarantees about a maximum size, so use care when fetching potentially
742 /// large attachments.
743 pub fn get_attachment(&self, attachment_location: &str) -> Result<Vec<u8>> {
744 Ok(self.get_attachment_raw(attachment_location)?.body)
745 }
746
747 /// Fetches a raw network [Response] for an attachment.
748 pub fn get_attachment_raw(&self, attachment_location: &str) -> Result<Response> {
749 // Important: We use a `let` binding here to ensure that the mutex is
750 // unlocked immediately after cloning the URL. If we matched directly on
751 // the `.lock()` expression, the mutex would stay locked until the end
752 // of the `match`, causing a deadlock.
753 let maybe_attachments_base_url = self.remote_state.lock().attachments_base_url.clone();
754
755 let attachments_base_url = match maybe_attachments_base_url {
756 Some(attachments_base_url) => attachments_base_url,
757 None => {
758 let server_info = self
759 .make_request(self.endpoints.root_url.clone())?
760 .json::<ServerInfo>()?;
761 let attachments_base_url = match server_info.capabilities.attachments {
762 Some(capability) => Url::parse(&capability.base_url)?,
763 None => Err(Error::AttachmentsUnsupportedError)?,
764 };
765 self.remote_state.lock().attachments_base_url = Some(attachments_base_url.clone());
766 attachments_base_url
767 }
768 };
769
770 self.make_request(attachments_base_url.join(attachment_location)?)
771 }
772
773 fn make_request(&self, url: Url) -> Result<Response> {
774 let mut current_remote_state = self.remote_state.lock();
775 current_remote_state.ensure_no_backoff()?;
776 drop(current_remote_state);
777
778 let req = Request::get(url);
779 let resp = req.send()?;
780
781 let mut current_remote_state = self.remote_state.lock();
782 current_remote_state.handle_backoff_hint(&resp)?;
783
784 if resp.is_success() {
785 Ok(resp)
786 } else {
787 Err(Error::ResponseError(format!(
788 "status code: {}",
789 resp.status
790 )))
791 }
792 }
793 }
794
795 /// Stores all the endpoints for a Remote Settings server
796 ///
797 /// There's actually not to many of these, so we can just pack them all into a struct
798 struct RemoteSettingsEndpoints {
799 /// Root URL for Remote Settings server
800 ///
801 /// This has the form `[base-url]/`. It's where we get the attachment base url from.
802 root_url: Url,
803 /// URL for the collections endpoint
804 ///
805 /// This has the form:
806 /// `[base-url]/buckets/[bucket-name]/collections/[collection-name]`.
807 ///
808 /// It can be used to fetch some metadata about the collection, but the real reason we use it
809 /// is to get a URL that uniquely identifies the server + bucket name. This is used by the
810 /// [Storage] component to know when to throw away cached records because the user has changed
811 /// one of these,
812 collection_url: Url,
813 /// URL for the changeset request
814 ///
815 /// This has the form:
816 /// `[base-url]/buckets/[bucket-name]/collections/[collection-name]/changeset`.
817 ///
818 /// This is the URL for fetching records and changes to records
819 changeset_url: Url,
820 /// URL for the records request
821 ///
822 /// This has the form:
823 /// `[base-url]/buckets/[bucket-name]/collections/[collection-name]/records`.
824 ///
825 /// This is the old/deprecated way to get records
826 records_url: Url,
827 }
828
829 impl RemoteSettingsEndpoints {
830 /// Construct a new RemoteSettingsEndpoints
831 ///
832 /// `base_url` should have the form `https://[domain]/v1` (no trailing slash).
833 fn new(base_url: &BaseUrl, bucket_name: &str, collection_name: &str) -> Self {
834 let mut root_url = base_url.clone();
835 // Push the empty string to add the trailing slash.
836 root_url.path_segments_mut().push("");
837
838 let mut collection_url = base_url.clone();
839 collection_url
840 .path_segments_mut()
841 .push("buckets")
842 .push(bucket_name)
843 .push("collections")
844 .push(collection_name);
845
846 let mut records_url = collection_url.clone();
847 records_url.path_segments_mut().push("records");
848
849 let mut changeset_url = collection_url.clone();
850 changeset_url.path_segments_mut().push("changeset");
851
852 Self {
853 root_url: root_url.into_inner(),
854 collection_url: collection_url.into_inner(),
855 records_url: records_url.into_inner(),
856 changeset_url: changeset_url.into_inner(),
857 }
858 }
859 }
860
861 /// Data structure representing the top-level response from the Remote Settings.
862 /// [last_modified] will be extracted from the etag header of the response.
863 #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize, uniffi::Record)]
864 pub struct RemoteSettingsResponse {
865 pub records: Vec<RemoteSettingsRecord>,
866 pub last_modified: u64,
867 }
868
869 #[derive(Deserialize, Serialize)]
870 struct RecordsResponse {
871 data: Vec<RemoteSettingsRecord>,
872 }
873
874 #[derive(Clone, Deserialize, Serialize)]
875 pub struct ChangesetResponse {
876 changes: Vec<RemoteSettingsRecord>,
877 timestamp: u64,
878 metadata: CollectionMetadata,
879 }
880
881 #[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
882 pub struct CollectionMetadata {
883 pub bucket: String,
884 pub signature: CollectionSignature,
885 }
886
887 #[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
888 pub struct CollectionSignature {
889 pub signature: String,
890 /// X.509 certificate chain Url (x5u)
891 pub x5u: String,
892 }
893
894 /// A parsed Remote Settings record. Records can contain arbitrary fields, so clients
895 /// are required to further extract expected values from the [fields] member.
896 #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq, uniffi::Record)]
897 pub struct RemoteSettingsRecord {
898 pub id: String,
899 pub last_modified: u64,
900 /// Tombstone flag (see https://remote-settings.readthedocs.io/en/latest/client-specifications.html#local-state)
901 #[serde(default)]
902 pub deleted: bool,
903 pub attachment: Option<Attachment>,
904 #[serde(flatten)]
905 pub fields: RsJsonObject,
906 }
907
908 /// Attachment metadata that can be optionally attached to a [Record]. The [location] should
909 /// included in calls to [Client::get_attachment].
910 #[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq, uniffi::Record)]
911 pub struct Attachment {
912 pub filename: String,
913 pub mimetype: String,
914 pub location: String,
915 pub hash: String,
916 pub size: u64,
917 }
918
919 // Define a UniFFI custom types to pass JSON objects across the FFI as a string
920 //
921 // This is named `RsJsonObject` because, UniFFI cannot currently rename iOS bindings and JsonObject
922 // conflicted with the declaration in Nimbus. This shouldn't really impact Android, since the type
923 // is converted into the platform JsonObject thanks to the UniFFI binding.
924 pub type RsJsonObject = serde_json::Map<String, serde_json::Value>;
925 uniffi::custom_type!(RsJsonObject, String, {
926 remote,
927 try_lift: |val| {
928 let json: serde_json::Value = serde_json::from_str(&val)?;
929
930 match json {
931 serde_json::Value::Object(obj) => Ok(obj),
932 _ => Err(uniffi::deps::anyhow::anyhow!(
933 "Unexpected JSON-non-object in the bagging area"
934 )),
935 }
936 },
937 lower: |obj| serde_json::Value::Object(obj).to_string(),
938 });
939
940 #[derive(Clone, Debug)]
941 pub(crate) struct RemoteState {
942 attachments_base_url: Option<Url>,
943 backoff: BackoffState,
944 }
945
946 impl Default for RemoteState {
947 fn default() -> Self {
948 Self {
949 attachments_base_url: None,
950 backoff: BackoffState::Ok,
951 }
952 }
953 }
954
955 impl RemoteState {
956 pub fn handle_backoff_hint(&mut self, response: &Response) -> Result<()> {
957 let extract_backoff_header = |header| -> Result<u64> {
958 Ok(response
959 .headers
960 .get_as::<u64, _>(header)
961 .transpose()
962 .unwrap_or_default() // Ignore number parsing errors.
963 .unwrap_or(0))
964 };
965 // In practice these two headers are mutually exclusive.
966 let backoff = extract_backoff_header(HEADER_BACKOFF)?;
967 let retry_after = extract_backoff_header(HEADER_RETRY_AFTER)?;
968 let max_backoff = backoff.max(retry_after);
969
970 if max_backoff > 0 {
971 self.backoff = BackoffState::Backoff {
972 observed_at: Instant::now(),
973 duration: Duration::from_secs(max_backoff),
974 };
975 }
976 Ok(())
977 }
978
979 pub fn ensure_no_backoff(&mut self) -> Result<()> {
980 if let BackoffState::Backoff {
981 observed_at,
982 duration,
983 } = self.backoff
984 {
985 let elapsed_time = observed_at.elapsed();
986 if elapsed_time >= duration {
987 self.backoff = BackoffState::Ok;
988 } else {
989 let remaining = duration - elapsed_time;
990 return Err(Error::BackoffError(remaining.as_secs()));
991 }
992 }
993 Ok(())
994 }
995 }
996
997 /// Used in handling backoff responses from the Remote Settings server.
998 #[derive(Clone, Copy, Debug)]
999 pub(crate) enum BackoffState {
1000 Ok,
1001 Backoff {
1002 observed_at: Instant,
1003 duration: Duration,
1004 },
1005 }
1006
1007 #[derive(Deserialize)]
1008 struct ServerInfo {
1009 capabilities: Capabilities,
1010 }
1011
1012 #[derive(Deserialize)]
1013 struct Capabilities {
1014 attachments: Option<AttachmentsCapability>,
1015 }
1016
1017 #[derive(Deserialize)]
1018 struct AttachmentsCapability {
1019 base_url: String,
1020 }
1021
1022 /// Options for requests to endpoints that return multiple items.
1023 #[derive(Clone, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
1024 pub struct GetItemsOptions {
1025 filters: Vec<Filter>,
1026 sort: Vec<Sort>,
1027 fields: Vec<String>,
1028 limit: Option<u64>,
1029 }
1030
1031 impl GetItemsOptions {
1032 /// Creates an empty option set.
1033 pub fn new() -> Self {
1034 Self::default()
1035 }
1036
1037 /// Sets an option to only return items whose `field` is equal to the given
1038 /// `value`.
1039 ///
1040 /// `field` can be a simple or dotted field name, like `author` or
1041 /// `author.name`. `value` can be a bare number or string (like
1042 /// `2` or `Ben`), or a stringified JSON value (`"2.0"`, `[1, 2]`,
1043 /// `{"checked": true}`).
1044 pub fn filter_eq(&mut self, field: impl Into<String>, value: impl Into<String>) -> &mut Self {
1045 self.filters.push(Filter::Eq(field.into(), value.into()));
1046 self
1047 }
1048
1049 /// Sets an option to only return items whose `field` is not equal to the
1050 /// given `value`.
1051 pub fn filter_not(&mut self, field: impl Into<String>, value: impl Into<String>) -> &mut Self {
1052 self.filters.push(Filter::Not(field.into(), value.into()));
1053 self
1054 }
1055
1056 /// Sets an option to only return items whose `field` is an array that
1057 /// contains the given `value`. If `value` is a stringified JSON array, the
1058 /// field must contain all its elements.
1059 pub fn filter_contains(
1060 &mut self,
1061 field: impl Into<String>,
1062 value: impl Into<String>,
1063 ) -> &mut Self {
1064 self.filters
1065 .push(Filter::Contains(field.into(), value.into()));
1066 self
1067 }
1068
1069 /// Sets an option to only return items whose `field` is strictly less
1070 /// than the given `value`.
1071 pub fn filter_lt(&mut self, field: impl Into<String>, value: impl Into<String>) -> &mut Self {
1072 self.filters.push(Filter::Lt(field.into(), value.into()));
1073 self
1074 }
1075
1076 /// Sets an option to only return items whose `field` is strictly greater
1077 /// than the given `value`.
1078 pub fn filter_gt(&mut self, field: impl Into<String>, value: impl Into<String>) -> &mut Self {
1079 self.filters.push(Filter::Gt(field.into(), value.into()));
1080 self
1081 }
1082
1083 /// Sets an option to only return items whose `field` is less than or equal
1084 /// to the given `value`.
1085 pub fn filter_max(&mut self, field: impl Into<String>, value: impl Into<String>) -> &mut Self {
1086 self.filters.push(Filter::Max(field.into(), value.into()));
1087 self
1088 }
1089
1090 /// Sets an option to only return items whose `field` is greater than or
1091 /// equal to the given `value`.
1092 pub fn filter_min(&mut self, field: impl Into<String>, value: impl Into<String>) -> &mut Self {
1093 self.filters.push(Filter::Min(field.into(), value.into()));
1094 self
1095 }
1096
1097 /// Sets an option to only return items whose `field` is a string that
1098 /// contains the substring `value`. `value` can contain `*` wildcards.
1099 pub fn filter_like(&mut self, field: impl Into<String>, value: impl Into<String>) -> &mut Self {
1100 self.filters.push(Filter::Like(field.into(), value.into()));
1101 self
1102 }
1103
1104 /// Sets an option to only return items that have the given `field`.
1105 pub fn filter_has(&mut self, field: impl Into<String>) -> &mut Self {
1106 self.filters.push(Filter::Has(field.into()));
1107 self
1108 }
1109
1110 /// Sets an option to only return items that do not have the given `field`.
1111 pub fn filter_has_not(&mut self, field: impl Into<String>) -> &mut Self {
1112 self.filters.push(Filter::HasNot(field.into()));
1113 self
1114 }
1115
1116 /// Sets an option to return items in `order` for the given `field`.
1117 pub fn sort(&mut self, field: impl Into<String>, order: SortOrder) -> &mut Self {
1118 self.sort.push(Sort(field.into(), order));
1119 self
1120 }
1121
1122 /// Sets an option to only return the given `field` of each item.
1123 ///
1124 /// The special `id` and `last_modified` fields are always returned.
1125 pub fn field(&mut self, field: impl Into<String>) -> &mut Self {
1126 self.fields.push(field.into());
1127 self
1128 }
1129
1130 /// Sets the option to return at most `count` items.
1131 pub fn limit(&mut self, count: u64) -> &mut Self {
1132 self.limit = Some(count);
1133 self
1134 }
1135
1136 /// Returns an iterator of (name, value) query pairs for these options.
1137 pub fn iter_query_pairs(&self) -> impl Iterator<Item = (Cow<str>, Cow<str>)> {
1138 self.filters
1139 .iter()
1140 .map(Filter::as_query_pair)
1141 .chain({
1142 // For sorting (https://docs.kinto-storage.org/en/latest/api/1.x/sorting.html),
1143 // the query pair syntax is `_sort=field1,-field2`, where the
1144 // fields to sort by are specified in a comma-separated ordered
1145 // list, and `-` indicates descending order.
1146 (!self.sort.is_empty()).then(|| {
1147 (
1148 "_sort".into(),
1149 (self
1150 .sort
1151 .iter()
1152 .map(Sort::as_query_value)
1153 .collect::<Vec<_>>()
1154 .join(","))
1155 .into(),
1156 )
1157 })
1158 })
1159 .chain({
1160 // For selecting fields (https://docs.kinto-storage.org/en/latest/api/1.x/selecting_fields.html),
1161 // the query pair syntax is `_fields=field1,field2`.
1162 (!self.fields.is_empty()).then(|| ("_fields".into(), self.fields.join(",").into()))
1163 })
1164 .chain({
1165 // For pagination (https://docs.kinto-storage.org/en/latest/api/1.x/pagination.html),
1166 // the query pair syntax is `_limit={count}`.
1167 self.limit
1168 .map(|count| ("_limit".into(), count.to_string().into()))
1169 })
1170 }
1171 }
1172
1173 /// The order in which to return items.
1174 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
1175 pub enum SortOrder {
1176 /// Smaller values first.
1177 Ascending,
1178 /// Larger values first.
1179 Descending,
1180 }
1181
1182 #[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
1183 enum Filter {
1184 Eq(String, String),
1185 Not(String, String),
1186 Contains(String, String),
1187 Lt(String, String),
1188 Gt(String, String),
1189 Max(String, String),
1190 Min(String, String),
1191 Like(String, String),
1192 Has(String),
1193 HasNot(String),
1194 }
1195
1196 impl Filter {
1197 fn as_query_pair(&self) -> (Cow<str>, Cow<str>) {
1198 // For filters (https://docs.kinto-storage.org/en/latest/api/1.x/filtering.html),
1199 // the query pair syntax is `[operator_]field=value` for each field.
1200 match self {
1201 Filter::Eq(field, value) => (field.into(), value.into()),
1202 Filter::Not(field, value) => (format!("not_{field}").into(), value.into()),
1203 Filter::Contains(field, value) => (format!("contains_{field}").into(), value.into()),
1204 Filter::Lt(field, value) => (format!("lt_{field}").into(), value.into()),
1205 Filter::Gt(field, value) => (format!("gt_{field}").into(), value.into()),
1206 Filter::Max(field, value) => (format!("max_{field}").into(), value.into()),
1207 Filter::Min(field, value) => (format!("min_{field}").into(), value.into()),
1208 Filter::Like(field, value) => (format!("like_{field}").into(), value.into()),
1209 Filter::Has(field) => (format!("has_{field}").into(), "true".into()),
1210 Filter::HasNot(field) => (format!("has_{field}").into(), "false".into()),
1211 }
1212 }
1213 }
1214
1215 #[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
1216 struct Sort(String, SortOrder);
1217
1218 impl Sort {
1219 fn as_query_value(&self) -> Cow<str> {
1220 match self.1 {
1221 SortOrder::Ascending => self.0.as_str().into(),
1222 SortOrder::Descending => format!("-{}", self.0).into(),
1223 }
1224 }
1225 }
1226
1227 #[cfg(test)]
1228 mod test {
1229 use super::*;
1230 use expect_test::expect;
1231 use mockito::{mock, Matcher};
1232 #[test]
1233 fn test_defaults() {
1234 let config = RemoteSettingsConfig {
1235 server: None,
1236 server_url: None,
1237 bucket_name: None,
1238 collection_name: String::from("the-collection"),
1239 };
1240 let client = Client::new(config).unwrap();
1241 assert_eq!(
1242 Url::parse("https://firefox.settings.services.mozilla.com/v1/buckets/main/collections/the-collection").unwrap(),
1243 client.endpoints.collection_url
1244 );
1245 }
1246
1247 #[test]
1248 fn test_deprecated_server_url() {
1249 let config = RemoteSettingsConfig {
1250 server: None,
1251 server_url: Some("https://example.com".into()),
1252 bucket_name: None,
1253 collection_name: String::from("the-collection"),
1254 };
1255 let client = Client::new(config).unwrap();
1256 assert_eq!(
1257 Url::parse("https://example.com/v1/buckets/main/collections/the-collection").unwrap(),
1258 client.endpoints.collection_url
1259 );
1260 }
1261
1262 #[test]
1263 fn test_invalid_config() {
1264 let config = RemoteSettingsConfig {
1265 server: Some(RemoteSettingsServer::Prod),
1266 server_url: Some("https://example.com".into()),
1267 bucket_name: None,
1268 collection_name: String::from("the-collection"),
1269 };
1270 match Client::new(config) {
1271 Ok(_) => panic!("Wanted config error; got client"),
1272 Err(Error::ConfigError(_)) => {}
1273 Err(err) => panic!("Wanted config error; got {}", err),
1274 }
1275 }
1276
1277 #[test]
1278 fn test_attachment_can_be_downloaded() {
1279 viaduct_reqwest::use_reqwest_backend();
1280 let server_info_m = mock("GET", "/v1/")
1281 .with_body(attachment_metadata(mockito::server_url()))
1282 .with_status(200)
1283 .with_header("content-type", "application/json")
1284 .create();
1285
1286 let attachment_location = "123.jpg";
1287 let attachment_bytes: Vec<u8> = "I'm a JPG, I swear".into();
1288 let attachment_m = mock(
1289 "GET",
1290 format!("/attachments/{}", attachment_location).as_str(),
1291 )
1292 .with_body(attachment_bytes.clone())
1293 .with_status(200)
1294 .with_header("content-type", "application/json")
1295 .create();
1296
1297 let config = RemoteSettingsConfig {
1298 server: Some(RemoteSettingsServer::Custom {
1299 url: mockito::server_url(),
1300 }),
1301 server_url: None,
1302 collection_name: String::from("the-collection"),
1303 bucket_name: None,
1304 };
1305
1306 let client = Client::new(config).unwrap();
1307 let first_resp = client.get_attachment(attachment_location).unwrap();
1308 let second_resp = client.get_attachment(attachment_location).unwrap();
1309
1310 server_info_m.expect(1).assert();
1311 attachment_m.expect(2).assert();
1312 assert_eq!(first_resp, attachment_bytes);
1313 assert_eq!(second_resp, attachment_bytes);
1314 }
1315
1316 #[test]
1317 fn test_attachment_errors_if_server_not_configured_for_attachments() {
1318 viaduct_reqwest::use_reqwest_backend();
1319 let server_info_m = mock("GET", "/v1/")
1320 .with_body(NO_ATTACHMENTS_METADATA)
1321 .with_status(200)
1322 .with_header("content-type", "application/json")
1323 .create();
1324
1325 let attachment_location = "123.jpg";
1326 let attachment_bytes: Vec<u8> = "I'm a JPG, I swear".into();
1327 let attachment_m = mock(
1328 "GET",
1329 format!("/attachments/{}", attachment_location).as_str(),
1330 )
1331 .with_body(attachment_bytes)
1332 .with_status(200)
1333 .with_header("content-type", "application/json")
1334 .create();
1335
1336 let config = RemoteSettingsConfig {
1337 server: Some(RemoteSettingsServer::Custom {
1338 url: mockito::server_url(),
1339 }),
1340 server_url: None,
1341 collection_name: String::from("the-collection"),
1342 bucket_name: None,
1343 };
1344
1345 let client = Client::new(config).unwrap();
1346 let resp = client.get_attachment(attachment_location);
1347 server_info_m.expect(1).assert();
1348 attachment_m.expect(0).assert();
1349 assert!(matches!(resp, Err(Error::AttachmentsUnsupportedError)))
1350 }
1351
1352 #[test]
1353 fn test_backoff() {
1354 viaduct_reqwest::use_reqwest_backend();
1355 let m = mock(
1356 "GET",
1357 "/v1/buckets/the-bucket/collections/the-collection/records",
1358 )
1359 .with_body(response_body())
1360 .with_status(200)
1361 .with_header("content-type", "application/json")
1362 .with_header("Backoff", "60")
1363 .with_header("etag", "\"1000\"")
1364 .create();
1365 let config = RemoteSettingsConfig {
1366 server: Some(RemoteSettingsServer::Custom {
1367 url: mockito::server_url(),
1368 }),
1369 server_url: None,
1370 collection_name: String::from("the-collection"),
1371 bucket_name: Some(String::from("the-bucket")),
1372 };
1373 let http_client = Client::new(config).unwrap();
1374
1375 assert!(http_client.get_records().is_ok());
1376 let second_resp = http_client.get_records();
1377 assert!(matches!(second_resp, Err(Error::BackoffError(_))));
1378 m.expect(1).assert();
1379 }
1380
1381 #[test]
1382 fn test_500_retry_after() {
1383 viaduct_reqwest::use_reqwest_backend();
1384 let m = mock(
1385 "GET",
1386 "/v1/buckets/the-bucket/collections/the-collection/records",
1387 )
1388 .with_body("Boom!")
1389 .with_status(500)
1390 .with_header("Retry-After", "60")
1391 .create();
1392 let config = RemoteSettingsConfig {
1393 server: Some(RemoteSettingsServer::Custom {
1394 url: mockito::server_url(),
1395 }),
1396 server_url: None,
1397 collection_name: String::from("the-collection"),
1398 bucket_name: Some(String::from("the-bucket")),
1399 };
1400 let http_client = Client::new(config).unwrap();
1401 assert!(http_client.get_records().is_err());
1402 let second_request = http_client.get_records();
1403 assert!(matches!(second_request, Err(Error::BackoffError(_))));
1404 m.expect(1).assert();
1405 }
1406
1407 #[test]
1408 fn test_options() {
1409 viaduct_reqwest::use_reqwest_backend();
1410 let m = mock(
1411 "GET",
1412 "/v1/buckets/the-bucket/collections/the-collection/records",
1413 )
1414 .match_query(Matcher::AllOf(vec![
1415 Matcher::UrlEncoded("a".into(), "b".into()),
1416 Matcher::UrlEncoded("lt_c.d".into(), "5".into()),
1417 Matcher::UrlEncoded("gt_e".into(), "15".into()),
1418 Matcher::UrlEncoded("max_f".into(), "20".into()),
1419 Matcher::UrlEncoded("min_g".into(), "10".into()),
1420 Matcher::UrlEncoded("not_h".into(), "i".into()),
1421 Matcher::UrlEncoded("like_j".into(), "*k*".into()),
1422 Matcher::UrlEncoded("has_l".into(), "true".into()),
1423 Matcher::UrlEncoded("has_m".into(), "false".into()),
1424 Matcher::UrlEncoded("contains_n".into(), "o".into()),
1425 Matcher::UrlEncoded("_sort".into(), "-b,a".into()),
1426 Matcher::UrlEncoded("_fields".into(), "a,c,b".into()),
1427 Matcher::UrlEncoded("_limit".into(), "3".into()),
1428 ]))
1429 .with_body(response_body())
1430 .with_status(200)
1431 .with_header("content-type", "application/json")
1432 .with_header("etag", "\"1000\"")
1433 .create();
1434 let config = RemoteSettingsConfig {
1435 server: Some(RemoteSettingsServer::Custom {
1436 url: mockito::server_url(),
1437 }),
1438 server_url: None,
1439 collection_name: String::from("the-collection"),
1440 bucket_name: Some(String::from("the-bucket")),
1441 };
1442 let http_client = Client::new(config).unwrap();
1443 let mut options = GetItemsOptions::new();
1444 options
1445 .field("a")
1446 .field("c")
1447 .field("b")
1448 .filter_eq("a", "b")
1449 .filter_lt("c.d", "5")
1450 .filter_gt("e", "15")
1451 .filter_max("f", "20")
1452 .filter_min("g", "10")
1453 .filter_not("h", "i")
1454 .filter_like("j", "*k*")
1455 .filter_has("l")
1456 .filter_has_not("m")
1457 .filter_contains("n", "o")
1458 .sort("b", SortOrder::Descending)
1459 .sort("a", SortOrder::Ascending)
1460 .limit(3);
1461
1462 assert!(http_client.get_records_raw_with_options(&options).is_ok());
1463 expect![[r#"
1464 RemoteSettingsResponse {
1465 records: [
1466 RemoteSettingsRecord {
1467 id: "c5dcd1da-7126-4abb-846b-ec85b0d4d0d7",
1468 last_modified: 1677694949407,
1469 deleted: false,
1470 attachment: Some(
1471 Attachment {
1472 filename: "jgp-attachment.jpg",
1473 mimetype: "image/jpeg",
1474 location: "the-bucket/the-collection/d3a5eccc-f0ca-42c3-b0bb-c0d4408c21c9.jpg",
1475 hash: "2cbd593f3fd5f1585f92265433a6696a863bc98726f03e7222135ff0d8e83543",
1476 size: 1374325,
1477 },
1478 ),
1479 fields: {
1480 "title": String(
1481 "jpg-attachment",
1482 ),
1483 "content": String(
1484 "content",
1485 ),
1486 "schema": Number(
1487 1677694447771,
1488 ),
1489 },
1490 },
1491 RemoteSettingsRecord {
1492 id: "ff301910-6bf5-4cfe-bc4c-5c80308661a5",
1493 last_modified: 1677694470354,
1494 deleted: false,
1495 attachment: Some(
1496 Attachment {
1497 filename: "pdf-attachment.pdf",
1498 mimetype: "application/pdf",
1499 location: "the-bucket/the-collection/5f7347c2-af92-411d-a65b-f794f9b5084c.pdf",
1500 hash: "de1cde3571ef3faa77ea0493276de9231acaa6f6651602e93aa1036f51181e9b",
1501 size: 157,
1502 },
1503 ),
1504 fields: {
1505 "title": String(
1506 "with-attachment",
1507 ),
1508 "content": String(
1509 "content",
1510 ),
1511 "schema": Number(
1512 1677694447771,
1513 ),
1514 },
1515 },
1516 RemoteSettingsRecord {
1517 id: "7403c6f9-79be-4e0c-a37a-8f2b5bd7ad58",
1518 last_modified: 1677694455368,
1519 deleted: false,
1520 attachment: None,
1521 fields: {
1522 "title": String(
1523 "no-attachment",
1524 ),
1525 "content": String(
1526 "content",
1527 ),
1528 "schema": Number(
1529 1677694447771,
1530 ),
1531 },
1532 },
1533 RemoteSettingsRecord {
1534 id: "9320f53c-0a39-4997-9120-62ff597ffb26",
1535 last_modified: 1690921847416,
1536 deleted: true,
1537 attachment: None,
1538 fields: {},
1539 },
1540 ],
1541 last_modified: 1000,
1542 }
1543 "#]].assert_debug_eq(&http_client
1544 .get_records_with_options(&options)
1545 .unwrap());
1546 m.expect(2).assert();
1547 }
1548
1549 #[test]
1550 fn test_backoff_recovery() {
1551 viaduct_reqwest::use_reqwest_backend();
1552 let m = mock(
1553 "GET",
1554 "/v1/buckets/the-bucket/collections/the-collection/records",
1555 )
1556 .with_body(response_body())
1557 .with_status(200)
1558 .with_header("content-type", "application/json")
1559 .with_header("etag", "\"1000\"")
1560 .create();
1561 let config = RemoteSettingsConfig {
1562 server: Some(RemoteSettingsServer::Custom {
1563 url: mockito::server_url(),
1564 }),
1565 server_url: None,
1566 collection_name: String::from("the-collection"),
1567 bucket_name: Some(String::from("the-bucket")),
1568 };
1569 let http_client = Client::new(config).unwrap();
1570 // First, sanity check that manipulating the remote state does something.
1571 let mut current_remote_state = http_client.remote_state.lock();
1572 current_remote_state.backoff = BackoffState::Backoff {
1573 observed_at: Instant::now(),
1574 duration: Duration::from_secs(30),
1575 };
1576 drop(current_remote_state);
1577 assert!(matches!(
1578 http_client.get_records(),
1579 Err(Error::BackoffError(_))
1580 ));
1581 // Then do the actual test.
1582 let mut current_remote_state = http_client.remote_state.lock();
1583 current_remote_state.backoff = BackoffState::Backoff {
1584 observed_at: Instant::now() - Duration::from_secs(31),
1585 duration: Duration::from_secs(30),
1586 };
1587 drop(current_remote_state);
1588 assert!(http_client.get_records().is_ok());
1589 m.expect(1).assert();
1590 }
1591
1592 #[test]
1593 fn test_record_fields() {
1594 viaduct_reqwest::use_reqwest_backend();
1595 let m = mock(
1596 "GET",
1597 "/v1/buckets/the-bucket/collections/the-collection/records",
1598 )
1599 .with_body(response_body())
1600 .with_status(200)
1601 .with_header("content-type", "application/json")
1602 .with_header("etag", "\"1000\"")
1603 .create();
1604 let config = RemoteSettingsConfig {
1605 server: Some(RemoteSettingsServer::Custom {
1606 url: mockito::server_url(),
1607 }),
1608 server_url: None,
1609 collection_name: String::from("the-collection"),
1610 bucket_name: Some(String::from("the-bucket")),
1611 };
1612 let http_client = Client::new(config).unwrap();
1613 let response = http_client.get_records().unwrap();
1614 expect![[r#"
1615 RemoteSettingsResponse {
1616 records: [
1617 RemoteSettingsRecord {
1618 id: "c5dcd1da-7126-4abb-846b-ec85b0d4d0d7",
1619 last_modified: 1677694949407,
1620 deleted: false,
1621 attachment: Some(
1622 Attachment {
1623 filename: "jgp-attachment.jpg",
1624 mimetype: "image/jpeg",
1625 location: "the-bucket/the-collection/d3a5eccc-f0ca-42c3-b0bb-c0d4408c21c9.jpg",
1626 hash: "2cbd593f3fd5f1585f92265433a6696a863bc98726f03e7222135ff0d8e83543",
1627 size: 1374325,
1628 },
1629 ),
1630 fields: {
1631 "title": String(
1632 "jpg-attachment",
1633 ),
1634 "content": String(
1635 "content",
1636 ),
1637 "schema": Number(
1638 1677694447771,
1639 ),
1640 },
1641 },
1642 RemoteSettingsRecord {
1643 id: "ff301910-6bf5-4cfe-bc4c-5c80308661a5",
1644 last_modified: 1677694470354,
1645 deleted: false,
1646 attachment: Some(
1647 Attachment {
1648 filename: "pdf-attachment.pdf",
1649 mimetype: "application/pdf",
1650 location: "the-bucket/the-collection/5f7347c2-af92-411d-a65b-f794f9b5084c.pdf",
1651 hash: "de1cde3571ef3faa77ea0493276de9231acaa6f6651602e93aa1036f51181e9b",
1652 size: 157,
1653 },
1654 ),
1655 fields: {
1656 "title": String(
1657 "with-attachment",
1658 ),
1659 "content": String(
1660 "content",
1661 ),
1662 "schema": Number(
1663 1677694447771,
1664 ),
1665 },
1666 },
1667 RemoteSettingsRecord {
1668 id: "7403c6f9-79be-4e0c-a37a-8f2b5bd7ad58",
1669 last_modified: 1677694455368,
1670 deleted: false,
1671 attachment: None,
1672 fields: {
1673 "title": String(
1674 "no-attachment",
1675 ),
1676 "content": String(
1677 "content",
1678 ),
1679 "schema": Number(
1680 1677694447771,
1681 ),
1682 },
1683 },
1684 RemoteSettingsRecord {
1685 id: "9320f53c-0a39-4997-9120-62ff597ffb26",
1686 last_modified: 1690921847416,
1687 deleted: true,
1688 attachment: None,
1689 fields: {},
1690 },
1691 ],
1692 last_modified: 1000,
1693 }
1694 "#]].assert_debug_eq(&response);
1695 m.expect(1).assert();
1696 }
1697
1698 #[test]
1699 fn test_missing_etag() {
1700 viaduct_reqwest::use_reqwest_backend();
1701 let m = mock(
1702 "GET",
1703 "/v1/buckets/the-bucket/collections/the-collection/records",
1704 )
1705 .with_body(response_body())
1706 .with_status(200)
1707 .with_header("content-type", "application/json")
1708 .create();
1709
1710 let config = RemoteSettingsConfig {
1711 server: Some(RemoteSettingsServer::Custom {
1712 url: mockito::server_url(),
1713 }),
1714 server_url: None,
1715 bucket_name: Some(String::from("the-bucket")),
1716 collection_name: String::from("the-collection"),
1717 };
1718 let client = Client::new(config).unwrap();
1719
1720 let err = client.get_records().unwrap_err();
1721 assert!(
1722 matches!(err, Error::ResponseError(_)),
1723 "Want response error for missing `ETag`; got {}",
1724 err
1725 );
1726 m.expect(1).assert();
1727 }
1728
1729 #[test]
1730 fn test_invalid_etag() {
1731 viaduct_reqwest::use_reqwest_backend();
1732 let m = mock(
1733 "GET",
1734 "/v1/buckets/the-bucket/collections/the-collection/records",
1735 )
1736 .with_body(response_body())
1737 .with_status(200)
1738 .with_header("content-type", "application/json")
1739 .with_header("etag", "bad!")
1740 .create();
1741
1742 let config = RemoteSettingsConfig {
1743 server: Some(RemoteSettingsServer::Custom {
1744 url: mockito::server_url(),
1745 }),
1746 server_url: None,
1747 bucket_name: Some(String::from("the-bucket")),
1748 collection_name: String::from("the-collection"),
1749 };
1750 let client = Client::new(config).unwrap();
1751
1752 let err = client.get_records().unwrap_err();
1753 assert!(
1754 matches!(err, Error::ResponseError(_)),
1755 "Want response error for invalid `ETag`; got {}",
1756 err
1757 );
1758 m.expect(1).assert();
1759 }
1760
1761 fn attachment_metadata(base_url: String) -> String {
1762 format!(
1763 r#"
1764 {{
1765 "capabilities": {{
1766 "admin": {{
1767 "description": "Serves the admin console.",
1768 "url": "https://github.com/Kinto/kinto-admin/",
1769 "version": "2.0.0"
1770 }},
1771 "attachments": {{
1772 "description": "Add file attachments to records",
1773 "url": "https://github.com/Kinto/kinto-attachment/",
1774 "version": "6.3.1",
1775 "base_url": "{}/attachments/"
1776 }}
1777 }}
1778 }}
1779 "#,
1780 base_url
1781 )
1782 }
1783
1784 const NO_ATTACHMENTS_METADATA: &str = r#"
1785 {
1786 "capabilities": {
1787 "admin": {
1788 "description": "Serves the admin console.",
1789 "url": "https://github.com/Kinto/kinto-admin/",
1790 "version": "2.0.0"
1791 }
1792 }
1793 }
1794 "#;
1795
1796 fn response_body() -> String {
1797 format!(
1798 r#"
1799 {{
1800 "data": [
1801 {},
1802 {},
1803 {},
1804 {}
1805 ]
1806 }}"#,
1807 JPG_ATTACHMENT, PDF_ATTACHMENT, NO_ATTACHMENT, TOMBSTONE
1808 )
1809 }
1810
1811 const JPG_ATTACHMENT: &str = r#"
1812 {
1813 "title": "jpg-attachment",
1814 "content": "content",
1815 "attachment": {
1816 "filename": "jgp-attachment.jpg",
1817 "location": "the-bucket/the-collection/d3a5eccc-f0ca-42c3-b0bb-c0d4408c21c9.jpg",
1818 "hash": "2cbd593f3fd5f1585f92265433a6696a863bc98726f03e7222135ff0d8e83543",
1819 "mimetype": "image/jpeg",
1820 "size": 1374325
1821 },
1822 "id": "c5dcd1da-7126-4abb-846b-ec85b0d4d0d7",
1823 "schema": 1677694447771,
1824 "last_modified": 1677694949407
1825 }
1826 "#;
1827
1828 const PDF_ATTACHMENT: &str = r#"
1829 {
1830 "title": "with-attachment",
1831 "content": "content",
1832 "attachment": {
1833 "filename": "pdf-attachment.pdf",
1834 "location": "the-bucket/the-collection/5f7347c2-af92-411d-a65b-f794f9b5084c.pdf",
1835 "hash": "de1cde3571ef3faa77ea0493276de9231acaa6f6651602e93aa1036f51181e9b",
1836 "mimetype": "application/pdf",
1837 "size": 157
1838 },
1839 "id": "ff301910-6bf5-4cfe-bc4c-5c80308661a5",
1840 "schema": 1677694447771,
1841 "last_modified": 1677694470354
1842 }
1843 "#;
1844
1845 const NO_ATTACHMENT: &str = r#"
1846 {
1847 "title": "no-attachment",
1848 "content": "content",
1849 "schema": 1677694447771,
1850 "id": "7403c6f9-79be-4e0c-a37a-8f2b5bd7ad58",
1851 "last_modified": 1677694455368
1852 }
1853 "#;
1854
1855 const TOMBSTONE: &str = r#"
1856 {
1857 "id": "9320f53c-0a39-4997-9120-62ff597ffb26",
1858 "last_modified": 1690921847416,
1859 "deleted": true
1860 }
1861 "#;
1862 }
1863
1864 #[cfg(test)]
1865 mod test_new_client {
1866 use super::*;
1867
1868 #[test]
1869 fn test_endpoints() {
1870 let endpoints = RemoteSettingsEndpoints::new(
1871 &BaseUrl::parse("http://rs.example.com/v1").unwrap(),
1872 "main",
1873 "test-collection",
1874 );
1875 assert_eq!(endpoints.root_url.to_string(), "http://rs.example.com/v1/");
1876 assert_eq!(
1877 endpoints.collection_url.to_string(),
1878 "http://rs.example.com/v1/buckets/main/collections/test-collection",
1879 );
1880 assert_eq!(
1881 endpoints.records_url.to_string(),
1882 "http://rs.example.com/v1/buckets/main/collections/test-collection/records",
1883 );
1884 assert_eq!(
1885 endpoints.changeset_url.to_string(),
1886 "http://rs.example.com/v1/buckets/main/collections/test-collection/changeset",
1887 );
1888 }
1889 }
1890
1891 #[cfg(test)]
1892 mod jexl_tests {
1893 use super::*;
1894
1895 #[test]
1896 fn test_get_records_filtered_app_version_pass() {
1897 let mut api_client = MockApiClient::new();
1898 let records = vec![RemoteSettingsRecord {
1899 id: "record-0001".into(),
1900 last_modified: 100,
1901 deleted: false,
1902 attachment: None,
1903 fields: serde_json::json!({
1904 "filter_expression": "env.version|versionCompare(\"128.0a1\") > 0"
1905 })
1906 .as_object()
1907 .unwrap()
1908 .clone(),
1909 }];
1910 let changeset = ChangesetResponse {
1911 changes: records.clone(),
1912 timestamp: 42,
1913 metadata: CollectionMetadata::default(),
1914 };
1915 api_client.expect_collection_url().returning(|| {
1916 "http://rs.example.com/v1/buckets/main/collections/test-collection".into()
1917 });
1918 api_client.expect_fetch_changeset().returning({
1919 let changeset = changeset.clone();
1920 move |timestamp| {
1921 assert_eq!(timestamp, None);
1922 Ok(changeset.clone())
1923 }
1924 });
1925 api_client.expect_is_prod_server().returning(|| Ok(false));
1926
1927 let context = RemoteSettingsContext {
1928 app_version: Some("129.0.0".to_string()),
1929 ..Default::default()
1930 };
1931
1932 let mut storage = Storage::new(":memory:".into());
1933 let _ = storage.insert_collection_content(
1934 "http://rs.example.com/v1/buckets/main/collections/test-collection",
1935 &records,
1936 42,
1937 CollectionMetadata::default(),
1938 );
1939
1940 let rs_client = RemoteSettingsClient::new_from_parts(
1941 "test-collection".into(),
1942 storage,
1943 JexlFilter::new(Some(context)),
1944 api_client,
1945 );
1946
1947 assert_eq!(
1948 rs_client.get_records(false).expect("Error getting records"),
1949 Some(records)
1950 );
1951 }
1952
1953 #[test]
1954 fn test_get_records_filtered_app_version_too_low() {
1955 let mut api_client = MockApiClient::new();
1956 let records = vec![RemoteSettingsRecord {
1957 id: "record-0001".into(),
1958 last_modified: 100,
1959 deleted: false,
1960 attachment: None,
1961 fields: serde_json::json!({
1962 "filter_expression": "env.version|versionCompare(\"128.0a1\") > 0"
1963 })
1964 .as_object()
1965 .unwrap()
1966 .clone(),
1967 }];
1968 let changeset = ChangesetResponse {
1969 changes: records.clone(),
1970 timestamp: 42,
1971 metadata: CollectionMetadata::default(),
1972 };
1973 api_client.expect_collection_url().returning(|| {
1974 "http://rs.example.com/v1/buckets/main/collections/test-collection".into()
1975 });
1976 api_client.expect_fetch_changeset().returning({
1977 let changeset = changeset.clone();
1978 move |timestamp| {
1979 assert_eq!(timestamp, None);
1980 Ok(changeset.clone())
1981 }
1982 });
1983 api_client.expect_is_prod_server().returning(|| Ok(false));
1984
1985 let context = RemoteSettingsContext {
1986 app_version: Some("127.0.0.".to_string()),
1987 ..Default::default()
1988 };
1989
1990 let mut storage = Storage::new(":memory:".into());
1991 let _ = storage.insert_collection_content(
1992 "http://rs.example.com/v1/buckets/main/collections/test-collection",
1993 &records,
1994 42,
1995 CollectionMetadata::default(),
1996 );
1997
1998 let rs_client = RemoteSettingsClient::new_from_parts(
1999 "test-collection".into(),
2000 storage,
2001 JexlFilter::new(Some(context)),
2002 api_client,
2003 );
2004
2005 assert_eq!(
2006 rs_client.get_records(false).expect("Error getting records"),
2007 Some(vec![])
2008 );
2009 }
2010
2011 #[test]
2012 fn test_update_jexl_context() {
2013 let mut api_client = MockApiClient::new();
2014 let records = vec![RemoteSettingsRecord {
2015 id: "record-0001".into(),
2016 last_modified: 100,
2017 deleted: false,
2018 attachment: None,
2019 fields: serde_json::json!({
2020 "filter_expression": "env.country == \"US\""
2021 })
2022 .as_object()
2023 .unwrap()
2024 .clone(),
2025 }];
2026 let changeset = ChangesetResponse {
2027 changes: records.clone(),
2028 timestamp: 42,
2029 metadata: CollectionMetadata::default(),
2030 };
2031 api_client.expect_collection_url().returning(|| {
2032 "http://rs.example.com/v1/buckets/main/collections/test-collection".into()
2033 });
2034 api_client.expect_fetch_changeset().returning({
2035 let changeset = changeset.clone();
2036 move |timestamp| {
2037 assert_eq!(timestamp, None);
2038 Ok(changeset.clone())
2039 }
2040 });
2041 api_client.expect_is_prod_server().returning(|| Ok(false));
2042
2043 let context = RemoteSettingsContext {
2044 country: Some("US".to_string()),
2045 ..Default::default()
2046 };
2047
2048 let mut storage = Storage::new(":memory:".into());
2049 let _ = storage.insert_collection_content(
2050 "http://rs.example.com/v1/buckets/main/collections/test-collection",
2051 &records,
2052 42,
2053 CollectionMetadata::default(),
2054 );
2055
2056 let rs_client = RemoteSettingsClient::new_from_parts(
2057 "test-collection".into(),
2058 storage,
2059 JexlFilter::new(Some(context)),
2060 api_client,
2061 );
2062
2063 assert_eq!(
2064 rs_client.get_records(false).expect("Error getting records"),
2065 Some(records)
2066 );
2067
2068 // We can't call `update_config` directly, since that only works with a real API client.
2069 // Instead, just execute the code from that method that updates the JEXL filter.
2070 rs_client.inner.lock().jexl_filter = JexlFilter::new(Some(RemoteSettingsContext {
2071 country: Some("UK".to_string()),
2072 ..Default::default()
2073 }));
2074
2075 assert_eq!(
2076 rs_client.get_records(false).expect("Error getting records"),
2077 Some(vec![])
2078 );
2079 }
2080 }
2081
2082 #[cfg(feature = "signatures")]
2083 #[cfg(test)]
2084 mod test_signatures {
2085 use core::assert_eq;
2086
2087 use crate::RemoteSettingsContext;
2088
2089 use super::*;
2090 use nss::ensure_initialized;
2091
2092 const VALID_CERTIFICATE: &str = "\
2093 -----BEGIN CERTIFICATE-----
2094 MIIDBjCCAougAwIBAgIIFml6g0ldRGowCgYIKoZIzj0EAwMwgaMxCzAJBgNVBAYT
2095 AlVTMRwwGgYDVQQKExNNb3ppbGxhIENvcnBvcmF0aW9uMS8wLQYDVQQLEyZNb3pp
2096 bGxhIEFNTyBQcm9kdWN0aW9uIFNpZ25pbmcgU2VydmljZTFFMEMGA1UEAww8Q29u
2097 dGVudCBTaWduaW5nIEludGVybWVkaWF0ZS9lbWFpbEFkZHJlc3M9Zm94c2VjQG1v
2098 emlsbGEuY29tMB4XDTIxMDIwMzE1MDQwNVoXDTIxMDQyNDE1MDQwNVowgakxCzAJ
2099 BgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQHEw1Nb3VudGFp
2100 biBWaWV3MRwwGgYDVQQKExNNb3ppbGxhIENvcnBvcmF0aW9uMRcwFQYDVQQLEw5D
2101 bG91ZCBTZXJ2aWNlczE2MDQGA1UEAxMtcmVtb3RlLXNldHRpbmdzLmNvbnRlbnQt
2102 c2lnbmF0dXJlLm1vemlsbGEub3JnMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8pKb
2103 HX4IiD0SCy+NO7gwKqRR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qUZLF4z+AOMYgWtDpmg
2186 IKdcFKAt3fFrpyMhlfIKkLfmm0iDjmfmIXbDGBJw9SE=
2187 -----END CERTIFICATE-----";
2188 const VALID_SIGNATURE: &str = r#"fJJcOpwdnkjEWFeHXfdOJN6GaGLuDTPGzQOxA2jn6ldIleIk6KqMhZcy2GZv2uYiGwl6DERWwpaoUfQFLyCAOcVjck1qlaaEFZGY1BQba9p99xEc9FNQ3YPPfvSSZqsw"#;
2189 const VALID_CERT_EPOCH_SECONDS: u64 = 1615559719;
2190
2191 fn run_client_sync(
2192 diff_records: &[RemoteSettingsRecord],
2193 full_records: &[RemoteSettingsRecord],
2194 certificate: &str,
2195 signature: &str,
2196 epoch_secs: u64,
2197 bucket: &str,
2198 ) -> Result<()> {
2199 let collection_name = "pioneer-study-addons";
2200
2201 MOCK_TIME.with(|cell| cell.set(Some(epoch_secs)));
2202
2203 let some_metadata = CollectionMetadata {
2204 bucket: bucket.into(),
2205 signature: CollectionSignature {
2206 signature: signature.to_string(),
2207 x5u: "http://mocked".into(),
2208 },
2209 };
2210 // Changeset for when client fetches diff.
2211 let diff_changeset = ChangesetResponse {
2212 changes: diff_records.to_vec(),
2213 timestamp: 1603992731957,
2214 metadata: some_metadata.clone(),
2215 };
2216 // Changeset for when client retries from scratch.
2217 let full_changeset = ChangesetResponse {
2218 changes: full_records.to_vec(),
2219 timestamp: 1603992731957,
2220 metadata: some_metadata.clone(),
2221 };
2222
2223 let mut api_client = MockApiClient::new();
2224 api_client
2225 .expect_collection_url()
2226 .returning(move || format!("http://server/{}", collection_name));
2227 api_client.expect_is_prod_server().returning(|| Ok(false));
2228 api_client.expect_fetch_changeset().returning(move |since| {
2229 Ok(if since.is_some() {
2230 diff_changeset.clone()
2231 } else {
2232 full_changeset.clone()
2233 })
2234 });
2235
2236 let certificate = certificate.to_string();
2237 api_client
2238 .expect_fetch_cert()
2239 .returning(move |_| Ok(certificate.clone().into_bytes()));
2240
2241 let storage = Storage::new(":memory:".into());
2242 let jexl_filter = JexlFilter::new(Some(RemoteSettingsContext::default()));
2243 let rs_client = RemoteSettingsClient::new_from_parts(
2244 collection_name.to_string(),
2245 storage,
2246 jexl_filter,
2247 api_client,
2248 );
2249
2250 rs_client.sync()
2251 }
2252
2253 #[test]
2254 fn test_valid_signature() -> Result<()> {
2255 ensure_initialized();
2256 run_client_sync(
2257 &[],
2258 &[],
2259 VALID_CERTIFICATE,
2260 VALID_SIGNATURE,
2261 VALID_CERT_EPOCH_SECONDS,
2262 "main",
2263 )
2264 .expect("Valid signature");
2265 Ok(())
2266 }
2267
2268 #[test]
2269 fn test_valid_signature_after_retry() -> Result<()> {
2270 ensure_initialized();
2271 run_client_sync(
2272 &vec![RemoteSettingsRecord {
2273 id: "bad-record".to_string(),
2274 last_modified: 9999,
2275 deleted: true,
2276 attachment: None,
2277 fields: serde_json::Map::new(),
2278 }],
2279 &[],
2280 VALID_CERTIFICATE,
2281 VALID_SIGNATURE,
2282 VALID_CERT_EPOCH_SECONDS,
2283 "main",
2284 )
2285 .expect("Valid signature");
2286 Ok(())
2287 }
2288
2289 #[test]
2290 fn test_invalid_signature_value() -> Result<()> {
2291 ensure_initialized();
2292 let err = run_client_sync(
2293 &[],
2294 &[],
2295 VALID_CERTIFICATE,
2296 "invalid signature",
2297 VALID_CERT_EPOCH_SECONDS,
2298 "main",
2299 )
2300 .unwrap_err();
2301 assert!(matches!(err, Error::SignatureError(_)));
2302 assert_eq!(format!("{}", err), "Signature could not be verified: Signature content error: Encoded text cannot have a 6-bit remainder.");
2303
2304 Ok(())
2305 }
2306
2307 #[test]
2308 fn test_invalid_certificate_value() -> Result<()> {
2309 ensure_initialized();
2310 let err = run_client_sync(
2311 &[],
2312 &[],
2313 "some bad PEM content",
2314 VALID_SIGNATURE,
2315 VALID_CERT_EPOCH_SECONDS,
2316 "main",
2317 )
2318 .unwrap_err();
2319
2320 assert!(matches!(err, Error::SignatureError(_)));
2321 assert_eq!(
2322 format!("{}", err),
2323 "Signature could not be verified: PEM content format error: Missing PEM data"
2324 );
2325
2326 Ok(())
2327 }
2328
2329 #[test]
2330 fn test_invalid_signature_expired_cert() -> Result<()> {
2331 ensure_initialized();
2332 let december_20_2024 = 1734651582;
2333
2334 let err = run_client_sync(
2335 &[],
2336 &[],
2337 VALID_CERTIFICATE,
2338 VALID_SIGNATURE,
2339 december_20_2024,
2340 "main",
2341 )
2342 .unwrap_err();
2343
2344 assert!(matches!(err, Error::SignatureError(_)));
2345 assert_eq!(
2346 format!("{}", err),
2347 "Signature could not be verified: Certificate not yet valid or expired"
2348 );
2349
2350 Ok(())
2351 }
2352
2353 #[test]
2354 fn test_invalid_signature_invalid_data() -> Result<()> {
2355 ensure_initialized();
2356 // The signature is valid for an empty list of records.
2357 let records = vec![RemoteSettingsRecord {
2358 id: "unexpected-data".to_string(),
2359 last_modified: 42,
2360 deleted: false,
2361 attachment: None,
2362 fields: serde_json::Map::new(),
2363 }];
2364 let err = run_client_sync(
2365 &records,
2366 &records,
2367 VALID_CERTIFICATE,
2368 VALID_SIGNATURE,
2369 VALID_CERT_EPOCH_SECONDS,
2370 "main",
2371 )
2372 .unwrap_err();
2373
2374 assert!(matches!(err, Error::SignatureError(_)));
2375 assert_eq!(format!("{}", err), "Signature could not be verified: Content signature mismatch error: NSS error: NSS error: -8182 ");
2376
2377 Ok(())
2378 }
2379
2380 #[test]
2381 fn test_invalid_signature_invalid_signer_name() -> Result<()> {
2382 ensure_initialized();
2383 let err = run_client_sync(
2384 &[],
2385 &[],
2386 VALID_CERTIFICATE,
2387 VALID_SIGNATURE,
2388 VALID_CERT_EPOCH_SECONDS,
2389 "security-state",
2390 )
2391 .unwrap_err();
2392 assert!(matches!(err, Error::SignatureError(_)));
2393 assert_eq!(
2394 format!("{}", err),
2395 "Signature could not be verified: Certificate subject mismatch"
2396 );
2397
2398 Ok(())
2399 }
2400 }