Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 4851d93

Browse files
authored
fix: Split host and port before storing IP (coder#2594)
The IP was always nil prior, and this fixes the test to check for that as well!
1 parent 545a9f3 commit 4851d93

File tree

3 files changed

+8
-5
lines changed

3 files changed

+8
-5
lines changed

coderd/httpmw/apikey.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,8 @@ func ExtractAPIKey(db database.Store, oauth *OAuth2Configs) func(http.Handler) h
167167
// Only update LastUsed once an hour to prevent database spam.
168168
if now.Sub(key.LastUsed) > time.Hour {
169169
key.LastUsed = now
170-
remoteIP := net.ParseIP(r.RemoteAddr)
170+
host, _, _ := net.SplitHostPort(r.RemoteAddr)
171+
remoteIP := net.ParseIP(host)
171172
if remoteIP == nil {
172173
remoteIP = net.IPv4(0, 0, 0, 0)
173174
}

coderd/httpmw/apikey_test.go

+4-3
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"context"
55
"crypto/sha256"
66
"fmt"
7+
"net"
78
"net/http"
89
"net/http/httptest"
910
"testing"
@@ -413,13 +414,13 @@ func TestAPIKey(t *testing.T) {
413414
rw = httptest.NewRecorder()
414415
user = createUser(r.Context(), t, db)
415416
)
416-
r.RemoteAddr = "1.1.1.1"
417+
r.RemoteAddr = "1.1.1.1:3555"
417418
r.AddCookie(&http.Cookie{
418419
Name: httpmw.SessionTokenKey,
419420
Value: fmt.Sprintf("%s-%s", id, secret),
420421
})
421422

422-
sentAPIKey, err := db.InsertAPIKey(r.Context(), database.InsertAPIKeyParams{
423+
_, err := db.InsertAPIKey(r.Context(), database.InsertAPIKeyParams{
423424
ID: id,
424425
HashedSecret: hashed[:],
425426
LastUsed: database.Now().AddDate(0, 0, -1),
@@ -435,7 +436,7 @@ func TestAPIKey(t *testing.T) {
435436
gotAPIKey, err := db.GetAPIKeyByID(r.Context(), id)
436437
require.NoError(t, err)
437438

438-
require.NotEqual(t, sentAPIKey.IPAddress, gotAPIKey.IPAddress)
439+
require.Equal(t, net.ParseIP("1.1.1.1"), gotAPIKey.IPAddress.IPNet.IP)
439440
})
440441
}
441442

coderd/users.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -782,7 +782,8 @@ func (api *API) createAPIKey(rw http.ResponseWriter, r *http.Request, params dat
782782
}
783783
}
784784

785-
ip := net.ParseIP(r.RemoteAddr)
785+
host, _, _ := net.SplitHostPort(r.RemoteAddr)
786+
ip := net.ParseIP(host)
786787
if ip == nil {
787788
ip = net.IPv4(0, 0, 0, 0)
788789
}

0 commit comments

Comments
 (0)