Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion coderd/httpmw/apikey.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
7 changes: 4 additions & 3 deletions coderd/httpmw/apikey_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"crypto/sha256"
"fmt"
"net"
"net/http"
"net/http/httptest"
"testing"
Expand Down Expand Up @@ -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),
Expand All @@ -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)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

noob question: I see you added :3555 on L417 but then here on L439, you're passing in "1.1.1.1. So why add the :3555 if we're not testing it here? (or are we??)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're testing that it gets stripped correctly!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ahh! I misread - that makes sense! thanks Colin!

})
}

Expand Down
3 changes: 2 additions & 1 deletion coderd/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down