oficina / docs Public

Live push 1b: the limiter keys on the person, the binding on auth's cookie (#175 finding 1)

The late-answer limiter keyed on a hash of every rastrillo_session cookie
while authentication reads only the first, so appending a junk cookie made
a new limiter key per request: 45 POSTs from one session in 100 ms all
answered 204. It now keys on the authenticated actor (person id) from the
request. The stream binding hashes exactly the cookie auth reads (the
first with the configured name: __Host-rastrillo_session on an https
origin), so appended cookies change neither.

TestLateAnswersIgnoreAppendedCookies: 45 concurrent POSTs with appended
junk cookies are paced (some 503, no 4xx), and own still arrives with a
junk cookie appended; before the fix all 45 answered 204.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 946c4aedf5b1837121785499356b2f931ea97bd6 parent 2a97f52
4 files changed, +75 −30
  • internal/docs/handlers.go +2 −2
  • internal/docs/push.go +25 −27
  • internal/docs/push_test.go +47 −0
  • internal/docs/stream.go +1 −1
diff --git a/internal/docs/handlers.go b/internal/docs/handlers.go
index 009bd4c..c64cf10 100644
--- a/internal/docs/handlers.go
+++ b/internal/docs/handlers.go
@@ -1053,7 +1053,7 @@ func (h *handlers) updatesPost(w http.ResponseWriter, r *http.Request) {
// §5: a session over the rate waits here, before ApplyUpdate takes
// the document's lock or the writer; too many waiting is a 503 the
// clients retry. Never a 4xx: the web save queue drops a 4xx batch.
- if ok, busy := h.late.admit(r.Context(), h.hub.draining(), sessionBinding(r), doc.ID); !ok {
+ if ok, busy := h.late.admit(r.Context(), h.hub.draining(), "person:"+strconv.FormatInt(actor.PersonID, 10), doc.ID); !ok {
if busy || h.hub.isDraining() {
w.Header().Set("Retry-After", "1")
http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusServiceUnavailable)
@@ -1062,7 +1062,7 @@ func (h *handlers) updatesPost(w http.ResponseWriter, r *http.Request) {
}
// §3.4: a Docs-Stream header from this session's own push stream on
// this document is recorded with the row, inside its transaction.
- if o, ok := h.pushRegistry.origin(r, doc.ID); ok {
+ if o, ok := h.pushRegistry.origin(r, doc.ID, h.sessionBinding(r)); ok {
applyCtx = context.WithValue(applyCtx, postOriginKey{}, o)
}
}
diff --git a/internal/docs/push.go b/internal/docs/push.go
index 70b9d60..52b031a 100644
--- a/internal/docs/push.go
+++ b/internal/docs/push.go
@@ -41,28 +41,25 @@ const (
// unset is off. Anything else is a startup refusal.
func ParseLivePush(v string) (bool, error) { return parseOnOff("DOCS_LIVE_PUSH", v) }
-// sessionBinding identifies the session a request presents: a hash of its
-// session cookie (rastrillo's, which Home and the native apps' approved
-// sessions use too) or, failing that, its Authorization header. A stream
-// id is bound to it, so a Docs-Stream header from another session is
-// ignored (§3.4). Empty means nothing to bind to: that stream never gets
-// `own`.
-func sessionBinding(r *http.Request) string {
- sum := sha256.New()
- found := false
- for _, c := range r.Cookies() {
- if c.Name == "rastrillo_session" || c.Name == "__Host-rastrillo_session" {
- sum.Write([]byte(c.Name + "=" + c.Value + ";"))
- found = true
- }
+// sessionBinding identifies the session a request presents: a hash of the
+// session cookie authentication reads, exactly as it reads it (the first
+// cookie with the configured name, rastrillo sessions' CookieName: the
+// __Host- form on an https origin), or, failing that, its Authorization
+// header. Home and the native apps' approved sessions use the same cookie.
+// A stream id is bound to it, so a Docs-Stream header from another session
+// is ignored (§3.4). Cookies appended after it change nothing (#175 finding
+// 1). Empty means nothing to bind to: that stream never gets `own`.
+func (h *handlers) sessionBinding(r *http.Request) string {
+ name := "rastrillo_session"
+ if strings.HasPrefix(h.origin, "https://") {
+ name = "__Host-rastrillo_session"
}
- if !found {
- if a := r.Header.Get("Authorization"); a != "" {
- sum.Write([]byte(a))
- found = true
- }
- }
- if !found {
+ sum := sha256.New()
+ if c, err := r.Cookie(name); err == nil {
+ sum.Write([]byte(name + "=" + c.Value))
+ } else if a := r.Header.Get("Authorization"); a != "" {
+ sum.Write([]byte(a))
+ } else {
return ""
}
return hex.EncodeToString(sum.Sum(nil))
@@ -121,7 +118,7 @@ func (p *pushRegistry) close(id string) {
// origin resolves a Docs-Stream header ("<stream id>.<counter>") on a POST
// to docID: only a stream open on that document, bound to the same
// session. Anything else is ignored, as if the header were absent.
-func (p *pushRegistry) origin(r *http.Request, docID int64) (postOrigin, bool) {
+func (p *pushRegistry) origin(r *http.Request, docID int64, session string) (postOrigin, bool) {
header := r.Header.Get("Docs-Stream")
id, counter, ok := strings.Cut(header, ".")
if !ok || id == "" || len(id) > 64 || counter == "" || len(counter) > 20 {
@@ -130,7 +127,6 @@ func (p *pushRegistry) origin(r *http.Request, docID int64) (postOrigin, bool) {
if _, err := strconv.ParseUint(counter, 10, 64); err != nil {
return postOrigin{}, false
}
- session := sessionBinding(r)
p.mu.Lock()
s, open := p.streams[id]
p.mu.Unlock()
@@ -319,12 +315,14 @@ func (h *handlers) pushFrames(docID int64, id string, rows []pushRow, current, s
return b.String(), last
}
-// lateAnswers paces a session that posts too fast to one document (§5):
-// over lateLimit updates in a second, its next answer waits, before the
+// lateAnswers paces a person who posts too fast to one document (§5):
+// over lateLimit updates in a second, the next answer waits, before the
// POST takes the document's lock or the writer, for at most lateMaxWait,
// ended by the request's cancellation or the process draining. At most
-// lateMaxWaiting answers per session wait; beyond that, 503 with
-// Retry-After: 1 (never a 4xx: the web save queue drops a 4xx batch).
+// lateMaxWaiting answers per person wait; beyond that, 503 with
+// Retry-After: 1 (never a 4xx: the web save queue drops a 4xx batch). Keyed
+// on the authenticated actor, never on request bytes (#175 finding 1: a
+// key from cookies let appended cookies make a new key per request).
type lateAnswers struct {
mu sync.Mutex
recent map[lateKey][]time.Time
diff --git a/internal/docs/push_test.go b/internal/docs/push_test.go
index 60dca02..211296a 100644
--- a/internal/docs/push_test.go
+++ b/internal/docs/push_test.go
@@ -990,3 +990,50 @@ func TestPushFrameCacheIsTransparent(t *testing.T) {
}
t.Logf("4 streams x 10 rows: %d row reads without the cache, %d with it (%d hits)", offReads, onReads, hits)
}
+
+// #175 finding 1: the limiter keys on the authenticated person, not on
+// cookie bytes. One real session posting 45 times at once, each request with
+// an extra rastrillo_session cookie appended (auth reads only the first),
+// must still be paced: some answers 503, none 4xx. And the junk cookie
+// does not change the stream binding: own still arrives.
+func TestLateAnswersIgnoreAppendedCookies(t *testing.T) {
+ f := newPushFixture(t, pushOn())
+ poster := f.open(f.cookies, "?push=1&since=0", nil)
+ id, _, _ := poster.hello(t)
+ u := f.update(1, "same")
+ var mu sync.Mutex
+ codes := map[int]int{}
+ var wg sync.WaitGroup
+ for i := 0; i < 45; i++ {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ cookies := append(append([]*http.Cookie(nil), f.cookies...), &http.Cookie{Name: "rastrillo_session", Value: fmt.Sprint("junk", i)})
+ code, _ := f.post(cookies, u, "")
+ mu.Lock()
+ codes[code]++
+ mu.Unlock()
+ }(i)
+ }
+ wg.Wait()
+ for code := range codes {
+ if code >= 400 && code < 500 {
+ t.Fatalf("answers %v: a 4xx", codes)
+ }
+ }
+ if codes[http.StatusServiceUnavailable] == 0 {
+ t.Fatalf("answers %v: 45 POSTs at once were not paced (junk cookies made 45 limiter keys)", codes)
+ }
+ time.Sleep(1100 * time.Millisecond) // out of the window
+ junk := append(append([]*http.Cookie(nil), f.cookies...), &http.Cookie{Name: "rastrillo_session", Value: "junk"})
+ f.post(junk, f.update(2, "mine"), id+".9")
+ for {
+ fr := poster.next(t)
+ if fr.event == "own" && strings.HasSuffix(fr.data, " 9") {
+ break
+ }
+ if fr.event == "push" && strings.Contains(fr.data, base64.StdEncoding.EncodeToString(f.update(2, "mine"))) {
+ t.Fatal("an appended cookie broke the stream binding: own came back as push")
+ }
+ }
+}
diff --git a/internal/docs/stream.go b/internal/docs/stream.go
index 2f7f993..9bb64af 100644
--- a/internal/docs/stream.go
+++ b/internal/docs/stream.go
@@ -213,7 +213,7 @@ func (h *handlers) stream(w http.ResponseWriter, r *http.Request) {
flushFrames := func() bool { return true }
if push {
streamID = newStreamID()
- h.pushRegistry.open(streamID, pushStream{session: sessionBinding(r), docID: doc.ID})
+ h.pushRegistry.open(streamID, pushStream{session: h.sessionBinding(r), docID: doc.ID})
defer h.pushRegistry.close(streamID)
if h.pushFrameCache {
cache = h.pushRegistry.cacheFor(doc.ID)