carlos / platform Public

Merge remote-tracking branch 'origin/main' into feat/platform-mail-submission

# Conflicts:
#	internal/provision/testdata/plan14-root-reads-chain.tsv
Paul Campbell pushed by paul@keymail.dev 1de971f59a2c5a65d969338eeef1ecbcc437bc6d parent 05591a0parent 0ac7576
12 files changed, +509 −9
  • docs/superpowers/notes/census-proposal-fleet-tunnel-tls-state.md +11 −0
  • docs/superpowers/notes/census-proposal-platform-mail-submission.md +1 −1
  • docs/superpowers/notes/census-proposal-replica-console-account.md +19 −0
  • internal/edge/edge.go +13 −1
  • internal/edge/replicaconsole.go +96 −4
  • internal/edge/replicaconsole_test.go +171 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +3 −1
  • internal/provision/testdata/plan14-root-reads-fleet-tunnel-tls-state.tsv +3 −0
  • internal/provision/testdata/plan14-root-reads-replica-console-account.tsv +5 −0
  • internal/tunnelclient/tlsstate_test.go +145 −0
  • internal/tunnelclient/tunnelclient.go +41 −1
  • internal/tunnelclient/upgrade.go +1 −1
diff --git a/docs/superpowers/notes/census-proposal-fleet-tunnel-tls-state.md b/docs/superpowers/notes/census-proposal-fleet-tunnel-tls-state.md
new file mode 100644
index 000000000..755f68b8a
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-fleet-tunnel-tls-state.md
@@ -0,0 +1,11 @@
+# Census approval: fleet-tunnel-tls-state
+
+Ruling `census-ruling-fleet-tunnel-tls-state`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+Envelopes re-pinned: `internal/tunnelclient`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Seal: `846d1f22e6eb6b2cd8b3086fa554f15deba70418c6542b46b2e2a6a138b6c332` → `846d1f22e6eb6b2cd8b3086fa554f15deba70418c6542b46b2e2a6a138b6c332`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-fleet-tunnel-tls-state.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-proposal-platform-mail-submission.md b/docs/superpowers/notes/census-proposal-platform-mail-submission.md
index b7ae69f38..9f39a9dbc 100644
--- a/docs/superpowers/notes/census-proposal-platform-mail-submission.md
+++ b/docs/superpowers/notes/census-proposal-platform-mail-submission.md
@@ -86,6 +86,6 @@ New dispositions, which census-propose wrote and the reviewer checks against the
- new `internal/mailsubmit/forward.go:SocketForwarder.Send`: reads +file:ReadAll; written legacy, accepted-legacy, frozen
- new `internal/mailsubmit/verb.go:Mount`: reads +registry:App, +registry:Host, +whole:Route; written legacy, accepted-legacy, frozen
-Seal: `846d1f22e6eb6b2cd8b3086fa554f15deba70418c6542b46b2e2a6a138b6c332` → `72eca621463fbdb5c15b2f273b443bc9e931c67266329b124664dc4220240814`.
+Seal: `87e151a55efb12fb84e9c5939f2ead9058527d8213e2eb16ee6c0f109787bb16` → `b782f324a4791147024602f46ab73eab48a589ae3ab9a5035d56a722c92da50e`.
Overlay: `internal/provision/testdata/plan14-root-reads-platform-mail-submission.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-proposal-replica-console-account.md b/docs/superpowers/notes/census-proposal-replica-console-account.md
new file mode 100644
index 000000000..975028b18
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-replica-console-account.md
@@ -0,0 +1,19 @@
+# Census approval: replica-console-account
+
+Ruling `census-ruling-replica-console-account`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/edge/replicaconsole.go` `Edge.serveReplicaConsole` | body | unchanged (6) | when operator config CARLOS_REPLICA_CONSOLE_ADDR (hub host.env, read once in enableTunnelsFromEnv, refused at load unless a literal loopback IP and port) is set, replica calls go to a proxy built only from that address, stamping the hub build as X-Carlos-Version; no route field is read, so records can neither choose, redirect nor disable the endpoint. Unset, the selection is byte-identical to main (accountless console.service local route). Witnesses TestReplicaConsoleConfiguredEndpoint (distinct destinations, injected and rewritten rows, endpoint down), TestReplicaConsoleUnconfiguredIgnoresAccountRows, TestParseReplicaConsoleAddr, TestReplicaConsoleAddrFromHostEnv. Same reads, no new read source, no write. |
+
+Envelopes re-pinned: `internal/edge`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/edge/replicaconsole.go` `Edge.serveReplicaConsole`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-stateless-coordinator-route;basis=Reads existing in-memory route fields to select a unique accountless console.service local upstream; refuses missing or ambiguous console, tenant routes, remote and tunnel upstreams. Reuses proxy and version wrapper; leaves fleet identity authentication at console.;rev3=census-ruling-retry-after-503;basis=the missing/ambiguous-console 503s go through UnavailableHeader (adds Retry-After 2 and answer/box headers); selection unchanged; no read added
+
+Seal: `846d1f22e6eb6b2cd8b3086fa554f15deba70418c6542b46b2e2a6a138b6c332` → `87e151a55efb12fb84e9c5939f2ead9058527d8213e2eb16ee6c0f109787bb16`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-replica-console-account.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 57e8ca19c..f6fc9eadb 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -115,7 +115,11 @@ type Activator interface {
// its backend. The host→backend map is swapped atomically, so reloads and
// zero-downtime deploys never drop a live connection.
type Edge struct {
- shutdownStarted func(time.Time)
+ shutdownStarted func(time.Time)
+ // replicaConsole forwards fleet replica calls to the operator-configured
+ // console endpoint (replicaConsoleAddrEnv); nil uses the accountless
+ // console.service route. Set before serving.
+ replicaConsole http.Handler
haIngress atomic.Pointer[haIngressLookup]
haIngressBlocked atomic.Pointer[map[string]bool]
// ReplicaProbe is configured before the first syncReplicaProbes call.
@@ -5453,6 +5457,14 @@ func enableTunnelsFromEnv(e *Edge) error {
return fmt.Errorf("CARLOS_TUNNEL_CLIENTS: %q is not a valid tunnel name — want [a-z0-9-]{1,32}, and it must match a route's --tunnel to carry anything", name)
}
}
+ consoleAddr, err := parseReplicaConsoleAddr(os.Getenv(replicaConsoleAddrEnv))
+ if err != nil {
+ return err
+ }
+ if consoleAddr != "" {
+ e.replicaConsole = newReplicaConsoleProxy(consoleAddr)
+ log.Printf("edge: fleet replica calls go to the console at %s (%s)", consoleAddr, replicaConsoleAddrEnv)
+ }
e.EnableTunnels(NewTunnelHub(host, clients))
// Rebuild the route table so tunnel-backed routes that were skipped (or
// left on their old socket/addr) by the startup reload pick up the hub,
diff --git a/internal/edge/replicaconsole.go b/internal/edge/replicaconsole.go
index 6af26c9f5..508310010 100644
--- a/internal/edge/replicaconsole.go
+++ b/internal/edge/replicaconsole.go
@@ -1,11 +1,103 @@
package edge
-import "net/http"
+import (
+ "fmt"
+ "net"
+ "net/http"
+ "net/http/httputil"
+ "net/netip"
+ "strconv"
+ "strings"
+ "time"
-// serveReplicaConsole reuses the local console route, including its version
-// header. Only POSTs on the reserved tunnel host enter here; other methods
-// keep the hub's 404. Authentication remains the console's fleetIdentityOK.
+ "github.com/carlosframework/platform/internal/version"
+)
+
+// replicaConsoleAddrEnv names, in the hub's host.env, the loopback address
+// of the console process the hub hands fleet boxes' replica calls to. It is
+// operator configuration, and the only source trusted for that endpoint:
+// route rows come from deployment records, and records are not a tenancy
+// boundary (a legacy direct-S3 fleet box can write them), so no route field
+// may choose, redirect or disable where those calls and their fleet bearer
+// tokens go. A self-hosted deployment whose console is installed into its
+// operator account sets it (Tito: 127.0.0.1:8090); the platform's own hubs
+// need not.
+const replicaConsoleAddrEnv = "CARLOS_REPLICA_CONSOLE_ADDR"
+
+// WithReplicaConsoleAddr configures the replica console endpoint (tests;
+// the process reads replicaConsoleAddrEnv in enableTunnelsFromEnv). addr
+// must already have passed parseReplicaConsoleAddr.
+func WithReplicaConsoleAddr(addr string) RunOption {
+ return func(e *Edge) { e.replicaConsole = newReplicaConsoleProxy(addr) }
+}
+
+// parseReplicaConsoleAddr checks replicaConsoleAddrEnv's value: unset is ""
+// and no error; otherwise a literal loopback IP and a port, so the endpoint
+// is always this box's own process. A host name (localhost included) or any
+// other address fails the boot, naming the variable.
+func parseReplicaConsoleAddr(raw string) (string, error) {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return "", nil
+ }
+ host, port, err := net.SplitHostPort(raw)
+ if err != nil {
+ return "", fmt.Errorf("%s: %q is not ip:port: %v", replicaConsoleAddrEnv, raw, err)
+ }
+ ip, err := netip.ParseAddr(host)
+ if err != nil || !ip.IsLoopback() || ip.Zone() != "" {
+ return "", fmt.Errorf("%s: %q must be a loopback IP address, such as 127.0.0.1:8090", replicaConsoleAddrEnv, raw)
+ }
+ if n, err := strconv.Atoi(port); err != nil || n < 1 || n > 65535 {
+ return "", fmt.Errorf("%s: %q has no valid port", replicaConsoleAddrEnv, raw)
+ }
+ return net.JoinHostPort(ip.String(), port), nil
+}
+
+// newReplicaConsoleProxy forwards replica calls to the configured console
+// endpoint. Nothing in it comes from route data: the upstream is addr, and
+// X-Carlos-Version, which the box reads only as proof that the console
+// answered (internal/host replicaCoordinatorAPI.post), is this hub's own
+// build. A failed dial answers 502 with no version, which the box reads as
+// the console unreachable.
+func newReplicaConsoleProxy(addr string) http.Handler {
+ return &httputil.ReverseProxy{
+ Rewrite: func(pr *httputil.ProxyRequest) {
+ setForwarded(pr)
+ pr.Out.URL.Scheme = "http"
+ pr.Out.URL.Host = addr
+ pr.Out.Host = pr.In.Host
+ },
+ Transport: &http.Transport{
+ DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext,
+ MaxIdleConns: 8,
+ IdleConnTimeout: 90 * time.Second,
+ ResponseHeaderTimeout: 30 * time.Second,
+ },
+ ModifyResponse: func(resp *http.Response) error {
+ resp.Header.Set("X-Carlos-Version", version.Build)
+ return nil
+ },
+ ErrorHandler: func(w http.ResponseWriter, _ *http.Request, _ error) {
+ w.WriteHeader(http.StatusBadGateway)
+ },
+ }
+}
+
+// serveReplicaConsole hands a box's replica call to the console. Only POSTs
+// on the reserved tunnel host enter here; other methods keep the hub's 404.
+// Authentication remains the console's fleetIdentityOK.
+//
+// With replicaConsoleAddrEnv set, the call goes to that endpoint and route
+// data plays no part. Unset, the console is the one route for app console
+// with unit console.service and no account (the platform console's shape),
+// on a loopback upstream or a socket, not an alias, regional, via a tunnel
+// or activator-owned, and its proxy (with its version header) is reused.
func (e *Edge) serveReplicaConsole(w http.ResponseWriter, r *http.Request) {
+ if e.replicaConsole != nil {
+ e.replicaConsole.ServeHTTP(w, e.withForwardKey(r))
+ return
+ }
var console http.Handler
for host, up := range *e.upstreams.Load() {
rt := up.route
diff --git a/internal/edge/replicaconsole_test.go b/internal/edge/replicaconsole_test.go
index 277102b77..f665415a6 100644
--- a/internal/edge/replicaconsole_test.go
+++ b/internal/edge/replicaconsole_test.go
@@ -100,3 +100,174 @@ func TestFleetReplicaConsoleOnTunnelHost(t *testing.T) {
t.Fatalf("tenant console: %d", w.Code)
}
}
+
+// TestReplicaConsoleConfiguredEndpoint (#511): with CARLOS_REPLICA_CONSOLE_ADDR
+// set, a box's replica call goes to that endpoint and nowhere else, whatever
+// the registry holds. Route rows come from deployment records, which a
+// legacy direct-S3 fleet box can write: an injected console.service row, a
+// system console row, or the configured console's own row rewritten to
+// another loopback port neither take the call nor make it ambiguous. The
+// version header the box needs is the hub's build, never a route's.
+func TestReplicaConsoleConfiguredEndpoint(t *testing.T) {
+ server := func(name string, hits *atomic.Int32) *httptest.Server {
+ s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ hits.Add(1)
+ if r.Header.Get("Authorization") != "Bearer fleet-token" || r.URL.Path != "/api/fleet/replicas/a/app/h/coordinator" {
+ t.Errorf("%s got %s %v", name, r.URL, r.Header)
+ }
+ _, _ = io.WriteString(w, name)
+ }))
+ t.Cleanup(s.Close)
+ return s
+ }
+ var configuredHits, systemHits, injectedHits, rewrittenHits atomic.Int32
+ configured := server("configured", &configuredHits)
+ system := server("system", &systemHits)
+ injected := server("injected", &injectedHits)
+ rewritten := server("rewritten", &rewrittenHits)
+ addr, err := parseReplicaConsoleAddr(configured.Listener.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ reg := openReg(t)
+ rows := []registry.Route{
+ // Tito's shape: the console row in its operator account, at the
+ // configured address, plus the platform row for the same app.
+ {Host: "console.staging.example.com", Account: "bab", App: "console", Unit: "console.service", Kind: "instance", Addr: addr, Status: "ready", Version: "route-version"},
+ {Host: "console.bab.staging.example.com", Account: "bab", App: "console", Kind: "instance", Addr: addr, Status: "ready", Platform: true},
+ {Host: "console.test", App: "console", Unit: "console.service", Kind: "instance", Addr: system.Listener.Addr().String(), Status: "ready", Version: "route-version"},
+ {Host: "injected.test", Account: "x", App: "console", Unit: "console.service", Kind: "instance", Addr: injected.Listener.Addr().String(), Status: "ready", Version: "route-version"},
+ }
+ for _, rt := range rows {
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ }
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer e.probers.Stop()
+ WithReplicaConsoleAddr(addr)(e)
+ e.EnableTunnels(NewTunnelHub("tunnel.test", nil))
+ post := func() *httptest.ResponseRecorder {
+ t.Helper()
+ req := httptest.NewRequest("POST", "https://tunnel.test/api/fleet/replicas/a/app/h/coordinator", strings.NewReader(`{"op":"acquire"}`))
+ req.Header.Set("Authorization", "Bearer fleet-token")
+ w := httptest.NewRecorder()
+ e.ServeHTTP(w, req)
+ return w
+ }
+ check := func(stage string) {
+ t.Helper()
+ w := post()
+ if w.Code != 200 || w.Body.String() != "configured" {
+ t.Fatalf("%s: %d %q", stage, w.Code, w.Body.String())
+ }
+ if v := w.Header().Get("X-Carlos-Version"); v == "" || v == "route-version" {
+ t.Fatalf("%s: version header %q, want the hub's build", stage, v)
+ }
+ }
+ check("configured")
+ // The configured console's own row rewritten to another loopback
+ // port, as a record writer could: the call still goes to the endpoint.
+ rows[0].Addr = rewritten.Listener.Addr().String()
+ if err := reg.Upsert(rows[0]); err != nil {
+ t.Fatal(err)
+ }
+ if err := e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ check("row rewritten")
+ if systemHits.Load()+injectedHits.Load()+rewrittenHits.Load() != 0 {
+ t.Fatalf("route upstreams reached: system %d injected %d rewritten %d", systemHits.Load(), injectedHits.Load(), rewrittenHits.Load())
+ }
+ // The endpoint down: 502 with no version, which the box reads as the
+ // console unreachable; no route upstream stands in.
+ configured.Close()
+ if w := post(); w.Code != http.StatusBadGateway || w.Header().Get("X-Carlos-Version") != "" {
+ t.Fatalf("endpoint down: %d %q", w.Code, w.Header().Get("X-Carlos-Version"))
+ }
+ if systemHits.Load()+injectedHits.Load()+rewrittenHits.Load() != 0 {
+ t.Fatal("a route upstream stood in for the configured endpoint")
+ }
+}
+
+// TestReplicaConsoleUnconfiguredIgnoresAccountRows: without the setting, an
+// account-owned console.service row beside the system console neither takes
+// the call nor makes it ambiguous, and alone it is not the console.
+func TestReplicaConsoleUnconfiguredIgnoresAccountRows(t *testing.T) {
+ var systemHits, ownedHits atomic.Int32
+ system := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { systemHits.Add(1) }))
+ defer system.Close()
+ owned := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ownedHits.Add(1) }))
+ defer owned.Close()
+ ownedRow := registry.Route{Host: "console.staging.example.com", Account: "bab", App: "console", Unit: "console.service", Kind: "instance", Addr: owned.Listener.Addr().String(), Status: "ready", Version: "v"}
+ systemRow := registry.Route{Host: "console.test", App: "console", Unit: "console.service", Kind: "instance", Addr: system.Listener.Addr().String(), Status: "ready", Version: "v"}
+ for _, tc := range []struct {
+ name string
+ rows []registry.Route
+ code int
+ answer string
+ }{
+ {"system beside account-owned", []registry.Route{systemRow, ownedRow}, 200, ""},
+ {"account-owned alone", []registry.Route{ownedRow}, 503, "replica-console-missing"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ systemHits.Store(0)
+ ownedHits.Store(0)
+ reg := openReg(t)
+ for _, rt := range tc.rows {
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ }
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer e.probers.Stop()
+ e.EnableTunnels(NewTunnelHub("tunnel.test", nil))
+ w := httptest.NewRecorder()
+ e.ServeHTTP(w, httptest.NewRequest("POST", "https://tunnel.test/api/fleet/replicas/a/app/h/coordinator", strings.NewReader(`{}`)))
+ if w.Code != tc.code || w.Header().Get("X-Carlos-Answer") != tc.answer || ownedHits.Load() != 0 || (systemHits.Load() == 1) != (tc.code == 200) {
+ t.Fatalf("%d %q system %d owned %d", w.Code, w.Header().Get("X-Carlos-Answer"), systemHits.Load(), ownedHits.Load())
+ }
+ })
+ }
+}
+
+func TestParseReplicaConsoleAddr(t *testing.T) {
+ for in, want := range map[string]string{"": "", " 127.0.0.1:8090 ": "127.0.0.1:8090", "[::1]:8090": "[::1]:8090", "127.0.0.2:1": "127.0.0.2:1"} {
+ got, err := parseReplicaConsoleAddr(in)
+ if err != nil || got != want {
+ t.Errorf("%q: %q %v", in, got, err)
+ }
+ }
+ for _, bad := range []string{"localhost:8090", "10.0.0.1:8090", "0.0.0.0:8090", "console.example.com:8090", "127.0.0.1", "127.0.0.1:0", "127.0.0.1:65536", "127.0.0.1:http", "http://127.0.0.1:8090", "[fe80::1%eth0]:8090"} {
+ if got, err := parseReplicaConsoleAddr(bad); err == nil {
+ t.Errorf("%q accepted as %q", bad, got)
+ }
+ }
+}
+
+// TestReplicaConsoleAddrFromHostEnv: the hub reads the setting when it arms
+// its tunnels, and a bad value fails the boot.
+func TestReplicaConsoleAddrFromHostEnv(t *testing.T) {
+ reg := openReg(t)
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer e.probers.Stop()
+ t.Setenv("CARLOS_FLEET", "")
+ t.Setenv("CARLOS_TUNNEL_HOST", "tunnel.test")
+ t.Setenv(replicaConsoleAddrEnv, "10.0.0.1:8090")
+ if err := enableTunnelsFromEnv(e); err == nil || !strings.Contains(err.Error(), replicaConsoleAddrEnv) {
+ t.Fatalf("bad value: %v", err)
+ }
+ t.Setenv(replicaConsoleAddrEnv, "127.0.0.1:8090")
+ if err := enableTunnelsFromEnv(e); err != nil || e.replicaConsole == nil {
+ t.Fatalf("good value: %v, configured %v", err, e.replicaConsole != nil)
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 109e84eb3..8816bc7b6 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -209,4 +209,6 @@ plan14-root-reads-ppv2-operator-copy.tsv 19c9f395547d998f4b5e87e89c0dfa3b5f012d1
plan14-root-reads-same-box-edge-fence.tsv 76c986ad534d23071100a9a573ffb38afc60b26c8942baf218436bf6a3ff03b3
plan14-root-reads-g6-fence.tsv 3f43afa4b0c18ad678a952b48b511e74e849992cd629b9aa1442bbe0055d5631
plan14-root-reads-offline-move-stage-refusals-339.tsv 846d1f22e6eb6b2cd8b3086fa554f15deba70418c6542b46b2e2a6a138b6c332
-plan14-root-reads-platform-mail-submission.tsv 72eca621463fbdb5c15b2f273b443bc9e931c67266329b124664dc4220240814
+plan14-root-reads-fleet-tunnel-tls-state.tsv 846d1f22e6eb6b2cd8b3086fa554f15deba70418c6542b46b2e2a6a138b6c332
+plan14-root-reads-replica-console-account.tsv 87e151a55efb12fb84e9c5939f2ead9058527d8213e2eb16ee6c0f109787bb16
+plan14-root-reads-platform-mail-submission.tsv b782f324a4791147024602f46ab73eab48a589ae3ab9a5035d56a722c92da50e
diff --git a/internal/provision/testdata/plan14-root-reads-fleet-tunnel-tls-state.tsv b/internal/provision/testdata/plan14-root-reads-fleet-tunnel-tls-state.tsv
new file mode 100644
index 000000000..fadfa1955
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-fleet-tunnel-tls-state.tsv
@@ -0,0 +1,3 @@
+# Census overlay fleet-tunnel-tls-state, written by census-propose (#369). census-ruling-fleet-tunnel-tls-state, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-fleet-tunnel-tls-state.md.
+# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@coverage internal/tunnelclient 68935c92a74f148c57ff72311be08d79851691aef6791c1b8b8bde34085457b3
diff --git a/internal/provision/testdata/plan14-root-reads-replica-console-account.tsv b/internal/provision/testdata/plan14-root-reads-replica-console-account.tsv
new file mode 100644
index 000000000..1f9cca79e
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-replica-console-account.tsv
@@ -0,0 +1,5 @@
+# Census overlay replica-console-account, written by census-propose (#369). census-ruling-replica-console-account, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-replica-console-account.md.
+# 1 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@legacy 12edbd2e5eccec79415e4d335e95074759a35a5279200bf2500e4de01182b9f2 internal/edge/replicaconsole.go Edge.serveReplicaConsole legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-coordinator-route;basis=Reads existing in-memory route fields to select a unique accountless console.service local upstream; refuses missing or ambiguous console, tenant routes, remote and tunnel upstreams. Reuses proxy and version wrapper; leaves fleet identity authentication at console.;rev3=census-ruling-retry-after-503;basis=the missing/ambiguous-console 503s go through UnavailableHeader (adds Retry-After 2 and answer/box headers); selection unchanged; no read added;rev3=census-ruling-replica-console-account;basis=when operator config CARLOS_REPLICA_CONSOLE_ADDR (hub host.env, read once in enableTunnelsFromEnv, refused at load unless a literal loopback IP and port) is set, replica calls go to a proxy built only from that address, stamping the hub build as X-Carlos-Version; no route field is read, so records can neither choose, redirect nor disable the endpoint. Unset, the selection is byte-identical to main (accountless console.service local route). Witnesses TestReplicaConsoleConfiguredEndpoint (distinct destinations, injected and rewritten rows, endpoint down), TestReplicaConsoleUnconfiguredIgnoresAccountRows, TestParseReplicaConsoleAddr, TestReplicaConsoleAddrFromHostEnv. Same reads, no new read source, no write. registry:Account@332,registry:App@352,registry:Host@273,registry:Socket@450,registry:Unit@375,whole:Route@254 31e8a1bc5fd1903daed1e82189e214b46ba6348761f2300525788b6a90393f97
+internal/edge/replicaconsole.go Edge.serveReplicaConsole legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-coordinator-route;basis=Reads existing in-memory route fields to select a unique accountless console.service local upstream; refuses missing or ambiguous console, tenant routes, remote and tunnel upstreams. Reuses proxy and version wrapper; leaves fleet identity authentication at console.;rev3=census-ruling-retry-after-503;basis=the missing/ambiguous-console 503s go through UnavailableHeader (adds Retry-After 2 and answer/box headers); selection unchanged; no read added;rev3=census-ruling-replica-console-account;basis=when operator config CARLOS_REPLICA_CONSOLE_ADDR (hub host.env, read once in enableTunnelsFromEnv, refused at load unless a literal loopback IP and port) is set, replica calls go to a proxy built only from that address, stamping the hub build as X-Carlos-Version; no route field is read, so records can neither choose, redirect nor disable the endpoint. Unset, the selection is byte-identical to main (accountless console.service local route). Witnesses TestReplicaConsoleConfiguredEndpoint (distinct destinations, injected and rewritten rows, endpoint down), TestReplicaConsoleUnconfiguredIgnoresAccountRows, TestParseReplicaConsoleAddr, TestReplicaConsoleAddrFromHostEnv. Same reads, no new read source, no write. registry:Account@332,registry:App@352,registry:Host@273,registry:Socket@450,registry:Unit@375,whole:Route@254 31e8a1bc5fd1903daed1e82189e214b46ba6348761f2300525788b6a90393f97
+@coverage internal/edge c21d213f8c8d08e121493dc87a9211045ae20a45fc256b7dc672b8e6d09d24a1
diff --git a/internal/tunnelclient/tlsstate_test.go b/internal/tunnelclient/tlsstate_test.go
new file mode 100644
index 000000000..0f4963f30
--- /dev/null
+++ b/internal/tunnelclient/tlsstate_test.go
@@ -0,0 +1,145 @@
+package tunnelclient
+
+import (
+ "context"
+ "crypto/tls"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/http/httputil"
+ "net/url"
+ "testing"
+ "time"
+
+ "golang.org/x/net/http2"
+)
+
+// TestFleetTunnelKeepsHTTPS (v0.35.0 regression): a request that reaches a
+// box over its TLS tunnel is an https request on the box, on a fleet
+// tunnel (Drain set, served through refusingConn) exactly as on a static
+// one. The box's edge derives X-Forwarded-Proto from r.TLS
+// (httputil.ProxyRequest.SetXForwarded), and x/net's server sets r.TLS only
+// when the conn it serves exposes ConnectionState. v0.35.0's refusingConn
+// hid it, so every fleet app saw X-Forwarded-Proto: http, and a Rails app
+// with force_ssl answered every request with a 301 to its own URL.
+//
+// The app here is that app: it redirects unless X-Forwarded-Proto is
+// https, behind a ReverseProxy whose Rewrite calls SetXForwarded, as the
+// box's edge does (setForwarded, internal/edge/homemap.go).
+func TestFleetTunnelKeepsHTTPS(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ drain bool
+ }{{"static tunnel", false}, {"fleet tunnel", true}} {
+ t.Run(tc.name, func(t *testing.T) {
+ app := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("X-Forwarded-Proto") != "https" {
+ http.Redirect(w, r, "https://"+r.Host+r.URL.RequestURI(), http.StatusMovedPermanently)
+ return
+ }
+ io.WriteString(w, "secure")
+ }))
+ defer app.Close()
+ appURL, _ := url.Parse(app.URL)
+ edge := &httputil.ReverseProxy{Rewrite: func(pr *httputil.ProxyRequest) {
+ pr.SetURL(appURL)
+ pr.Out.Host = pr.In.Host
+ pr.SetXForwarded()
+ }}
+ sawTLS := make(chan bool, 1)
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ select {
+ case sawTLS <- r.TLS != nil:
+ default:
+ }
+ edge.ServeHTTP(w, r)
+ })
+
+ conns := make(chan *http2.ClientConn, 1)
+ hub := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ conn, bufrw, err := w.(http.Hijacker).Hijack()
+ if err != nil {
+ t.Errorf("hijack: %v", err)
+ return
+ }
+ fmt.Fprintf(bufrw, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: carlos-tunnel/1\r\nConnection: Upgrade\r\n\r\n")
+ bufrw.Flush()
+ cc, err := (&http2.Transport{}).NewClientConn(conn)
+ if err != nil {
+ t.Errorf("h2 client: %v", err)
+ return
+ }
+ conns <- cc
+ }))
+ defer hub.Close()
+ roots := hub.Client().Transport.(*http.Transport).TLSClientConfig.RootCAs
+ old := dialRootCAs
+ dialRootCAs = roots
+ t.Cleanup(func() { dialRootCAs = old })
+
+ var drain chan struct{}
+ if tc.drain {
+ drain = make(chan struct{})
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ Loop(ctx, Config{URL: hub.URL, Name: "pi/box-1", Token: "t", Handler: handler, Drain: drain, Logf: t.Logf})
+ }()
+ defer func() { cancel(); <-done }()
+ var cc *http2.ClientConn
+ select {
+ case cc = <-conns:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the box never connected")
+ }
+ defer cc.Close()
+
+ req, _ := http.NewRequest("GET", "https://shop.example.com/sign_in", nil)
+ resp, err := cc.RoundTrip(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ body, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ if !<-sawTLS {
+ t.Error("the box saw the tunnelled request without TLS")
+ }
+ if resp.StatusCode != http.StatusOK || string(body) != "secure" {
+ t.Fatalf("got %d %q (location %q), want 200 \"secure\": the app saw the request as http", resp.StatusCode, body, resp.Header.Get("Location"))
+ }
+ })
+ }
+}
+
+// TestWrappedConnsKeepTLSState: each conn the tunnel wraps around its TLS
+// conn (the handshake's over-read replay, the fleet refusal) still exposes
+// that conn's state, and a plain conn's wrapper does not claim one (x/net
+// would reject a zero state as TLS below 1.2).
+func TestWrappedConnsKeepTLSState(t *testing.T) {
+ type stater interface{ ConnectionState() tls.ConnectionState }
+ a, b := net.Pipe()
+ defer a.Close()
+ defer b.Close()
+ tc := tls.Client(a, &tls.Config{InsecureSkipVerify: true})
+ for name, c := range map[string]net.Conn{
+ "buffered": withTLSState(bufferedConn{r: tc, Conn: tc}, tc),
+ "refusing": servedConn(newRefusingConn(tc)),
+ "refusing+buffered": servedConn(newRefusingConn(withTLSState(bufferedConn{r: tc, Conn: tc}, tc))),
+ } {
+ if _, ok := c.(stater); !ok {
+ t.Errorf("%s: TLS state hidden", name)
+ }
+ }
+ for name, c := range map[string]net.Conn{
+ "buffered": withTLSState(bufferedConn{r: a, Conn: a}, a),
+ "refusing": servedConn(newRefusingConn(a)),
+ } {
+ if _, ok := c.(stater); ok {
+ t.Errorf("%s: a plain conn claims TLS state", name)
+ }
+ }
+}
diff --git a/internal/tunnelclient/tunnelclient.go b/internal/tunnelclient/tunnelclient.go
index ce331bfe6..44fb974a6 100644
--- a/internal/tunnelclient/tunnelclient.go
+++ b/internal/tunnelclient/tunnelclient.go
@@ -18,6 +18,7 @@ import (
"bufio"
"context"
"crypto/tls"
+ "crypto/x509"
"fmt"
"io"
"log"
@@ -210,6 +211,44 @@ type bufferedConn struct {
func (b bufferedConn) Read(p []byte) (int, error) { return b.r.Read(p) }
+// dialRootCAs verifies the edge's certificate; nil is the system roots.
+// Only tests set it.
+var dialRootCAs *x509.CertPool
+
+// connectionStater is the method x/net's h2 server looks for on the conn
+// it serves (server.go, ServeConn): only when the conn has it does a
+// request with scheme https get r.TLS. The box's edge derives
+// X-Forwarded-Proto from r.TLS, so a tunnel conn that loses it turns every
+// tunnelled request into plain http at the app (the v0.35.0 fleet tunnel
+// regression: Rails force_ssl answered every request with a 301 to its own
+// URL).
+type connectionStater interface {
+ ConnectionState() tls.ConnectionState
+}
+
+// tlsStateConn is a wrapper conn that still exposes the TLS state of the
+// conn it wraps.
+type tlsStateConn struct {
+ net.Conn
+ st connectionStater
+}
+
+func (c tlsStateConn) ConnectionState() tls.ConnectionState { return c.st.ConnectionState() }
+
+// withTLSState returns outer, a conn wrapping inner, with inner's TLS state
+// when inner has one. A plain inner stays plain: x/net rejects a zero state
+// as TLS below 1.2.
+func withTLSState(outer, inner net.Conn) net.Conn {
+ if st, ok := inner.(connectionStater); ok {
+ return tlsStateConn{Conn: outer, st: st}
+ }
+ return outer
+}
+
+// servedConn is the conn a fleet tunnel's h2 server serves: rc, with the
+// TLS state of the conn rc wraps.
+func servedConn(rc *refusingConn) net.Conn { return withTLSState(rc, rc.Conn) }
+
// Dial performs the registration handshake and returns the raw conn, ready to
// serve h2 on. https URLs use real TLS (the edge's public cert — server auth
// by PKI, client auth by bearer token); http is for tests.
@@ -238,6 +277,7 @@ func Dial(ctx context.Context, rawURL, name, token string) (net.Conn, error) {
// fails the dial instead of hanging it — and ctx on top of that.
td := &tls.Dialer{NetDialer: dialer, Config: &tls.Config{
ServerName: u.Hostname(),
+ RootCAs: dialRootCAs,
NextProtos: []string{"http/1.1"}, // the handshake is 1.1; h2 starts after the 101
}}
conn, err = td.DialContext(ctx, "tcp", addr)
@@ -290,7 +330,7 @@ func Dial(ctx context.Context, rawURL, name, token string) (net.Conn, error) {
return nil, fmt.Errorf("tunnel: clear handshake deadline: %w", err)
}
if br.Buffered() > 0 {
- return bufferedConn{r: io.MultiReader(br, conn), Conn: conn}, nil
+ return withTLSState(bufferedConn{r: io.MultiReader(br, conn), Conn: conn}, conn), nil
}
return conn, nil
}
diff --git a/internal/tunnelclient/upgrade.go b/internal/tunnelclient/upgrade.go
index 4abf9ed5a..c071ec79c 100644
--- a/internal/tunnelclient/upgrade.go
+++ b/internal/tunnelclient/upgrade.go
@@ -152,7 +152,7 @@ func serveConn(conn net.Conn, handler http.Handler, l Limits, drain <-chan struc
_ = base.Shutdown(context.Background())
}()
rc := newRefusingConn(conn)
- srv.ServeConn(rc, &http2.ServeConnOpts{Handler: streamGate{h: handler, drain: drain, conn: rc}, BaseConfig: base})
+ srv.ServeConn(servedConn(rc), &http2.ServeConnOpts{Handler: streamGate{h: handler, drain: drain, conn: rc}, BaseConfig: base})
}
// upgradeShim is the box half of an upgrade, applied by Mark. A request