Documentation
¶
Overview ¶
Package cookies is a cookie jar that keeps and sends cookies as a given browser does: SameSite, third-party and partitioned cookies, redirects, order, and byte-for-byte values, by the rules in a profile's cookies section (profile.Cookies) on top of RFC 6265bis.
mimicry's transport drives the jar itself, because the rules need what an http.CookieJar never sees: the page a request comes from, whether it is a top-level navigation, its redirect chain, its credentials mode. Use Jar.CookieJar for code that needs an http.CookieJar; it cannot apply those rules and loses values net/http alters.
Index ¶
- Constants
- func Header(cs []*Cookie) string
- type Config
- type Cookie
- type Event
- type Jar
- func (j *Jar) All() []*Cookie
- func (j *Jar) Clear()
- func (j *Jar) ClearExpired() int
- func (j *Jar) ClearSession() int
- func (j *Jar) Clone() *Jar
- func (j *Jar) CookieJar() http.CookieJar
- func (j *Jar) Cookies(r Request) []*Cookie
- func (j *Jar) Delete(match func(*Cookie) bool) int
- func (j *Jar) Peek(r Request) []*Cookie
- func (j *Jar) ReadJSON(r io.Reader) error
- func (j *Jar) ReadNetscape(r io.Reader) error
- func (j *Jar) Set(c Cookie) error
- func (j *Jar) SetCookies(r Request, lines []string)
- func (j *Jar) SetHTTPCookies(u *url.URL, cs []*http.Cookie) error
- func (j *Jar) SetHostString(host, cookies string) error
- func (j *Jar) SetString(domain, cookies string) error
- func (j *Jar) String(name string) string
- func (j *Jar) WriteJSON(w io.Writer) error
- func (j *Jar) WriteNetscape(w io.Writer) error
- type Request
- type SameSite
Examples ¶
Constants ¶
const AnySite = "*"
AnySite as a domain stores a cookie sent to every host of every site. No browser has such a cookie, and it leaks to every site the jar talks to. WriteJSON and ReadJSON keep AnySite cookies, WriteNetscape omits them, and they count towards no site's limit. A __Host- cookie cannot be one.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Config ¶
type Config struct {
// Rules are the browser's cookie rules; nil uses
// profile.DefaultCookies (RFC 6265bis).
Rules *profile.Cookies
// Clock tells the time; nil uses the real clock.
Clock clockwork.Clock
// OnSetCookie, when set, is told about every Set-Cookie line the jar
// receives: stored, or rejected and why. It is called with the jar's
// lock released, in the order lines arrive.
OnSetCookie func(Event)
}
Config configures a Jar.
type Cookie ¶
type Cookie struct {
// Name and Value as stored: exactly as received, except where the
// browser changes them (Safari's Latin-1 re-encoding). Name is empty
// for a pair without "=" in browsers that keep it as a value.
Name string `json:"name"`
Value string `json:"value"`
// Domain is the host for a host-only cookie, else the Domain
// attribute without its leading dot.
Domain string `json:"domain"`
HostOnly bool `json:"hostOnly,omitempty"`
Path string `json:"path"`
// Expires is when the cookie expires; zero for a session cookie.
Expires time.Time `json:"expires,omitzero"`
Secure bool `json:"secure,omitempty"`
HTTPOnly bool `json:"httpOnly,omitempty"`
SameSite SameSite `json:"sameSite,omitempty"`
// Partitioned is the attribute; Partition is the top-level site the
// cookie is kept under ("https://example.com"), set for Partitioned
// cookies and, in Firefox, for every cookie of a cross-site context.
// Empty: the unpartitioned jar.
Partitioned bool `json:"partitioned,omitempty"`
Partition string `json:"partition,omitempty"`
Created time.Time `json:"created"`
LastAccess time.Time `json:"lastAccess,omitzero"`
// Raw is the Set-Cookie line that set it; empty for one set with
// Jar.Set.
Raw string `json:"raw,omitempty"`
}
Cookie is a stored cookie.
type Event ¶
type Event struct {
URL *url.URL
Line string
// Cookie is the cookie stored, or nil when Rejected says why not. A
// line that deletes a cookie (expired, Max-Age=0) has neither.
Cookie *Cookie
Rejected string
Deleted bool
}
Event reports one Set-Cookie line.
type Jar ¶
type Jar struct {
// contains filtered or unexported fields
}
Jar keeps cookies. It is safe for concurrent use.
func FromString ¶
FromString returns a new jar (New(cfg)) holding domain's cookies from a Cookie header string, stored as SetString stores them; for host-only cookies, call SetHostString on a New jar.
func New ¶
New returns an empty jar. Its rules, when given, must be valid (profile.Cookies.Validate).
func (*Jar) All ¶
All returns copies of every cookie, expired ones included until a request to their domain or ClearExpired removes them, in creation order.
func (*Jar) ClearExpired ¶
ClearExpired removes expired cookies, and returns how many.
func (*Jar) ClearSession ¶
ClearSession removes session cookies, as closing a browser does, and returns how many.
func (*Jar) CookieJar ¶
CookieJar returns the jar as an http.CookieJar. It is lossy, which is why mimicry's transport does not use it: net/http drops values it cannot parse, re-quotes others, and asks for cookies with only a URL, so every request is treated as a navigation from nowhere.
func (*Jar) Cookies ¶
Cookies returns the cookies the browser would send with r, in its order. It updates their last-access times.
func (*Jar) Delete ¶
Delete removes every cookie match reports true for, and returns how many. match gets a copy of each cookie, with the jar unlocked: it may use the jar. A cookie replaced while match runs stays.
func (*Jar) Peek ¶
Peek returns the cookies Cookies would, changing nothing: last-access times stay, and expired cookies stay stored.
func (*Jar) ReadNetscape ¶
ReadNetscape adds the cookies of a Netscape cookies.txt file, through Set; lines are created in file order.
func (*Jar) Set ¶
Set stores c as given, bypassing URL and browser rules, for restoring a session or seeding a jar. Name and value must hold no control characters or ";"; Domain is required (AnySite for every site); an empty Path is "/" and a zero Created is now. It replaces a cookie with the same name, domain, path and partition.
Example ¶
Seed a cookie whose attributes you know (a saved session's, another tool's export), then ask which requests the browser would send it with. For a Cookie header string ("name=value; ..."), SetString does this for each pair.
package main
import (
"fmt"
"log"
"net/url"
"github.com/roachadam/mimicry/cookies"
"github.com/roachadam/mimicry/profiles"
)
func main() {
jar, err := cookies.New(cookies.Config{
Rules: profiles.Chrome().Cookies,
})
if err != nil {
log.Fatal(err)
}
// For every host of shop.test, over HTTPS only. SameSite is left
// unset, which Chrome treats as Lax.
if err := jar.Set(cookies.Cookie{
Name: "session",
Value: "s1",
Domain: "shop.test",
Path: "/",
Secure: true,
}); err != nil {
log.Fatal(err)
}
shop := mustParse("https://www.shop.test/cart")
outlet := mustParse("https://www.outlet.test/")
// Typed into the address bar: sent.
fmt.Printf("%q\n", cookies.Header(jar.Cookies(cookies.Request{
URL: shop,
Method: "GET",
Navigation: true,
})))
// A link from another site: Lax cookies go on a top-level GET.
fmt.Printf("%q\n", cookies.Header(jar.Cookies(cookies.Request{
URL: shop,
Method: "GET",
Navigation: true,
Page: outlet,
})))
// A fetch() from another site's page: not sent.
fmt.Printf("%q\n", cookies.Header(jar.Cookies(cookies.Request{
URL: shop,
Method: "GET",
Page: outlet,
})))
// Plain HTTP: not sent, the cookie is Secure.
fmt.Printf("%q\n", cookies.Header(jar.Cookies(cookies.Request{
URL: mustParse("http://www.shop.test/"),
Method: "GET",
Navigation: true,
})))
}
func mustParse(rawURL string) *url.URL {
u, err := url.Parse(rawURL)
if err != nil {
log.Fatal(err)
}
return u
}
Output: "session=s1" "session=s1" "" ""
func (*Jar) SetCookies ¶
SetCookies stores the cookies of a response to r: its raw Set-Cookie lines, as received.
func (*Jar) SetHTTPCookies ¶
SetHTTPCookies stores cs as if a top-level navigation to u had received them as Set-Cookie lines, through the profile's rules. Raw is ignored; a Domain makes a Domain cookie and none a host-only cookie. It stores every cookie it can and returns an error naming each one refused.
func (*Jar) SetHostString ¶
SetHostString stores the pairs of a Cookie header string as host-only cookies of host, as a browser keeps a cookie set without a Domain attribute. host is a host name, IP address or URL. Pairs are read as SetString reads them; on error nothing is stored.
Example ¶
Cookies a host keeps to itself, as one set without a Domain attribute (a local dev server's, say), go in with SetHostString: that host alone, not the names under it. IP addresses, which no Domain may name, too.
package main
import (
"fmt"
"log"
"net/url"
"github.com/roachadam/mimicry/cookies"
"github.com/roachadam/mimicry/profiles"
)
func main() {
jar, err := cookies.New(cookies.Config{
Rules: profiles.Chrome().Cookies,
})
if err != nil {
log.Fatal(err)
}
if err := jar.SetHostString("https://shop.test/", "visit=1"); err != nil {
log.Fatal(err)
}
if err := jar.SetHostString("127.0.0.1:8080", "dev=1"); err != nil {
log.Fatal(err)
}
for _, u := range []string{"https://shop.test/", "https://www.shop.test/", "http://127.0.0.1:8080/"} {
fmt.Printf("%s %q\n", u, cookies.Header(jar.Cookies(cookies.Request{
URL: mustParse(u),
Method: "GET",
Navigation: true,
})))
}
}
func mustParse(rawURL string) *url.URL {
u, err := url.Parse(rawURL)
if err != nil {
log.Fatal(err)
}
return u
}
Output: https://shop.test/ "visit=1" https://www.shop.test/ "" http://127.0.0.1:8080/ "dev=1"
func (*Jar) SetString ¶
SetString stores the pairs of a Cookie header string ("a=1; b=2") as Domain cookies of domain, sent to domain and every name under it. domain is a host name (a port is ignored) or a URL whose host is taken; it is never widened to the whole site. SetString(AnySite, ...) stores cookies for every site.
Each pair becomes a cookie with path /, no expiry, not Secure and no SameSite, replacing any cookie with the same name, Domain and path. A pair without "=" is a nameless cookie. Name prefixes are honoured case-insensitively: __Host- is stored host-only on domain itself, Secure, path /; __Secure- is stored Secure; __Http- and __Host-Http- are Secure and HttpOnly where the profile enforces them.
It stores nothing and returns an error when domain is not a host name or URL, is an IP address (use SetHostString), is a public suffix, a pair is one Set refuses, or a __Host- cookie is given for AnySite.
Example ¶
Start from a Cookie header string kept from an earlier session (another tool's, a database row), browse, then keep the cookies as a string again. The name given is the cookies' Domain, as a browser reads one: that name and every name under it get them, nothing wider.
package main
import (
"fmt"
"log"
"net/url"
"github.com/roachadam/mimicry/cookies"
"github.com/roachadam/mimicry/profiles"
)
func main() {
jar, err := cookies.FromString("shop.test", "session=s1; cart=c9; __Host-sid=h1", cookies.Config{
Rules: profiles.Chrome().Cookies,
})
if err != nil {
log.Fatal(err)
}
// www.shop.test and names under it only: not shop.test or api.shop.test.
if err := jar.SetString("www.shop.test", "lang=en"); err != nil {
log.Fatal(err)
}
// shop.test's cookies reach every name under it, but __Host-sid stays
// on the bare shop.test host, as a __Host- cookie must.
for _, u := range []string{"https://shop.test/", "https://www.shop.test/cart", "https://api.shop.test/v1/stock", "https://www.outlet.test/"} {
fmt.Printf("%s %q\n", u, cookies.Header(jar.Cookies(cookies.Request{
URL: mustParse(u),
Method: "GET",
Navigation: true,
})))
}
// The site's responses set more (mimicry's Transport stores them;
// here by hand). Its own Domain cookie named cart replaces the seeded
// one; Chrome counts a new value as a new cookie, so it moves last.
jar.SetCookies(cookies.Request{
URL: mustParse("https://www.shop.test/cart"),
Method: "GET",
Navigation: true,
}, []string{
"cart=c10; Domain=shop.test; Path=/",
"seen=1; Path=/; Max-Age=3600",
})
// Every cookie for shop.test and the names under it; then
// www.shop.test's own, without the shop.test cookies it is also sent.
fmt.Printf("%q\n", jar.String("shop.test"))
fmt.Printf("%q\n", jar.String("www.shop.test"))
}
func mustParse(rawURL string) *url.URL {
u, err := url.Parse(rawURL)
if err != nil {
log.Fatal(err)
}
return u
}
Output: https://shop.test/ "session=s1; cart=c9; __Host-sid=h1" https://www.shop.test/cart "session=s1; cart=c9; lang=en" https://api.shop.test/v1/stock "session=s1; cart=c9" https://www.outlet.test/ "" "session=s1; __Host-sid=h1; lang=en; cart=c10; seen=1" "lang=en; seen=1"
Example (AnySite) ¶
A cookie for every site, such as a flag you want every server to see, is not something a browser has: ask for it explicitly with AnySite. Every site the jar talks to receives it, trackers and CDNs included, and a site's own cookie of the same name goes as well.
package main
import (
"fmt"
"log"
"net/url"
"github.com/roachadam/mimicry/cookies"
"github.com/roachadam/mimicry/profiles"
)
func main() {
jar, err := cookies.New(cookies.Config{
Rules: profiles.Chrome().Cookies,
})
if err != nil {
log.Fatal(err)
}
if err := jar.SetString(cookies.AnySite, "debug=1"); err != nil {
log.Fatal(err)
}
if err := jar.SetString("shop.test", "debug=0"); err != nil {
log.Fatal(err)
}
for _, u := range []string{"https://www.shop.test/", "https://cdn.tracker.test/pixel.gif"} {
fmt.Printf("%s %q\n", u, cookies.Header(jar.Cookies(cookies.Request{
URL: mustParse(u),
Method: "GET",
Navigation: true,
})))
}
fmt.Printf("%q\n", jar.String(cookies.AnySite))
// A __Host- cookie belongs to one host, so it cannot go to every site.
fmt.Println(jar.SetString(cookies.AnySite, "__Host-id=1"))
}
func mustParse(rawURL string) *url.URL {
u, err := url.Parse(rawURL)
if err != nil {
log.Fatal(err)
}
return u
}
Output: https://www.shop.test/ "debug=1; debug=0" https://cdn.tracker.test/pixel.gif "debug=1" "debug=1" cookies: cookie "__Host-id": a __Host- cookie belongs to one host, not to every site
func (*Jar) String ¶
String returns, as a Cookie header string, every unexpired, unpartitioned cookie whose domain is name or ends in "."+name, in creation order. Domain cookies of a parent domain are not included. name is read as SetString reads it. Hosts, paths and attributes are lost; WriteJSON keeps them. It is empty for an invalid name.
func (*Jar) WriteJSON ¶
WriteJSON writes every cookie as a JSON array, every attribute kept: the lossless way to save a jar.
Example ¶
Save a jar between runs and restore it, every attribute kept.
package main
import (
"bytes"
"fmt"
"log"
"net/url"
"github.com/roachadam/mimicry/cookies"
"github.com/roachadam/mimicry/profiles"
)
func main() {
rules := profiles.Chrome().Cookies
jar, err := cookies.New(cookies.Config{
Rules: rules,
})
if err != nil {
log.Fatal(err)
}
home := mustParse("https://www.shop.test/")
jar.SetCookies(cookies.Request{
URL: home,
Method: "GET",
Navigation: true,
}, []string{
"session=s1; Path=/; Secure; HttpOnly; SameSite=Lax",
"cart=c9; Domain=shop.test; Path=/; Max-Age=86400",
})
var saved bytes.Buffer // a file, or a row in a database
if err := jar.WriteJSON(&saved); err != nil {
log.Fatal(err)
}
restored, err := cookies.New(cookies.Config{
Rules: rules,
})
if err != nil {
log.Fatal(err)
}
if err := restored.ReadJSON(&saved); err != nil {
log.Fatal(err)
}
for _, c := range restored.All() {
fmt.Printf("%s=%s domain=%s host-only=%v same-site=%q\n", c.Name, c.Value, c.Domain, c.HostOnly, c.SameSite)
}
}
func mustParse(rawURL string) *url.URL {
u, err := url.Parse(rawURL)
if err != nil {
log.Fatal(err)
}
return u
}
Output: session=s1 domain=www.shop.test host-only=true same-site="Lax" cart=c9 domain=shop.test host-only=false same-site=""
type Request ¶
type Request struct {
URL *url.URL
Method string
// page.
Navigation bool
// Page is the page the request is made from: the page loading a
// subresource or frame, or the page a navigation leaves. Nil: none (a
// typed URL).
Page *url.URL
// Redirects are the URLs that redirected to URL, first first.
Redirects []*url.URL
// WebSocket marks a WebSocket's opening handshake, made from Page: a
// credentialed subresource, unless the rules say otherwise
// (profile.Cookies.WebSocketUnpartitioned). A ws:// or wss:// URL
// counts as http:// or https:// (RFC 6455, section 4.1).
WebSocket bool
}
Request is a request as cookies see it.
type SameSite ¶
type SameSite int
SameSite is a cookie's SameSite attribute.
SameSite values. Unset behaves as the profile says (profile.Cookies.UnsetSameSite).
func (SameSite) MarshalText ¶
MarshalText writes the attribute value ("Lax"; empty when unset).
func (*SameSite) UnmarshalText ¶
UnmarshalText reads an attribute value, case-blind; anything else is unset, as in a Set-Cookie line.