package fetch import ( "encoding/json" "errors" "io/fs" "maps" "net/url" "os" "slices" "strings" "sync" "time" http "github.com/bogdanfinn/fhttp" "github.com/bogdanfinn/fhttp/cookiejar" "golang.org/x/net/publicsuffix" "git.security-command.org/Overlord/dibs/internal/fsutil" ) // Cookie is a stored cookie, in a form that survives a restart and can be // handed to and from a browser. type Cookie struct { Name string `json:"name"` Value string `json:"value"` Domain string `json:"domain"` // the host for host-only cookies HostOnly bool `json:"host_only,omitempty"` Path string `json:"path"` Expires time.Time `json:"expires,omitzero"` // zero for session cookies Secure bool `json:"secure,omitempty"` HTTPOnly bool `json:"http_only,omitempty"` // Set is when the cookie was last set. When dibs processes share a // cookie file, the newest version of each cookie wins. Set time.Time `json:"set,omitzero"` } func (c Cookie) expired(now time.Time) bool { return !c.Expires.IsZero() && !c.Expires.After(now) } // forgetDeleted is how long a deleted cookie is remembered, so that saving // does not bring back the copy another process still has on file. const forgetDeleted = 24 * time.Hour // Jar is an RFC 6265 cookie jar that remembers every cookie by the host that // set it, so the cookies can be saved, restored and exported per host. type Jar struct { mu sync.Mutex jar *cookiejar.Jar // cookies keeps deleted and expired cookies too, until forgetDeleted // has passed. cookies map[string]map[string]Cookie // host -> domain|path|name -> cookie now func() time.Time } func NewJar() *Jar { jar, _ := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List}) return &Jar{ jar: jar, cookies: map[string]map[string]Cookie{}, now: time.Now, } } func (j *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) { j.mu.Lock() defer j.mu.Unlock() j.jar.SetCookies(u, cookies) host := strings.ToLower(u.Hostname()) now := j.now() for _, hc := range cookies { c := Cookie{ Name: hc.Name, Value: hc.Value, Domain: strings.TrimPrefix(strings.ToLower(hc.Domain), "."), Path: hc.Path, Expires: hc.Expires, Secure: hc.Secure, HTTPOnly: hc.HttpOnly, } if c.Domain == "" { c.Domain, c.HostOnly = host, true } if c.Path == "" || !strings.HasPrefix(c.Path, "/") { c.Path = defaultPath(u.Path) } switch { case hc.MaxAge < 0: c.Expires = now case hc.MaxAge > 0: c.Expires = now.Add(time.Duration(hc.MaxAge) * time.Second) default: // No Max-Age: Expires decides. } j.store(host, c, now) } } func (j *Jar) Cookies(u *url.URL) []*http.Cookie { j.mu.Lock() defer j.mu.Unlock() return j.jar.Cookies(u) } // Export returns the live cookies of every host, sorted by name. func (j *Jar) Export() map[string][]Cookie { j.mu.Lock() defer j.mu.Unlock() now := j.now() out := map[string][]Cookie{} for host, byKey := range j.cookies { for _, key := range slices.Sorted(maps.Keys(byKey)) { if c := byKey[key]; !c.expired(now) { out[host] = append(out[host], c) } } } return out } // Import adds cookies as if host had set them, unless the jar has a newer // version. A cookie without a Set time loses to any version in the jar. func (j *Jar) Import(host string, cookies []Cookie) { j.mu.Lock() defer j.mu.Unlock() j.importLocked(strings.ToLower(host), cookies, j.now()) } // importLocked is Import. Callers hold mu. func (j *Jar) importLocked(host string, cookies []Cookie, now time.Time) { for _, c := range cookies { if have, ok := j.cookies[host][key(c)]; ok && !c.Set.After(have.Set) { continue } hc := &http.Cookie{ Name: c.Name, Value: c.Value, Path: c.Path, Expires: c.Expires, Secure: c.Secure, HttpOnly: c.HTTPOnly, } if !c.HostOnly { hc.Domain = c.Domain } if c.expired(now) { hc.MaxAge = -1 } j.jar.SetCookies(&url.URL{Scheme: "https", Host: host, Path: c.Path}, []*http.Cookie{hc}) j.store(host, c, now) } } // Clear deletes every cookie. The deletions are saved like any other // change, so other processes sharing the file drop the cookies too. func (j *Jar) Clear() { j.mu.Lock() defer j.mu.Unlock() now := j.now() for host, byKey := range j.cookies { for _, c := range byKey { if c.expired(now) { continue } hc := &http.Cookie{Name: c.Name, Path: c.Path, MaxAge: -1} if !c.HostOnly { hc.Domain = c.Domain } j.jar.SetCookies(&url.URL{Scheme: "https", Host: host, Path: c.Path}, []*http.Cookie{hc}) c.Expires, c.Set = now, now j.store(host, c, now) } } } func key(c Cookie) string { return c.Domain + "|" + c.Path + "|" + c.Name } // store records c for host. Callers hold mu. func (j *Jar) store(host string, c Cookie, now time.Time) { if c.Set.IsZero() { c.Set = now } if j.cookies[host] == nil { j.cookies[host] = map[string]Cookie{} } j.cookies[host][key(c)] = c } // Codec turns the cookie file's JSON into what is stored on disk and back, // such as to encrypt it. type Codec interface { Encode(data []byte) ([]byte, error) Decode(data []byte) ([]byte, error) } // Save writes the cookies to path, readable only by the user. Other dibs // processes may share the file, so it first takes in their newer cookies. func (j *Jar) Save(path string) error { return j.SaveWith(path, nil) } // SaveWith is Save through codec, which may be nil. func (j *Jar) SaveWith(path string, codec Codec) error { unlock, err := fsutil.Lock(path + ".lock") if err != nil { return err } defer unlock() saved, err := readCookies(path, codec) if err != nil { return err } j.mu.Lock() now := j.now() for host, cookies := range saved { j.importLocked(host, cookies, now) } out := map[string][]Cookie{} for host, byKey := range j.cookies { for _, k := range slices.Sorted(maps.Keys(byKey)) { c := byKey[k] if c.expired(now) && now.Sub(c.Set) > forgetDeleted { delete(byKey, k) continue } out[host] = append(out[host], c) } } j.mu.Unlock() data, err := json.MarshalIndent(out, "", " ") if err != nil { return err } if codec != nil { if data, err = codec.Encode(data); err != nil { return err } } return fsutil.WriteFileAtomic(path, data, 0o600) } // Load imports the cookies saved at path. A missing file is not an error. func (j *Jar) Load(path string) error { return j.LoadWith(path, nil) } // LoadWith is Load through codec, which may be nil. func (j *Jar) LoadWith(path string, codec Codec) error { saved, err := readCookies(path, codec) if err != nil { return err } for host, cookies := range saved { j.Import(host, cookies) } return nil } func readCookies(path string, codec Codec) (map[string][]Cookie, error) { data, err := os.ReadFile(path) if errors.Is(err, fs.ErrNotExist) { return nil, nil } if err != nil { return nil, err } if codec != nil { if data, err = codec.Decode(data); err != nil { return nil, err } } var saved map[string][]Cookie if err := json.Unmarshal(data, &saved); err != nil { return nil, err } return saved, nil } // defaultPath is the RFC 6265 default-path of a request path. func defaultPath(p string) string { if p == "" || p[0] != '/' { return "/" } i := strings.LastIndex(p, "/") if i == 0 { return "/" } return p[:i] }