diff --git a/agent/agent_endpoint.go b/agent/agent_endpoint.go index 8d7728f1c..75d5807c0 100644 --- a/agent/agent_endpoint.go +++ b/agent/agent_endpoint.go @@ -554,6 +554,14 @@ func (s *HTTPServer) AgentRegisterService(resp http.ResponseWriter, req *http.Re return nil, nil } + // Run validation. This is the same validation that would happen on + // the catalog endpoint so it helps ensure the sync will work properly. + if err := ns.Validate(); err != nil { + resp.WriteHeader(http.StatusBadRequest) + fmt.Fprintf(resp, err.Error()) + return nil, nil + } + // Verify the check type. chkTypes, err := args.CheckTypes() if err != nil { diff --git a/agent/agent_endpoint_test.go b/agent/agent_endpoint_test.go index e30323007..05e8b6ca3 100644 --- a/agent/agent_endpoint_test.go +++ b/agent/agent_endpoint_test.go @@ -1398,6 +1398,35 @@ func TestAgent_RegisterService_ConnectProxy(t *testing.T) { assert.Equal("abc123", a.State.ServiceToken("connect-proxy")) } +func TestAgent_RegisterService_ConnectProxyInvalid(t *testing.T) { + t.Parallel() + + assert := assert.New(t) + a := NewTestAgent(t.Name(), "") + defer a.Shutdown() + + args := &structs.ServiceDefinition{ + Kind: structs.ServiceKindConnectProxy, + Name: "connect-proxy", + ProxyDestination: "db", + Check: structs.CheckType{ + TTL: 15 * time.Second, + }, + } + + req, _ := http.NewRequest("PUT", "/v1/agent/service/register?token=abc123", jsonReader(args)) + resp := httptest.NewRecorder() + obj, err := a.srv.AgentRegisterService(resp, req) + assert.Nil(err) + assert.Nil(obj) + assert.Equal(http.StatusBadRequest, resp.Code) + assert.Contains(resp.Body.String(), "Port") + + // Ensure the service doesn't exist + _, ok := a.State.Services()["connect-proxy"] + assert.False(ok) +} + func TestAgent_DeregisterService(t *testing.T) { t.Parallel() a := NewTestAgent(t.Name(), "")