diff --git a/coderd/httpmw/apikey.go b/coderd/httpmw/apikey.go index 704fa5a3a4..05ad040042 100644 --- a/coderd/httpmw/apikey.go +++ b/coderd/httpmw/apikey.go @@ -167,7 +167,8 @@ func ExtractAPIKey(db database.Store, oauth *OAuth2Configs) func(http.Handler) h // Only update LastUsed once an hour to prevent database spam. if now.Sub(key.LastUsed) > time.Hour { key.LastUsed = now - remoteIP := net.ParseIP(r.RemoteAddr) + host, _, _ := net.SplitHostPort(r.RemoteAddr) + remoteIP := net.ParseIP(host) if remoteIP == nil { remoteIP = net.IPv4(0, 0, 0, 0) } diff --git a/coderd/httpmw/apikey_test.go b/coderd/httpmw/apikey_test.go index 2e7c127296..e904093515 100644 --- a/coderd/httpmw/apikey_test.go +++ b/coderd/httpmw/apikey_test.go @@ -4,6 +4,7 @@ import ( "context" "crypto/sha256" "fmt" + "net" "net/http" "net/http/httptest" "testing" @@ -413,13 +414,13 @@ func TestAPIKey(t *testing.T) { rw = httptest.NewRecorder() user = createUser(r.Context(), t, db) ) - r.RemoteAddr = "1.1.1.1" + r.RemoteAddr = "1.1.1.1:3555" r.AddCookie(&http.Cookie{ Name: httpmw.SessionTokenKey, Value: fmt.Sprintf("%s-%s", id, secret), }) - sentAPIKey, err := db.InsertAPIKey(r.Context(), database.InsertAPIKeyParams{ + _, err := db.InsertAPIKey(r.Context(), database.InsertAPIKeyParams{ ID: id, HashedSecret: hashed[:], LastUsed: database.Now().AddDate(0, 0, -1), @@ -435,7 +436,7 @@ func TestAPIKey(t *testing.T) { gotAPIKey, err := db.GetAPIKeyByID(r.Context(), id) require.NoError(t, err) - require.NotEqual(t, sentAPIKey.IPAddress, gotAPIKey.IPAddress) + require.Equal(t, net.ParseIP("1.1.1.1"), gotAPIKey.IPAddress.IPNet.IP) }) } diff --git a/coderd/users.go b/coderd/users.go index 8d81471f3d..9cf13dcdb7 100644 --- a/coderd/users.go +++ b/coderd/users.go @@ -782,7 +782,8 @@ func (api *API) createAPIKey(rw http.ResponseWriter, r *http.Request, params dat } } - ip := net.ParseIP(r.RemoteAddr) + host, _, _ := net.SplitHostPort(r.RemoteAddr) + ip := net.ParseIP(host) if ip == nil { ip = net.IPv4(0, 0, 0, 0) }