From c705422cfb932ef71473f235d8bd943f6bcb9208 Mon Sep 17 00:00:00 2001 From: fabriciojs Date: Mon, 30 Nov 2026 22:16:18 -0300 Subject: [PATCH] fix(proxy): make Caddy admin writes single and safe to repeat Every config change makes Caddy replace its admin server, and the old server can close connections while kool is still sending requests. #551 resends a request once when that happens; this makes the resend fire less often and keeps it harmless when it does. - Send every admin request with Connection: close. The old admin server closes the connections it served, so a reused keep-alive connection could fail a POST or PATCH with EOF. The retry still covers a new connection dropped while the old server shuts down. - Create a new listener's server with its route in a single POST. The server body already sets automatic_https or tls_connection_policies, so the follow-up listener-mode write and the routes GET+PATCH were redundant changes right after Caddy added its first listener. Existing servers keep the previous path. - Write the project's TLS automation policy by @id: read the tls app, replace or add the policy, and PATCH the list back (or set the app or its automation when missing). The previous DELETE plus appending POST would add a second policy with the same @id if a resent POST had already been applied. Duplicates already present collapse into one. Closes #554 --- services/proxy/manager.go | 84 +++++---- services/proxy/manager_test.go | 299 ++++++++++++++++++++++++++++++--- 2 files changed, 326 insertions(+), 57 deletions(-) diff --git a/services/proxy/manager.go b/services/proxy/manager.go index 420fb59c..5061ab80 100644 --- a/services/proxy/manager.go +++ b/services/proxy/manager.go @@ -872,9 +872,17 @@ func (m *DefaultManager) registerWithResult(route route) (created bool, err erro func (m *DefaultManager) registerUnlocked(route route) (bool, error) { serverID := "kool-" + strconv.Itoa(route.Listen) - server := caddyServerConfig(route) - serverBody, _ := json.Marshal(server) serverURL := m.adminURL + "/config/apps/http/servers/" + serverID + routeConfig := map[string]interface{}{ + "@id": m.routeID(route), + "match": []interface{}{map[string]interface{}{"host": m.routeHosts(route)}}, + "handle": []interface{}{map[string]interface{}{ + "@id": m.projectMarker() + "-" + m.routeID(route) + "-" + m.generation, + "handler": "reverse_proxy", + "upstreams": []interface{}{map[string]string{"dial": m.alias(route.Service) + ":" + strconv.Itoa(route.Target)}}, + }}, + "terminal": true, + } response, err := m.request(http.MethodGet, serverURL, nil) if err != nil { return false, err @@ -906,6 +914,11 @@ func (m *DefaultManager) registerUnlocked(route route) (bool, error) { } } if serverMissing { + // Create the server with its listener mode and route in one change: each + // change replaces Caddy's admin server, which can drop the next request. + server := caddyServerConfig(route) + server["routes"] = []interface{}{routeConfig} + serverBody, _ := json.Marshal(server) response, err = m.request(http.MethodPost, serverURL, serverBody) if err != nil { return false, err @@ -914,6 +927,7 @@ func (m *DefaultManager) registerUnlocked(route route) (bool, error) { if response.StatusCode >= 400 { return false, responseError(response) } + return true, nil } if route.HTTPS { if err = m.setTLSPolicy(serverURL); err != nil { @@ -922,17 +936,6 @@ func (m *DefaultManager) registerUnlocked(route route) (bool, error) { } else if err = m.disableAutomaticHTTPS(serverURL); err != nil { return false, err } - - routeConfig := map[string]interface{}{ - "@id": m.routeID(route), - "match": []interface{}{map[string]interface{}{"host": m.routeHosts(route)}}, - "handle": []interface{}{map[string]interface{}{ - "@id": m.projectMarker() + "-" + m.routeID(route) + "-" + m.generation, - "handler": "reverse_proxy", - "upstreams": []interface{}{map[string]string{"dial": m.alias(route.Service) + ":" + strconv.Itoa(route.Target)}}, - }}, - "terminal": true, - } return m.upsertRouteUnlocked(serverURL, routeConfig) } @@ -1411,31 +1414,46 @@ func (m *DefaultManager) registerTLSUnlocked(routes []route) error { if err != nil { return err } - status := response.StatusCode - _ = response.Body.Close() - if status == http.StatusNotFound { - body := []byte(`{"automation":{"policies":[]}}`) - if response, err = m.request(http.MethodPost, tlsURL, body); err != nil { - return err - } + if response.StatusCode >= 400 && response.StatusCode != http.StatusNotFound { defer func() { _ = response.Body.Close() }() - if response.StatusCode >= 400 { - return responseError(response) + return responseError(response) + } + // Caddy answers null for a missing app; a 404 means the same. + var tlsApp map[string]interface{} + if response.StatusCode != http.StatusNotFound { + if err = json.NewDecoder(response.Body).Decode(&tlsApp); err != nil && err != io.EOF { + _ = response.Body.Close() + return err } - } else if status >= 400 { - return fmt.Errorf("caddy Admin API returned %s", response.Status) } - - if err = m.deleteRoute(m.tlsID()); err != nil { + if err = response.Body.Close(); err != nil { return err } + policy := map[string]interface{}{ "@id": m.tlsID(), "subjects": subjects, "issuers": []interface{}{map[string]string{"module": "internal"}}, } - body, _ := json.Marshal(policy) - response, err = m.request(http.MethodPost, tlsURL+"/automation/policies", body) + // Replace the policy by ID rather than appending it, so that sending this + // write twice never leaves two policies with the same ID. PATCH replaces an + // existing value and POST sets a missing one; neither appends. + apps := map[string]interface{}{} + if tlsApp != nil { + apps["tls"] = tlsApp + } + policies, automation := caddyPolicies(apps) + policies = replaceObjectByID(policies, m.tlsID(), policy, true) + method, url, value := http.MethodPatch, tlsURL+"/automation/policies", interface{}(policies) + if _, listExists := automation["policies"].([]interface{}); !listExists { + automation["policies"] = policies + method, url, value = http.MethodPatch, tlsURL, apps["tls"] + if tlsApp == nil { + method = http.MethodPost + } + } + body, _ := json.Marshal(value) + response, err = m.request(method, url, body) if err != nil { return err } @@ -1655,7 +1673,8 @@ func replaceObjectByID(objects []interface{}, id string, replacement interface{} replaced := false for _, object := range objects { if caddyObjectID(object) == id { - if replacementPresent { + // Caddy before 2.11 accepts duplicate IDs; keep only one. + if replacementPresent && !replaced { result = append(result, replacement) } replaced = true @@ -1676,9 +1695,12 @@ func (m *DefaultManager) request(method, url string, body []byte) (*http.Respons return nil, err } request.Header.Set("Content-Type", "application/json") - response, err := m.http.Do(request) // Each configuration change replaces Caddy's admin server, and the old - // server can close a connection before it reads the request on it. + // server closes the connections it served, so never reuse one. + request.Close = true + response, err := m.http.Do(request) + // The old server can also drop a new connection before it reads the + // request on it. dropped := errors.Is(err, io.EOF) || errors.Is(err, syscall.ECONNRESET) if !dropped || attempt == 2 { return response, err diff --git a/services/proxy/manager_test.go b/services/proxy/manager_test.go index fcd2773e..56374753 100644 --- a/services/proxy/manager_test.go +++ b/services/proxy/manager_test.go @@ -8,6 +8,7 @@ import ( "kool-dev/kool/core/builder" "kool-dev/kool/core/environment" "kool-dev/kool/core/shell" + "net" "net/http" "net/http/httptest" "net/url" @@ -15,6 +16,7 @@ import ( "path/filepath" "regexp" "strings" + "sync/atomic" "testing" ) @@ -360,6 +362,14 @@ func TestRegisterWorkspaceRoute(t *testing.T) { case request.Method == http.MethodPost && strings.HasSuffix(request.URL.Path, "/kool-80"): serverCreated = true events = append(events, "server") + body, _ := io.ReadAll(request.Body) + var server struct { + Routes []map[string]interface{} `json:"routes"` + } + _ = json.Unmarshal(body, &server) + if len(server.Routes) == 1 { + registered = server.Routes[0] + } return case request.Method == http.MethodDelete: response.WriteHeader(http.StatusNotFound) @@ -391,8 +401,8 @@ func TestRegisterWorkspaceRoute(t *testing.T) { if err := manager.register(route{Service: "app", Listen: 80, Target: 8080, Hosts: []string{"@", "*"}}); err != nil { t.Fatal(err) } - if strings.Join(events, ",") != "server,route" { - t.Errorf("expected server creation before route registration, got %v", events) + if strings.Join(events, ",") != "server" { + t.Errorf("expected the route to be registered with the new server, got %v", events) } encoded, _ := json.Marshal(registered) result := string(encoded) @@ -935,41 +945,135 @@ func TestRegisterRouteCreatesServerAfterNotFound(t *testing.T) { } } -func TestRegisterRouteSucceedsWhenAdminClosesConnectionAfterChange(t *testing.T) { - serverCreated := false +func TestRegisterRouteResendsChangeWhenAdminDropsConnection(t *testing.T) { + var posts []string server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) { switch { case request.Method == http.MethodPost && strings.HasSuffix(request.URL.Path, "/kool-80"): - serverCreated = true - // Caddy can answer a configuration change without "Connection: close" - // and then close the connection without answering the next request. - connection, buffered, err := response.(http.Hijacker).Hijack() + body, _ := io.ReadAll(request.Body) + posts = append(posts, string(body)) + if len(posts) > 1 { + return + } + // While Caddy replaces its admin server, the old one can close a new + // connection without answering the request on it. + connection, _, err := response.(http.Hijacker).Hijack() if err != nil { t.Error(err) return } - defer func() { _ = connection.Close() }() - _, _ = buffered.WriteString("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n") - _ = buffered.Flush() - if next, err := http.ReadRequest(buffered.Reader); err == nil { - _, _ = io.Copy(io.Discard, next.Body) - } - case request.Method == http.MethodGet && strings.HasSuffix(request.URL.Path, "/routes") && serverCreated: - _, _ = response.Write([]byte(`[]`)) + _ = connection.Close() case request.Method == http.MethodGet: response.WriteHeader(http.StatusNotFound) } })) defer server.Close() - env := environment.NewFakeEnvStorage() - env.Set("KOOL_NAME", "example") - env.Set("KOOL_PROXY_HOST", "app.localhost") - manager := NewManager(&shell.FakeShell{}, env).(*DefaultManager) - manager.adminURL = server.URL + manager := testRouteManager(server.URL, "example", "app.localhost") + mustRegister(t, manager, route{Service: "app", Listen: 80, Target: 8080, Hosts: []string{"@"}}) + if len(posts) != 2 || posts[0] != posts[1] || !strings.Contains(posts[1], "kool-example-app-80-8080") { + t.Fatalf("expected the dropped server creation to be sent again unchanged, got %q", posts) + } +} - if err := manager.register(route{Service: "app", Listen: 80, Target: 8080, Hosts: []string{"@"}}); err != nil { - t.Fatal(err) +func TestAdminRequestsDoNotReuseConnections(t *testing.T) { + var connections, requests atomic.Int32 + server := httptest.NewUnstartedServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) { + requests.Add(1) + switch { + case request.Method == http.MethodGet && strings.HasSuffix(request.URL.Path, "/routes"): + _, _ = response.Write([]byte(`[]`)) + case request.Method == http.MethodGet: + _, _ = response.Write([]byte(`{"listen":[":80"],"automatic_https":{"disable":true},"routes":[]}`)) + } + })) + server.Config.ConnState = func(_ net.Conn, state http.ConnState) { + if state == http.StateNew { + connections.Add(1) + } + } + server.Start() + defer server.Close() + + // Caddy closes the connections its old admin server served after each + // configuration change, without always telling the client first. + manager := testRouteManager(server.URL, "example", "app.localhost") + mustRegister(t, manager, route{Service: "app", Listen: 80, Target: 8080, Hosts: []string{"@"}}) + if requests.Load() < 2 || connections.Load() != requests.Load() { + t.Fatalf("expected one connection per admin request, got %d connections for %d requests", connections.Load(), requests.Load()) + } +} + +func TestRegisterRouteRequests(t *testing.T) { + const serverPath = "/config/apps/http/servers/kool-80" + newServer := []string{"GET " + serverPath, "POST " + serverPath} + tests := []struct { + name string + server string + https bool + expected []string + }{ + {name: "new HTTP server", server: "null", expected: newServer}, + {name: "new HTTPS server", server: "null", https: true, expected: newServer}, + {name: "existing HTTP server", server: `{"listen":[":80"],"automatic_https":{"disable":true},"routes":[]}`, expected: []string{ + "GET " + serverPath, "POST " + serverPath + "/automatic_https", "GET " + serverPath + "/routes", "PATCH " + serverPath + "/routes", + }}, + {name: "existing HTTPS server", server: `{"listen":[":80"],"tls_connection_policies":[{}],"routes":[]}`, https: true, expected: []string{ + "GET " + serverPath, "GET " + serverPath + "/tls_connection_policies", "PATCH " + serverPath + "/tls_connection_policies", + "GET " + serverPath + "/routes", "PATCH " + serverPath + "/routes", + }}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + var requests []string + var created []byte + server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) { + requests = append(requests, request.Method+" "+request.URL.Path) + switch { + case request.Method == http.MethodGet && request.URL.Path == serverPath: + _, _ = response.Write([]byte(test.server)) + case request.Method == http.MethodGet && strings.HasSuffix(request.URL.Path, "/routes"): + _, _ = response.Write([]byte(`[]`)) + case request.Method == http.MethodGet && strings.HasSuffix(request.URL.Path, "/tls_connection_policies"): + _, _ = response.Write([]byte(`[{}]`)) + case request.Method == http.MethodPost && request.URL.Path == serverPath: + created, _ = io.ReadAll(request.Body) + } + })) + defer server.Close() + + manager := testRouteManager(server.URL, "example", "app.localhost") + createdRoute, err := manager.registerWithResult(route{Service: "app", Listen: 80, Target: 8080, Hosts: []string{"@"}, HTTPS: test.https}) + if err != nil { + t.Fatal(err) + } + if !createdRoute { + t.Error("expected registration to report a newly created route") + } + if strings.Join(requests, ",") != strings.Join(test.expected, ",") { + t.Fatalf("expected requests %v, got %v", test.expected, requests) + } + if test.server != "null" { + return + } + var config struct { + Listen []string `json:"listen"` + AutomaticHTTPS *struct { + Disable bool `json:"disable"` + } `json:"automatic_https"` + TLSConnectionPolicies []interface{} `json:"tls_connection_policies"` + Routes []json.RawMessage `json:"routes"` + } + if err = json.Unmarshal(created, &config); err != nil { + t.Fatal(err) + } + if strings.Join(config.Listen, ",") != ":80" || len(config.Routes) != 1 || caddyRouteID(config.Routes[0]) != "kool-example-app-80-8080" { + t.Fatalf("expected the new server to carry its listener and route, got %s", created) + } + if test.https != (config.AutomaticHTTPS == nil) || test.https != (len(config.TLSConnectionPolicies) == 1) || !test.https && !config.AutomaticHTTPS.Disable { + t.Fatalf("expected the new server to carry its listener mode, got %s", created) + } + }) } } @@ -981,9 +1085,13 @@ func TestRegisterTLS(t *testing.T) { _, _ = response.Write([]byte(`{"automation":{"policies":[]}}`)) case request.Method == http.MethodDelete: response.WriteHeader(http.StatusNotFound) - case request.Method == http.MethodPost && strings.HasSuffix(request.URL.Path, "/policies"): + case request.Method == http.MethodPatch && strings.HasSuffix(request.URL.Path, "/policies"): body, _ := io.ReadAll(request.Body) - _ = json.Unmarshal(body, &policy) + var policies []map[string]interface{} + _ = json.Unmarshal(body, &policies) + if len(policies) == 1 { + policy = policies[0] + } default: response.WriteHeader(http.StatusOK) } @@ -1033,6 +1141,135 @@ func TestRegisterTLSRemovesPolicyWhenHTTPSIsDisabled(t *testing.T) { } } +func TestRegisterTLSReplacesPolicyByID(t *testing.T) { + const ( + other = `{"@id":"kool-other-tls","subjects":["other.localhost"]}` + stale = `{"@id":"kool-example-tls","subjects":["stale.localhost"]}` + ) + tests := []struct { + name string + tls string + notFound bool + write string + others []string + }{ + {name: "missing app", tls: "null", write: "POST /config/apps/tls"}, + {name: "app not found", tls: "null", notFound: true, write: "POST /config/apps/tls"}, + {name: "missing automation", tls: `{}`, write: "PATCH /config/apps/tls"}, + {name: "null automation", tls: `{"automation":null}`, write: "PATCH /config/apps/tls"}, + {name: "null policies", tls: `{"automation":{"policies":null}}`, write: "PATCH /config/apps/tls"}, + {name: "other project's policy", tls: `{"automation":{"policies":[` + other + `]}}`, write: "PATCH /config/apps/tls/automation/policies", others: []string{"kool-other-tls"}}, + {name: "stale policy", tls: `{"automation":{"policies":[` + stale + `,` + other + `]}}`, write: "PATCH /config/apps/tls/automation/policies", others: []string{"kool-other-tls"}}, + {name: "duplicate policies", tls: `{"automation":{"policies":[` + stale + `,` + other + `,` + stale + `]}}`, write: "PATCH /config/apps/tls/automation/policies", others: []string{"kool-other-tls"}}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + var tlsApp interface{} + if err := json.Unmarshal([]byte(test.tls), &tlsApp); err != nil { + t.Fatal(err) + } + var writes []string + server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) { + var value interface{} + if request.Method != http.MethodGet { + if err := json.NewDecoder(request.Body).Decode(&value); err != nil { + http.Error(response, err.Error(), http.StatusBadRequest) + return + } + writes = append(writes, request.Method+" "+request.URL.Path) + } + // Model Caddy: POST sets a missing value (or appends to a list), + // PATCH replaces an existing one. + switch { + case request.Method == http.MethodGet && request.URL.Path == "/config/apps/tls": + if tlsApp == nil && test.notFound { + response.WriteHeader(http.StatusNotFound) + return + } + _ = json.NewEncoder(response).Encode(tlsApp) + return + case request.Method == http.MethodPost && request.URL.Path == "/config/apps/tls": + tlsApp = value + case request.Method == http.MethodPatch && request.URL.Path == "/config/apps/tls" && tlsApp != nil: + tlsApp = value + case request.URL.Path == "/config/apps/tls/automation/policies": + app, _ := tlsApp.(map[string]interface{}) + automation, _ := app["automation"].(map[string]interface{}) + policies, exists := automation["policies"].([]interface{}) + switch { + case request.Method == http.MethodPatch && exists: + automation["policies"] = value + case request.Method == http.MethodPost && exists: + automation["policies"] = append(policies, value) + default: + response.WriteHeader(http.StatusNotFound) + return + } + default: + response.WriteHeader(http.StatusNotFound) + return + } + if len(writes) > 1 { + return + } + // Apply the first write, then close the connection without an + // answer, so that the write is sent a second time. + connection, _, err := response.(http.Hijacker).Hijack() + if err != nil { + t.Error(err) + return + } + _ = connection.Close() + })) + defer server.Close() + + manager := testRouteManager(server.URL, "example", "first.localhost") + proxyRoutes := []route{{Service: "app", Listen: 443, Target: 80, Hosts: []string{"@"}, HTTPS: true}} + if err := manager.registerTLS(proxyRoutes); err != nil { + t.Fatal(err) + } + if len(writes) != 2 || writes[0] != test.write || writes[1] != test.write { + t.Fatalf("expected %s to be sent twice, got %v", test.write, writes) + } + manager.env.Set("KOOL_PROXY_HOST", "second.localhost") + if err := manager.registerTLS(proxyRoutes); err != nil { + t.Fatal(err) + } + + encoded, _ := json.Marshal(tlsApp) + var config struct { + Automation struct { + Policies []struct { + ID string `json:"@id"` + Subjects []string `json:"subjects"` + } `json:"policies"` + } `json:"automation"` + } + if err := json.Unmarshal(encoded, &config); err != nil { + t.Fatal(err) + } + var others []string + found := 0 + for _, policy := range config.Automation.Policies { + if policy.ID != "kool-example-tls" { + others = append(others, policy.ID) + continue + } + found++ + if strings.Join(policy.Subjects, ",") != "second.localhost" { + t.Errorf("expected the policy to be replaced, got subjects %v", policy.Subjects) + } + } + if found != 1 { + t.Fatalf("expected exactly one kool-example-tls policy, got %s", encoded) + } + if strings.Join(others, ",") != strings.Join(test.others, ",") { + t.Fatalf("expected other policies %v to be preserved, got %s", test.others, encoded) + } + }) + } +} + func TestStopIfUnusedStopsOnlyAfterLastManagedRoute(t *testing.T) { state, server := newCaddyRouteState(t) manager := testRouteManager(server.URL, "example", "app.localhost") @@ -1516,7 +1753,17 @@ func newCaddyRouteState(t *testing.T) (*caddyRouteState, *httptest.Server) { } _ = json.NewEncoder(response).Encode(map[string]interface{}{"routes": routes}) case request.Method == http.MethodPost && len(parts) == 1: - state.routes[serverID] = []json.RawMessage{} + var server struct { + Routes []json.RawMessage `json:"routes"` + } + if err := json.NewDecoder(request.Body).Decode(&server); err != nil { + http.Error(response, err.Error(), http.StatusBadRequest) + return + } + if server.Routes == nil { + server.Routes = []json.RawMessage{} + } + state.routes[serverID] = server.Routes case request.Method == http.MethodPatch && isRoutes: var routes []json.RawMessage if err := json.NewDecoder(request.Body).Decode(&routes); err != nil {