Skip to main content

CookieStore

Struct CookieStore 

Source
pub struct CookieStore { /* private fields */ }
Expand description

A client-side cookie store: RFC 6265 §5.3 storage, §5.4 retrieval, §6.1 capacity limits — the state a cookie-aware HTTP client keeps between a response’s Set-Cookie and the next request’s Cookie:.

The store is a plain value — &mut self writes, &self reads — with no lock of its own; share it the standard way:

use std::sync::RwLock;

use kekse::{CookieStore, Insertion, OffsetDateTime};

let now = OffsetDateTime::from_unix_timestamp(1_752_000_000)?;
let url = url::Url::parse("https://example.test/")?;
let store = RwLock::new(CookieStore::new());

let stored = store.write().unwrap().insert(&url, "SID=deadbeef; Secure", now);
assert_eq!(stored, Insertion::Stored);
let header = store.read().unwrap().cookie_header(&url, now);
assert_eq!(header.unwrap(), "SID=deadbeef");

Implementations§

Source§

impl CookieStore

Source

pub fn new() -> Self

An empty store with the default StoreConfig (RFC 6265 §6.1: 3000 cookies, 50 per domain).

Source

pub fn with_config(config: StoreConfig) -> Self

An empty store with explicit capacity limits.

Source

pub fn insert( &mut self, origin: &Url, set_cookie: &str, now: OffsetDateTime, ) -> Insertion

Ingest one Set-Cookie header value per RFC 6265 §5.3, with the RFC 6265bis storage gates. The outcome is always reported: stored, replaced (same (name, domain, path) identity, creation order kept), deleted (the already-expired idiom, including a negative Max-Age), or rejected with a RejectionReason.

Storage follows the user-agent rules. A Domain must cover the origin host (the anti-planting rule; under psl a refused public-suffix Domain is rejected for a foreign host and degrades to host-only when the origin is the suffix — §5.3 step 5 exactly), a missing or relative Path takes the origin’s default-path, and Max-Age wins over Expires, with a negative Max-Age honored as “expire now”. The RFC 6265bis gates then apply: a Secure cookie only over a secure origin — a TLS scheme (https/wss) or a loopback destination (loopback IPs, localhost, *.localhost), the trustworthy-origin convention — and the __Host-/__Secure- prefix requirements and CHIPS’ Partitioned/Secure pairing as witnessed by the parse; a case-variant prefix whose requirements are met stores verbatim, as user agents do. Finally the StoreConfig caps evict, expired cookies first, then oldest by creation.

The line is parsed leniently (SetCookie::parse) — the store mirrors a user agent, and a recoverable deviation never costs the cookie. A caller who wants strict grading gates before feeding the store.

use kekse::{CookieStore, Insertion, OffsetDateTime, RejectionReason};

let now = OffsetDateTime::from_unix_timestamp(1_752_000_000)?;
let origin = url::Url::parse("https://shop.example.test/cart")?;
let mut store = CookieStore::new();

let stored = store.insert(&origin, "SID=deadbeef; Path=/; Secure", now);
assert_eq!(stored, Insertion::Stored);

// The anti-planting rule: a foreign Domain is refused.
let planted = store.insert(&origin, "SID=evil; Domain=victim.test", now);
assert_eq!(
    planted,
    Insertion::Rejected(RejectionReason::DomainMismatch)
);
Source

pub fn insert_all<'s>( &mut self, origin: &Url, lines: impl IntoIterator<Item = &'s str>, now: OffsetDateTime, )

Ingest several Set-Cookie header values from one response, in order. Per-line outcomes are discarded — use insert where they matter.

Source

pub fn insert_response( &mut self, origin: &Url, headers: &HeaderMap, now: OffsetDateTime, )

Ingest every Set-Cookie header of a response’s http::HeaderMap, in order. A header value that is not valid UTF-8 is skipped (the parse boundary is &str); per-line outcomes are discarded — use insert where they matter.

Source

pub fn matches<'s>( &'s self, request: &Url, now: OffsetDateTime, ) -> impl Iterator<Item = StoredRef<'s>> + 's

The cookies to attach to a request, per RFC 6265 §5.4: not expired at now, Secure only onto a secure request (a TLS scheme or a loopback destination), host or domain match, path match — ordered per §5.4.2 (longest path first, then earliest creation). A hostless URL matches nothing.

Source

pub fn cookie_header( &self, request: &Url, now: OffsetDateTime, ) -> Option<HeaderValue>

The request Cookie: header for request — the matches rendered through a CookieJar with the canonical Percent encoding — or None when nothing matches (send no header at all, rather than an empty one).

Source

pub fn iter(&self) -> impl Iterator<Item = StoredRef<'_>>

Every stored cookie, in storage order — including cookies already expired but not yet purged (purge_expired).

Source

pub fn get<'s>( &'s self, name: &'s str, ) -> impl Iterator<Item = StoredRef<'s>> + 's

Every stored cookie with this name (any domain and path), in storage order.

Source

pub fn remove(&mut self, name: &str, domain: &str, path: &str) -> bool

Remove the cookie with exactly this (name, domain, path) identity — domain is the effective domain (the setting host for a host-only cookie); a leading dot is stripped and the comparison is case-insensitive, like storage. true iff a cookie was removed.

Source

pub fn clear(&mut self)

Drop every cookie.

Source

pub fn purge_expired(&mut self, now: OffsetDateTime)

Drop every cookie expired at now. Retrieval already filters expiry, so this is housekeeping, not correctness.

Source

pub fn len(&self) -> usize

The number of stored cookies — including expired-but-unpurged ones.

Source

pub fn is_empty(&self) -> bool

Whether the store holds no cookies at all.

Source§

impl CookieStore

Source

pub fn export(&self) -> PersistedStore

Export the stored representation for persistence: every cookie — session cookies and the expired-but-unpurged included — in creation order, as plain data.

Source

pub fn import( persisted: PersistedStore, config: StoreConfig, now: OffsetDateTime, ) -> Self

Rebuild a store from its persisted representation, under config: list order becomes creation order, cookies already expired at now are dropped, and the capacity caps apply immediately. Import trusts its input — the persisted form is the caller’s own export — and an unrecognized same_site token degrades to unset.

Trait Implementations§

Source§

impl Clone for CookieStore

Source§

fn clone(&self) -> CookieStore

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for CookieStore

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for CookieStore

Source§

fn default() -> CookieStore

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more