From c144668e59771bbd51695e014137c6c2f4b5084f Mon Sep 17 00:00:00 2001 From: bircni Date: Sun, 15 Nov 2026 20:42:12 +0000 Subject: [PATCH] fix(audit): record missing user and authentication events (#40317) Several entry points change users, credentials or 2FA without writing an audit event, while the equivalent web or service path does. This records the existing actions on those paths: - `user:create` for self sign-up, OAuth2 auto-registration, link-account registration and `gitea admin user create` - `user:accesstoken:add` for `gitea admin user generate-access-token` and `user create --access-token`; `user:accesstoken:remove` for `DELETE /api/v1/token` - `user:twofactor:disable` for the admin "reset 2FA" option and `gitea admin user disable-2fa` - `user:key:ssh:add`, `user:key:gpg:add/remove` for the API - `user:email:primary`, `user:email:activate`, `user:status:active` for settings, the activation page/links and OAuth2 source sync deactivation - `user:oauth2application:grant` when a grant's scope changes, `user:externallogin:add` on registration via an external login - `user:authentication:fail:twofactor` for wrong recovery codes, failed WebAuthn assertions and 2FA during password reset Should be backported to v28. --------- Co-authored-by: silverwind --- cmd/admin_user_create.go | 4 + cmd/admin_user_create_test.go | 15 +++ cmd/admin_user_disable_2fa.go | 5 + cmd/admin_user_disable_2fa_test.go | 6 ++ cmd/admin_user_generate_access_token.go | 10 +- models/user/external_login_user.go | 10 +- routers/api/v1/token/token.go | 5 + routers/api/v1/user/gpg_key.go | 14 +++ routers/api/v1/user/key.go | 3 + routers/web/admin/users.go | 6 +- routers/web/auth/2fa.go | 3 + routers/web/auth/auth.go | 4 + routers/web/auth/oauth2_provider.go | 1 + routers/web/auth/oauth_test.go | 4 + routers/web/auth/password.go | 4 +- routers/web/auth/webauthn.go | 5 + routers/web/user/setting/account.go | 10 +- services/auth/source/oauth2/source_sync.go | 7 +- .../auth/source/oauth2/source_sync_test.go | 20 ++-- services/externalaccount/user.go | 7 +- tests/integration/admin_audit_test.go | 101 ++++++++++++++++++ tests/integration/api_keys_test.go | 6 ++ tests/integration/api_token_self_test.go | 6 ++ tests/integration/signup_test.go | 6 ++ 24 files changed, 242 insertions(+), 20 deletions(-) diff --git a/cmd/admin_user_create.go b/cmd/admin_user_create.go index ef1eca7ff40..6c8e51c44d5 100644 --- a/cmd/admin_user_create.go +++ b/cmd/admin_user_create.go @@ -9,12 +9,14 @@ import ( "fmt" "strings" + audit_model "gitea.dev/models/audit" auth_model "gitea.dev/models/auth" "gitea.dev/models/db" user_model "gitea.dev/models/user" pwd "gitea.dev/modules/auth/password" "gitea.dev/modules/optional" "gitea.dev/modules/setting" + "gitea.dev/services/audit" "github.com/urfave/cli/v3" ) @@ -224,6 +226,7 @@ func runCreateUser(ctx context.Context, c *cli.Command) error { if err := user_model.CreateUser(ctx, u, &user_model.Meta{}, overwriteDefault); err != nil { return fmt.Errorf("CreateUser: %w", err) } + audit.Record(ctx, audit_model.UserCreate, u) cprintf(c, "New user '%s' has been successfully created!\n", username) // create the access token @@ -232,6 +235,7 @@ func runCreateUser(ctx context.Context, c *cli.Command) error { if err := auth_model.NewAccessToken(ctx, t); err != nil { return err } + audit.Record(ctx, audit_model.UserAccessTokenAdd, u, "token", t.Name, "token_scope", t.Scope) cprintf(c, "Access token was successfully created... %s\n", t.Token) } return nil diff --git a/cmd/admin_user_create_test.go b/cmd/admin_user_create_test.go index 66b93683d23..239ca2e675e 100644 --- a/cmd/admin_user_create_test.go +++ b/cmd/admin_user_create_test.go @@ -8,10 +8,13 @@ import ( "strings" "testing" + audit_model "gitea.dev/models/audit" auth_model "gitea.dev/models/auth" "gitea.dev/models/db" "gitea.dev/models/unittest" user_model "gitea.dev/models/user" + "gitea.dev/modules/setting" + "gitea.dev/modules/test" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -139,4 +142,16 @@ func TestAdminUserCreate(t *testing.T) { u := unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: "u-fullnameempty"}) assert.Empty(t, u.FullName) }) + + t.Run("AuditEvents", func(t *testing.T) { + defer test.MockVariableValue(&setting.Audit.RecordOutput, setting.AuditRecordOutputDatabase)() + reset() + require.NoError(t, db.TruncateBeans(t.Context(), &audit_model.Event{})) + + require.NoError(t, createUser("u", "--random-password", "--access-token")) + require.NoError(t, newUserGenerateAccessTokenCommand().Run(t.Context(), []string{"generate-access-token", "--username", "u", "--token-name", "cli-token", "--scopes", "read:user", "--raw"})) + + unittest.AssertExistsAndLoadBean(t, &audit_model.Event{Action: audit_model.UserCreate, ScopeName: "u"}) + unittest.AssertCount(t, &audit_model.Event{Action: audit_model.UserAccessTokenAdd, ScopeName: "u"}, 2) + }) } diff --git a/cmd/admin_user_disable_2fa.go b/cmd/admin_user_disable_2fa.go index b5b59e59a0f..56f58940fd4 100644 --- a/cmd/admin_user_disable_2fa.go +++ b/cmd/admin_user_disable_2fa.go @@ -9,9 +9,11 @@ import ( "fmt" "strings" + audit_model "gitea.dev/models/audit" auth_model "gitea.dev/models/auth" user_model "gitea.dev/models/user" "gitea.dev/modules/setting" + "gitea.dev/services/audit" "github.com/urfave/cli/v3" ) @@ -66,6 +68,9 @@ func runDisableTwoFactor(ctx context.Context, c *cli.Command) error { if err != nil { return err } + if totp+webAuthn > 0 { + audit.Record(ctx, audit_model.UserTwoFactorDisable, user) + } cprintf(c, "Disabled 2FA for user %q (removed %d TOTP and %d WebAuthn credential(s))\n", user.Name, totp, webAuthn) return nil diff --git a/cmd/admin_user_disable_2fa_test.go b/cmd/admin_user_disable_2fa_test.go index 4fe94974bbf..debbc278e9a 100644 --- a/cmd/admin_user_disable_2fa_test.go +++ b/cmd/admin_user_disable_2fa_test.go @@ -8,10 +8,13 @@ import ( "strconv" "testing" + audit_model "gitea.dev/models/audit" auth_model "gitea.dev/models/auth" "gitea.dev/models/db" "gitea.dev/models/unittest" user_model "gitea.dev/models/user" + "gitea.dev/modules/setting" + "gitea.dev/modules/test" "github.com/go-webauthn/webauthn/webauthn" "github.com/stretchr/testify/assert" @@ -20,6 +23,7 @@ import ( func TestDisableTwoFactorCommand(t *testing.T) { ctx := t.Context() + defer test.MockVariableValue(&setting.Audit.RecordOutput, setting.AuditRecordOutputDatabase)() defer func() { require.NoError(t, db.TruncateBeans(t.Context(), &user_model.User{}, &auth_model.TwoFactor{}, &auth_model.WebAuthnCredential{})) @@ -50,6 +54,7 @@ func TestDisableTwoFactorCommand(t *testing.T) { has, err = auth_model.HasTwoFactorOrWebAuthn(ctx, user.ID) require.NoError(t, err) assert.False(t, has) + unittest.AssertExistsAndLoadBean(t, &audit_model.Event{Action: audit_model.UserTwoFactorDisable, ScopeID: user.ID}) }) t.Run("disable by id", func(t *testing.T) { @@ -70,6 +75,7 @@ func TestDisableTwoFactorCommand(t *testing.T) { t.Run("no enrollment is a no-op", func(t *testing.T) { require.NoError(t, microcmdUserCreate().Run(ctx, []string{"create", "--username", "plainuser", "--email", "plainuser@gitea.local", "--random-password"})) require.NoError(t, microcmdUserDisableTwoFactor().Run(ctx, []string{"disable-2fa", "--username", "plainuser"})) + unittest.AssertNotExistsBean(t, &audit_model.Event{Action: audit_model.UserTwoFactorDisable, ScopeName: "plainuser"}) }) t.Run("id and username must match when both given", func(t *testing.T) { diff --git a/cmd/admin_user_generate_access_token.go b/cmd/admin_user_generate_access_token.go index e1b0e9837c4..9d2cec5fc2f 100644 --- a/cmd/admin_user_generate_access_token.go +++ b/cmd/admin_user_generate_access_token.go @@ -8,8 +8,11 @@ import ( "errors" "fmt" + audit_model "gitea.dev/models/audit" auth_model "gitea.dev/models/auth" user_model "gitea.dev/models/user" + "gitea.dev/modules/setting" + "gitea.dev/services/audit" "github.com/urfave/cli/v3" ) @@ -49,8 +52,10 @@ func runGenerateAccessToken(ctx context.Context, c *cli.Command) error { return errors.New("you must provide a username to generate a token for") } - if err := initDB(ctx); err != nil { - return err + if !setting.IsInTesting { + if err := initDB(ctx); err != nil { + return err + } } user, err := user_model.GetUserByName(ctx, c.String("username")) @@ -86,6 +91,7 @@ func runGenerateAccessToken(ctx context.Context, c *cli.Command) error { if err := auth_model.NewAccessToken(ctx, t); err != nil { return err } + audit.Record(ctx, audit_model.UserAccessTokenAdd, user, "token", t.Name, "token_scope", t.Scope) if c.Bool("raw") { cprintln(c, t.Token) diff --git a/models/user/external_login_user.go b/models/user/external_login_user.go index 06397d3bc0d..63f202f11e3 100644 --- a/models/user/external_login_user.go +++ b/models/user/external_login_user.go @@ -157,23 +157,23 @@ func UpdateExternalUserByExternalID(ctx context.Context, external *ExternalLogin return err } -// EnsureLinkExternalToUser link the external user to the user -func EnsureLinkExternalToUser(ctx context.Context, external *ExternalLoginUser) error { +// EnsureLinkExternalToUser links the external user to the user and reports whether a new link was inserted +func EnsureLinkExternalToUser(ctx context.Context, external *ExternalLoginUser) (bool, error) { has, err := db.Exist[ExternalLoginUser](ctx, builder.Eq{ "external_id": external.ExternalID, "login_source_id": external.LoginSourceID, }) if err != nil { - return err + return false, err } if has { _, err = db.GetEngine(ctx).Where("external_id=? AND login_source_id=?", external.ExternalID, external.LoginSourceID).AllCols().Update(external) - return err + return false, err } _, err = db.GetEngine(ctx).Insert(external) - return err + return err == nil, err } // FindExternalUserOptions represents an options to find external users diff --git a/routers/api/v1/token/token.go b/routers/api/v1/token/token.go index 7712a7c8c2e..b34bf06c396 100644 --- a/routers/api/v1/token/token.go +++ b/routers/api/v1/token/token.go @@ -7,11 +7,13 @@ import ( "errors" "net/http" + audit_model "gitea.dev/models/audit" auth_model "gitea.dev/models/auth" user_model "gitea.dev/models/user" "gitea.dev/modules/auth/httpauth" api "gitea.dev/modules/structs" "gitea.dev/modules/util" + "gitea.dev/services/audit" "gitea.dev/services/context" ) @@ -73,6 +75,9 @@ func DeleteCurrentToken(ctx *context.APIContext) { ctx.APIErrorAuto(err) return } + if err == nil { + audit.Record(ctx, audit_model.UserAccessTokenRemove, audit.ScopeFromUserID(ctx, accessToken.UID), "token", accessToken.Name) + } ctx.Status(http.StatusNoContent) } diff --git a/routers/api/v1/user/gpg_key.go b/routers/api/v1/user/gpg_key.go index 9ad011218e4..f2f2dff27f0 100644 --- a/routers/api/v1/user/gpg_key.go +++ b/routers/api/v1/user/gpg_key.go @@ -8,12 +8,14 @@ import ( "strings" asymkey_model "gitea.dev/models/asymkey" + audit_model "gitea.dev/models/audit" "gitea.dev/models/db" user_model "gitea.dev/models/user" "gitea.dev/modules/setting" api "gitea.dev/modules/structs" "gitea.dev/modules/web" "gitea.dev/routers/api/v1/utils" + "gitea.dev/services/audit" "gitea.dev/services/context" "gitea.dev/services/convert" ) @@ -151,6 +153,10 @@ func CreateUserGPGKey(ctx *context.APIContext, form api.CreateGPGKeyOption, uid HandleAddGPGKeyError(ctx, err, token) return } + owner := audit.ScopeFromUserID(ctx, uid) + for _, key := range keys { + audit.Record(ctx, audit_model.UserKeyGPGAdd, owner, "gpg_key_id", key.KeyID) + } ctx.JSON(http.StatusCreated, convert.ToGPGKey(keys[0])) } @@ -275,10 +281,18 @@ func DeleteGPGKey(ctx *context.APIContext) { return } + key, err := asymkey_model.GetGPGKeyForUserByID(ctx, ctx.Doer.ID, ctx.PathParamInt64("id")) + if err != nil && !asymkey_model.IsErrGPGKeyNotExist(err) { + ctx.APIErrorInternal(err) + return + } if err := asymkey_model.DeleteGPGKey(ctx, ctx.Doer, ctx.PathParamInt64("id")); err != nil { ctx.APIErrorInternal(err) return } + if key != nil { + audit.Record(ctx, audit_model.UserKeyGPGRemove, ctx.Doer, "gpg_key_id", key.KeyID) + } ctx.Status(http.StatusNoContent) } diff --git a/routers/api/v1/user/key.go b/routers/api/v1/user/key.go index 5d74e34779f..45a55e18a85 100644 --- a/routers/api/v1/user/key.go +++ b/routers/api/v1/user/key.go @@ -9,6 +9,7 @@ import ( "net/http" asymkey_model "gitea.dev/models/asymkey" + audit_model "gitea.dev/models/audit" "gitea.dev/models/db" "gitea.dev/models/perm" user_model "gitea.dev/models/user" @@ -18,6 +19,7 @@ import ( "gitea.dev/routers/api/v1/repo" "gitea.dev/routers/api/v1/utils" asymkey_service "gitea.dev/services/asymkey" + "gitea.dev/services/audit" "gitea.dev/services/context" "gitea.dev/services/convert" ) @@ -217,6 +219,7 @@ func CreateUserPublicKey(ctx *context.APIContext, form api.CreateKeyOption, uid repo.HandleAddKeyError(ctx, err) return } + audit.Record(ctx, audit_model.UserKeySSHAdd, audit.ScopeFromUserID(ctx, uid), "fingerprint", key.Fingerprint) apiLink := composePublicKeysAPILink() apiKey := convert.ToPublicKey(apiLink, key) if ctx.Doer.IsAdmin || ctx.Doer.ID == key.OwnerID { diff --git a/routers/web/admin/users.go b/routers/web/admin/users.go index de29e958686..47a85b31283 100644 --- a/routers/web/admin/users.go +++ b/routers/web/admin/users.go @@ -555,10 +555,14 @@ func EditUserPost(ctx *context.Context) { log.Trace("Account profile updated by admin (%s): %s", ctx.Doer.Name, u.Name) if form.Reset2FA { - if _, _, err := auth.DisableTwoFactor(ctx, u.ID); err != nil { + totp, webAuthn, err := auth.DisableTwoFactor(ctx, u.ID) + if err != nil { ctx.ServerErrorAuto(err) return } + if totp+webAuthn > 0 { + audit.Record(ctx, audit_model.UserTwoFactorDisable, u) + } } ctx.Flash.Success(ctx.Tr("admin.users.update_profile_success")) diff --git a/routers/web/auth/2fa.go b/routers/web/auth/2fa.go index d990200a9e0..8625cd3b891 100644 --- a/routers/web/auth/2fa.go +++ b/routers/web/auth/2fa.go @@ -163,5 +163,8 @@ func TwoFactorScratchPost(ctx *context.Context) { return } + if u, err := user_model.GetUserByID(ctx, id); err == nil { + audit.RecordAs(ctx, u, audit_model.UserAuthenticationFailTwoFactor, u) + } ctx.RenderWithErrDeprecated(ctx.Tr("auth.twofa_scratch_token_incorrect"), tplTwofaScratch, forms.TwoFactorScratchAuthForm{}) } diff --git a/routers/web/auth/auth.go b/routers/web/auth/auth.go index 4446f17746f..0306871326e 100644 --- a/routers/web/auth/auth.go +++ b/routers/web/auth/auth.go @@ -696,6 +696,7 @@ func createUserInContext(ctx *context.Context, tpl templates.TplName, form any, } return false } + audit.RecordAs(ctx, u, audit_model.UserCreate, u) log.Trace("Account created: %s", u.Name) return true } @@ -840,6 +841,7 @@ func ActivatePost(ctx *context.Context) { return } ctx.Doer.Email = newEmail + audit.Record(ctx, audit_model.UserEmailPrimaryChange, ctx.Doer, "email", newEmail) } // FIXME: at the moment, GET request handles the "send confirmation email" action. But the old code does this redirect and then send a confirmation email. ctx.Redirect(setting.AppSubURL + "/user/activate") @@ -888,6 +890,7 @@ func handleAccountActivation(ctx *context.Context, user *user_model.User) { return } + audit.RecordAs(ctx, user, audit_model.UserActive, user, "active", true) log.Trace("User activated: %s", user.Name) if err := regenerateSession(ctx, map[string]any{session.KeyUID: user.ID}); err != nil { @@ -928,6 +931,7 @@ func ActivateEmail(ctx *context.Context) { if u, err := user_model.GetUserByID(ctx, email.UID); err != nil { log.Warn("GetUserByID: %d", email.UID) } else { + audit.RecordAs(ctx, u, audit_model.UserEmailActivate, u, "email", email.Email, "activated", true) // Allow user to validate more emails _ = ctx.Cache.Delete("MailResendLimit_" + u.LowerName) } diff --git a/routers/web/auth/oauth2_provider.go b/routers/web/auth/oauth2_provider.go index 034b40d5063..ba6bc9922b9 100644 --- a/routers/web/auth/oauth2_provider.go +++ b/routers/web/auth/oauth2_provider.go @@ -452,6 +452,7 @@ func GrantApplicationOAuth(ctx *context.Context) { handleServerError(ctx, form.State, form.RedirectURI) return } + audit.Record(ctx, audit_model.UserOAuth2ApplicationGrant, ctx.Doer, "oauth2_application", app.Name, "granted_scope", form.Scope) } if len(form.Nonce) > 0 { diff --git a/routers/web/auth/oauth_test.go b/routers/web/auth/oauth_test.go index da5808beaf7..abc83522e8e 100644 --- a/routers/web/auth/oauth_test.go +++ b/routers/web/auth/oauth_test.go @@ -10,6 +10,7 @@ import ( "sync/atomic" "testing" + audit_model "gitea.dev/models/audit" "gitea.dev/models/auth" "gitea.dev/models/unittest" user_model "gitea.dev/models/user" @@ -129,6 +130,7 @@ func TestOAuth2AvatarClientBlocksCloudMetadata(t *testing.T) { func TestOAuth2ScopeChange(t *testing.T) { require.NoError(t, unittest.PrepareTestDatabase()) + defer test.MockVariableValue(&setting.Audit.RecordOutput, setting.AuditRecordOutputDatabase)() app := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ID: 1}) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) mockOpt := contexttest.MockContextOption{SessionStore: session.NewMockMemStore("oauth2-scope-change")} @@ -175,6 +177,8 @@ func TestOAuth2ScopeChange(t *testing.T) { assert.Empty(t, redirect.Query().Get("error")) assert.Equal(t, "state", redirect.Query().Get("state")) unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Grant{ID: 1, Scope: tt.wantScope}) + event := unittest.AssertExistsAndLoadBean(t, &audit_model.Event{Action: audit_model.UserOAuth2ApplicationGrant, ScopeID: doer.ID}, unittest.OrderBy("id DESC")) + assert.Equal(t, tt.wantScope, audit_model.DecodeMetadata(event.Metadata)["granted_scope"]) assert.NotEmpty(t, redirect.Query().Get("code")) resp = authorize(tt.scope) assert.Equal(t, http.StatusSeeOther, resp.Code) diff --git a/routers/web/auth/password.go b/routers/web/auth/password.go index d79b1490296..ed30c9465d3 100644 --- a/routers/web/auth/password.go +++ b/routers/web/auth/password.go @@ -180,6 +180,7 @@ func ResetPasswdPost(ctx *context.Context) { if twofa != nil { if ctx.FormBool("scratch_code") { if !twofa.VerifyScratchToken(ctx.FormString("token")) { + audit.RecordAs(ctx, u, audit_model.UserAuthenticationFailTwoFactor, u) ctx.Data["IsResetForm"] = true ctx.Data["Err_Token"] = true ctx.RenderWithErrDeprecated(ctx.Tr("auth.twofa_scratch_token_incorrect"), tplResetPassword, nil) @@ -195,6 +196,7 @@ func ResetPasswdPost(ctx *context.Context) { } if tfaResult != auth.TwoFactorResultValid { log.Warn("Failed authentication attempt for %s from %s: invalid two-factor passcode", u.Name, ctx.RemoteAddr()) + audit.RecordAs(ctx, u, audit_model.UserAuthenticationFailTwoFactor, u) ctx.Data["IsResetForm"] = true ctx.Data["Err_Passcode"] = true errMsg := ctx.Tr(util.Iif(tfaResult == auth.TwoFactorResultTooManyAttempts, "auth.twofa_too_many_attempts", "auth.twofa_passcode_incorrect")) @@ -208,7 +210,7 @@ func ResetPasswdPost(ctx *context.Context) { Password: optional.Some(ctx.FormString("password")), MustChangePassword: optional.Some(false), } - if err := user_service.UpdateAuth(ctx, u, opts); err != nil { + if err := user_service.UpdateAuth(audit.WithDoer(ctx, u), u, opts); err != nil { ctx.Data["IsResetForm"] = true ctx.Data["Err_Password"] = true switch { diff --git a/routers/web/auth/webauthn.go b/routers/web/auth/webauthn.go index 8f1ddce4d8c..d0aee7a2df8 100644 --- a/routers/web/auth/webauthn.go +++ b/routers/web/auth/webauthn.go @@ -8,12 +8,14 @@ import ( "errors" "net/http" + audit_model "gitea.dev/models/audit" "gitea.dev/models/auth" user_model "gitea.dev/models/user" wa "gitea.dev/modules/auth/webauthn" "gitea.dev/modules/log" "gitea.dev/modules/setting" "gitea.dev/modules/templates" + "gitea.dev/services/audit" "gitea.dev/services/context" "github.com/go-webauthn/webauthn/protocol" @@ -226,6 +228,7 @@ func WebAuthnLoginAssertionPost(ctx *context.Context) { if err != nil { // Failed authentication attempt. log.Info("Failed authentication attempt for %s from %s: %v", user.Name, ctx.RemoteAddr(), err) + audit.RecordAs(ctx, user, audit_model.UserAuthenticationFailTwoFactor, user) ctx.Status(http.StatusForbidden) return } @@ -236,6 +239,7 @@ func WebAuthnLoginAssertionPost(ctx *context.Context) { if err != nil { // Failed authentication attempt. log.Info("Failed authentication attempt for %s from %s: %v", user.Name, ctx.RemoteAddr(), err) + audit.RecordAs(ctx, user, audit_model.UserAuthenticationFailTwoFactor, user) ctx.Status(http.StatusForbidden) return } @@ -244,6 +248,7 @@ func WebAuthnLoginAssertionPost(ctx *context.Context) { // (This is set if the sign counter is less than the one we have stored.) if cred.Authenticator.CloneWarning { log.Info("Failed authentication attempt for %s from %s: cloned credential", user.Name, ctx.RemoteAddr()) + audit.RecordAs(ctx, user, audit_model.UserAuthenticationFailTwoFactor, user) ctx.Status(http.StatusForbidden) return } diff --git a/routers/web/user/setting/account.go b/routers/web/user/setting/account.go index 51505cf8636..33a81ee3e26 100644 --- a/routers/web/user/setting/account.go +++ b/routers/web/user/setting/account.go @@ -9,6 +9,7 @@ import ( "net/http" "time" + audit_model "gitea.dev/models/audit" org_model "gitea.dev/models/organization" packages_model "gitea.dev/models/packages" repo_model "gitea.dev/models/repo" @@ -21,6 +22,7 @@ import ( "gitea.dev/modules/timeutil" "gitea.dev/modules/util" "gitea.dev/modules/web" + "gitea.dev/services/audit" "gitea.dev/services/auth" "gitea.dev/services/auth/source/db" "gitea.dev/services/auth/source/smtp" @@ -114,7 +116,8 @@ func EmailPost(ctx *context.Context) { // Make email address primary. if ctx.FormString("_method") == "PRIMARY" { - if err := user_model.MakeActiveEmailPrimary(ctx, ctx.Doer.ID, ctx.FormInt64("id")); err != nil { + emailID := ctx.FormInt64("id") + if err := user_model.MakeActiveEmailPrimary(ctx, ctx.Doer.ID, emailID); err != nil { if user_model.IsErrEmailAddressNotExist(err) { ctx.Flash.Error(ctx.Tr("settings.email_primary_not_found")) ctx.Redirect(setting.AppSubURL + "/user/settings/account") @@ -124,6 +127,11 @@ func EmailPost(ctx *context.Context) { return } + if email, err := user_model.GetEmailAddressByID(ctx, ctx.Doer.ID, emailID); err != nil { + log.Error("GetEmailAddressByID: %v", err) + } else if email != nil { + audit.Record(ctx, audit_model.UserEmailPrimaryChange, ctx.Doer, "email", email.Email) + } log.Trace("Email made primary: %s", ctx.Doer.Name) ctx.Redirect(setting.AppSubURL + "/user/settings/account") return diff --git a/services/auth/source/oauth2/source_sync.go b/services/auth/source/oauth2/source_sync.go index 3827e81633f..e9ba77e717f 100644 --- a/services/auth/source/oauth2/source_sync.go +++ b/services/auth/source/oauth2/source_sync.go @@ -11,6 +11,9 @@ import ( "gitea.dev/models/db" user_model "gitea.dev/models/user" "gitea.dev/modules/log" + "gitea.dev/modules/optional" + "gitea.dev/services/audit" + user_service "gitea.dev/services/user" "github.com/markbates/goth" "golang.org/x/oauth2" @@ -73,8 +76,8 @@ func (source *Source) refresh(ctx context.Context, provider goth.Provider, u *us return db.WithTx(ctx, func(ctx context.Context) error { if hasUser { log.Info("SyncExternalUsers[%s] disabling user %d", source.AuthSource.Name, user.ID) - user.IsActive = false - if err := user_model.UpdateUserCols(ctx, user, "is_active"); err != nil { + opts := &user_service.UpdateOptions{IsActive: optional.Some(false)} + if err := user_service.UpdateUser(audit.WithDoer(ctx, user_model.NewAuthSourceUser()), user, opts); err != nil { return err } } diff --git a/services/auth/source/oauth2/source_sync_test.go b/services/auth/source/oauth2/source_sync_test.go index 888ca55e507..d82a040fe18 100644 --- a/services/auth/source/oauth2/source_sync_test.go +++ b/services/auth/source/oauth2/source_sync_test.go @@ -6,15 +6,19 @@ package oauth2 import ( "testing" + audit_model "gitea.dev/models/audit" "gitea.dev/models/auth" "gitea.dev/models/unittest" user_model "gitea.dev/models/user" + "gitea.dev/modules/setting" + "gitea.dev/modules/test" "github.com/stretchr/testify/assert" ) func TestSource(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) + defer test.MockVariableValue(&setting.Audit.RecordOutput, setting.AuditRecordOutputDatabase)() source := &Source{ Provider: "fake", @@ -69,13 +73,15 @@ func TestSource(t *testing.T) { }) t.Run("expired", func(t *testing.T) { - err := source.refresh(t.Context(), provider, &user_model.ExternalLoginUser{ - ExternalID: "external", - UserID: user.ID, - LoginSourceID: user.LoginSource, - RefreshToken: "expired", - }) - assert.NoError(t, err) + for range 2 { + assert.NoError(t, source.refresh(t.Context(), provider, &user_model.ExternalLoginUser{ + ExternalID: "external", + UserID: user.ID, + LoginSourceID: user.LoginSource, + RefreshToken: "expired", + })) + } + unittest.AssertCount(t, &audit_model.Event{Action: audit_model.UserActive, ScopeID: user.ID, ActorID: user_model.AuthSourceUserID}, 1) e, ok, err := user_model.GetExternalLogin(t.Context(), e.LoginSourceID, e.ExternalID) assert.NoError(t, err) diff --git a/services/externalaccount/user.go b/services/externalaccount/user.go index 13b74720941..945769a060d 100644 --- a/services/externalaccount/user.go +++ b/services/externalaccount/user.go @@ -71,7 +71,12 @@ func LinkAccountToUser(ctx context.Context, authSourceID int64, user *user_model // EnsureLinkExternalToUser link the gothUser to the user func EnsureLinkExternalToUser(ctx context.Context, authSourceID int64, user *user_model.User, gothUser goth.User) error { externalLoginUser := toExternalLoginUser(authSourceID, user, gothUser) - return user_model.EnsureLinkExternalToUser(ctx, externalLoginUser) + inserted, err := user_model.EnsureLinkExternalToUser(ctx, externalLoginUser) + if inserted { + audit.RecordAs(ctx, user, audit_model.UserExternalLoginAdd, user, + "external_id", externalLoginUser.ExternalID, "provider", externalLoginUser.Provider) + } + return err } // UpdateMigrationsByType updates all migrated repositories' posterid from gitServiceType to replace originalAuthorID to posterID diff --git a/tests/integration/admin_audit_test.go b/tests/integration/admin_audit_test.go index fccc0a73844..140c03c494a 100644 --- a/tests/integration/admin_audit_test.go +++ b/tests/integration/admin_audit_test.go @@ -8,19 +8,25 @@ import ( "fmt" "mime" "net/http" + "strconv" "strings" "testing" + asymkey_model "gitea.dev/models/asymkey" audit_model "gitea.dev/models/audit" auth_model "gitea.dev/models/auth" "gitea.dev/models/unittest" + user_model "gitea.dev/models/user" "gitea.dev/modules/json" "gitea.dev/modules/setting" api "gitea.dev/modules/structs" "gitea.dev/modules/test" "gitea.dev/modules/timeutil" + "gitea.dev/services/auth/source/oauth2" "gitea.dev/tests" + "github.com/markbates/goth" + "github.com/markbates/goth/gothic" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -172,6 +178,101 @@ func TestAdminAuditLogExport(t *testing.T) { }) } +func TestAuditLogUserEvents(t *testing.T) { + defer tests.PrepareTestEnv(t)() + defer test.MockVariableValue(&setting.Audit.RecordOutput, setting.AuditRecordOutputDatabase)() + + findEvent := func(t *testing.T, action audit_model.Action, scopeID int64) *audit_model.Event { + t.Helper() + events, _, err := audit_model.FindEvents(t.Context(), &audit_model.EventSearchOptions{Action: action, ScopeType: audit_model.ScopeUser, ScopeID: scopeID}) + require.NoError(t, err) + require.Len(t, events, 1, "audit events for %s", action) + return events[0] + } + + t.Run("EmailPrimaryAndActivate", func(t *testing.T) { + email, err := user_model.InsertEmailAddress(t.Context(), &user_model.EmailAddress{UID: 2, Email: "audit-primary@example.com", IsActivated: true}) + require.NoError(t, err) + + loginUser(t, "user2").MakeRequest(t, NewRequestWithValues(t, "POST", "/user/settings/account/email", map[string]string{ + "_method": "PRIMARY", + "id": strconv.FormatInt(email.ID, 10), + }), http.StatusSeeOther) + + assert.Equal(t, email.Email, audit_model.DecodeMetadata(findEvent(t, audit_model.UserEmailPrimaryChange, 2).Metadata)["email"]) + + code := user_model.GenerateUserTimeLimitCode(&user_model.TimeLimitCodeOptions{Purpose: user_model.TimeLimitCodeActivateEmail, NewEmail: "user2-2@example.com"}, unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})) + MakeRequest(t, NewRequest(t, "GET", "/user/activate_email?code="+code+"&email=user2-2%40example.com"), http.StatusSeeOther) + assert.Equal(t, "user2-2@example.com", audit_model.DecodeMetadata(findEvent(t, audit_model.UserEmailActivate, 2).Metadata)["email"]) + }) + + t.Run("APIGPGKey", func(t *testing.T) { + token := getTokenForLoggedInUser(t, loginUser(t, "user2"), auth_model.AccessTokenScopeWriteUser) + testCreateValidGPGKey(t, MakeRequest, token, http.StatusCreated) + findEvent(t, audit_model.UserKeyGPGAdd, 2) + + key := unittest.AssertExistsAndLoadBean(t, &asymkey_model.GPGKey{OwnerID: 2, KeyID: "38EA3BCED732982C"}) + MakeRequest(t, NewRequest(t, "DELETE", "/api/v1/user/gpg_keys/"+strconv.FormatInt(key.ID, 10)).AddTokenAuth(token), http.StatusNoContent) + findEvent(t, audit_model.UserKeyGPGRemove, 2) + }) + + t.Run("TwoFactorFailOnSignInAndPasswordReset", func(t *testing.T) { + loginUser(t, "user24").MakeRequest(t, NewRequestWithValues(t, "POST", "/user/two_factor/scratch", map[string]string{ + "token": "wrong-token", + }), http.StatusOK) + findEvent(t, audit_model.UserAuthenticationFailTwoFactor, 24) + + code := user_model.GenerateUserTimeLimitCode(&user_model.TimeLimitCodeOptions{Purpose: user_model.TimeLimitCodeResetPassword}, unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 24})) + for _, scratchCode := range []string{"true", "false"} { + MakeRequest(t, NewRequestWithValues(t, "POST", "/user/recover_account", map[string]string{ + "code": code, + "scratch_code": scratchCode, + "token": "wrong-token", + }), http.StatusOK) + } + unittest.AssertCount(t, &audit_model.Event{Action: audit_model.UserAuthenticationFailTwoFactor, ScopeID: 24, ActorID: 24}, 3) + }) + + t.Run("PasswordResetActor", func(t *testing.T) { + user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) + code := user_model.GenerateUserTimeLimitCode(&user_model.TimeLimitCodeOptions{Purpose: user_model.TimeLimitCodeResetPassword}, user) + MakeRequest(t, NewRequestWithValues(t, "POST", "/user/recover_account", map[string]string{ + "code": code, + "password": "examplePassword!1", + }), http.StatusSeeOther) + assert.Equal(t, user.ID, findEvent(t, audit_model.UserPassword, user.ID).ActorID) + }) + + t.Run("AdminResetTwoFactor", func(t *testing.T) { + session := loginUser(t, "user1") + for range 2 { + session.MakeRequest(t, NewRequestWithValues(t, "POST", "/-/admin/users/24/edit", map[string]string{ + "login_name": "user24", + "login_type": "0-0", + "email": "user24@example.com", + "active": "on", + "reset_2fa": "on", + }), http.StatusSeeOther) + } + assert.Equal(t, int64(1), findEvent(t, audit_model.UserTwoFactorDisable, 24).ActorID) + }) + + t.Run("OAuth2AutoRegisterWithoutAccountLinking", func(t *testing.T) { + defer test.MockVariableValue(&setting.OAuth2Client.EnableAutoRegistration, true)() + defer test.MockVariableValue(&setting.OAuth2Client.AccountLinking, setting.OAuth2AccountLinkingDisabled)() + defer test.MockVariableValue(&gothic.CompleteUserAuth, func(http.ResponseWriter, *http.Request) (goth.User, error) { + return goth.User{Provider: "gitea", UserID: "audit-oauth2", NickName: "audit-oauth2", Email: "audit-oauth2@example.com"}, nil + })() + addOAuth2Source(t, "audit-oauth2", oauth2.Source{}) + + for range 2 { + emptyTestSession(t).MakeRequest(t, NewRequest(t, "GET", "/user/oauth2/audit-oauth2/callback?code=XYZ&state=XYZ"), http.StatusSeeOther) + } + user := unittest.AssertExistsAndLoadBean(t, &user_model.User{LoginName: "audit-oauth2"}) + assert.Equal(t, "audit-oauth2", audit_model.DecodeMetadata(findEvent(t, audit_model.UserExternalLoginAdd, user.ID).Metadata)["external_id"]) + }) +} + func TestAuditLogRepositoryAPIEvents(t *testing.T) { defer tests.PrepareTestEnv(t)() defer test.MockVariableValue(&setting.Audit.RecordOutput, setting.AuditRecordOutputDatabase)() diff --git a/tests/integration/api_keys_test.go b/tests/integration/api_keys_test.go index 0224a4a0ca0..7c2e9fcff64 100644 --- a/tests/integration/api_keys_test.go +++ b/tests/integration/api_keys_test.go @@ -10,13 +10,16 @@ import ( "testing" asymkey_model "gitea.dev/models/asymkey" + audit_model "gitea.dev/models/audit" auth_model "gitea.dev/models/auth" deploykey_model "gitea.dev/models/deploykey" "gitea.dev/models/perm" repo_model "gitea.dev/models/repo" "gitea.dev/models/unittest" user_model "gitea.dev/models/user" + "gitea.dev/modules/setting" api "gitea.dev/modules/structs" + "gitea.dev/modules/test" "gitea.dev/tests" "github.com/stretchr/testify/assert" @@ -100,6 +103,7 @@ func TestCreateDeployKey(t *testing.T) { func TestCreateUserKey(t *testing.T) { defer tests.PrepareTestEnv(t)() + defer test.MockVariableValue(&setting.Audit.RecordOutput, setting.AuditRecordOutputDatabase)() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user1"}) session := loginUser(t, "user1") @@ -124,6 +128,8 @@ func TestCreateUserKey(t *testing.T) { Fingerprint: fingerprint, Mode: perm.AccessModeWrite, }) + event := unittest.AssertExistsAndLoadBean(t, &audit_model.Event{Action: audit_model.UserKeySSHAdd, ScopeID: user.ID}) + assert.Equal(t, fingerprint, audit_model.DecodeMetadata(event.Metadata)["fingerprint"]) // Search by fingerprint for _, url := range []string{ diff --git a/tests/integration/api_token_self_test.go b/tests/integration/api_token_self_test.go index 8f6841e76b3..beb6c699c86 100644 --- a/tests/integration/api_token_self_test.go +++ b/tests/integration/api_token_self_test.go @@ -7,10 +7,13 @@ import ( "net/http" "testing" + audit_model "gitea.dev/models/audit" auth_model "gitea.dev/models/auth" "gitea.dev/models/unittest" user_model "gitea.dev/models/user" + "gitea.dev/modules/setting" api "gitea.dev/modules/structs" + "gitea.dev/modules/test" "gitea.dev/tests" "github.com/stretchr/testify/assert" @@ -55,6 +58,7 @@ func TestAPIGetCurrentToken(t *testing.T) { // TestAPITokenSelfService tests delete operations on token t.Run("SelfService", func(t *testing.T) { t.Run("Success then verify deleted", func(t *testing.T) { + defer test.MockVariableValue(&setting.Audit.RecordOutput, setting.AuditRecordOutputDatabase)() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) accessToken := createAPIAccessTokenWithoutCleanUp(t, "test-delete-current-token", user, []auth_model.AccessTokenScope{auth_model.AccessTokenScopeAll}) @@ -65,6 +69,8 @@ func TestAPIGetCurrentToken(t *testing.T) { // Verify the token is deleted unittest.AssertNotExistsBean(t, &auth_model.AccessToken{ID: accessToken.ID}) + event := unittest.AssertExistsAndLoadBean(t, &audit_model.Event{Action: audit_model.UserAccessTokenRemove, ScopeID: user.ID}) + assert.Equal(t, accessToken.Name, audit_model.DecodeMetadata(event.Metadata)["token"]) // Verify the token can no longer be used for GET req = NewRequest(t, "GET", "/api/v1/token"). diff --git a/tests/integration/signup_test.go b/tests/integration/signup_test.go index 0390108e419..2960a0898bb 100644 --- a/tests/integration/signup_test.go +++ b/tests/integration/signup_test.go @@ -9,6 +9,7 @@ import ( "strings" "testing" + audit_model "gitea.dev/models/audit" "gitea.dev/models/db" "gitea.dev/models/unittest" user_model "gitea.dev/models/user" @@ -25,6 +26,7 @@ import ( func TestSignup(t *testing.T) { defer tests.PrepareTestEnv(t)() defer test.MockVariableValue(&setting.Service.EnableCaptcha, false)() + defer test.MockVariableValue(&setting.Audit.RecordOutput, setting.AuditRecordOutputDatabase)() req := NewRequestWithValues(t, "POST", "/user/sign_up", map[string]string{ "user_name": "exampleUser", @@ -33,6 +35,7 @@ func TestSignup(t *testing.T) { "retype": "examplePassword!1", }) MakeRequest(t, req, http.StatusSeeOther) + unittest.AssertExistsAndLoadBean(t, &audit_model.Event{Action: audit_model.UserCreate, ActorName: "exampleUser", ScopeName: "exampleUser"}) // should be able to view new user's page req = NewRequest(t, "GET", "/exampleUser") @@ -125,6 +128,7 @@ func TestSignupEmailValidation(t *testing.T) { func TestSignupEmailActive(t *testing.T) { defer tests.PrepareTestEnv(t)() defer test.MockVariableValue(&setting.Service.RegisterEmailConfirm, true)() + defer test.MockVariableValue(&setting.Audit.RecordOutput, setting.AuditRecordOutputDatabase)() // try to sign up and send the activation email req := NewRequestWithValues(t, "POST", "/user/sign_up", map[string]string{ @@ -152,6 +156,7 @@ func TestSignupEmailActive(t *testing.T) { email := unittest.AssertExistsAndLoadBean(t, &user_model.EmailAddress{Email: "email-changed@example.com"}) assert.False(t, email.IsActivated) assert.True(t, email.IsPrimary) + unittest.AssertExistsAndLoadBean(t, &audit_model.Event{Action: audit_model.UserEmailPrimaryChange, ScopeID: user.ID}) // generate an activation code from lower-cased email activationCode := user_model.GenerateUserTimeLimitCode(&user_model.TimeLimitCodeOptions{Purpose: user_model.TimeLimitCodeActivateAccount}, user) @@ -184,4 +189,5 @@ func TestSignupEmailActive(t *testing.T) { assert.Equal(t, "/", test.RedirectURL(resp)) user = unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "Test-User-1"}) assert.True(t, user.IsActive) + unittest.AssertExistsAndLoadBean(t, &audit_model.Event{Action: audit_model.UserActive, ScopeID: user.ID, ActorID: user.ID}) }