From 6c4a11013169ce1997da62e066be33ad6a36fa2f Mon Sep 17 00:00:00 2001 From: mo khan Date: Tue, 1 Sep 2026 11:21:19 -0600 Subject: [PATCH] chore: fix golangci-lint errors ```bash $ golangci-lint run --fix ./... ``` --- internal/api/custom_oauth_admin.go | 10 ++++++---- internal/api/e2e_test.go | 2 +- internal/api/external.go | 2 +- internal/api/hooks.go | 5 +---- internal/api/mail.go | 5 +++-- internal/api/mfa_test.go | 10 ++++++---- internal/api/provider/custom_oauth_test.go | 15 +++++++++------ internal/api/provider/facebook.go | 2 +- internal/api/provider/google.go | 2 +- internal/api/provider/twitch.go | 2 +- internal/api/resend_test.go | 5 +++-- internal/api/sms_provider/twilio_verify.go | 2 +- internal/api/sso_test.go | 7 ++++--- internal/api/verify.go | 5 +++-- internal/api/verify_test.go | 15 ++++++++------- internal/conf/configuration.go | 2 +- internal/conf/envparse/envparse.go | 2 +- internal/models/audit_log_entry.go | 2 +- internal/models/custom_oauth_provider_test.go | 5 +++-- internal/models/oauth_authorization_test.go | 2 +- internal/storage/dial.go | 2 +- 21 files changed, 57 insertions(+), 47 deletions(-) diff --git a/internal/api/custom_oauth_admin.go b/internal/api/custom_oauth_admin.go index 1d614a449e..b8da661d49 100644 --- a/internal/api/custom_oauth_admin.go +++ b/internal/api/custom_oauth_admin.go @@ -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") } @@ -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, diff --git a/internal/api/e2e_test.go b/internal/api/e2e_test.go index 2231ac1293..f58acc47b1 100644 --- a/internal/api/e2e_test.go +++ b/internal/api/e2e_test.go @@ -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 diff --git a/internal/api/external.go b/internal/api/external.go index 14bdfe087b..ab6dfafbf8 100644 --- a/internal/api/external.go +++ b/internal/api/external.go @@ -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 diff --git a/internal/api/hooks.go b/internal/api/hooks.go index 7b02f4889b..a9a3eeb338 100644 --- a/internal/api/hooks.go +++ b/internal/api/hooks.go @@ -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 { diff --git a/internal/api/mail.go b/internal/api/mail.go index 9a42651c42..ba9f80aa88 100644 --- a/internal/api/mail.go +++ b/internal/api/mail.go @@ -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") diff --git a/internal/api/mfa_test.go b/internal/api/mfa_test.go index 73d26cf5dc..48746b7736 100644 --- a/internal/api/mfa_test.go +++ b/internal/api/mfa_test.go @@ -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) @@ -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) diff --git a/internal/api/provider/custom_oauth_test.go b/internal/api/provider/custom_oauth_test.go index ac71377c59..8abb85cafa 100644 --- a/internal/api/provider/custom_oauth_test.go +++ b/internal/api/provider/custom_oauth_test.go @@ -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, @@ -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{}{}, @@ -385,7 +386,8 @@ 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, @@ -393,7 +395,7 @@ func TestCustomOIDCProvider_AuthCodeURL(t *testing.T) { "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{}{}, @@ -487,7 +489,8 @@ 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, @@ -495,7 +498,7 @@ func TestCustomOIDCProvider_RequiresPKCE(t *testing.T) { "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{}{}, diff --git a/internal/api/provider/facebook.go b/internal/api/provider/facebook.go index 5940cf57cf..f78f7b3c50 100644 --- a/internal/api/provider/facebook.go +++ b/internal/api/provider/facebook.go @@ -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)) diff --git a/internal/api/provider/google.go b/internal/api/provider/google.go index 0d7f3fd28c..32439ee675 100644 --- a/internal/api/provider/google.go +++ b/internal/api/provider/google.go @@ -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, }) diff --git a/internal/api/provider/twitch.go b/internal/api/provider/twitch.go index f662b8e28c..b15f333c91 100644 --- a/internal/api/provider/twitch.go +++ b/internal/api/provider/twitch.go @@ -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} diff --git a/internal/api/resend_test.go b/internal/api/resend_test.go index 90e556fb40..30653eda16 100644 --- a/internal/api/resend_test.go +++ b/internal/api/resend_test.go @@ -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) } diff --git a/internal/api/sms_provider/twilio_verify.go b/internal/api/sms_provider/twilio_verify.go index 8ec546396b..45e4d88c02 100644 --- a/internal/api/sms_provider/twilio_verify.go +++ b/internal/api/sms_provider/twilio_verify.go @@ -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 diff --git a/internal/api/sso_test.go b/internal/api/sso_test.go index bae1bebf3c..bb67753671 100644 --- a/internal/api/sso_test.go +++ b/internal/api/sso_test.go @@ -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"` } @@ -715,7 +716,7 @@ func (ts *SSOTestSuite) TestSingleSignOn() { require.NotEmpty(ts.T(), response.URL) locationURLString = response.URL - } else { + default: continue } diff --git a/internal/api/verify.go b/internal/api/verify.go index c0b58e4a68..024617093d 100644 --- a/internal/api/verify.go +++ b/internal/api/verify.go @@ -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 { @@ -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 } diff --git a/internal/api/verify_test.go b/internal/api/verify_test.go index a75df9c15d..65704bc0d2 100644 --- a/internal/api/verify_test.go +++ b/internal/api/verify_test.go @@ -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)) } @@ -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)) @@ -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) }) } } diff --git a/internal/conf/configuration.go b/internal/conf/configuration.go index 63a8144d29..6772bf1963 100644 --- a/internal/conf/configuration.go +++ b/internal/conf/configuration.go @@ -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 } diff --git a/internal/conf/envparse/envparse.go b/internal/conf/envparse/envparse.go index 1982994f16..208b99db76 100644 --- a/internal/conf/envparse/envparse.go +++ b/internal/conf/envparse/envparse.go @@ -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) diff --git a/internal/models/audit_log_entry.go b/internal/models/audit_log_entry.go index d16170782e..f8b493a783 100644 --- a/internal/models/audit_log_entry.go +++ b/internal/models/audit_log_entry.go @@ -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) { diff --git a/internal/models/custom_oauth_provider_test.go b/internal/models/custom_oauth_provider_test.go index 6333faaf45..dff1943b4f 100644 --- a/internal/models/custom_oauth_provider_test.go +++ b/internal/models/custom_oauth_provider_test.go @@ -539,7 +539,8 @@ 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" @@ -547,7 +548,7 @@ func (ts *CustomOAuthProviderTestSuite) createTestProvider(providerType Provider 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 diff --git a/internal/models/oauth_authorization_test.go b/internal/models/oauth_authorization_test.go index 29f35900bd..ce9f942399 100644 --- a/internal/models/oauth_authorization_test.go +++ b/internal/models/oauth_authorization_test.go @@ -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} diff --git a/internal/storage/dial.go b/internal/storage/dial.go index 03d7205e89..c296b7af09 100644 --- a/internal/storage/dial.go +++ b/internal/storage/dial.go @@ -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() }