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
10 changes: 6 additions & 4 deletions internal/api/custom_oauth_admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -436,11 +436,12 @@ func validateProviderParams(params *AdminCustomOAuthProviderParams, providerType
}

// Type-specific validations
if providerType == models.ProviderTypeOIDC {
switch providerType {
case models.ProviderTypeOIDC:
if params.Issuer == "" {
return apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "issuer is required for OIDC providers")
}
} else if providerType == models.ProviderTypeOAuth2 {
case models.ProviderTypeOAuth2:
if params.AuthorizationURL == "" {
return apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "authorization_url is required for OAuth2 providers")
}
Expand All @@ -459,12 +460,13 @@ func validateProviderParams(params *AdminCustomOAuthProviderParams, providerType
func validateProviderURLs(params *AdminCustomOAuthProviderParams, providerType models.ProviderType) error {
var urls []string

if providerType == models.ProviderTypeOIDC {
switch providerType {
case models.ProviderTypeOIDC:
urls = append(urls, params.Issuer)
if params.DiscoveryURL != nil && *params.DiscoveryURL != "" {
urls = append(urls, *params.DiscoveryURL)
}
} else if providerType == models.ProviderTypeOAuth2 {
case models.ProviderTypeOAuth2:
urls = []string{
params.AuthorizationURL,
params.TokenURL,
Expand Down
2 changes: 1 addition & 1 deletion internal/api/e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func genPhone() string {
sb.WriteString("1")
for range 9 {
// #nosec G404
sb.WriteString(fmt.Sprintf("%d", rand.Intn(9)))
fmt.Fprintf(&sb, "%d", rand.Intn(9))
}
phone := sb.String()
return phone
Expand Down
2 changes: 1 addition & 1 deletion internal/api/external.go
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@ func (a *API) createAccountFromExternalIdentity(tx *storage.Connection, r *http.
return 0, nil, apierrors.NewForbiddenError(apierrors.ErrorCodeUserBanned, "User is banned")
}

hasEmails := providerType != Web3Provider && !(emailOptional && decision.CandidateEmail.Email == "")
hasEmails := providerType != Web3Provider && (!emailOptional || decision.CandidateEmail.Email != "")

if hasEmails && !user.IsConfirmed() {
// The user may have other unconfirmed email + password
Expand Down
5 changes: 1 addition & 4 deletions internal/api/hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,7 @@ func (a *API) triggerBeforeUserCreatedExternal(
Data: identityData,
}

isSSOUser := false
if strings.HasPrefix(decision.LinkingDomain, "sso:") {
isSSOUser = true
}
isSSOUser := strings.HasPrefix(decision.LinkingDomain, "sso:")

user, err := params.ToUserModel(isSSOUser)
if err != nil {
Expand Down
5 changes: 3 additions & 2 deletions internal/api/mail.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,9 +255,10 @@ func (a *API) adminGenerateLink(w http.ResponseWriter, r *http.Request) error {
user.EmailChangeSentAt = &now
user.EmailChange = params.NewEmail
user.EmailChangeConfirmStatus = zeroConfirmation
if params.Type == "email_change_current" {
switch params.Type {
case "email_change_current":
user.EmailChangeTokenCurrent = hashedToken
} else if params.Type == "email_change_new" {
case "email_change_new":
user.EmailChangeTokenNew = crypto.GenerateTokenHash(params.NewEmail, otp)
}
terr = tx.UpdateOnly(user, "email_change_token_current", "email_change_token_new", "email_change", "email_change_sent_at", "email_change_confirm_status")
Expand Down
10 changes: 6 additions & 4 deletions internal/api/mfa_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -528,13 +528,14 @@ func (ts *MFATestSuite) TestMFAVerifyFactor() {
var f *models.Factor
var sharedSecret string

if v.factorType == models.TOTP {
switch v.factorType {
case models.TOTP:
friendlyName := uuid.Must(uuid.NewV4()).String()
f = models.NewTOTPFactor(ts.TestUser, friendlyName)
sharedSecret = ts.TestOTPKey.Secret()
f.Secret = sharedSecret
require.NoError(ts.T(), ts.API.db.Create(f), "Error updating new test factor")
} else if v.factorType == models.Phone {
case models.Phone:
friendlyName := uuid.Must(uuid.NewV4()).String()
numDigits := 10
otp := crypto.GenerateOtp(numDigits)
Expand All @@ -550,12 +551,13 @@ func (ts *MFATestSuite) TestMFAVerifyFactor() {

var c *models.Challenge
var code string
if v.factorType == models.TOTP {
switch v.factorType {
case models.TOTP:
c = f.CreateChallenge(utilities.GetIPAddress(req))
// Verify TOTP code
code, err = totp.GenerateCode(sharedSecret, time.Now().UTC())
require.NoError(ts.T(), err)
} else if v.factorType == models.Phone {
case models.Phone:
code = "123456"
c, err = f.CreatePhoneChallenge(utilities.GetIPAddress(req), code, ts.Config.Security.DBEncryption.Encrypt, ts.Config.Security.DBEncryption.EncryptionKeyID, ts.Config.Security.DBEncryption.EncryptionKey)
require.NoError(ts.T(), err)
Expand Down
15 changes: 9 additions & 6 deletions internal/api/provider/custom_oauth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,8 @@ func TestNewCustomOIDCProvider(t *testing.T) {
// Mock OIDC provider server
var server *httptest.Server
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/.well-known/openid-configuration" {
switch r.URL.Path {
case "/.well-known/openid-configuration":
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"issuer": server.URL,
Expand All @@ -262,7 +263,7 @@ func TestNewCustomOIDCProvider(t *testing.T) {
"userinfo_endpoint": server.URL + "/userinfo",
"jwks_uri": server.URL + "/jwks",
})
} else if r.URL.Path == "/jwks" {
case "/jwks":
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"keys": []interface{}{},
Expand Down Expand Up @@ -385,15 +386,16 @@ func TestCustomOIDCProvider_AuthCodeURL(t *testing.T) {
// Mock OIDC provider server
var server *httptest.Server
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/.well-known/openid-configuration" {
switch r.URL.Path {
case "/.well-known/openid-configuration":
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"issuer": server.URL,
"authorization_endpoint": server.URL + "/authorize",
"token_endpoint": server.URL + "/token",
"jwks_uri": server.URL + "/jwks",
})
} else if r.URL.Path == "/jwks" {
case "/jwks":
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"keys": []interface{}{},
Expand Down Expand Up @@ -487,15 +489,16 @@ func TestCustomOIDCProvider_RequiresPKCE(t *testing.T) {
// Mock OIDC provider server
var server *httptest.Server
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/.well-known/openid-configuration" {
switch r.URL.Path {
case "/.well-known/openid-configuration":
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"issuer": server.URL,
"authorization_endpoint": server.URL + "/authorize",
"token_endpoint": server.URL + "/token",
"jwks_uri": server.URL + "/jwks",
})
} else if r.URL.Path == "/jwks" {
case "/jwks":
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"keys": []interface{}{},
Expand Down
2 changes: 1 addition & 1 deletion internal/api/provider/facebook.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ func (p facebookProvider) RequiresPKCE() bool {
}

func (p facebookProvider) GetUserData(ctx context.Context, tok *oauth2.Token) (*UserProvidedData, error) {
hash := hmac.New(sha256.New, []byte(p.Config.ClientSecret))
hash := hmac.New(sha256.New, []byte(p.ClientSecret))
hash.Write([]byte(tok.AccessToken))
appsecretProof := hex.EncodeToString(hash.Sum(nil))

Expand Down
2 changes: 1 addition & 1 deletion internal/api/provider/google.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ var internalUserInfoEndpointGoogle = UserInfoEndpointGoogle
func (g googleProvider) GetUserData(ctx context.Context, tok *oauth2.Token) (*UserProvidedData, error) {
if idToken := tok.Extra("id_token"); idToken != nil {
_, data, err := ParseIDToken(ctx, g.oidc, &oidc.Config{
ClientID: g.Config.ClientID,
ClientID: g.ClientID,
}, idToken.(string), ParseIDTokenOptions{
AccessToken: tok.AccessToken,
})
Expand Down
2 changes: 1 addition & 1 deletion internal/api/provider/twitch.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func (t twitchProvider) GetUserData(ctx context.Context, tok *oauth2.Token) (*Us
}

// set headers
req.Header.Set("Client-Id", t.Config.ClientID)
req.Header.Set("Client-Id", t.ClientID)
req.Header.Set("Authorization", "Bearer "+tok.AccessToken)

client := &http.Client{Timeout: defaultTimeout}
Expand Down
5 changes: 3 additions & 2 deletions internal/api/resend_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -266,10 +266,11 @@ func (ts *ResendTestSuite) TestResendSuccess() {
require.NoError(ts.T(), err)
require.NotEmpty(ts.T(), dbUser)

if c.params["type"] == mail.SignupVerification {
switch c.params["type"] {
case mail.SignupVerification:
require.NotEqual(ts.T(), dbUser.ConfirmationToken, c.user.ConfirmationToken)
require.NotEqual(ts.T(), dbUser.ConfirmationSentAt, c.user.ConfirmationSentAt)
} else if c.params["type"] == mail.EmailChangeVerification {
case mail.EmailChangeVerification:
require.NotEqual(ts.T(), dbUser.EmailChangeTokenNew, c.user.EmailChangeTokenNew)
require.NotEqual(ts.T(), dbUser.EmailChangeSentAt, c.user.EmailChangeSentAt)
}
Expand Down
2 changes: 1 addition & 1 deletion internal/api/sms_provider/twilio_verify.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ func (t *TwilioVerifyProvider) SendSms(phone, message, channel string) (string,
return "", err
}
defer utilities.SafeClose(res.Body)
if !(res.StatusCode == http.StatusOK || res.StatusCode == http.StatusCreated) {
if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated {
resp := &twilioErrResponse{}
if err := json.NewDecoder(res.Body).Decode(resp); err != nil {
return "", err
Expand Down
7 changes: 4 additions & 3 deletions internal/api/sso_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -703,9 +703,10 @@ func (ts *SSOTestSuite) TestSingleSignOn() {

locationURLString := ""

if example.Code == http.StatusSeeOther {
switch example.Code {
case http.StatusSeeOther:
locationURLString = w.Header().Get("Location")
} else if example.Code == http.StatusOK {
case http.StatusOK:
var response struct {
URL string `json:"url"`
}
Expand All @@ -715,7 +716,7 @@ func (ts *SSOTestSuite) TestSingleSignOn() {
require.NotEmpty(ts.T(), response.URL)

locationURLString = response.URL
} else {
default:
continue
}

Expand Down
5 changes: 3 additions & 2 deletions internal/api/verify.go
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,8 @@ func (a *API) smsVerify(r *http.Request, conn *storage.Connection, user *models.
phoneIdentityWasCreated := false
err := conn.Transaction(func(tx *storage.Connection) error {

if params.Type == smsVerification {
switch params.Type {
case smsVerification:
if terr := models.NewAuditLogEntry(config.AuditLog, r, tx, user, models.UserSignedUpAction, "", map[string]interface{}{
"provider": PhoneProvider,
}); terr != nil {
Expand All @@ -415,7 +416,7 @@ func (a *API) smsVerify(r *http.Request, conn *storage.Connection, user *models.
if terr := user.ConfirmPhone(tx); terr != nil {
return apierrors.NewInternalServerError("Error confirming user").WithInternalError(terr)
}
} else if params.Type == phoneChangeVerification {
case phoneChangeVerification:
if terr := models.NewAuditLogEntry(config.AuditLog, r, tx, user, models.UserModifiedAction, "", nil); terr != nil {
return terr
}
Expand Down
15 changes: 8 additions & 7 deletions internal/api/verify_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -751,9 +751,10 @@ func (ts *VerifyTestSuite) TestVerifyPKCEOTP() {
var buffer bytes.Buffer
// since the test user is the same, the tokens are being cleared after each successful verification attempt
// so we create them on each run
if c.payload.Type == "signup" {
switch c.payload.Type {
case "signup":
require.NoError(ts.T(), models.CreateOneTimeToken(ts.API.db, u.ID, u.GetEmail(), c.payload.Token, models.ConfirmationToken))
} else if c.payload.Type == "magiclink" {
case "magiclink":
require.NoError(ts.T(), models.CreateOneTimeToken(ts.API.db, u.ID, u.GetEmail(), c.payload.Token, models.RecoveryToken))
}

Expand Down Expand Up @@ -1034,10 +1035,10 @@ func (ts *VerifyTestSuite) TestVerifyValidOtp() {
u.EmailChangeSentAt = &c.sentTime
u.PhoneChangeSentAt = &c.sentTime

u.ConfirmationToken = c.expected.tokenHash
u.RecoveryToken = c.expected.tokenHash
u.EmailChangeTokenNew = c.expected.tokenHash
u.PhoneChangeToken = c.expected.tokenHash
u.ConfirmationToken = c.tokenHash
u.RecoveryToken = c.tokenHash
u.EmailChangeTokenNew = c.tokenHash
u.PhoneChangeToken = c.tokenHash

require.NoError(ts.T(), models.CreateOneTimeToken(ts.API.db, u.ID, "relates_to not used", u.ConfirmationToken, models.ConfirmationToken))
require.NoError(ts.T(), models.CreateOneTimeToken(ts.API.db, u.ID, "relates_to not used", u.RecoveryToken, models.RecoveryToken))
Expand All @@ -1056,7 +1057,7 @@ func (ts *VerifyTestSuite) TestVerifyValidOtp() {
// Setup response recorder
w := httptest.NewRecorder()
ts.API.handler.ServeHTTP(w, req)
assert.Equal(ts.T(), c.expected.code, w.Code)
assert.Equal(ts.T(), c.code, w.Code)
})
}
}
Expand Down
2 changes: 1 addition & 1 deletion internal/conf/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -785,7 +785,7 @@ type SmsProviderConfiguration struct {
}

func (c *SmsProviderConfiguration) GetTestOTP(phone string, now time.Time) (string, bool) {
if c.TestOTP != nil && (c.TestOTPValidUntil.Time.IsZero() || now.Before(c.TestOTPValidUntil.Time)) {
if c.TestOTP != nil && (c.TestOTPValidUntil.IsZero() || now.Before(c.TestOTPValidUntil.Time)) {
testOTP, ok := c.TestOTP[phone]
return testOTP, ok
}
Expand Down
2 changes: 1 addition & 1 deletion internal/conf/envparse/envparse.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ const (
)

func parseBytes(src []byte, out map[string]string) error {
src = bytes.Replace(src, []byte("\r\n"), []byte("\n"), -1)
src = bytes.ReplaceAll(src, []byte("\r\n"), []byte("\n"))
cutset := src
for {
cutset = getStatementStart(cutset)
Expand Down
2 changes: 1 addition & 1 deletion internal/models/audit_log_entry.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ func FindAuditLogEntries(tx *storage.Connection, filterColumns []string, filterV
values := make([]interface{}, len(filterColumns))

for idx, col := range filterColumns {
builder.WriteString(fmt.Sprintf("payload->>'%s' ILIKE ?", col))
fmt.Fprintf(builder, "payload->>'%s' ILIKE ?", col)
values[idx] = lf

if idx+1 < len(filterColumns) {
Expand Down
5 changes: 3 additions & 2 deletions internal/models/custom_oauth_provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -539,15 +539,16 @@ func (ts *CustomOAuthProviderTestSuite) createTestProvider(providerType Provider
Enabled: true,
}

if providerType == ProviderTypeOAuth2 {
switch providerType {
case ProviderTypeOAuth2:
authURL := "https://example.com/authorize"
// #nosec G101 - These are test URLs, not actual credentials
tokenURL := "https://example.com/token"
userinfoURL := "https://example.com/userinfo"
provider.AuthorizationURL = &authURL
provider.TokenURL = &tokenURL
provider.UserinfoURL = &userinfoURL
} else if providerType == ProviderTypeOIDC {
case ProviderTypeOIDC:
// For OIDC, generate a unique issuer to avoid constraint violations
issuer := "https://oidc-" + identifier + ".example.com"
provider.Issuer = &issuer
Expand Down
2 changes: 1 addition & 1 deletion internal/models/oauth_authorization_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ func TestFindOAuthServerAuthorizationByIDForUpdate_SkipLocked(t *testing.T) {
})
require.NoError(t, CreateOAuthServerAuthorization(db, auth))

holdTx, err := db.Connection.NewTransaction()
holdTx, err := db.NewTransaction()
require.NoError(t, err)
defer func() { _ = holdTx.TX.Rollback() }()
held := &storage.Connection{Connection: holdTx}
Expand Down
2 changes: 1 addition & 1 deletion internal/storage/dial.go
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ func (c *Connection) WithContext(ctx context.Context) *Connection {
func getExcludedColumns(model interface{}, includeColumns ...string) ([]string, error) {
sm := &pop.Model{Value: model}
st := reflect.TypeOf(model)
if st.Kind() == reflect.Ptr {
if st.Kind() == reflect.Pointer {
_ = st.Elem()
}

Expand Down
Loading