fix: resolve nil pointer dereference on missing oauth config (#8352)

This commit is contained in:
Steven Masley
2023-07-06 16:46:22 -04:00
committed by GitHub
parent 9f5bc7c10b
commit 2ebd0ec6c5
2 changed files with 43 additions and 0 deletions

View File

@ -237,6 +237,13 @@ func ExtractAPIKey(rw http.ResponseWriter, r *http.Request, cfg ExtractAPIKeyCon
} }
// Check if the OAuth token is expired // Check if the OAuth token is expired
if link.OAuthExpiry.Before(now) && !link.OAuthExpiry.IsZero() && link.OAuthRefreshToken != "" { if link.OAuthExpiry.Before(now) && !link.OAuthExpiry.IsZero() && link.OAuthRefreshToken != "" {
if cfg.OAuth2Configs == nil {
return write(http.StatusInternalServerError, codersdk.Response{
Message: internalErrorMessage,
Detail: fmt.Sprintf("Unable to refresh OAuth token for login type %q. "+
"No OAuth2Configs provided. Contact an administrator to configure this login type.", key.LoginType),
})
}
var oauthConfig OAuth2Config var oauthConfig OAuth2Config
switch key.LoginType { switch key.LoginType {
case database.LoginTypeGithub: case database.LoginTypeGithub:

View File

@ -4,6 +4,7 @@ import (
"context" "context"
"crypto/sha256" "crypto/sha256"
"fmt" "fmt"
"io"
"net" "net"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
@ -595,4 +596,39 @@ func TestAPIKey(t *testing.T) {
require.Equal(t, sentAPIKey.ExpiresAt, gotAPIKey.ExpiresAt) require.Equal(t, sentAPIKey.ExpiresAt, gotAPIKey.ExpiresAt)
require.Equal(t, sentAPIKey.LoginType, gotAPIKey.LoginType) require.Equal(t, sentAPIKey.LoginType, gotAPIKey.LoginType)
}) })
t.Run("MissongConfig", func(t *testing.T) {
t.Parallel()
var (
db = dbfake.New()
user = dbgen.User(t, db, database.User{})
_, token = dbgen.APIKey(t, db, database.APIKey{
UserID: user.ID,
LastUsed: database.Now(),
ExpiresAt: database.Now().AddDate(0, 0, 1),
LoginType: database.LoginTypeOIDC,
})
_ = dbgen.UserLink(t, db, database.UserLink{
UserID: user.ID,
LoginType: database.LoginTypeOIDC,
OAuthRefreshToken: "random",
// expired
OAuthExpiry: time.Now().Add(time.Hour * -1),
})
r = httptest.NewRequest("GET", "/", nil)
rw = httptest.NewRecorder()
)
r.Header.Set(codersdk.SessionTokenHeader, token)
httpmw.ExtractAPIKeyMW(httpmw.ExtractAPIKeyConfig{
DB: db,
RedirectToLogin: false,
})(successHandler).ServeHTTP(rw, r)
res := rw.Result()
defer res.Body.Close()
require.Equal(t, http.StatusInternalServerError, res.StatusCode)
out, _ := io.ReadAll(res.Body)
require.Contains(t, string(out), "Unable to refresh")
})
} }