From e9e6514c9b0b57f759bb294e49cf55ebad969bde Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Wed, 13 Jun 2018 09:00:23 +0100 Subject: [PATCH] agent: disallow deregistering a managed proxy directly --- agent/agent_endpoint.go | 8 ++++++ agent/agent_endpoint_test.go | 48 ++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/agent/agent_endpoint.go b/agent/agent_endpoint.go index c2f4fc045c..1cba53efc0 100644 --- a/agent/agent_endpoint.go +++ b/agent/agent_endpoint.go @@ -653,6 +653,14 @@ func (s *HTTPServer) AgentDeregisterService(resp http.ResponseWriter, req *http. return nil, err } + // Verify this isn't a proxy + if s.agent.State.Proxy(serviceID) != nil { + return nil, &BadRequestError{ + Reason: "Managed proxy service cannot be deregistered directly. " + + "Deregister the service that has a managed proxy to automatically " + + "deregister the managed proxy itself."} + } + if err := s.agent.RemoveService(serviceID, true); err != nil { return nil, err } diff --git a/agent/agent_endpoint_test.go b/agent/agent_endpoint_test.go index 5824570c79..f19a496115 100644 --- a/agent/agent_endpoint_test.go +++ b/agent/agent_endpoint_test.go @@ -1708,6 +1708,54 @@ func TestAgent_DeregisterService_withManagedProxy(t *testing.T) { require.Len(a.State.Proxies(), 0) } +// Test that we can't deregister a managed proxy service directly. +func TestAgent_DeregisterService_managedProxyDirect(t *testing.T) { + t.Parallel() + require := require.New(t) + a := NewTestAgent(t.Name(), ` + connect { + proxy { + allow_managed_api_registration = true + } + } + `) + + defer a.Shutdown() + + // Register a service with a managed proxy + { + reg := &structs.ServiceDefinition{ + ID: "test-id", + Name: "test", + Address: "127.0.0.1", + Port: 8000, + Check: structs.CheckType{ + TTL: 15 * time.Second, + }, + Connect: &structs.ServiceConnect{ + Proxy: &structs.ServiceDefinitionConnectProxy{}, + }, + } + + req, _ := http.NewRequest("PUT", "/v1/agent/service/register", jsonReader(reg)) + resp := httptest.NewRecorder() + _, err := a.srv.AgentRegisterService(resp, req) + require.NoError(err) + require.Equal(200, resp.Code, "body: %s", resp.Body.String()) + } + + // Get the proxy ID + var proxyID string + for _, p := range a.State.Proxies() { + proxyID = p.Proxy.ProxyService.ID + } + + req, _ := http.NewRequest("PUT", "/v1/agent/service/deregister/"+proxyID, nil) + obj, err := a.srv.AgentDeregisterService(nil, req) + require.Error(err) + require.Nil(obj) +} + func TestAgent_ServiceMaintenance_BadRequest(t *testing.T) { t.Parallel() a := NewTestAgent(t.Name(), "")