diff --git a/modules/auth/pam/pam.go b/modules/auth/pam/pam.go index a8b608e6be..a801f39a56 100644 --- a/modules/auth/pam/pam.go +++ b/modules/auth/pam/pam.go @@ -7,10 +7,15 @@ package pam import ( "errors" + "fmt" "github.com/msteinert/pam/v2" ) +// ErrInvalidCredentials is returned when PAM reports an authentication +// or account error (wrong password, unknown user, expired account, etc.). +var ErrInvalidCredentials = errors.New("invalid PAM credentials") + // Supported is true when built with PAM var Supported = true @@ -31,10 +36,16 @@ func Auth(serviceName, userName, passwd string) (string, error) { defer t.End() if err = t.Authenticate(0); err != nil { + if errors.Is(err, pam.ErrAuth) || errors.Is(err, pam.ErrUserUnknown) { + return "", fmt.Errorf("%w: %v", ErrInvalidCredentials, err) + } return "", err } if err = t.AcctMgmt(0); err != nil { + if errors.Is(err, pam.ErrAcctExpired) || errors.Is(err, pam.ErrPermDenied) { + return "", fmt.Errorf("%w: %v", ErrInvalidCredentials, err) + } return "", err } diff --git a/modules/auth/pam/pam_stub.go b/modules/auth/pam/pam_stub.go index 3631eeeda7..41993ed701 100644 --- a/modules/auth/pam/pam_stub.go +++ b/modules/auth/pam/pam_stub.go @@ -9,6 +9,10 @@ import ( "errors" ) +// ErrInvalidCredentials is returned when PAM reports an authentication +// or account error (wrong password, unknown user, expired account, etc.). +var ErrInvalidCredentials = errors.New("invalid PAM credentials") + // Supported is false when built without PAM var Supported = false diff --git a/modules/auth/pam/pam_test.go b/modules/auth/pam/pam_test.go index e9b844e955..c155207426 100644 --- a/modules/auth/pam/pam_test.go +++ b/modules/auth/pam/pam_test.go @@ -15,6 +15,6 @@ import ( func TestPamAuth(t *testing.T) { result, err := Auth("gitea", "user1", "false-pwd") require.Error(t, err) - assert.EqualError(t, err, "Authentication failure") + assert.ErrorIs(t, err, ErrInvalidCredentials) assert.Len(t, result, 0) } diff --git a/services/auth/source/pam/source_authenticate.go b/services/auth/source/pam/source_authenticate.go index 6f3ffc2d9d..8a84683d29 100644 --- a/services/auth/source/pam/source_authenticate.go +++ b/services/auth/source/pam/source_authenticate.go @@ -5,6 +5,7 @@ package pam import ( "context" + "errors" "fmt" "strings" @@ -23,7 +24,7 @@ import ( func (source *Source) Authenticate(ctx context.Context, user *user_model.User, userName, password string) (*user_model.User, error) { pamLogin, err := pam.Auth(source.ServiceName, userName, password) if err != nil { - if strings.Contains(err.Error(), "Authentication failure") { + if errors.Is(err, pam.ErrInvalidCredentials) { return nil, user_model.ErrUserNotExist{Name: userName} } return nil, err