script/dom/cookiestore/cookiestore.rs
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 https://mozilla.org/MPL/2.0/. */
4
5use std::cell::Cell;
6use std::collections::VecDeque;
7
8use cookie::{Cookie, SameSite};
9use dom_struct::dom_struct;
10use hyper_serde::Serde;
11use itertools::Itertools;
12use js::context::JSContext;
13use js::jsval::NullValue;
14use net_traits::CookieSource::NonHTTP;
15use net_traits::{
16 CookieAsyncResponse, CookieChange, CookieChangeType, CookieData, CoreResourceMsg,
17};
18use script_bindings::cell::DomRefCell;
19use script_bindings::codegen::GenericBindings::CookieStoreBinding::CookieSameSite;
20use script_bindings::reflector::reflect_dom_object;
21use servo_base::generic_channel::{GenericCallback, GenericSend, GenericSender};
22use servo_base::id::CookieStoreId;
23use servo_url::ServoUrl;
24use style::Atom;
25use style::str::starts_with_ignore_ascii_case;
26use time::OffsetDateTime;
27
28use crate::dom::bindings::codegen::Bindings::CookieStoreBinding::{
29 CookieInit, CookieListItem, CookieStoreDeleteOptions, CookieStoreGetOptions, CookieStoreMethods,
30};
31use crate::dom::bindings::error::Error;
32use crate::dom::bindings::inheritance::Castable;
33use crate::dom::bindings::refcounted::Trusted;
34use crate::dom::bindings::reflector::DomGlobal;
35use crate::dom::bindings::root::DomRoot;
36use crate::dom::bindings::str::USVString;
37use crate::dom::cookiechangeevent::CookieChangeEvent;
38use crate::dom::document::get_registrable_domain_suffix_of_or_is_equal_to;
39use crate::dom::event::Event;
40use crate::dom::eventtarget::EventTarget;
41use crate::dom::globalscope::GlobalScope;
42use crate::dom::promise::Promise;
43use crate::dom::window::Window;
44use crate::dom::{RootedPromise, TracedPromise};
45use crate::tasks::task_source::SendableTaskSource;
46
47#[derive(JSTraceable, MallocSizeOf)]
48struct DroppableCookieStore {
49 // Store an id so that we can send it with requests and the resource thread knows who to respond to
50 #[no_trace]
51 store_id: CookieStoreId,
52 #[no_trace]
53 unregister_channel: GenericSender<CoreResourceMsg>,
54 unregistered: Cell<bool>,
55}
56
57impl DroppableCookieStore {
58 fn unregister(&self) {
59 if !self.unregistered.get() {
60 self.unregistered.set(true);
61 let res = self
62 .unregister_channel
63 .send(CoreResourceMsg::RemoveCookieListener(self.store_id));
64 if res.is_err() {
65 error!("Failed to send cookiestore message to resource threads");
66 }
67 }
68 }
69}
70
71impl Drop for DroppableCookieStore {
72 fn drop(&mut self) {
73 self.unregister();
74 }
75}
76
77/// <https://cookiestore.spec.whatwg.org/>
78/// CookieStore provides an async API for pages and service workers to access and modify cookies.
79/// This requires setting up communication with resource thread's cookie storage that allows for
80/// the page to have multiple cookie storage promises in flight at the same time.
81#[dom_struct]
82pub(crate) struct CookieStore {
83 eventtarget: EventTarget,
84 in_flight: DomRefCell<VecDeque<TracedPromise>>,
85 droppable: DroppableCookieStore,
86}
87
88struct CookieListener {
89 // TODO:(whatwg/cookiestore#239) The spec is missing details for what task source to use
90 task_source: SendableTaskSource,
91 context: Trusted<CookieStore>,
92}
93
94impl CookieListener {
95 pub(crate) fn handle(&self, message: CookieAsyncResponse) {
96 let context = self.context.clone();
97
98 // https://cookiestore.spec.whatwg.org/#process-cookie-changes
99 if let CookieData::Change(changes) = message.data {
100 // 1.4. Queue a global task on the DOM manipulation task source given window to fire a
101 // change event named "change" with changes at window’s CookieStore.
102 self.task_source.queue(task!(cookie_change: move |cx| {
103 let store = context.root();
104 let global = store.global();
105 let Some(window) = global.downcast::<Window>() else {
106 return;
107 };
108 store.fire_a_change_event(cx, atom!("change"), changes, window);
109 }));
110
111 return;
112 }
113
114 self.task_source.queue(task!(cookie_message: move |cx| {
115 let Some(promise) = context.root().in_flight.safe_borrow_mut(cx.no_gc()).pop_front().map(|promise| promise.root(cx)) else {
116 warn!("No promise exists for cookie store response");
117 return;
118 };
119 match message.data {
120 CookieData::Get(cookie) => {
121 // If list is failure, then reject p with a TypeError and abort these steps.
122 // (There is currently no way for list to result in failure)
123 if let Some(cookie) = cookie {
124 // Otherwise, resolve p with the first item of list.
125 promise.resolve_native(cx, &cookie_to_list_item(cookie.into_inner()));
126 } else {
127 // If list is empty, then resolve p with null.
128 promise.resolve_native(cx, &NullValue());
129 }
130 },
131 CookieData::GetAll(cookies) => {
132 // If list is failure, then reject p with a TypeError and abort these steps.
133 promise.resolve_native(cx,
134 &cookies
135 .into_iter()
136 .map(|cookie| cookie_to_list_item(cookie.0))
137 .collect_vec(),);
138 },
139 CookieData::Set(_) => {
140 promise.resolve_native(cx, &());
141 }
142 CookieData::Change(_) => unreachable!()
143 }
144 }));
145 }
146}
147
148impl CookieStore {
149 fn new_inherited(unregister_channel: GenericSender<CoreResourceMsg>) -> CookieStore {
150 CookieStore {
151 eventtarget: EventTarget::new_inherited(),
152 in_flight: Default::default(),
153 droppable: DroppableCookieStore {
154 store_id: CookieStoreId::new(),
155 unregister_channel,
156 unregistered: Cell::new(false),
157 },
158 }
159 }
160
161 pub(crate) fn new(cx: &mut JSContext, global: &GlobalScope) -> DomRoot<CookieStore> {
162 let store = reflect_dom_object(
163 cx,
164 Box::new(CookieStore::new_inherited(
165 global.resource_threads().core_thread.clone(),
166 )),
167 global,
168 );
169 store.setup_route();
170 store
171 }
172
173 /// Called when the global scope is being torn down to clean up the cookie store listener
174 /// and break the circular reference held by the resource thread.
175 pub(crate) fn clean_up(&self) {
176 self.droppable.unregister();
177 self.in_flight.borrow_mut().clear();
178 }
179
180 fn setup_route(&self) {
181 let context = Trusted::new(self);
182 let cs_listener = CookieListener {
183 task_source: self
184 .global()
185 .task_manager()
186 .dom_manipulation_task_source()
187 .to_sendable(),
188 context,
189 };
190
191 let callback = GenericCallback::new(move |message| match message {
192 Ok(msg) => cs_listener.handle(msg),
193 Err(err) => warn!("Error receiving a CookieStore message: {:?}", err),
194 })
195 .expect("Could not create cookie store callback");
196
197 let res = self
198 .global()
199 .resource_threads()
200 .send(CoreResourceMsg::NewCookieListener(
201 self.droppable.store_id,
202 callback,
203 self.global().creation_url(),
204 ));
205 if res.is_err() {
206 error!("Failed to send cookiestore message to resource threads");
207 }
208 }
209}
210
211/// <https://cookiestore.spec.whatwg.org/#create-a-cookielistitem>
212fn cookie_to_list_item(cookie: Cookie) -> CookieListItem {
213 // TODO: Investigate if we need to explicitly UTF-8 decode without BOM here or if thats
214 // already being done by cookie-rs or implicitly by using rust strings
215 CookieListItem {
216 // Let name be the result of running UTF-8 decode without BOM on cookie’s name.
217 name: Some(cookie.name().to_string().into()),
218
219 // Let value be the result of running UTF-8 decode without BOM on cookie’s value.
220 value: Some(cookie.value().to_string().into()),
221 }
222}
223
224/// <https://cookiestore.spec.whatwg.org/#prepare-lists>
225fn prepare_lists(changes: Vec<CookieChange>) -> (Vec<CookieListItem>, Vec<CookieListItem>) {
226 // 1. Let changedList be « ».
227 let mut changed_list = Vec::<CookieListItem>::new();
228
229 // 2. Let deletedList be « ».
230 let mut deleted_list = Vec::<CookieListItem>::new();
231
232 // 3. For each change in changes, run these steps:
233 for change in changes {
234 // 3.1. Let item be the result of running create a CookieListItem from change’s cookie.
235 let mut item = cookie_to_list_item(change.cookie.into_inner());
236
237 match change.type_ {
238 // 3.2. If change’s type is changed, then append item to changedList.
239 CookieChangeType::Changed => {
240 changed_list.push(item);
241 },
242 // 3.3. Otherwise, run these steps:
243 CookieChangeType::Deleted => {
244 // 3.3.1. Set item["value"] to undefined.
245 item.value = None;
246
247 // 3.3.2. Append item to deletedList.
248 deleted_list.push(item);
249 },
250 }
251 }
252
253 // 4. Return changedList and deletedList.
254 (changed_list, deleted_list)
255}
256
257impl CookieStoreMethods<crate::DomTypeHolder> for CookieStore {
258 /// <https://cookiestore.spec.whatwg.org/#dom-cookiestore-get>
259 fn Get(&self, cx: &mut JSContext, name: USVString) -> RootedPromise {
260 // 1. Let settings be this’s relevant settings object.
261 let global = self.global();
262
263 // 2. Let origin be settings’s origin.
264 let origin = global.origin();
265
266 // 5. Let p be a new promise.
267 let p = Promise::new(cx, &global);
268
269 // 3. If origin is an opaque origin, then return a promise rejected with a "SecurityError" DOMException.
270 if !origin.is_tuple() {
271 p.reject_error(cx, Error::Security(None));
272 return p;
273 }
274
275 // 4. Let url be settings’s creation URL.
276 let creation_url = global.creation_url();
277
278 let name = CookieStore::normalize(&name);
279
280 // 6. Run the following steps in parallel:
281 let res = self
282 .global()
283 .resource_threads()
284 .send(CoreResourceMsg::GetCookieDataForUrlAsync(
285 self.droppable.store_id,
286 creation_url,
287 Some(name),
288 ));
289 if res.is_err() {
290 error!("Failed to send cookiestore message to resource threads");
291 } else {
292 self.in_flight
293 .safe_borrow_mut(cx.no_gc())
294 .push_back(p.to_traced());
295 }
296
297 // 7. Return p.
298 p
299 }
300
301 /// <https://cookiestore.spec.whatwg.org/#dom-cookiestore-get-options>
302 fn Get_(&self, cx: &mut JSContext, options: &CookieStoreGetOptions) -> RootedPromise {
303 // 1. Let settings be this’s relevant settings object.
304 let global = self.global();
305
306 // 2. Let origin be settings’s origin.
307 let origin = global.origin();
308
309 // 7. Let p be a new promise.
310 let p = Promise::new(cx, &global);
311
312 // 3. If origin is an opaque origin, then return a promise rejected with a "SecurityError" DOMException.
313 if !origin.is_tuple() {
314 p.reject_error(cx, Error::Security(None));
315 return p;
316 }
317
318 // 4. Let url be settings’s creation URL.
319 let creation_url = global.creation_url();
320
321 // 5. If options is empty, then return a promise rejected with a TypeError.
322 // "is empty" is not strictly defined anywhere in the spec but the only value we require here is "url"
323 if options.url.is_none() && options.name.is_none() {
324 p.reject_error(cx, Error::Type(c"Options cannot be empty".to_owned()));
325 return p;
326 }
327
328 let mut final_url = creation_url.clone();
329
330 // 6. If options["url"] is present, then run these steps:
331 if let Some(get_url) = &options.url {
332 // 6.1. Let parsed be the result of parsing options["url"] with settings’s API base URL.
333 let parsed_url = ServoUrl::parse_with_base(Some(&global.api_base_url()), get_url);
334
335 // 6.2. If this’s relevant global object is a Window object and parsed does not equal url with exclude fragments set to true,
336 // then return a promise rejected with a TypeError.
337 if let Some(_window) = DomRoot::downcast::<Window>(self.global()) &&
338 parsed_url
339 .as_ref()
340 .is_ok_and(|parsed| !parsed.is_equal_excluding_fragments(&creation_url))
341 {
342 p.reject_error(cx, Error::Type(c"URL does not match context".to_owned()));
343 return p;
344 }
345
346 // 6.3. If parsed’s origin and url’s origin are not the same origin,
347 // then return a promise rejected with a TypeError.
348 if parsed_url
349 .as_ref()
350 .is_ok_and(|parsed| creation_url.origin() != parsed.origin())
351 {
352 p.reject_error(cx, Error::Type(c"Not same origin".to_owned()));
353 return p;
354 }
355
356 // 6.4. Set url to parsed.
357 if let Ok(url) = parsed_url {
358 final_url = url;
359 }
360 }
361
362 // 6. Run the following steps in parallel:
363 let res = self
364 .global()
365 .resource_threads()
366 .send(CoreResourceMsg::GetCookieDataForUrlAsync(
367 self.droppable.store_id,
368 final_url,
369 options.name.clone().map(|val| CookieStore::normalize(&val)),
370 ));
371 if res.is_err() {
372 error!("Failed to send cookiestore message to resource threads");
373 } else {
374 self.in_flight
375 .safe_borrow_mut(cx.no_gc())
376 .push_back(p.to_traced());
377 }
378
379 p
380 }
381
382 /// <https://cookiestore.spec.whatwg.org/#dom-cookiestore-getall>
383 fn GetAll(&self, cx: &mut JSContext, name: USVString) -> RootedPromise {
384 // 1. Let settings be this’s relevant settings object.
385 let global = self.global();
386
387 // 2. Let origin be settings’s origin.
388 let origin = global.origin();
389
390 // 5. Let p be a new promise.
391 let p = Promise::new(cx, &global);
392
393 // 3. If origin is an opaque origin, then return a promise rejected with a "SecurityError" DOMException.
394 if !origin.is_tuple() {
395 p.reject_error(cx, Error::Security(None));
396 return p;
397 }
398 // 4. Let url be settings’s creation URL.
399 let creation_url = global.creation_url();
400
401 // Normalize name here rather than passing the un-nomarlized name around to the resource thread and back
402 let name = CookieStore::normalize(&name);
403
404 // 6. Run the following steps in parallel:
405 let res =
406 self.global()
407 .resource_threads()
408 .send(CoreResourceMsg::GetAllCookieDataForUrlAsync(
409 self.droppable.store_id,
410 creation_url,
411 Some(name),
412 ));
413 if res.is_err() {
414 error!("Failed to send cookiestore message to resource threads");
415 } else {
416 self.in_flight
417 .safe_borrow_mut(cx.no_gc())
418 .push_back(p.to_traced());
419 }
420
421 // 7. Return p.
422 p
423 }
424
425 /// <https://cookiestore.spec.whatwg.org/#dom-cookiestore-getall-options>
426 fn GetAll_(&self, cx: &mut JSContext, options: &CookieStoreGetOptions) -> RootedPromise {
427 // 1. Let settings be this’s relevant settings object.
428 let global = self.global();
429
430 // 2. Let origin be settings’s origin.
431 let origin = global.origin();
432
433 // 6. Let p be a new promise.
434 let p = Promise::new(cx, &global);
435
436 // 3. If origin is an opaque origin, then return a promise rejected with a "SecurityError" DOMException.
437 if !origin.is_tuple() {
438 p.reject_error(cx, Error::Security(None));
439 return p;
440 }
441
442 // 4. Let url be settings’s creation URL.
443 let creation_url = global.creation_url();
444
445 let mut final_url = creation_url.clone();
446
447 // 5. If options["url"] is present, then run these steps:
448 if let Some(get_url) = &options.url {
449 // 5.1. Let parsed be the result of parsing options["url"] with settings’s API base URL.
450 let parsed_url = ServoUrl::parse_with_base(Some(&global.api_base_url()), get_url);
451
452 // If this’s relevant global object is a Window object and parsed does not equal url with exclude fragments set to true,
453 // then return a promise rejected with a TypeError.
454 if let Some(_window) = DomRoot::downcast::<Window>(self.global()) &&
455 parsed_url
456 .as_ref()
457 .is_ok_and(|parsed| !parsed.is_equal_excluding_fragments(&creation_url))
458 {
459 p.reject_error(cx, Error::Type(c"URL does not match context".to_owned()));
460 return p;
461 }
462
463 // 5.3. If parsed’s origin and url’s origin are not the same origin,
464 // then return a promise rejected with a TypeError.
465 if parsed_url
466 .as_ref()
467 .is_ok_and(|parsed| creation_url.origin() != parsed.origin())
468 {
469 p.reject_error(cx, Error::Type(c"Not same origin".to_owned()));
470 return p;
471 }
472
473 // 5.4. Set url to parsed.
474 if let Ok(url) = parsed_url {
475 final_url = url;
476 }
477 }
478
479 // 7. Run the following steps in parallel:
480 let res =
481 self.global()
482 .resource_threads()
483 .send(CoreResourceMsg::GetAllCookieDataForUrlAsync(
484 self.droppable.store_id,
485 final_url,
486 options.name.clone().map(|val| CookieStore::normalize(&val)),
487 ));
488 if res.is_err() {
489 error!("Failed to send cookiestore message to resource threads");
490 } else {
491 self.in_flight
492 .safe_borrow_mut(cx.no_gc())
493 .push_back(p.to_traced());
494 }
495
496 // 8. Return p
497 p
498 }
499
500 /// <https://cookiestore.spec.whatwg.org/#dom-cookiestore-set>
501 fn Set(&self, cx: &mut JSContext, name: USVString, value: USVString) -> RootedPromise {
502 // 1. Let settings be this’s relevant settings object.
503 let global = self.global();
504
505 // 2. Let origin be settings’s origin.
506 let origin = global.origin();
507
508 // 5. Let p be a new promise.
509 let p = Promise::new(cx, &global);
510
511 // 3. If origin is an opaque origin, then return a promise rejected with a "SecurityError" DOMException.
512 if !origin.is_tuple() {
513 p.reject_error(cx, Error::Security(None));
514 return p;
515 }
516
517 // 4. Let url be settings’s creation URL.
518 let creation_url = global.creation_url();
519
520 // 6.1 Let r be the result of running set a cookie with url, name, value, null, null, "/", "strict", false, and null.
521 let properties = CookieInit {
522 name,
523 value,
524 expires: None,
525 domain: None,
526 path: USVString(String::from("/")),
527 sameSite: CookieSameSite::Strict,
528 partitioned: false,
529 maxAge: None,
530 };
531 let Some(cookie) = CookieStore::set_a_cookie(&creation_url, &properties) else {
532 // 6.2. If r is failure, then reject p with a TypeError and abort these steps.
533 p.reject_error(cx, Error::Type(c"Invalid cookie".to_owned()));
534 return p;
535 };
536
537 // 6. Run the following steps in parallel:
538 let res = self
539 .global()
540 .resource_threads()
541 .send(CoreResourceMsg::SetCookieForUrlAsync(
542 self.droppable.store_id,
543 creation_url.clone(),
544 Serde(cookie),
545 NonHTTP,
546 ));
547 if res.is_err() {
548 error!("Failed to send cookiestore message to resource threads");
549 } else {
550 self.in_flight
551 .safe_borrow_mut(cx.no_gc())
552 .push_back(p.to_traced());
553 }
554
555 // 7. Return p.
556 p
557 }
558
559 /// <https://cookiestore.spec.whatwg.org/#dom-cookiestore-set-options>
560 fn Set_(&self, cx: &mut JSContext, options: &CookieInit) -> RootedPromise {
561 // 1. Let settings be this’s relevant settings object.
562 let global = self.global();
563
564 // 2. Let origin be settings’s origin.
565 let origin = global.origin();
566
567 // 5. Let p be a new promise.
568 let p = Promise::new(cx, &global);
569
570 // 3. If origin is an opaque origin, then return a promise rejected with a "SecurityError" DOMException.
571 if !origin.is_tuple() {
572 p.reject_error(cx, Error::Security(None));
573 return p;
574 }
575
576 // 4. Let url be settings’s creation URL.
577 let creation_url = global.creation_url();
578
579 // 6.1. Let r be the result of running set a cookie with url, options["name"], options["value"],
580 // options["expires"], options["domain"], options["path"], options["sameSite"], options["partitioned"],
581 // and options["maxAge"].
582 let Some(cookie) = CookieStore::set_a_cookie(&creation_url, options) else {
583 // 6.2. If r is failure, then reject p with a TypeError and abort these steps.
584 p.reject_error(cx, Error::Type(c"Invalid cookie".to_owned()));
585 return p;
586 };
587
588 // 6. Run the following steps in parallel:
589 let res = self
590 .global()
591 .resource_threads()
592 .send(CoreResourceMsg::SetCookieForUrlAsync(
593 self.droppable.store_id,
594 creation_url.clone(),
595 Serde(cookie),
596 NonHTTP,
597 ));
598 if res.is_err() {
599 error!("Failed to send cookiestore message to resource threads");
600 } else {
601 self.in_flight
602 .safe_borrow_mut(cx.no_gc())
603 .push_back(p.to_traced());
604 }
605
606 // 7. Return p
607 p
608 }
609
610 /// <https://cookiestore.spec.whatwg.org/#dom-cookiestore-delete>
611 fn Delete(&self, cx: &mut JSContext, name: USVString) -> RootedPromise {
612 // 1. Let settings be this’s relevant settings object.
613 let global = self.global();
614
615 // 2. Let origin be settings’s origin.
616 let origin = global.origin();
617
618 // 5. Let p be a new promise.
619 let p = Promise::new(cx, &global);
620
621 // 3. If origin is an opaque origin, then return a promise rejected with a "SecurityError" DOMException.
622 if !origin.is_tuple() {
623 p.reject_error(cx, Error::Security(None));
624 return p;
625 }
626
627 // 4. Let url be settings’s creation URL.
628 let creation_url = global.creation_url();
629
630 // 6.1. Let r be the result of running delete a cookie with url, name, null, "/", and true.
631 let options = CookieStoreDeleteOptions {
632 name,
633 domain: None,
634 path: USVString(String::from("/")),
635 partitioned: true,
636 };
637 let Some(cookie) = CookieStore::delete_a_cookie(&creation_url, &options) else {
638 // 6.2. If r is failure, then reject p with a TypeError and abort these steps.
639 p.reject_error(cx, Error::Type(c"Invalid cookie".to_owned()));
640 return p;
641 };
642
643 // 6. Run the following steps in parallel:
644 let res = global
645 .resource_threads()
646 .send(CoreResourceMsg::SetCookieForUrlAsync(
647 self.droppable.store_id,
648 creation_url.clone(),
649 Serde(cookie),
650 NonHTTP,
651 ));
652 if res.is_err() {
653 error!("Failed to send cookiestore message to resource threads");
654 } else {
655 self.in_flight
656 .safe_borrow_mut(cx.no_gc())
657 .push_back(p.to_traced());
658 }
659
660 // 7. Return p.
661 p
662 }
663
664 /// <https://cookiestore.spec.whatwg.org/#dom-cookiestore-delete-options>
665 fn Delete_(&self, cx: &mut JSContext, options: &CookieStoreDeleteOptions) -> RootedPromise {
666 // 1. Let settings be this’s relevant settings object.
667 let global = self.global();
668
669 // 2. Let origin be settings’s origin.
670 let origin = global.origin();
671
672 // 5. Let p be a new promise.
673 let p = Promise::new(cx, &global);
674
675 // 3. If origin is an opaque origin, then return a promise rejected with a "SecurityError" DOMException.
676 if !origin.is_tuple() {
677 p.reject_error(cx, Error::Security(None));
678 return p;
679 }
680
681 // 4. Let url be settings’s creation URL.
682 let creation_url = global.creation_url();
683
684 // 6.1. Let r be the result of running delete a cookie with url, options["name"],
685 // options["domain"], options["path"], and options["partitioned"].
686 let Some(cookie) = CookieStore::delete_a_cookie(&creation_url, options) else {
687 // 6.2. If r is failure, then reject p with a TypeError and abort these steps.
688 p.reject_error(cx, Error::Type(c"Invalid cookie".to_owned()));
689 return p;
690 };
691
692 // 6. Run the following steps in parallel:
693 let res = global
694 .resource_threads()
695 .send(CoreResourceMsg::SetCookieForUrlAsync(
696 self.droppable.store_id,
697 creation_url.clone(),
698 Serde(cookie),
699 NonHTTP,
700 ));
701 if res.is_err() {
702 error!("Failed to send cookiestore message to resource threads");
703 } else {
704 self.in_flight
705 .safe_borrow_mut(cx.no_gc())
706 .push_back(p.to_traced());
707 }
708
709 // 7. Return p.
710 p
711 }
712
713 // <https://cookiestore.spec.whatwg.org/#dom-cookiestore-onchange>
714 event_handler!(change, GetOnchange, SetOnchange);
715}
716
717impl CookieStore {
718 /// <https://cookiestore.spec.whatwg.org/#normalize-a-cookie-name-or-value>
719 pub(crate) fn normalize(value: &USVString) -> String {
720 value.trim_matches([' ', '\t']).into()
721 }
722
723 /// <https://cookiestore.spec.whatwg.org/#set-cookie-algorithm>
724 fn set_a_cookie(url: &ServoUrl, properties: &CookieInit) -> Option<Cookie<'static>> {
725 // 1. Normalize name.
726 let name = CookieStore::normalize(&properties.name);
727
728 // 2. Normalize value.
729 let value = CookieStore::normalize(&properties.value);
730
731 // 3. If name or value contain U+003B (;), any C0 control character except U+0009 TAB, or U+007F DELETE, then return failure.
732 if CookieStore::contains_control_characters(&name) ||
733 CookieStore::contains_control_characters(&value)
734 {
735 return None;
736 }
737
738 // 4. If name contains U+003D (=), then return failure.
739 if name.contains('=') {
740 return None;
741 }
742
743 // 5. If name’s length is 0:
744 if name.is_empty() {
745 // 5.1 If value contains U+003D (=), then return failure.
746 // 5.2 If value’s length is 0, then return failure.
747 if value.contains('=') || value.is_empty() {
748 return None;
749 }
750
751 // 5.3 If value, byte-lowercased, starts with `__host-`, `__host-http-`, `__http-`, or `__secure-`, then return failure.
752 if ["__host-", "__host-http-", "__http-", "__secure-"]
753 .into_iter()
754 .any(|prefix| starts_with_ignore_ascii_case(&value, prefix))
755 {
756 return None;
757 }
758 }
759
760 // 6. If name, byte-lowercased, starts with `__host-http-` or `__http-`, then return failure.
761 if ["__host-http-", "__http-"]
762 .into_iter()
763 .any(|prefix| starts_with_ignore_ascii_case(&name, prefix))
764 {
765 return None;
766 }
767 let name_starts_with_host = starts_with_ignore_ascii_case(&name, "__host-");
768
769 // 7. Let encodedName be the result of UTF-8 encoding name.
770 //
771 // Note: name is already UTF-8 encoded
772
773 // 8. Let encodedValue be the result of UTF-8 encoding value.
774 //
775 // Note: value is already UTF-8 encoded
776
777 // 9. If the byte sequence length of encodedName plus the byte sequence length of encodedValue is greater than the maximum name/value pair size, then return failure.
778 if name.len() + value.len() > 4096 {
779 return None;
780 }
781
782 // 10. Let host be url’s host
783 let host = url.host().map(|host| host.to_owned());
784
785 // 11. Let attributes be « ».
786 let mut cookie = Cookie::build((name, value));
787
788 // 12. If domain is non-null:
789 if let Some(domain) = &properties.domain {
790 // 12.1 If domain starts with U+002E (.), then return failure.
791 if domain.starts_with('.') {
792 return None;
793 }
794
795 // 12.2 If name, byte-lowercased, starts with `__host-`, then return failure.
796 if name_starts_with_host {
797 return None;
798 }
799
800 // 12.3 If domain is not a registrable domain suffix of and is not equal to host, then return failure.
801 // 12.4 Let parsedDomain be the result of host parsing domain.
802 // 12.5 Assert: parsedDomain is not failure.
803 // Note: this function parses the host and returns the parsed host on success
804 let domain = get_registrable_domain_suffix_of_or_is_equal_to(domain, host?)?;
805
806 // 12.6 Let encodedDomain be the result of UTF-8 encoding parsedDomain.
807 let domain = domain.to_string();
808
809 // 12.7 If the byte sequence length of encodedDomain is greater than the maximum attribute value size, then return failure.
810 if domain.len() > 1024 {
811 return None;
812 }
813
814 // 12.8 Append (`Domain`, encodedDomain) to attributes.
815 cookie.inner_mut().set_domain(domain);
816 }
817
818 // 13. If expires is non-null:
819 if let Some(expiry) = properties.expires {
820 // 13.1 If maxAge is non-null, then return failure.
821 if properties.maxAge.is_some() {
822 return None;
823 }
824
825 // 13.2 Append (`Expires`, expires (date serialized)) to attributes.
826 cookie.inner_mut().set_expires(
827 OffsetDateTime::from_unix_timestamp((*expiry / 1000.0) as i64)
828 .expect("cookie expiry out of range"),
829 );
830 }
831 // 14. Otherwise, if maxAge is non-null, then append (`Max-Age`, ToString(maxAge)) to attributes.
832 else if let Some(max_age) = properties.maxAge {
833 cookie
834 .inner_mut()
835 .set_max_age(time::Duration::seconds(max_age));
836 }
837
838 // 15. If path is the empty string, then set path to the serialized cookie default path of url.
839 let path = if properties.path.is_empty() {
840 CookieStore::serialized_cookie_default_path(url)
841 } else {
842 properties.path.to_string()
843 };
844
845 // 16. If path does not start with U+002F (/), then return failure.
846 if !path.starts_with('/') {
847 return None;
848 }
849
850 // 17. If path is not U+002F (/), and name, byte-lowercased, starts with `__host-`, then return failure.
851 if path != "/" && name_starts_with_host {
852 return None;
853 }
854
855 // 18. Let encodedPath be the result of UTF-8 encoding path.
856 //
857 // Note: path is already UTF-8 encoded
858
859 // 19. If the byte sequence length of encodedPath is greater than the maximum attribute value size, then return failure.
860 if path.len() > 1024 {
861 return None;
862 }
863
864 // 20. Append (`Path`, encodedPath) to attributes.
865 cookie.inner_mut().set_path(path);
866
867 // 21. Append (`Secure`, ``) to attributes.
868 cookie.inner_mut().set_secure(true);
869
870 // 22. Switch on sameSite:
871 cookie.inner_mut().set_same_site(match properties.sameSite {
872 CookieSameSite::None => SameSite::None,
873 CookieSameSite::Strict => SameSite::Strict,
874 CookieSameSite::Lax => SameSite::Lax,
875 });
876
877 // 23. If partitioned is true, Append (`Partitioned`, ``) to attributes.
878 cookie.inner_mut().set_partitioned(properties.partitioned);
879
880 // 24. Perform the steps defined in Cookies § Storage Model for when the user agent
881 // "receives a cookie" with url as request-uri, encodedName as cookie-name, encodedValue as
882 // cookie-value, and attributes as cookie-attribute-list.
883 //
884 // Note: This is done by the caller sending `CoreResourceMsg::SetCookieForUrlAsync`.
885
886 // 25. Return success.
887 Some(cookie.build())
888 }
889
890 /// <https://cookiestore.spec.whatwg.org/#delete-a-cookie>
891 fn delete_a_cookie(
892 url: &ServoUrl,
893 options: &CookieStoreDeleteOptions,
894 ) -> Option<Cookie<'static>> {
895 // 1. Normalize name.
896 let name = CookieStore::normalize(&options.name);
897
898 // 2. Let value be the empty string.
899 // 3. If name’s length is 0, then set value to any non-empty implementation-defined string.
900 let value = if name.is_empty() { "servo" } else { "" };
901
902 // 4. Return the results of running set a cookie with url, name, value, null, domain, path,
903 // "strict", partitioned, and 0.
904 let properties = CookieInit {
905 name: USVString(name),
906 value: USVString(value.to_owned()),
907 expires: None,
908 domain: options.domain.clone(),
909 path: options.path.clone(),
910 sameSite: CookieSameSite::Strict,
911 partitioned: options.partitioned,
912 maxAge: Some(0),
913 };
914 CookieStore::set_a_cookie(url, &properties)
915 }
916
917 /// <https://cookiestore.spec.whatwg.org/#set-cookie-algorithm>
918 fn contains_control_characters(val: &str) -> bool {
919 // If name or value contain U+003B (;), any C0 control character except U+0009 TAB, or U+007F DELETE, then return failure.
920 val.contains(
921 |v| matches!(v, '\u{0000}'..='\u{0008}' | '\u{000a}'..='\u{001f}' | '\u{007f}' | ';'),
922 )
923 }
924
925 /// <https://fetch.spec.whatwg.org/#serialized-cookie-default-path>
926 fn serialized_cookie_default_path(url: &ServoUrl) -> String {
927 // 1. Let cloneURL be a clone of url.
928 let mut cloned_url = url.clone();
929
930 // 2. Set cloneURL’s path to the cookie default path of cloneURL’s path.
931 let path = cloned_url
932 .path_segments()
933 .expect("document creation url cannot be a base")
934 .map(String::from)
935 .collect();
936 let path = CookieStore::cookie_default_path(path);
937 cloned_url
938 .as_mut_url()
939 .set_path(&format!("/{}", path.join("/")));
940
941 // 3. Return the URL path serialization of cloneURL.
942 cloned_url.path().to_owned()
943 }
944
945 /// <https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-layered-cookies#name-cookie-default-path>
946 fn cookie_default_path(mut path: Vec<String>) -> Vec<String> {
947 // 1. Assert: path is a non-empty list.
948 assert!(!path.is_empty());
949
950 // 2. If path's size is greater than 1, then remove path's last item.
951 if path.len() > 1 {
952 path.pop();
953 }
954 // 3. Otherwise, set path[0] to the empty string.
955 else {
956 path[0] = String::new();
957 }
958
959 // 4. Return path.
960 path
961 }
962
963 /// <https://cookiestore.spec.whatwg.org/#fire-a-change-event>
964 fn fire_a_change_event(
965 &self,
966 cx: &mut JSContext,
967 type_: Atom,
968 changes: Vec<CookieChange>,
969 window: &Window,
970 ) {
971 // 4. Let changedList and deletedList be the result of running prepare lists from changes.
972 let (changed, deleted) = prepare_lists(changes);
973
974 // 1. Let event be the result of creating an Event using CookieChangeEvent.
975 // 2. Set event’s type attribute to type.
976 // 3. Set event’s bubbles and cancelable attributes to false.
977 // 5. Set event’s changed attribute to changedList.
978 // 6. Set event’s deleted attribute to deletedList.
979 let event = CookieChangeEvent::new_with_proto(
980 cx, window, None, type_, false, false, &changed, &deleted,
981 );
982
983 // 7. Dispatch event at target.
984 event.upcast::<Event>().fire(cx, self.upcast());
985 }
986}