carlos / platform Public

edge PPv2 idle: Astra round 1 fixes (1 P1, 2 P2)

- P1: trust-status printed idle 0 for an older edge that sent none, which
  defeated ppv2-step.py's B-step refusal. trustCounters.Idle is now a
  pointer printed only when the edge reported it; an unarmed newer edge
  still prints idle 0.
- P2: the wire accepted idle in some places only. An answer carries idle
  in its counters and every listener, or nowhere; sums compare idle's
  presence too.
- P2: sentAnything's 5 ms read could still time out under a scheduling
  stall and miscount queued bytes as idle. It now clears the deadline and
  peeks with recv(MSG_PEEK|MSG_DONTWAIT) (queuedBytes, unix); when it
  cannot tell it answers true, so only a provably silent connection is
  idle. Non-unix builds never count idle.
- Tests: the verb's real output for an older edge has no idle; mixed
  presence refused; queuedBytes queued/silent/closed/expired deadline.
  Census overlay re-proposed (queuedBytes new, legacy).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev f007fe6580e5eaef492d9748516ec3e7a2516406 parent 1267156
11 files changed, +265 −26
  • docs/superpowers/notes/census-claims-edge-ppv2-idle.tsv +1 −1
  • docs/superpowers/notes/census-proposal-edge-ppv2-idle.md +2 −2
  • docs/superpowers/reviews/ASTRA-FINDINGS-edge-ppv2-idle-R1.md +38 −0
  • internal/host/edgetrust.go +50 −6
  • internal/host/edgetrust_test.go +39 −4
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −1
  • internal/provision/testdata/plan14-root-reads-edge-ppv2-idle.tsv +4 −4
  • internal/proxyproto/conn.go +9 −8
  • internal/proxyproto/peek_other.go +9 −0
  • internal/proxyproto/peek_unix.go +46 −0
  • internal/proxyproto/peek_unix_test.go +66 −0
diff --git a/docs/superpowers/notes/census-claims-edge-ppv2-idle.tsv b/docs/superpowers/notes/census-claims-edge-ppv2-idle.tsv
index 55811a6c9..8952c4e9a 100644
--- a/docs/superpowers/notes/census-claims-edge-ppv2-idle.tsv
+++ b/docs/superpowers/notes/census-claims-edge-ppv2-idle.tsv
@@ -1,2 +1,2 @@
internal/proxyproto/conn.go:Conn.parse A trusted connection whose header read times out with no byte read, and sentAnything finds no byte either, closes and counts idle instead of timeout. Same close, same state (failed); no new read beyond sentAnything. Edge (uid carlos), not root.
-internal/proxyproto/conn.go:Conn.sentAnything New. On a trusted connection about to be closed after a header-deadline timeout with nothing read: sets a 5 ms read deadline on the accepted socket and reads at most one byte from it, to tell an idle connection from one whose bytes arrived after the deadline had passed. The byte is dropped; the connection is closed straight after. Reads only the already accepted network connection; no file, no path, nothing run. Edge (uid carlos), not root.
+internal/proxyproto/peek_unix.go:queuedBytes New. One recv(MSG_PEEK|MSG_DONTWAIT) of one byte on the already accepted socket through syscall.RawConn, never waiting; consumes nothing. No file, no path, nothing run; known=false on any unexpected error. Edge (uid carlos), not root.
diff --git a/docs/superpowers/notes/census-proposal-edge-ppv2-idle.md b/docs/superpowers/notes/census-proposal-edge-ppv2-idle.md
index 7c8a60530..a306bebd7 100644
--- a/docs/superpowers/notes/census-proposal-edge-ppv2-idle.md
+++ b/docs/superpowers/notes/census-proposal-edge-ppv2-idle.md
@@ -16,8 +16,8 @@ Recorded dispositions, which each change must still satisfy:
New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
-- new `internal/proxyproto/conn.go:Conn.sentAnything`: reads +file:Read; written legacy, accepted-legacy, frozen
+- new `internal/proxyproto/peek_unix.go:queuedBytes`: reads +file:Read; written legacy, accepted-legacy, frozen
-Seal: `7ca068c5c146a679b4726d74fe43cf9c47f97080f9c08b761a36a9a12a5a3c54` → `f5c0ad32db5ee003f16ba314d7083e416cc18578d802ace49233f31afb7d164a`.
+Seal: `7ca068c5c146a679b4726d74fe43cf9c47f97080f9c08b761a36a9a12a5a3c54` → `d339e42410d313e010f3abba883235e0a9a697a6cb11ed3652952093919f1e8a`.
Overlay: `internal/provision/testdata/plan14-root-reads-edge-ppv2-idle.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/reviews/ASTRA-FINDINGS-edge-ppv2-idle-R1.md b/docs/superpowers/reviews/ASTRA-FINDINGS-edge-ppv2-idle-R1.md
new file mode 100644
index 000000000..224e99743
--- /dev/null
+++ b/docs/superpowers/reviews/ASTRA-FINDINGS-edge-ppv2-idle-R1.md
@@ -0,0 +1,38 @@
+Reviewed round 1 at `12671563b6c449b04149bc5c06a111a2b0254013`, against merge base `03ff5d17`.
+
+1. **P1 — Sections 3–4: the CLI defeats the old-edge B-step refusal.**
+ [`counters()`](internal/host/edgetrust.go:193) converts absent `idle` to zero. [`trustStatusLine()`](internal/host/edgetrust.go:573) then serializes it through the unconditional [`json:"idle"` field](internal/host/edgetrust.go:114). After binary adoption, while the older edge still runs, the CLI therefore advertises `idle: 0`. The [B-step check](scripts/ppv2-step.py:767) accepts that target for both apply and reverify, although idle connections still increment `timeout`.
+
+ **Fix:** preserve absence through CLI serialization, while continuing to accept older answers. Test an older socket response through the command’s actual JSON output and then the B-step check. The current tests exercise those halves separately and miss this conversion.
+ **Fault family:** capability evidence must describe the running edge, not the querying binary.
+
+2. **P2 — Sections 1 and 6: the 5 ms probe can misclassify queued header bytes as idle.**
+ [`sentAnything()`](internal/proxyproto/conn.go:361) installs another short deadline, then reads. If the goroutine is descheduled past that deadline, Go can return a timeout before inspecting the socket—even with header bytes queued. The local runtime checks the deadline [before its socket read](/home/paulca/.local/go-dist/src/internal/poll/fd_unix.go:154). `sentAnything()` discards that error and returns false, causing [`parse()`](internal/proxyproto/conn.go:257) to count `idle`.
+
+ This recreates the late-parse problem the helper intends to solve and makes `TestTrustedHeaderDeadlineFromAccept` vulnerable under load.
+ **Fix:** use a deadline-independent, nonblocking check for queued bytes, with conservative handling of errors. Add a deterministic test that pauses beyond the probe deadline with bytes already queued; increasing 5 ms only reduces the likelihood.
+ **Fault family:** absence of bytes must be established independently of scheduling delay.
+
+3. **P2 — Section 3: mixed idle presence passes Go validation.**
+ [`statusShape()`](internal/host/edgetrust.go:243) sums counters after missing values become zero. For example, total `idle: 5`, listener 443 `idle: 5`, and listener 80 with no `idle` passes. The CLI supplies the missing zero, hiding the inconsistency from Python’s stricter parser.
+
+ **Fix:** require `idle` everywhere or nowhere before conversion; retain acceptance of wholly older answers. Add mixed-presence cases, including zero-valued counters.
+ **Fault family:** counter presence and snapshot completeness.
+
+No P3 findings.
+
+Both timeout branches close the socket before the deferred deadline restoration. `Close` and `CloseTrusted` remain independent of the parse lock. Untrusted connections cannot enter the idle branch. The marker and no-client refusal paths, `STILL`, and the S3 metric remain unchanged. Restart detection includes idle decreases. The documentation’s old-edge refusal claim is not fulfilled because of finding 1.
+
+The three new Python test bodies passed through `unittest.FunctionTestCase`, bypassing their unused temporary-directory setup. Two failed against the base implementation; the idle-movement case preserves existing behavior. Standard Python execution and targeted Go tests were blocked by the read-only filesystem before test execution. No files changed.
+
+Census verdicts concern root authority; these approvals do not clear the functional findings above:
+
+| Unit or envelope | Verdict and evidence |
+|---|---|
+| `Conn.parse` | **Approve.** [Lines 243–313](internal/proxyproto/conn.go:243): classification changes; trust, marker and barrier checks remain. |
+| `Conn.sentAnything` | **Approve.** [Lines 354–378](internal/proxyproto/conn.go:354): reads one byte from the existing edge socket, then closes; no new root path or execution authority. `accepted-legacy` remains appropriate. |
+| `internal/edge` | **Approve.** [Sum](internal/edge/proxyingress.go:332) and [journal](internal/edge/proxyingress.go:407) only propagate the counter. |
+| `internal/host` | **Approve.** [Conversion and validation](internal/host/edgetrust.go:193), [root command handling](internal/host/edgetrust.go:534), and [serialization](internal/host/edgetrust.go:573) grant no root authority based on idle. Findings 1 and 3 remain required fixes. |
+| `internal/proxyproto` | **Approve.** [Parse and close paths](internal/proxyproto/conn.go:243) and [atomic snapshot](internal/proxyproto/counters.go:69) add no root-controlled resource access. Finding 2 remains required. |
+
+**NOT READY**
\ No newline at end of file
diff --git a/internal/host/edgetrust.go b/internal/host/edgetrust.go
index 5ed2eb7ac..0b06fa2e6 100644
--- a/internal/host/edgetrust.go
+++ b/internal/host/edgetrust.go
@@ -111,7 +111,10 @@ type trustCounters struct {
MarkerTrusted uint64 `json:"marker_trusted"`
Malformed uint64 `json:"malformed"`
Timeout uint64 `json:"timeout"`
- Idle uint64 `json:"idle"`
+ // Idle is nil when the running edge predates the counter: trust-status
+ // then prints no "idle", so a reader (ppv2-step.py refuses B steps on
+ // such a target) sees what the edge reports, not what this binary knows.
+ Idle *uint64 `json:"idle,omitempty"`
}
// trustStatus is GET /v1/edge/trust and trust-status's line. Counters and
@@ -204,7 +207,8 @@ func (c *trustCountersWire) counters() (trustCounters, bool) {
IgnoredPrivate: *c.IgnoredPrivate, MarkerTrusted: *c.MarkerTrusted, Malformed: *c.Malformed, Timeout: *c.Timeout,
}
if c.Idle != nil {
- out.Idle = *c.Idle
+ idle := *c.Idle
+ out.Idle = &idle
}
return out, true
}
@@ -214,8 +218,47 @@ func (c trustCounters) add(d trustCounters) trustCounters {
return trustCounters{
Proxied: c.Proxied + d.Proxied, NoClient: c.NoClient + d.NoClient, NoClientRefused: c.NoClientRefused + d.NoClientRefused,
Ignored: c.Ignored + d.Ignored, IgnoredPrivate: c.IgnoredPrivate + d.IgnoredPrivate, MarkerTrusted: c.MarkerTrusted + d.MarkerTrusted,
- Malformed: c.Malformed + d.Malformed, Timeout: c.Timeout + d.Timeout, Idle: c.Idle + d.Idle,
+ Malformed: c.Malformed + d.Malformed, Timeout: c.Timeout + d.Timeout, Idle: addIdle(c.Idle, d.Idle),
+ }
+}
+
+// addIdle sums two idle counts, nil when both are absent. Callers check
+// presence is consistent first (idleConsistent).
+func addIdle(a, b *uint64) *uint64 {
+ if a == nil && b == nil {
+ return nil
}
+ var v uint64
+ if a != nil {
+ v += *a
+ }
+ if b != nil {
+ v += *b
+ }
+ return &v
+}
+
+// equal is c == d by value, idle's presence included.
+func (c trustCounters) equal(d trustCounters) bool {
+ ci, di := c.Idle, d.Idle
+ c.Idle, d.Idle = nil, nil
+ if c != d || (ci == nil) != (di == nil) {
+ return false
+ }
+ return ci == nil || *ci == *di
+}
+
+// idleConsistent: an answer carries idle in its counters and in every
+// listener, or nowhere (an edge from before the counter). Anything else is
+// not one edge's snapshot.
+func (t *trustResult) idleConsistent() bool {
+ present := t.Counters != nil && t.Counters.Idle != nil
+ for _, l := range t.ByListener {
+ if l != nil && (l.Idle != nil) != present {
+ return false
+ }
+ }
+ return true
}
// statusShape is whether a status answer's instance and per-listener
@@ -230,7 +273,7 @@ func (t *trustResult) statusShape(armed bool, total trustCounters) bool {
if !armed {
return *t.EdgeInstance == "" && len(t.ByListener) == 0
}
- if *t.EdgeInstance == "" || len(t.ByListener) != len(trustListeners) {
+ if *t.EdgeInstance == "" || len(t.ByListener) != len(trustListeners) || !t.idleConsistent() {
return false
}
var sum trustCounters
@@ -249,7 +292,7 @@ func (t *trustResult) statusShape(armed bool, total trustCounters) bool {
byNode[a] += n
}
}
- if sum != total || len(byNode) != len(t.ProxiedByNode) {
+ if !sum.equal(total) || len(byNode) != len(t.ProxiedByNode) {
return false
}
for a, n := range byNode {
@@ -337,7 +380,7 @@ func trustCountersOf(c proxyproto.Counters) trustCounters {
return trustCounters{
Proxied: c.Proxied, NoClient: c.NoClient, NoClientRefused: c.NoClientRefused,
Ignored: c.Ignored, IgnoredPrivate: c.IgnoredPrivate, MarkerTrusted: c.MarkerTrusted,
- Malformed: c.Malformed, Timeout: c.Timeout, Idle: c.Idle,
+ Malformed: c.Malformed, Timeout: c.Timeout, Idle: &c.Idle,
}
}
@@ -357,6 +400,7 @@ func trustStatusOf(e trustEdge) trustStatus {
ByListener: map[string]trustListener{}}
if !armed {
s.EdgeInstance = ""
+ s.Counters = trustCountersOf(proxyproto.Counters{})
s.ProxiedByNode = map[string]uint64{}
return s
}
diff --git a/internal/host/edgetrust_test.go b/internal/host/edgetrust_test.go
index 6a8da4f54..28a68d3ef 100644
--- a/internal/host/edgetrust_test.go
+++ b/internal/host/edgetrust_test.go
@@ -495,6 +495,15 @@ func TestEdgeTrustVerbAnswers(t *testing.T) {
{"status, a counter missing", drainCallResult{V: 1, Trust: &trustResult{Armed: &armed, Barrier: &down, Counters: &trustCountersWire{Proxied: new(uint64)}, ProxiedByNode: map[string]uint64{}}}, nil, "", 0, []string{"trust-status"}, 1, "", "edge: the agent answered nothing usable\n"},
{"barrier, no closed", drainCallResult{V: 1, Trust: &trustResult{Barrier: &up}}, nil, "", 0, []string{"trust-barrier"}, 1, "", "edge: the agent answered nothing usable\n"},
{"status", drainCallResult{V: 1, Trust: status}, nil, "", 0, []string{"trust-status"}, 0, zeroStatusJSON + "\n", ""},
+ // An older edge sends no idle; the line printed for ppv2-step.py must
+ // not invent one (it refuses B steps on such a target).
+ {"status, older edge", drainCallResult{V: 1, Trust: withoutIdle(zeroStatusWire(true))}, nil, "", 0, []string{"trust-status"}, 0,
+ strings.ReplaceAll(zeroStatusJSON, `,"idle":0`, "") + "\n", ""},
+ {"status, idle in some places only", drainCallResult{V: 1, Trust: func() *trustResult {
+ t := zeroStatusWire(true)
+ t.ByListener["80"].Idle = nil
+ return t
+ }()}, nil, "", 0, []string{"trust-status"}, 1, "", "edge: the agent answered nothing usable\n"},
{"status unarmed", drainCallResult{V: 1, Trust: unarmedStatus}, nil, "", 0, []string{"trust-status"}, 2, unarmedStatusJSON + "\n",
"edge: this box is not armed for PROXY protocol\n"},
{"barrier unarmed", drainCallResult{V: 1, Trust: &trustResult{Armed: &notArmed, Barrier: &down}}, nil, "", 0, []string{"trust-barrier"}, 2, "", "edge: this box is not armed for PROXY protocol\n"},
@@ -551,12 +560,22 @@ func zeroStatusWire(armed bool) *trustResult {
// zeroCountersWire is a status answer's counters, every one present.
func zeroCountersWire() *trustCountersWire {
z := func() *uint64 { return new(uint64) }
- return &trustCountersWire{Proxied: z(), NoClient: z(), NoClientRefused: z(), Ignored: z(), IgnoredPrivate: z(), MarkerTrusted: z(), Malformed: z(), Timeout: z()}
+ return &trustCountersWire{Proxied: z(), NoClient: z(), NoClientRefused: z(), Ignored: z(), IgnoredPrivate: z(), MarkerTrusted: z(), Malformed: z(), Timeout: z(), Idle: z()}
+}
+
+// withoutIdle is t as an edge from before the idle counter answers it.
+func withoutIdle(t *trustResult) *trustResult {
+ t.Counters.Idle = nil
+ for _, l := range t.ByListener {
+ l.Idle = nil
+ }
+ return t
}
// TestTrustStatusIdleOptional: an edge from before the idle counter (still
// running while a newer binary asks during an update) sends no "idle"; its
-// status is accepted with idle read as zero. Every other counter stays
+// status is accepted and printed without idle, so a reader sees what the
+// edge reports. Idle is in every place or none; every other counter stays
// required.
func TestTrustStatusIdleOptional(t *testing.T) {
old := strings.ReplaceAll(trustStatusFixtureJSON, `,"idle":0`, "")
@@ -570,9 +589,12 @@ func TestTrustStatusIdleOptional(t *testing.T) {
if a, err := validTrust("trust-status", &r); err != nil || a != trustAnswerStatus {
t.Fatalf("old edge status: answer %v, err %v; want accepted", a, err)
}
- if line := trustStatusLine(&r); line.Counters.Idle != 0 || line.Counters.Timeout != 7 {
+ if line := trustStatusLine(&r); line.Counters.Idle != nil || line.ByListener["80"].Idle != nil || line.Counters.Timeout != 7 {
t.Fatalf("old edge status line counters = %+v", line.Counters)
}
+ if b, err := json.Marshal(trustStatusLine(&r)); err != nil || strings.Contains(string(b), "idle") {
+ t.Fatalf("old edge status line prints idle: %s %v", b, err)
+ }
withIdle := strings.Replace(strings.Replace(strings.Replace(trustStatusFixtureJSON,
`"timeout":7,"idle":0`, `"timeout":7,"idle":5`, 1),
@@ -585,9 +607,22 @@ func TestTrustStatusIdleOptional(t *testing.T) {
if a, err := validTrust("trust-status", &n); err != nil || a != trustAnswerStatus {
t.Fatalf("status with idle: answer %v, err %v; want accepted", a, err)
}
- if line := trustStatusLine(&n); line.Counters.Idle != 5 || line.ByListener["80"].Idle != 3 {
+ if line := trustStatusLine(&n); line.Counters.Idle == nil || *line.Counters.Idle != 5 || *line.ByListener["80"].Idle != 3 {
t.Fatalf("status with idle counters = %+v", line.Counters)
}
+ for _, mixed := range []string{
+ strings.Replace(withIdle, `"timeout":3,"idle":3`, `"timeout":3`, 1), // a listener without it
+ strings.Replace(strings.Replace(withIdle, `"timeout":7,"idle":5`, `"timeout":7`, 1), `,"idle":2`, ``, 1), // the total without it
+ strings.Replace(trustStatusFixtureJSON, `"timeout":7,"idle":0`, `"timeout":7`, 1), // zeros, total missing
+ } {
+ var x trustResult
+ if err := json.Unmarshal([]byte(mixed), &x); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := validTrust("trust-status", &x); err == nil {
+ t.Fatalf("idle present in some places only accepted: %s", mixed)
+ }
+ }
noTimeout := strings.Replace(trustStatusFixtureJSON, `"timeout":7,`, "", 1)
var m trustResult
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index dab43bebf..957063bd4 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -240,4 +240,4 @@ plan14-root-reads-audit-aws-timeouts.tsv c3e74a3069651a7ae638b2ecba5e38c4dbaec28
plan14-root-reads-config-receipts-1.tsv 4abde13ec40d53a479684b7f1e2079fbedb6c40cb1a28819c97853cdab768b2f
plan14-root-reads-audit-edge-test-sleeps.tsv 4abde13ec40d53a479684b7f1e2079fbedb6c40cb1a28819c97853cdab768b2f
plan14-root-reads-ha-generations-floor.tsv 7ca068c5c146a679b4726d74fe43cf9c47f97080f9c08b761a36a9a12a5a3c54
-plan14-root-reads-edge-ppv2-idle.tsv f5c0ad32db5ee003f16ba314d7083e416cc18578d802ace49233f31afb7d164a
+plan14-root-reads-edge-ppv2-idle.tsv d339e42410d313e010f3abba883235e0a9a697a6cb11ed3652952093919f1e8a
diff --git a/internal/provision/testdata/plan14-root-reads-edge-ppv2-idle.tsv b/internal/provision/testdata/plan14-root-reads-edge-ppv2-idle.tsv
index 034f92dde..dfc25978e 100644
--- a/internal/provision/testdata/plan14-root-reads-edge-ppv2-idle.tsv
+++ b/internal/provision/testdata/plan14-root-reads-edge-ppv2-idle.tsv
@@ -2,9 +2,9 @@
# 1 body, 0 sites, 3 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
# 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
@legacy 617bff46b6ba2741c56456fd1b5d9a0c31c779a4839831e81f7fb8919eff4a7a internal/proxyproto/conn.go Conn.parse legacy accepted-legacy accepted-legacy;rev3=census-ruling-edge-ppv2;basis=Edge (uid carlos), not root. Detects the signature, reads at most one header with ReadHeader (under the header deadline on a trusted peer), and resolves the connection's state (an untrusted peer: plain, or failed on a malformed header; a trusted one: proxied, no client or failed), consulting the barrier flag when it resolves. The scanner's +file:Command is the comparison h.Command != CommandProxy (the header's command nibble), not a process; no file, nothing run.;rev3=census-ruling-edge-ppv2-idle;basis=A trusted connection whose header read times out with no byte read, and sentAnything finds no byte either, closes and counts idle instead of timeout. Same close, same state (failed); no new read beyond sentAnything. Edge (uid carlos), not root. file:Command@1392 c113ea15ffb11367ee475f92010a612931fcce8d7fb37bfbc980dd6afa46e670
-@legacy 85184aecd4251f100e63e2dc38b22c44d293921fc032bfad6fd278e3c56ffb5e internal/proxyproto/conn.go Conn.sentAnything legacy accepted-legacy accepted-legacy;rev3=census-ruling-edge-ppv2-idle;basis=New. On a trusted connection about to be closed after a header-deadline timeout with nothing read: sets a 5 ms read deadline on the accepted socket and reads at most one byte from it, to tell an idle connection from one whose bytes arrived after the deadline had passed. The byte is dropped; the connection is closed straight after. Reads only the already accepted network connection; no file, no path, nothing run. Edge (uid carlos), not root. file:Read@113 c04a314029bdde08d4c60b2c2bfae53e15a4f2f75d0ed8b3d92c36656cc3c50a
+@legacy 1ddf544181054206e69248a86d15ec7c4bc7e42e2533a417f577dc5858cadf09 internal/proxyproto/peek_unix.go queuedBytes legacy accepted-legacy accepted-legacy;rev3=census-ruling-edge-ppv2-idle;basis=New. One recv(MSG_PEEK|MSG_DONTWAIT) of one byte on the already accepted socket through syscall.RawConn, never waiting; consumes nothing. No file, no path, nothing run; known=false on any unexpected error. Edge (uid carlos), not root. file:Read@237 71030cc4f0df9764846ee6ccdcbc635503668998ca4623972bd485f92fa2a629
internal/proxyproto/conn.go Conn.parse legacy accepted-legacy accepted-legacy;rev3=census-ruling-edge-ppv2;basis=Edge (uid carlos), not root. Detects the signature, reads at most one header with ReadHeader (under the header deadline on a trusted peer), and resolves the connection's state (an untrusted peer: plain, or failed on a malformed header; a trusted one: proxied, no client or failed), consulting the barrier flag when it resolves. The scanner's +file:Command is the comparison h.Command != CommandProxy (the header's command nibble), not a process; no file, nothing run.;rev3=census-ruling-edge-ppv2-idle;basis=A trusted connection whose header read times out with no byte read, and sentAnything finds no byte either, closes and counts idle instead of timeout. Same close, same state (failed); no new read beyond sentAnything. Edge (uid carlos), not root. file:Command@1392 c113ea15ffb11367ee475f92010a612931fcce8d7fb37bfbc980dd6afa46e670
-internal/proxyproto/conn.go Conn.sentAnything legacy accepted-legacy accepted-legacy;rev3=census-ruling-edge-ppv2-idle;basis=New. On a trusted connection about to be closed after a header-deadline timeout with nothing read: sets a 5 ms read deadline on the accepted socket and reads at most one byte from it, to tell an idle connection from one whose bytes arrived after the deadline had passed. The byte is dropped; the connection is closed straight after. Reads only the already accepted network connection; no file, no path, nothing run. Edge (uid carlos), not root. file:Read@113 c04a314029bdde08d4c60b2c2bfae53e15a4f2f75d0ed8b3d92c36656cc3c50a
+internal/proxyproto/peek_unix.go queuedBytes legacy accepted-legacy accepted-legacy;rev3=census-ruling-edge-ppv2-idle;basis=New. One recv(MSG_PEEK|MSG_DONTWAIT) of one byte on the already accepted socket through syscall.RawConn, never waiting; consumes nothing. No file, no path, nothing run; known=false on any unexpected error. Edge (uid carlos), not root. file:Read@237 71030cc4f0df9764846ee6ccdcbc635503668998ca4623972bd485f92fa2a629
@coverage internal/edge 5daba01cf2b64bca76359ec8fe240cbe0964555e681ebce6042a10a5f670de22
-@coverage internal/host 77b8af2eae59f5402e406bbd19659f82e5bd612946515e1c6b1c7c4dfeb63119
-@coverage internal/proxyproto 75dd4fd8131e3d2f9a934f1a61466ac86f50a8eca2fa550fd611feeb67eba441
+@coverage internal/host 9f7d69fa65e6945e38ee6c275634e6a3fe113dc10dfc10ddc8b0a2e4de1d5634
+@coverage internal/proxyproto f39d92b91a54e98e9e5b47576a18e206a66cde4bcf8542b9c679b0b875a6803e
diff --git a/internal/proxyproto/conn.go b/internal/proxyproto/conn.go
index 920d82ee1..457dc7a7e 100644
--- a/internal/proxyproto/conn.go
+++ b/internal/proxyproto/conn.go
@@ -351,18 +351,19 @@ func (c *Conn) fail(cause error) State {
return c.close(cause)
}
-// idleCheck bounds sentAnything's one read.
-const idleCheck = 5 * time.Millisecond
-
// sentAnything reports whether the peer had sent a byte that the header
// read never saw: a read whose deadline had already passed when the parse
// began (it starts on the first Read, not at accept) fails without reading.
-// Only for a connection about to be closed; the byte read is dropped.
+// It peeks without a deadline (queuedBytes), so scheduling delay cannot make
+// queued bytes look absent, and when it cannot tell it answers true: such a
+// connection counts as timeout, never idle.
func (c *Conn) sentAnything() bool {
- c.inner.SetReadDeadline(time.Now().Add(idleCheck))
- var b [1]byte
- m, _ := c.inner.Read(b[:])
- return m == 1
+ // The header deadline has passed; RawConn.Read would refuse before the
+ // peek. The connection is closed right after, and endHeaderDeadline
+ // restores the caller's deadline in any case.
+ c.inner.SetReadDeadline(time.Time{})
+ queued, known := queuedBytes(c.inner)
+ return queued || !known
}
// failIdle closes a trusted connection that sent nothing before its header
diff --git a/internal/proxyproto/peek_other.go b/internal/proxyproto/peek_other.go
new file mode 100644
index 000000000..911ba6762
--- /dev/null
+++ b/internal/proxyproto/peek_other.go
@@ -0,0 +1,9 @@
+//go:build !unix
+
+package proxyproto
+
+import "net"
+
+// queuedBytes cannot tell on this system; callers treat that as bytes
+// present, so nothing is counted idle.
+func queuedBytes(net.Conn) (queued, known bool) { return false, false }
diff --git a/internal/proxyproto/peek_unix.go b/internal/proxyproto/peek_unix.go
new file mode 100644
index 000000000..332fb3f6f
--- /dev/null
+++ b/internal/proxyproto/peek_unix.go
@@ -0,0 +1,46 @@
+//go:build unix
+
+package proxyproto
+
+import (
+ "errors"
+ "net"
+ "syscall"
+
+ "golang.org/x/sys/unix"
+)
+
+// queuedBytes reports whether conn's socket holds unread bytes, without
+// reading them and without waiting: one recv with MSG_PEEK|MSG_DONTWAIT on
+// the raw descriptor. No read deadline takes part, so how late the caller
+// runs cannot hide bytes already queued. known is false when it cannot
+// tell (not a socket, or an unexpected error); callers treat that as bytes
+// present.
+func queuedBytes(conn net.Conn) (queued, known bool) {
+ sc, ok := conn.(syscall.Conn)
+ if !ok {
+ return false, false
+ }
+ rc, err := sc.SyscallConn()
+ if err != nil {
+ return false, false
+ }
+ var (
+ n int
+ rerr error
+ )
+ if err := rc.Read(func(fd uintptr) bool {
+ var b [1]byte
+ n, _, rerr = unix.Recvfrom(int(fd), b[:], unix.MSG_PEEK|unix.MSG_DONTWAIT)
+ return true // never wait for readiness
+ }); err != nil {
+ return false, false
+ }
+ switch {
+ case rerr == nil:
+ return n > 0, true // n == 0: the peer closed having sent nothing
+ case errors.Is(rerr, unix.EAGAIN), errors.Is(rerr, unix.EWOULDBLOCK):
+ return false, true
+ }
+ return false, false
+}
diff --git a/internal/proxyproto/peek_unix_test.go b/internal/proxyproto/peek_unix_test.go
new file mode 100644
index 000000000..8da52d1f2
--- /dev/null
+++ b/internal/proxyproto/peek_unix_test.go
@@ -0,0 +1,66 @@
+//go:build unix
+
+package proxyproto
+
+import (
+ "net"
+ "testing"
+ "time"
+)
+
+// TestQueuedBytes: the peek sees queued bytes without consuming them and
+// none on a silent connection. With an expired read deadline still on the
+// socket it cannot peek and says so (known false, which callers count as
+// bytes present); sentAnything clears the deadline first.
+func TestQueuedBytes(t *testing.T) {
+ inner, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer inner.Close()
+ client, err := net.Dial("tcp", inner.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer client.Close()
+ server, err := inner.Accept()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer server.Close()
+
+ if queued, known := queuedBytes(server); queued || !known {
+ t.Fatalf("silent: queued %v known %v, want false true", queued, known)
+ }
+ if _, err := client.Write([]byte("x")); err != nil {
+ t.Fatal(err)
+ }
+ server.SetReadDeadline(time.Now().Add(-time.Second))
+ if _, known := queuedBytes(server); known {
+ t.Fatal("known true under an expired read deadline")
+ }
+ server.SetReadDeadline(time.Time{})
+ deadline := time.Now().Add(time.Second)
+ for {
+ queued, known := queuedBytes(server)
+ if !known {
+ t.Fatal("known false on a TCP socket")
+ }
+ if queued {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("written byte never seen")
+ }
+ time.Sleep(time.Millisecond)
+ }
+ b := make([]byte, 1)
+ if n, err := server.Read(b); n != 1 || b[0] != 'x' || err != nil {
+ t.Fatalf("peek consumed the byte: %d %q %v", n, b[:n], err)
+ }
+ client.Close()
+ time.Sleep(20 * time.Millisecond)
+ if queued, known := queuedBytes(server); queued || !known {
+ t.Fatalf("closed by peer: queued %v known %v, want false true", queued, known)
+ }
+}