session.go raw

   1  package deed
   2  
   3  import (
   4  	"crypto/hmac"
   5  	"crypto/sha256"
   6  	"encoding/base64"
   7  	"encoding/hex"
   8  	"fmt"
   9  	"net/http"
  10  	"strings"
  11  	"sync"
  12  	"time"
  13  )
  14  
  15  // SessionKey identifies a short-lived access session. The store is keyed by the
  16  // pair, not by the buyer alone, so one proof never grants another asset.
  17  type SessionKey struct {
  18  	Buyer string // hex pubkey
  19  	Asset string // asset id
  20  }
  21  
  22  // SessionStore records sessions established by a valid presentation proof.
  23  //
  24  // The store MUST be shared across workers, or requests MUST be routed sticky by
  25  // (buyer, asset). A per-worker store turns a token issued by one worker into a
  26  // random 402 on the next.
  27  type SessionStore interface {
  28  	// Put records a session that expires at the given time.
  29  	Put(k SessionKey, expires time.Time)
  30  	// Valid reports whether an unexpired session exists.
  31  	Valid(k SessionKey) bool
  32  }
  33  
  34  // MemorySessions is an in-process SessionStore. It is correct for a single
  35  // process and is the default; a multi-worker deployment supplies a shared
  36  // implementation instead.
  37  type MemorySessions struct {
  38  	mu   sync.Mutex
  39  	data map[SessionKey]time.Time
  40  }
  41  
  42  // NewMemorySessions creates an empty in-memory session store.
  43  func NewMemorySessions() *MemorySessions {
  44  	return &MemorySessions{data: make(map[SessionKey]time.Time)}
  45  }
  46  
  47  // Put records a session.
  48  func (m *MemorySessions) Put(k SessionKey, expires time.Time) {
  49  	if expires.IsZero() {
  50  		expires = time.Now().Add(12 * time.Hour)
  51  	}
  52  	m.mu.Lock()
  53  	m.data[k] = expires
  54  	m.mu.Unlock()
  55  }
  56  
  57  // Valid reports whether an unexpired session exists.
  58  func (m *MemorySessions) Valid(k SessionKey) bool {
  59  	m.mu.Lock()
  60  	defer m.mu.Unlock()
  61  	exp, ok := m.data[k]
  62  	if !ok {
  63  		return false
  64  	}
  65  	if time.Now().After(exp) {
  66  		delete(m.data, k)
  67  		return false
  68  	}
  69  	return true
  70  }
  71  
  72  // Delete removes a session.
  73  func (m *MemorySessions) Delete(k SessionKey) {
  74  	m.mu.Lock()
  75  	delete(m.data, k)
  76  	m.mu.Unlock()
  77  }
  78  
  79  // Prune drops expired sessions.
  80  func (m *MemorySessions) Prune() {
  81  	now := time.Now()
  82  	m.mu.Lock()
  83  	for k, exp := range m.data {
  84  		if now.After(exp) {
  85  			delete(m.data, k)
  86  		}
  87  	}
  88  	m.mu.Unlock()
  89  }
  90  
  91  // CookieCodec issues and reads the same-site session cookie.
  92  //
  93  // The cookie is signed with a host secret. Without the signature a client could
  94  // name any (buyer, asset) pair; the store lookup would then turn a forged cookie
  95  // into access if that pair happened to have a live session.
  96  type CookieCodec struct {
  97  	// Name is the cookie name; default "musiquay_session".
  98  	Name string
  99  	// Secret is the HMAC key. It must be stable across workers.
 100  	Secret []byte
 101  	// Secure marks the cookie Secure; default true.
 102  	Secure bool
 103  }
 104  
 105  // CookieName is the default cookie name.
 106  const CookieName = "musiquay_session"
 107  
 108  func (c *CookieCodec) name() string {
 109  	if c.Name != "" {
 110  		return c.Name
 111  	}
 112  	return CookieName
 113  }
 114  
 115  // Issue writes a signed cookie for a session. SameSite=Strict means it is only
 116  // sent when the client and host share a registrable domain, which is exactly
 117  // the case the cookie exists for.
 118  func (c *CookieCodec) Issue(w http.ResponseWriter, k SessionKey, expires time.Time) error {
 119  	if len(c.Secret) < 16 {
 120  		return fmt.Errorf("deed: cookie secret must be at least 16 bytes")
 121  	}
 122  	payload := k.Buyer + "|" + k.Asset + "|" + fmt.Sprintf("%d", expires.Unix())
 123  	mac := c.sign([]byte(payload))
 124  	value := base64.RawURLEncoding.EncodeToString([]byte(payload)) + "." +
 125  		base64.RawURLEncoding.EncodeToString(mac)
 126  	http.SetCookie(w, &http.Cookie{
 127  		Name:     c.name(),
 128  		Value:    value,
 129  		Path:     "/",
 130  		Expires:  expires,
 131  		MaxAge:   int(time.Until(expires).Seconds()),
 132  		HttpOnly: true,
 133  		Secure:   c.Secure,
 134  		SameSite: http.SameSiteStrictMode,
 135  	})
 136  	return nil
 137  }
 138  
 139  // Read returns the session the cookie names, if the signature is valid.
 140  func (c *CookieCodec) Read(r *http.Request) (SessionKey, time.Time, error) {
 141  	ck, err := r.Cookie(c.name())
 142  	if err != nil {
 143  		return SessionKey{}, time.Time{}, fmt.Errorf("deed: no session cookie")
 144  	}
 145  	parts := strings.SplitN(ck.Value, ".", 2)
 146  	if len(parts) != 2 {
 147  		return SessionKey{}, time.Time{}, fmt.Errorf("deed: malformed session cookie")
 148  	}
 149  	payload, err := base64.RawURLEncoding.DecodeString(parts[0])
 150  	if err != nil {
 151  		return SessionKey{}, time.Time{}, fmt.Errorf("deed: malformed session cookie")
 152  	}
 153  	mac, err := base64.RawURLEncoding.DecodeString(parts[1])
 154  	if err != nil {
 155  		return SessionKey{}, time.Time{}, fmt.Errorf("deed: malformed session cookie")
 156  	}
 157  	if !hmac.Equal(mac, c.sign(payload)) {
 158  		return SessionKey{}, time.Time{}, fmt.Errorf("deed: session cookie signature invalid")
 159  	}
 160  	fields := strings.Split(string(payload), "|")
 161  	if len(fields) != 3 {
 162  		return SessionKey{}, time.Time{}, fmt.Errorf("deed: malformed session cookie payload")
 163  	}
 164  	var exp int64
 165  	if _, err = fmt.Sscanf(fields[2], "%d", &exp); err != nil {
 166  		return SessionKey{}, time.Time{}, fmt.Errorf("deed: malformed session cookie expiry")
 167  	}
 168  	if len(fields[0]) != 64 || len(fields[1]) != 64 {
 169  		return SessionKey{}, time.Time{}, fmt.Errorf("deed: malformed session cookie keys")
 170  	}
 171  	if _, err = hex.DecodeString(fields[0]); err != nil {
 172  		return SessionKey{}, time.Time{}, fmt.Errorf("deed: malformed session cookie buyer")
 173  	}
 174  	expiry := time.Unix(exp, 0)
 175  	if time.Now().After(expiry) {
 176  		return SessionKey{}, time.Time{}, fmt.Errorf("deed: session cookie expired")
 177  	}
 178  	return SessionKey{Buyer: fields[0], Asset: fields[1]}, expiry, nil
 179  }
 180  
 181  // Clear expires the session cookie.
 182  func (c *CookieCodec) Clear(w http.ResponseWriter) {
 183  	http.SetCookie(w, &http.Cookie{
 184  		Name:     c.name(),
 185  		Value:    "",
 186  		Path:     "/",
 187  		MaxAge:   -1,
 188  		HttpOnly: true,
 189  		Secure:   c.Secure,
 190  		SameSite: http.SameSiteStrictMode,
 191  	})
 192  }
 193  
 194  func (c *CookieCodec) sign(payload []byte) []byte {
 195  	m := hmac.New(sha256.New, c.Secret)
 196  	m.Write(payload)
 197  	return m.Sum(nil)
 198  }
 199