package deed import ( "crypto/hmac" "crypto/sha256" "encoding/base64" "encoding/hex" "fmt" "net/http" "strings" "sync" "time" ) // SessionKey identifies a short-lived access session. The store is keyed by the // pair, not by the buyer alone, so one proof never grants another asset. type SessionKey struct { Buyer string // hex pubkey Asset string // asset id } // SessionStore records sessions established by a valid presentation proof. // // The store MUST be shared across workers, or requests MUST be routed sticky by // (buyer, asset). A per-worker store turns a token issued by one worker into a // random 402 on the next. type SessionStore interface { // Put records a session that expires at the given time. Put(k SessionKey, expires time.Time) // Valid reports whether an unexpired session exists. Valid(k SessionKey) bool } // MemorySessions is an in-process SessionStore. It is correct for a single // process and is the default; a multi-worker deployment supplies a shared // implementation instead. type MemorySessions struct { mu sync.Mutex data map[SessionKey]time.Time } // NewMemorySessions creates an empty in-memory session store. func NewMemorySessions() *MemorySessions { return &MemorySessions{data: make(map[SessionKey]time.Time)} } // Put records a session. func (m *MemorySessions) Put(k SessionKey, expires time.Time) { if expires.IsZero() { expires = time.Now().Add(12 * time.Hour) } m.mu.Lock() m.data[k] = expires m.mu.Unlock() } // Valid reports whether an unexpired session exists. func (m *MemorySessions) Valid(k SessionKey) bool { m.mu.Lock() defer m.mu.Unlock() exp, ok := m.data[k] if !ok { return false } if time.Now().After(exp) { delete(m.data, k) return false } return true } // Delete removes a session. func (m *MemorySessions) Delete(k SessionKey) { m.mu.Lock() delete(m.data, k) m.mu.Unlock() } // Prune drops expired sessions. func (m *MemorySessions) Prune() { now := time.Now() m.mu.Lock() for k, exp := range m.data { if now.After(exp) { delete(m.data, k) } } m.mu.Unlock() } // CookieCodec issues and reads the same-site session cookie. // // The cookie is signed with a host secret. Without the signature a client could // name any (buyer, asset) pair; the store lookup would then turn a forged cookie // into access if that pair happened to have a live session. type CookieCodec struct { // Name is the cookie name; default "musiquay_session". Name string // Secret is the HMAC key. It must be stable across workers. Secret []byte // Secure marks the cookie Secure; default true. Secure bool } // CookieName is the default cookie name. const CookieName = "musiquay_session" func (c *CookieCodec) name() string { if c.Name != "" { return c.Name } return CookieName } // Issue writes a signed cookie for a session. SameSite=Strict means it is only // sent when the client and host share a registrable domain, which is exactly // the case the cookie exists for. func (c *CookieCodec) Issue(w http.ResponseWriter, k SessionKey, expires time.Time) error { if len(c.Secret) < 16 { return fmt.Errorf("deed: cookie secret must be at least 16 bytes") } payload := k.Buyer + "|" + k.Asset + "|" + fmt.Sprintf("%d", expires.Unix()) mac := c.sign([]byte(payload)) value := base64.RawURLEncoding.EncodeToString([]byte(payload)) + "." + base64.RawURLEncoding.EncodeToString(mac) http.SetCookie(w, &http.Cookie{ Name: c.name(), Value: value, Path: "/", Expires: expires, MaxAge: int(time.Until(expires).Seconds()), HttpOnly: true, Secure: c.Secure, SameSite: http.SameSiteStrictMode, }) return nil } // Read returns the session the cookie names, if the signature is valid. func (c *CookieCodec) Read(r *http.Request) (SessionKey, time.Time, error) { ck, err := r.Cookie(c.name()) if err != nil { return SessionKey{}, time.Time{}, fmt.Errorf("deed: no session cookie") } parts := strings.SplitN(ck.Value, ".", 2) if len(parts) != 2 { return SessionKey{}, time.Time{}, fmt.Errorf("deed: malformed session cookie") } payload, err := base64.RawURLEncoding.DecodeString(parts[0]) if err != nil { return SessionKey{}, time.Time{}, fmt.Errorf("deed: malformed session cookie") } mac, err := base64.RawURLEncoding.DecodeString(parts[1]) if err != nil { return SessionKey{}, time.Time{}, fmt.Errorf("deed: malformed session cookie") } if !hmac.Equal(mac, c.sign(payload)) { return SessionKey{}, time.Time{}, fmt.Errorf("deed: session cookie signature invalid") } fields := strings.Split(string(payload), "|") if len(fields) != 3 { return SessionKey{}, time.Time{}, fmt.Errorf("deed: malformed session cookie payload") } var exp int64 if _, err = fmt.Sscanf(fields[2], "%d", &exp); err != nil { return SessionKey{}, time.Time{}, fmt.Errorf("deed: malformed session cookie expiry") } if len(fields[0]) != 64 || len(fields[1]) != 64 { return SessionKey{}, time.Time{}, fmt.Errorf("deed: malformed session cookie keys") } if _, err = hex.DecodeString(fields[0]); err != nil { return SessionKey{}, time.Time{}, fmt.Errorf("deed: malformed session cookie buyer") } expiry := time.Unix(exp, 0) if time.Now().After(expiry) { return SessionKey{}, time.Time{}, fmt.Errorf("deed: session cookie expired") } return SessionKey{Buyer: fields[0], Asset: fields[1]}, expiry, nil } // Clear expires the session cookie. func (c *CookieCodec) Clear(w http.ResponseWriter) { http.SetCookie(w, &http.Cookie{ Name: c.name(), Value: "", Path: "/", MaxAge: -1, HttpOnly: true, Secure: c.Secure, SameSite: http.SameSiteStrictMode, }) } func (c *CookieCodec) sign(payload []byte) []byte { m := hmac.New(sha256.New, c.Secret) m.Write(payload) return m.Sum(nil) }