From 7f18fe1a5b7de58fff270f8a45c31a6ed9d5dd96 Mon Sep 17 00:00:00 2001 From: Frank Schroeder Date: Thu, 1 Jun 2017 13:53:27 +0200 Subject: [PATCH] agent: LastContact cannot be negative (#3067) The X-Consul-LastContact header cannot be negative. Fixes #3067 --- command/agent/http.go | 3 +++ command/agent/http_test.go | 24 +++++++++++++++++++----- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/command/agent/http.go b/command/agent/http.go index 4731e25ee..8bae391f5 100644 --- a/command/agent/http.go +++ b/command/agent/http.go @@ -311,6 +311,9 @@ func setKnownLeader(resp http.ResponseWriter, known bool) { // setLastContact is used to set the last contact header func setLastContact(resp http.ResponseWriter, last time.Duration) { + if last < 0 { + last = 0 + } lastMsec := uint64(last / time.Millisecond) resp.Header().Set("X-Consul-LastContact", strconv.FormatUint(lastMsec, 10)) } diff --git a/command/agent/http_test.go b/command/agent/http_test.go index 0ccc55cfd..223af2693 100644 --- a/command/agent/http_test.go +++ b/command/agent/http_test.go @@ -150,11 +150,25 @@ func TestSetKnownLeader(t *testing.T) { func TestSetLastContact(t *testing.T) { t.Parallel() - resp := httptest.NewRecorder() - setLastContact(resp, 123456*time.Microsecond) - header := resp.Header().Get("X-Consul-LastContact") - if header != "123" { - t.Fatalf("Bad: %v", header) + tests := []struct { + desc string + d time.Duration + h string + }{ + {"neg", -1, "0"}, + {"zero", 0, "0"}, + {"pos", 123 * time.Millisecond, "123"}, + {"pos ms only", 123456 * time.Microsecond, "123"}, + } + for _, tt := range tests { + t.Run(tt.desc, func(t *testing.T) { + resp := httptest.NewRecorder() + setLastContact(resp, tt.d) + header := resp.Header().Get("X-Consul-LastContact") + if got, want := header, tt.h; got != want { + t.Fatalf("got X-Consul-LastContact header %q want %q", got, want) + } + }) } }