mirror of
https://github.com/go-gitea/gitea.git
synced 2026-11-23 18:54:51 +00:00
enhance(audit): record remaining security-relevant events (#40323)
Adds audit actions for security-relevant changes that were not logged at all, and records a few remaining events on paths that skipped them: - Account login prohibition (`user:status:prohibitlogin`) and the organization setting that lets repository admins change team access - Actions runner registration tokens issued, runners removed or enabled/disabled, and Actions variables, for every scope - Instance config changes, including maintenance mode (`system:config:update`) - Deploy token regeneration and pull mirror address changes - Review deletion and dismissal, package removal, and release and tag removal - Repository restores via `gitea admin restore-repo`, OAuth2 secret rotation on API update, and SSH keys added or removed by authentication source sync The authentication source SSH key sync moved from the asymkey model to the asymkey service so it can record events. Follow-up to https://github.com/go-gitea/gitea/pull/40317 and https://github.com/go-gitea/gitea/pull/40322. --------- Co-authored-by: silverwind <me@silverwind.io>
This commit is contained in:
1 parent
c144668e59
commit
3f1b738f09
35 files changed
+505
-182
No files matched your search
+2
-1
@@ -13,6 +13,7 @@ import (
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/modules/log"
|
||||
repo_module "gitea.dev/modules/repository"
|
||||
"gitea.dev/services/audit"
|
||||
|
||||
"github.com/urfave/cli/v3"
|
||||
)
|
||||
@@ -55,7 +56,7 @@ func newAuthCommand() *cli.Command {
|
||||
Name: "auth",
|
||||
Usage: "Modify external auth providers",
|
||||
Before: func(ctx context.Context, _ *cli.Command) (context.Context, error) {
|
||||
return cliAuditContext(ctx), nil
|
||||
return audit.WithCLIDoer(ctx), nil
|
||||
},
|
||||
Commands: []*cli.Command{
|
||||
microcmdAuthAddOauth(),
|
||||
|
||||
+2
-1
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/modules/util"
|
||||
"gitea.dev/services/audit"
|
||||
|
||||
"github.com/urfave/cli/v3"
|
||||
)
|
||||
@@ -30,7 +31,7 @@ func newUserCommand() *cli.Command {
|
||||
Name: "user",
|
||||
Usage: "Modify users",
|
||||
Before: func(ctx context.Context, _ *cli.Command) (context.Context, error) {
|
||||
return cliAuditContext(ctx), nil
|
||||
return audit.WithCLIDoer(ctx), nil
|
||||
},
|
||||
Commands: []*cli.Command{
|
||||
microcmdUserCreate(),
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
audit_model "gitea.dev/models/audit"
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/services/audit"
|
||||
)
|
||||
|
||||
func cliAuditContext(ctx context.Context) context.Context {
|
||||
ctx = audit.WithOrigin(ctx, audit_model.OriginCLI)
|
||||
return audit.WithDoer(ctx, user_model.NewCliUser())
|
||||
}
|
||||
+1
-1
@@ -229,7 +229,7 @@ func serveInstalled(c *cli.Command) error {
|
||||
// Set up Chi routes
|
||||
webRoutes := routers.NormalRoutes()
|
||||
|
||||
auditCtx := cliAuditContext(context.Background())
|
||||
auditCtx := audit.WithCLIDoer(context.Background())
|
||||
log.Info("Audit record output: %s", setting.Audit.RecordOutput)
|
||||
audit.Record(auditCtx, audit_model.SystemStartup, nil, "version", setting.AppVer)
|
||||
|
||||
|
||||
@@ -13,13 +13,10 @@ import (
|
||||
"gitea.dev/models/auth"
|
||||
"gitea.dev/models/db"
|
||||
"gitea.dev/models/perm"
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/timeutil"
|
||||
"gitea.dev/modules/util"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
"xorm.io/builder"
|
||||
)
|
||||
|
||||
@@ -319,134 +316,3 @@ func PublicKeyIsExternallyManaged(ctx context.Context, id int64) (bool, error) {
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// deleteKeysMarkedForDeletion returns true if ssh keys needs update
|
||||
func deleteKeysMarkedForDeletion(ctx context.Context, keys []string) (bool, error) {
|
||||
return db.WithTx2(ctx, func(ctx context.Context) (bool, error) {
|
||||
// Delete keys marked for deletion
|
||||
var sshKeysNeedUpdate bool
|
||||
for _, sshKeyToDelete := range keys {
|
||||
key, err := SearchPublicKeyForSSH(ctx, sshKeyToDelete)
|
||||
if err != nil {
|
||||
log.Error("SearchPublicKeyForSSH: %v", err)
|
||||
continue
|
||||
}
|
||||
if _, err = db.DeleteByID[PublicKey](ctx, key.ID); err != nil {
|
||||
log.Error("DeleteByID[PublicKey]: %v", err)
|
||||
continue
|
||||
}
|
||||
sshKeysNeedUpdate = true
|
||||
}
|
||||
|
||||
return sshKeysNeedUpdate, nil
|
||||
})
|
||||
}
|
||||
|
||||
// AddPublicKeysBySource add a users public keys. Returns true if there are changes.
|
||||
func AddPublicKeysBySource(ctx context.Context, usr *user_model.User, s *auth.Source, sshPublicKeys []string, verified bool) bool {
|
||||
var sshKeysNeedUpdate bool
|
||||
for _, sshKey := range sshPublicKeys {
|
||||
var err error
|
||||
found := false
|
||||
keys := []byte(sshKey)
|
||||
loop:
|
||||
for len(keys) > 0 && err == nil {
|
||||
var out ssh.PublicKey
|
||||
// We ignore options as they are not relevant to Gitea
|
||||
out, _, _, keys, err = ssh.ParseAuthorizedKey(keys)
|
||||
if err != nil {
|
||||
break loop
|
||||
}
|
||||
found = true
|
||||
marshalled := string(ssh.MarshalAuthorizedKey(out))
|
||||
marshalled = marshalled[:len(marshalled)-1]
|
||||
sshKeyName := fmt.Sprintf("%s-%s", s.Name, ssh.FingerprintSHA256(out))
|
||||
|
||||
if _, err := AddPublicKey(ctx, usr.ID, sshKeyName, marshalled, s.ID, verified); err != nil {
|
||||
if IsErrKeyAlreadyExist(err) {
|
||||
log.Trace("AddPublicKeysBySource[%s]: Public SSH Key %s already exists for user", sshKeyName, usr.Name)
|
||||
} else {
|
||||
log.Error("AddPublicKeysBySource[%s]: Error adding Public SSH Key for user %s: %v", sshKeyName, usr.Name, err)
|
||||
}
|
||||
} else {
|
||||
log.Trace("AddPublicKeysBySource[%s]: Added Public SSH Key for user %s", sshKeyName, usr.Name)
|
||||
sshKeysNeedUpdate = true
|
||||
}
|
||||
}
|
||||
if !found && err != nil {
|
||||
log.Warn("AddPublicKeysBySource[%s]: Skipping invalid Public SSH Key for user %s: %v", s.Name, usr.Name, sshKey)
|
||||
}
|
||||
}
|
||||
return sshKeysNeedUpdate
|
||||
}
|
||||
|
||||
// SynchronizePublicKeys updates a user's public keys. Returns true if there are changes.
|
||||
func SynchronizePublicKeys(ctx context.Context, usr *user_model.User, s *auth.Source, sshPublicKeys []string, verified bool) bool {
|
||||
var sshKeysNeedUpdate bool
|
||||
|
||||
log.Trace("synchronizePublicKeys[%s]: Handling Public SSH Key synchronization for user %s", s.Name, usr.Name)
|
||||
|
||||
// Get Public Keys from DB with the current auth source
|
||||
var giteaKeys []string
|
||||
keys, err := db.Find[PublicKey](ctx, FindPublicKeyOptions{
|
||||
OwnerID: usr.ID,
|
||||
LoginSourceID: s.ID,
|
||||
})
|
||||
if err != nil {
|
||||
log.Error("synchronizePublicKeys[%s]: Error listing Public SSH Keys for user %s: %v", s.Name, usr.Name, err)
|
||||
}
|
||||
|
||||
for _, v := range keys {
|
||||
giteaKeys = append(giteaKeys, v.OmitEmail())
|
||||
}
|
||||
|
||||
// Process the provided keys to remove duplicates and name part
|
||||
var providedKeys []string
|
||||
for _, v := range sshPublicKeys {
|
||||
sshKeySplit := strings.Split(v, " ")
|
||||
if len(sshKeySplit) > 1 {
|
||||
key := strings.Join(sshKeySplit[:2], " ")
|
||||
if !util.SliceContainsString(providedKeys, key) {
|
||||
providedKeys = append(providedKeys, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check if Public Key sync is needed
|
||||
if util.SliceSortedEqual(giteaKeys, providedKeys) {
|
||||
log.Trace("synchronizePublicKeys[%s]: Public Keys are already in sync for %s (Source:%v/DB:%v)", s.Name, usr.Name, len(providedKeys), len(giteaKeys))
|
||||
return false
|
||||
}
|
||||
log.Trace("synchronizePublicKeys[%s]: Public Key needs update for user %s (Source:%v/DB:%v)", s.Name, usr.Name, len(providedKeys), len(giteaKeys))
|
||||
|
||||
// Add new Public SSH Keys that doesn't already exist in DB
|
||||
var newKeys []string
|
||||
for _, key := range providedKeys {
|
||||
if !util.SliceContainsString(giteaKeys, key) {
|
||||
newKeys = append(newKeys, key)
|
||||
}
|
||||
}
|
||||
if AddPublicKeysBySource(ctx, usr, s, newKeys, verified) {
|
||||
sshKeysNeedUpdate = true
|
||||
}
|
||||
|
||||
// Mark keys from DB that no longer exist in the source for deletion
|
||||
var giteaKeysToDelete []string
|
||||
for _, giteaKey := range giteaKeys {
|
||||
if !util.SliceContainsString(providedKeys, giteaKey) {
|
||||
log.Trace("synchronizePublicKeys[%s]: Marking Public SSH Key for deletion for user %s: %v", s.Name, usr.Name, giteaKey)
|
||||
giteaKeysToDelete = append(giteaKeysToDelete, giteaKey)
|
||||
}
|
||||
}
|
||||
|
||||
// Delete keys from DB that no longer exist in the source
|
||||
needUpd, err := deleteKeysMarkedForDeletion(ctx, giteaKeysToDelete)
|
||||
if err != nil {
|
||||
log.Error("synchronizePublicKeys[%s]: Error deleting Public Keys marked for deletion for user %s: %v", s.Name, usr.Name, err)
|
||||
}
|
||||
if needUpd {
|
||||
sshKeysNeedUpdate = true
|
||||
}
|
||||
|
||||
return sshKeysNeedUpdate
|
||||
}
|
||||
@@ -71,6 +71,7 @@ var (
|
||||
UserActive = define("user:status:active", "Changed activation status of user {scope} to {active}.")
|
||||
UserRestricted = define("user:status:restricted", "Changed restricted status of user {scope} to {restricted}.")
|
||||
UserAdmin = define("user:status:admin", "Changed admin status of user {scope} to {admin}.")
|
||||
UserProhibitLogin = define("user:status:prohibitlogin", "Changed login prohibition of user {scope} to {prohibit_login}.")
|
||||
UserType = define("user:type:update", "Changed type of user {scope} to {user_type}.")
|
||||
UserName = define("user:name:update", "Changed user name from {previous_name} to {scope}.")
|
||||
UserPassword = define("user:password", "Changed password of user {scope}.")
|
||||
@@ -109,6 +110,13 @@ var (
|
||||
UserWebhookAdd = define("user:webhook:add", "Added webhook {webhook} to user {scope}.")
|
||||
UserWebhookUpdate = define("user:webhook:update", "Updated webhook {webhook} of user {scope}.")
|
||||
UserWebhookRemove = define("user:webhook:remove", "Removed webhook {webhook} of user {scope}.")
|
||||
UserRunnerToken = define("user:runner:token", "Issued Actions runner registration token for user {scope}.")
|
||||
UserRunnerUpdate = define("user:runner:update", "Updated Actions runner {runner} of user {scope}.")
|
||||
UserRunnerRemove = define("user:runner:remove", "Removed Actions runner {runner} from user {scope}.")
|
||||
UserVariableAdd = define("user:variable:add", "Added variable {variable} to user {scope}.")
|
||||
UserVariableUpdate = define("user:variable:update", "Updated variable {variable} of user {scope}.")
|
||||
UserVariableRemove = define("user:variable:remove", "Removed variable {variable} from user {scope}.")
|
||||
UserPackageRemove = define("user:package:remove", "Removed version {version} of package {package} from user {scope}.")
|
||||
|
||||
OrganizationCreate = define("organization:create", "Created organization {scope}.")
|
||||
OrganizationDelete = define("organization:delete", "Deleted organization {scope}.")
|
||||
@@ -131,6 +139,14 @@ var (
|
||||
OrganizationWebhookAdd = define("organization:webhook:add", "Added webhook {webhook} to organization {scope}.")
|
||||
OrganizationWebhookUpdate = define("organization:webhook:update", "Updated webhook {webhook} of organization {scope}.")
|
||||
OrganizationWebhookRemove = define("organization:webhook:remove", "Removed webhook {webhook} of organization {scope}.")
|
||||
OrganizationTeamAccess = define("organization:teamaccess:update", "Changed whether repository admins of organization {scope} can change team access to {repo_admin_change_team_access}.")
|
||||
OrganizationRunnerToken = define("organization:runner:token", "Issued Actions runner registration token for organization {scope}.")
|
||||
OrganizationRunnerUpdate = define("organization:runner:update", "Updated Actions runner {runner} of organization {scope}.")
|
||||
OrganizationRunnerRemove = define("organization:runner:remove", "Removed Actions runner {runner} from organization {scope}.")
|
||||
OrganizationVariableAdd = define("organization:variable:add", "Added variable {variable} to organization {scope}.")
|
||||
OrganizationVariableUpdate = define("organization:variable:update", "Updated variable {variable} of organization {scope}.")
|
||||
OrganizationVariableRemove = define("organization:variable:remove", "Removed variable {variable} from organization {scope}.")
|
||||
OrganizationPackageRemove = define("organization:package:remove", "Removed version {version} of package {package} from organization {scope}.")
|
||||
|
||||
RepositoryCreate = define("repository:create", "Created repository {scope}.")
|
||||
RepositoryCreateFork = define("repository:fork:create", "Created fork {scope} of repository {base_repo}.")
|
||||
@@ -143,6 +159,7 @@ var (
|
||||
RepositoryConvertMirror = define("repository:mirror:convert", "Converted repository {scope} from pull mirror to regular repository.")
|
||||
RepositoryMirrorPushAdd = define("repository:mirror:push:add", "Added push mirror to {remote_address} for repository {scope}.")
|
||||
RepositoryMirrorPushRemove = define("repository:mirror:push:remove", "Removed push mirror to {remote_address} for repository {scope}.")
|
||||
RepositoryMirrorPullUpdate = define("repository:mirror:pull:update", "Changed pull mirror address of repository {scope} to {remote_address}.")
|
||||
RepositorySigningVerification = define("repository:signingverification", "Changed signing verification of repository {scope} to {trust_model}.")
|
||||
RepositoryTransferStart = define("repository:transfer:start", "Started repository transfer of {scope} to {new_owner}.")
|
||||
RepositoryTransferFinish = define("repository:transfer:finish", "Transferred repository {scope} from {old_owner} to {new_owner}.")
|
||||
@@ -164,10 +181,19 @@ var (
|
||||
RepositoryWebhookUpdate = define("repository:webhook:update", "Updated webhook {webhook} of repository {scope}.")
|
||||
RepositoryWebhookRemove = define("repository:webhook:remove", "Removed webhook {webhook} of repository {scope}.")
|
||||
RepositoryDeployKeyAdd = define("repository:deploykey:add", "Added deploy key {deploy_key} for repository {scope}.")
|
||||
RepositoryDeployKeyRegenerate = define("repository:deploykey:regenerate", "Regenerated deploy token {deploy_key} of repository {scope}.")
|
||||
RepositoryDeployKeyRemove = define("repository:deploykey:remove", "Removed deploy key {deploy_key} from repository {scope}.")
|
||||
RepositorySecretAdd = define("repository:secret:add", "Added secret {secret} to repository {scope}.")
|
||||
RepositorySecretUpdate = define("repository:secret:update", "Updated secret {secret} of repository {scope}.")
|
||||
RepositorySecretRemove = define("repository:secret:remove", "Removed secret {secret} from repository {scope}.")
|
||||
RepositoryRunnerToken = define("repository:runner:token", "Issued Actions runner registration token for repository {scope}.")
|
||||
RepositoryRunnerUpdate = define("repository:runner:update", "Updated Actions runner {runner} of repository {scope}.")
|
||||
RepositoryRunnerRemove = define("repository:runner:remove", "Removed Actions runner {runner} from repository {scope}.")
|
||||
RepositoryVariableAdd = define("repository:variable:add", "Added variable {variable} to repository {scope}.")
|
||||
RepositoryVariableUpdate = define("repository:variable:update", "Updated variable {variable} of repository {scope}.")
|
||||
RepositoryVariableRemove = define("repository:variable:remove", "Removed variable {variable} from repository {scope}.")
|
||||
RepositoryReleaseRemove = define("repository:release:remove", "Removed release {release} from repository {scope}.")
|
||||
RepositoryTagRemove = define("repository:tag:remove", "Removed tag {tag} from repository {scope}.")
|
||||
|
||||
IssueCreate = define("issue:create", "Created issue {issue} in repository {scope}.")
|
||||
IssueDelete = define("issue:delete", "Deleted issue {issue} from repository {scope}.")
|
||||
@@ -179,6 +205,8 @@ var (
|
||||
PullRequestMerge = define("pr:merge", "Merged pull request {pull_request} in repository {scope}.")
|
||||
PullRequestCommentCreate = define("pr:comment:create", "Added comment {comment_id} to pull request {pull_request} in repository {scope}.")
|
||||
PullRequestCommentDelete = define("pr:comment:delete", "Deleted comment {comment_id} from pull request {pull_request} in repository {scope}.")
|
||||
PullRequestReviewDelete = define("pr:review:delete", "Deleted review {review_id} from pull request {pull_request} in repository {scope}.")
|
||||
PullRequestReviewDismiss = define("pr:review:dismiss", "Dismissed review {review_id} of pull request {pull_request} in repository {scope}.")
|
||||
|
||||
ProjectCreate = define("project:create", "Created project {project} in {scope}.")
|
||||
ProjectUpdate = define("project:update", "Updated project {project} in {scope}.")
|
||||
@@ -210,4 +238,11 @@ var (
|
||||
SystemOAuth2ApplicationUpdate = define("system:oauth2application:update", "Updated instance-wide OAuth2 application {oauth2_application}.")
|
||||
SystemOAuth2ApplicationSecret = define("system:oauth2application:secret", "Regenerated secret for instance-wide OAuth2 application {oauth2_application}.")
|
||||
SystemOAuth2ApplicationRemove = define("system:oauth2application:remove", "Removed instance-wide OAuth2 application {oauth2_application}.")
|
||||
SystemConfigUpdate = define("system:config:update", "Changed system setting {key}.")
|
||||
SystemRunnerToken = define("system:runner:token", "Issued instance-wide Actions runner registration token.")
|
||||
SystemRunnerUpdate = define("system:runner:update", "Updated instance-wide Actions runner {runner}.")
|
||||
SystemRunnerRemove = define("system:runner:remove", "Removed instance-wide Actions runner {runner}.")
|
||||
SystemVariableAdd = define("system:variable:add", "Added instance-wide variable {variable}.")
|
||||
SystemVariableUpdate = define("system:variable:update", "Updated instance-wide variable {variable}.")
|
||||
SystemVariableRemove = define("system:variable:remove", "Removed instance-wide variable {variable}.")
|
||||
)
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
audit_model "gitea.dev/models/audit"
|
||||
issues_model "gitea.dev/models/issues"
|
||||
"gitea.dev/models/organization"
|
||||
access_model "gitea.dev/models/perm/access"
|
||||
@@ -17,6 +18,7 @@ import (
|
||||
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"
|
||||
issue_service "gitea.dev/services/issue"
|
||||
@@ -429,7 +431,7 @@ func DeletePullReview(ctx *context.APIContext) {
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
review, _, statusSet := prepareSingleReview(ctx)
|
||||
review, pr, statusSet := prepareSingleReview(ctx)
|
||||
if statusSet {
|
||||
return
|
||||
}
|
||||
@@ -447,6 +449,7 @@ func DeletePullReview(ctx *context.APIContext) {
|
||||
ctx.APIErrorInternal(fmt.Errorf("can not delete ReviewID: %d", review.ID))
|
||||
return
|
||||
}
|
||||
audit.Record(ctx, audit_model.PullRequestReviewDelete, ctx.Repo.Repository, "pull_request", fmt.Sprintf("#%d", pr.Index), "review_id", review.ID)
|
||||
|
||||
ctx.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
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"
|
||||
)
|
||||
@@ -28,6 +29,7 @@ func GetRegistrationToken(ctx *context.APIContext, ownerID, repoID int64) {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
audit.RecordScopedByID(ctx, ownerID, repoID, audit.RunnerToken)
|
||||
|
||||
ctx.JSON(http.StatusOK, RegistrationToken{Token: token.Token})
|
||||
}
|
||||
@@ -112,11 +114,11 @@ func DeleteRunner(ctx *context.APIContext, ownerID, repoID, runnerID int64) {
|
||||
return
|
||||
}
|
||||
|
||||
err := actions_model.DeleteRunner(ctx, runner.ID)
|
||||
if err != nil {
|
||||
if err := actions_model.DeleteRunner(ctx, runner.ID); err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
audit.RecordScopedByID(ctx, runner.OwnerID, runner.RepoID, audit.RunnerRemove, "runner", runner.Name)
|
||||
ctx.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
@@ -136,6 +138,7 @@ func UpdateRunner(ctx *context.APIContext, ownerID, repoID, runnerID int64) {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
audit.RecordScopedByID(ctx, runner.OwnerID, runner.RepoID, audit.RunnerUpdate, "runner", runner.Name, "disabled", *form.Disabled)
|
||||
|
||||
GetRunner(ctx, ownerID, repoID, runnerID)
|
||||
}
|
||||
@@ -450,6 +450,7 @@ func UpdateOauth2Application(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
audit.Record(ctx, audit_model.UserOAuth2ApplicationUpdate, ctx.Doer, "oauth2_application", app.Name)
|
||||
audit.Record(ctx, audit_model.UserOAuth2ApplicationSecret, ctx.Doer, "oauth2_application", app.Name)
|
||||
|
||||
ctx.JSON(http.StatusOK, convert.ToOAuth2Application(app))
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/modules/json"
|
||||
"gitea.dev/modules/private"
|
||||
"gitea.dev/services/audit"
|
||||
"gitea.dev/services/context"
|
||||
)
|
||||
|
||||
@@ -37,6 +38,7 @@ func GenerateActionsRunnerToken(ctx *context.PrivateContext) {
|
||||
ctx.PrivateInternalErrorf("GetOrCreateActiveRunnerToken failed: %v", err)
|
||||
return
|
||||
}
|
||||
audit.RecordScopedByID(audit.WithCLIDoer(ctx), owner, repo, audit.RunnerToken)
|
||||
|
||||
ctx.PlainText(http.StatusOK, token.Token)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"gitea.dev/modules/json"
|
||||
"gitea.dev/services/audit"
|
||||
myCtx "gitea.dev/services/context"
|
||||
"gitea.dev/services/migrations"
|
||||
)
|
||||
@@ -32,7 +33,7 @@ func RestoreRepo(ctx *myCtx.PrivateContext) {
|
||||
}
|
||||
|
||||
if err := migrations.RestoreRepository(
|
||||
ctx,
|
||||
audit.WithCLIDoer(ctx),
|
||||
params.RepoDir,
|
||||
params.OwnerName,
|
||||
params.RepoName,
|
||||
|
||||
@@ -5,8 +5,11 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"maps"
|
||||
"net/http"
|
||||
"slices"
|
||||
|
||||
audit_model "gitea.dev/models/audit"
|
||||
system_model "gitea.dev/models/system"
|
||||
"gitea.dev/modules/cache"
|
||||
"gitea.dev/modules/git"
|
||||
@@ -16,6 +19,7 @@ import (
|
||||
"gitea.dev/modules/setting/config"
|
||||
"gitea.dev/modules/templates"
|
||||
"gitea.dev/modules/util"
|
||||
"gitea.dev/services/audit"
|
||||
"gitea.dev/services/context"
|
||||
"gitea.dev/services/mailer"
|
||||
)
|
||||
@@ -152,10 +156,20 @@ loop:
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
_, oldSettings, err := system_model.GetAllSettings(ctx)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
if err := system_model.SetSettings(ctx, configSettings); err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
for _, key := range slices.Sorted(maps.Keys(configSettings)) {
|
||||
if configSettings[key] != oldSettings[key] {
|
||||
audit.Record(ctx, audit_model.SystemConfigUpdate, nil, "key", key)
|
||||
}
|
||||
}
|
||||
config.GetDynGetter().InvalidateCache()
|
||||
ctx.JSONOK()
|
||||
}
|
||||
@@ -6,7 +6,6 @@ package auth
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
asymkey_model "gitea.dev/models/asymkey"
|
||||
"gitea.dev/models/auth"
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/modules/log"
|
||||
@@ -96,7 +95,7 @@ func oauth2UpdateSSHPubIfNeed(ctx *context.Context, authSource *auth.Source, got
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !asymkey_model.SynchronizePublicKeys(ctx, user, authSource, sshKeys, false) {
|
||||
if !asymkey_service.SynchronizePublicKeys(ctx, user, authSource, sshKeys, false) {
|
||||
return nil
|
||||
}
|
||||
return asymkey_service.RewriteAllPublicKeys(ctx)
|
||||
|
||||
@@ -119,6 +119,7 @@ func DeployKeyRegenerateToken(ctx *context.Context) {
|
||||
}
|
||||
return
|
||||
}
|
||||
audit.Record(ctx, audit_model.RepositoryDeployKeyRegenerate, ctx.Repo.Repository, "deploy_key", key.Name)
|
||||
|
||||
ctx.Flash.Success(ctx.Tr("repo.settings.regenerate_deploy_token_success", htmlutil.HTMLFormat("<code>%s</code>", key.Token)))
|
||||
ctx.JSONRedirect(ctx.Repo.RepoLink + "/settings/keys")
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"gitea.dev/modules/templates"
|
||||
"gitea.dev/modules/web"
|
||||
shared_user "gitea.dev/routers/web/shared/user"
|
||||
"gitea.dev/services/audit"
|
||||
"gitea.dev/services/context"
|
||||
"gitea.dev/services/forms"
|
||||
)
|
||||
@@ -274,6 +275,7 @@ func ResetRunnerRegistrationToken(ctx *context.Context) {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
audit.RecordScopedByID(ctx, ownerID, repoID, audit.RunnerToken)
|
||||
ctx.Flash.Success(ctx.Tr("actions.runners.reset_registration_token_success"))
|
||||
ctx.JSONRedirect(redirectTo)
|
||||
}
|
||||
@@ -307,6 +309,7 @@ func RunnerDeletePost(ctx *context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
audit.RecordScopedByID(ctx, runner.OwnerID, runner.RepoID, audit.RunnerRemove, "runner", runner.Name)
|
||||
log.Info("DeleteRunnerPost success: %s", ctx.Req.URL)
|
||||
|
||||
ctx.Flash.Success(ctx.Tr("actions.runners.delete_runner_success"))
|
||||
@@ -350,6 +353,7 @@ func RunnerUpdatePost(ctx *context.Context) {
|
||||
ctx.JSONRedirect("")
|
||||
return
|
||||
}
|
||||
audit.RecordScopedByID(ctx, runner.OwnerID, runner.RepoID, audit.RunnerUpdate, "runner", runner.Name, "disabled", isDisabled.Value())
|
||||
|
||||
ctx.Flash.Success(ctx.Tr(successKey))
|
||||
ctx.JSONRedirect("")
|
||||
@@ -404,14 +408,13 @@ func RunnerBulkActionPost(ctx *context.Context) {
|
||||
if err := actions_model.DeleteRunner(txCtx, r.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
case "disable":
|
||||
if err := actions_model.SetRunnerDisabled(txCtx, r, true); err != nil {
|
||||
return err
|
||||
}
|
||||
case "enable":
|
||||
if err := actions_model.SetRunnerDisabled(txCtx, r, false); err != nil {
|
||||
audit.RecordScopedByID(txCtx, r.OwnerID, r.RepoID, audit.RunnerRemove, "runner", r.Name)
|
||||
case "disable", "enable":
|
||||
disabled := action == "disable"
|
||||
if err := actions_model.SetRunnerDisabled(txCtx, r, disabled); err != nil {
|
||||
return err
|
||||
}
|
||||
audit.RecordScopedByID(txCtx, r.OwnerID, r.RepoID, audit.RunnerUpdate, "runner", r.Name, "disabled", disabled)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -190,7 +190,7 @@ func VariableDelete(ctx *context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := actions_service.DeleteVariableByID(ctx, variable.ID); err != nil {
|
||||
if err := actions_service.DeleteVariable(ctx, variable); err != nil {
|
||||
log.Error("Delete variable [%d] failed: %v", id, err)
|
||||
ctx.JSONError(ctx.Tr("actions.variables.deletion.failed"))
|
||||
return
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
actions_model "gitea.dev/models/actions"
|
||||
"gitea.dev/modules/util"
|
||||
"gitea.dev/services/audit"
|
||||
secret_service "gitea.dev/services/secrets"
|
||||
)
|
||||
|
||||
@@ -20,6 +21,7 @@ func CreateVariable(ctx context.Context, scope actions_model.BelongingScope, nam
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
audit.RecordScopedByID(ctx, v.OwnerID, v.RepoID, audit.VariableAdd, "variable", v.Name)
|
||||
|
||||
return v, nil
|
||||
}
|
||||
@@ -31,11 +33,19 @@ func UpdateVariableNameData(ctx context.Context, variable *actions_model.ActionV
|
||||
|
||||
variable.Data = util.NormalizeStringEOL(variable.Data)
|
||||
|
||||
return actions_model.UpdateVariableCols(ctx, variable, "name", "data", "description")
|
||||
updated, err := actions_model.UpdateVariableCols(ctx, variable, "name", "data", "description")
|
||||
if updated {
|
||||
audit.RecordScopedByID(ctx, variable.OwnerID, variable.RepoID, audit.VariableUpdate, "variable", variable.Name)
|
||||
}
|
||||
return updated, err
|
||||
}
|
||||
|
||||
func DeleteVariableByID(ctx context.Context, variableID int64) error {
|
||||
return actions_model.DeleteVariable(ctx, variableID)
|
||||
func DeleteVariable(ctx context.Context, variable *actions_model.ActionVariable) error {
|
||||
if err := actions_model.DeleteVariable(ctx, variable.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
audit.RecordScopedByID(ctx, variable.OwnerID, variable.RepoID, audit.VariableRemove, "variable", variable.Name)
|
||||
return nil
|
||||
}
|
||||
|
||||
func DeleteVariableByName(ctx context.Context, scope actions_model.BelongingScope, name string) error {
|
||||
@@ -43,8 +53,7 @@ func DeleteVariableByName(ctx context.Context, scope actions_model.BelongingScop
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return actions_model.DeleteVariable(ctx, v.ID)
|
||||
return DeleteVariable(ctx, v)
|
||||
}
|
||||
|
||||
func GetVariable(ctx context.Context, opts actions_model.FindVariablesOpts) (*actions_model.ActionVariable, error) {
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package asymkey
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
asymkey_model "gitea.dev/models/asymkey"
|
||||
audit_model "gitea.dev/models/audit"
|
||||
auth_model "gitea.dev/models/auth"
|
||||
"gitea.dev/models/db"
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/util"
|
||||
"gitea.dev/services/audit"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
// deleteKeysMarkedForDeletion returns true if ssh keys needs update
|
||||
func deleteKeysMarkedForDeletion(ctx context.Context, usr *user_model.User, keys []string) (bool, error) {
|
||||
return db.WithTx2(ctx, func(ctx context.Context) (bool, error) {
|
||||
// Delete keys marked for deletion
|
||||
var sshKeysNeedUpdate bool
|
||||
for _, sshKeyToDelete := range keys {
|
||||
key, err := asymkey_model.SearchPublicKeyForSSH(ctx, sshKeyToDelete)
|
||||
if err != nil {
|
||||
log.Error("SearchPublicKeyForSSH: %v", err)
|
||||
continue
|
||||
}
|
||||
if _, err = db.DeleteByID[asymkey_model.PublicKey](ctx, key.ID); err != nil {
|
||||
log.Error("DeleteByID[PublicKey]: %v", err)
|
||||
continue
|
||||
}
|
||||
audit.RecordAs(ctx, user_model.NewAuthSourceUser(), audit_model.UserKeySSHRemove, usr, "fingerprint", key.Fingerprint)
|
||||
sshKeysNeedUpdate = true
|
||||
}
|
||||
|
||||
return sshKeysNeedUpdate, nil
|
||||
})
|
||||
}
|
||||
|
||||
// AddPublicKeysBySource add a users public keys. Returns true if there are changes.
|
||||
func AddPublicKeysBySource(ctx context.Context, usr *user_model.User, s *auth_model.Source, sshPublicKeys []string, verified bool) bool {
|
||||
var sshKeysNeedUpdate bool
|
||||
for _, sshKey := range sshPublicKeys {
|
||||
var err error
|
||||
found := false
|
||||
keys := []byte(sshKey)
|
||||
loop:
|
||||
for len(keys) > 0 && err == nil {
|
||||
var out ssh.PublicKey
|
||||
// We ignore options as they are not relevant to Gitea
|
||||
out, _, _, keys, err = ssh.ParseAuthorizedKey(keys)
|
||||
if err != nil {
|
||||
break loop
|
||||
}
|
||||
found = true
|
||||
marshalled := string(ssh.MarshalAuthorizedKey(out))
|
||||
marshalled = marshalled[:len(marshalled)-1]
|
||||
sshKeyName := fmt.Sprintf("%s-%s", s.Name, ssh.FingerprintSHA256(out))
|
||||
|
||||
key, addErr := asymkey_model.AddPublicKey(ctx, usr.ID, sshKeyName, marshalled, s.ID, verified)
|
||||
if addErr != nil {
|
||||
if asymkey_model.IsErrKeyAlreadyExist(addErr) {
|
||||
log.Trace("AddPublicKeysBySource[%s]: Public SSH Key %s already exists for user", sshKeyName, usr.Name)
|
||||
} else {
|
||||
log.Error("AddPublicKeysBySource[%s]: Error adding Public SSH Key for user %s: %v", sshKeyName, usr.Name, addErr)
|
||||
}
|
||||
} else {
|
||||
audit.RecordAs(ctx, user_model.NewAuthSourceUser(), audit_model.UserKeySSHAdd, usr, "fingerprint", key.Fingerprint)
|
||||
log.Trace("AddPublicKeysBySource[%s]: Added Public SSH Key for user %s", sshKeyName, usr.Name)
|
||||
sshKeysNeedUpdate = true
|
||||
}
|
||||
}
|
||||
if !found && err != nil {
|
||||
log.Warn("AddPublicKeysBySource[%s]: Skipping invalid Public SSH Key for user %s: %v", s.Name, usr.Name, sshKey)
|
||||
}
|
||||
}
|
||||
return sshKeysNeedUpdate
|
||||
}
|
||||
|
||||
// SynchronizePublicKeys updates a user's public keys. Returns true if there are changes.
|
||||
func SynchronizePublicKeys(ctx context.Context, usr *user_model.User, s *auth_model.Source, sshPublicKeys []string, verified bool) bool {
|
||||
var sshKeysNeedUpdate bool
|
||||
|
||||
log.Trace("synchronizePublicKeys[%s]: Handling Public SSH Key synchronization for user %s", s.Name, usr.Name)
|
||||
|
||||
// Get Public Keys from DB with the current auth source
|
||||
var giteaKeys []string
|
||||
keys, err := db.Find[asymkey_model.PublicKey](ctx, asymkey_model.FindPublicKeyOptions{
|
||||
OwnerID: usr.ID,
|
||||
LoginSourceID: s.ID,
|
||||
})
|
||||
if err != nil {
|
||||
log.Error("synchronizePublicKeys[%s]: Error listing Public SSH Keys for user %s: %v", s.Name, usr.Name, err)
|
||||
}
|
||||
|
||||
for _, v := range keys {
|
||||
giteaKeys = append(giteaKeys, v.OmitEmail())
|
||||
}
|
||||
|
||||
// Process the provided keys to remove duplicates and name part
|
||||
var providedKeys []string
|
||||
for _, v := range sshPublicKeys {
|
||||
sshKeySplit := strings.Split(v, " ")
|
||||
if len(sshKeySplit) > 1 {
|
||||
key := strings.Join(sshKeySplit[:2], " ")
|
||||
if !util.SliceContainsString(providedKeys, key) {
|
||||
providedKeys = append(providedKeys, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check if Public Key sync is needed
|
||||
if util.SliceSortedEqual(giteaKeys, providedKeys) {
|
||||
log.Trace("synchronizePublicKeys[%s]: Public Keys are already in sync for %s (Source:%v/DB:%v)", s.Name, usr.Name, len(providedKeys), len(giteaKeys))
|
||||
return false
|
||||
}
|
||||
log.Trace("synchronizePublicKeys[%s]: Public Key needs update for user %s (Source:%v/DB:%v)", s.Name, usr.Name, len(providedKeys), len(giteaKeys))
|
||||
|
||||
// Add new Public SSH Keys that doesn't already exist in DB
|
||||
var newKeys []string
|
||||
for _, key := range providedKeys {
|
||||
if !util.SliceContainsString(giteaKeys, key) {
|
||||
newKeys = append(newKeys, key)
|
||||
}
|
||||
}
|
||||
if AddPublicKeysBySource(ctx, usr, s, newKeys, verified) {
|
||||
sshKeysNeedUpdate = true
|
||||
}
|
||||
|
||||
// Mark keys from DB that no longer exist in the source for deletion
|
||||
var giteaKeysToDelete []string
|
||||
for _, giteaKey := range giteaKeys {
|
||||
if !util.SliceContainsString(providedKeys, giteaKey) {
|
||||
log.Trace("synchronizePublicKeys[%s]: Marking Public SSH Key for deletion for user %s: %v", s.Name, usr.Name, giteaKey)
|
||||
giteaKeysToDelete = append(giteaKeysToDelete, giteaKey)
|
||||
}
|
||||
}
|
||||
|
||||
// Delete keys from DB that no longer exist in the source
|
||||
needUpd, err := deleteKeysMarkedForDeletion(ctx, usr, giteaKeysToDelete)
|
||||
if err != nil {
|
||||
log.Error("synchronizePublicKeys[%s]: Error deleting Public Keys marked for deletion for user %s: %v", s.Name, usr.Name, err)
|
||||
}
|
||||
if needUpd {
|
||||
sshKeysNeedUpdate = true
|
||||
}
|
||||
|
||||
return sshKeysNeedUpdate
|
||||
}
|
||||
@@ -7,10 +7,13 @@ import (
|
||||
"testing"
|
||||
|
||||
asymkey_model "gitea.dev/models/asymkey"
|
||||
audit_model "gitea.dev/models/audit"
|
||||
"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"
|
||||
)
|
||||
@@ -36,7 +39,7 @@ func TestAddLdapSSHPublicKeys(t *testing.T) {
|
||||
{rsaKey + " nocomment\n382488320jasdj1lasmva/vasodifipi4193-fksma.cm\n" + ed25519Key + " nocomment", 2, []string{rsaKey, ed25519Key}},
|
||||
} {
|
||||
s.ID = int64(i) + 20
|
||||
asymkey_model.AddPublicKeysBySource(t.Context(), user, s, []string{kase.keyString}, false)
|
||||
AddPublicKeysBySource(t.Context(), user, s, []string{kase.keyString}, false)
|
||||
keys, err := db.Find[asymkey_model.PublicKey](t.Context(), asymkey_model.FindPublicKeyOptions{
|
||||
OwnerID: user.ID,
|
||||
LoginSourceID: s.ID,
|
||||
@@ -55,3 +58,20 @@ func TestAddLdapSSHPublicKeys(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSynchronizePublicKeysAudit(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
defer test.MockVariableValue(&setting.Audit.RecordOutput, setting.AuditRecordOutputDatabase)()
|
||||
|
||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
s := &auth.Source{ID: 30, Name: "ldap"}
|
||||
const key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEYv1rUQ6Sx6XQNM5o8URz8xvuXaV9bGXfj+OMkh8T0X"
|
||||
|
||||
assert.True(t, SynchronizePublicKeys(t.Context(), user, s, []string{key + " comment"}, false))
|
||||
assert.True(t, SynchronizePublicKeys(t.Context(), user, s, nil, false))
|
||||
|
||||
for _, action := range []audit_model.Action{audit_model.UserKeySSHAdd, audit_model.UserKeySSHRemove} {
|
||||
e := unittest.AssertExistsAndLoadBean(t, &audit_model.Event{Action: action, ScopeType: audit_model.ScopeUser, ScopeID: user.ID})
|
||||
assert.Equal(t, user_model.AuthSourceUserID, e.ActorID)
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ package audit
|
||||
import (
|
||||
"context"
|
||||
|
||||
audit_model "gitea.dev/models/audit"
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/modules/web/middleware"
|
||||
)
|
||||
@@ -35,6 +36,10 @@ func WithDoer(ctx context.Context, doer *user_model.User) context.Context {
|
||||
return context.WithValue(ctx, doerContextKey, doer)
|
||||
}
|
||||
|
||||
func WithCLIDoer(ctx context.Context) context.Context {
|
||||
return WithDoer(WithOrigin(ctx, audit_model.OriginCLI), user_model.NewCliUser())
|
||||
}
|
||||
|
||||
// doerFromContext resolves the actor of an audit event: an explicit WithDoer
|
||||
// value wins over the signed-in user of the surrounding request. Returns nil
|
||||
// when neither is available, which Record turns into an unknown actor.
|
||||
|
||||
@@ -5,6 +5,7 @@ package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
audit_model "gitea.dev/models/audit"
|
||||
@@ -91,6 +92,14 @@ func TestBuildEvent(t *testing.T) {
|
||||
assert.InDelta(t, float64(m.ID), audit_model.DecodeMetadata(e.Metadata)["mirror_id"], 0)
|
||||
})
|
||||
|
||||
t.Run("LongMessageTruncatedToColumnSize", func(t *testing.T) {
|
||||
e := buildEvent(context.Background(), RecordParams{
|
||||
Action: audit_model.RepositoryMirrorPullUpdate,
|
||||
Metadata: metaPairs("remote_address", strings.Repeat("a", 300)),
|
||||
})
|
||||
assert.Len(t, e.Message, 255)
|
||||
})
|
||||
|
||||
t.Run("StatusChangesIncludeTheirNewValue", func(t *testing.T) {
|
||||
e := buildEvent(context.Background(), RecordParams{
|
||||
Action: audit_model.UserRestricted,
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"gitea.dev/modules/reqctx"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/timeutil"
|
||||
"gitea.dev/modules/util"
|
||||
)
|
||||
|
||||
// RecordParams describes an audit event. Callers (or domain-specific helpers)
|
||||
@@ -68,7 +69,7 @@ func buildEvent(ctx context.Context, params RecordParams) *audit_model.Event {
|
||||
ScopeType: params.Scope.Type,
|
||||
ScopeID: params.Scope.ID,
|
||||
ScopeName: params.Scope.DisplayName(),
|
||||
Message: renderMessage(params.Action, params.Actor, params.Scope, params.Metadata),
|
||||
Message: util.TruncateRunes(renderMessage(params.Action, params.Actor, params.Scope, params.Metadata), 255), // VARCHAR(255) column
|
||||
Metadata: audit_model.EncodeMetadata(params.Metadata),
|
||||
IPAddress: getIPAddress(ctx),
|
||||
Origin: getOrigin(ctx),
|
||||
|
||||
@@ -9,8 +9,10 @@ import (
|
||||
|
||||
audit_model "gitea.dev/models/audit"
|
||||
issues_model "gitea.dev/models/issues"
|
||||
packages_model "gitea.dev/models/packages"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/modules/log"
|
||||
notify_service "gitea.dev/services/notify"
|
||||
)
|
||||
@@ -174,3 +176,20 @@ func (n *auditNotifier) EditWikiPage(ctx context.Context, doer *user_model.User,
|
||||
func (n *auditNotifier) DeleteWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page string) {
|
||||
RecordAs(ctx, doer, audit_model.WikiPageDelete, repo, "page", page)
|
||||
}
|
||||
|
||||
func (n *auditNotifier) PullReviewDismiss(ctx context.Context, doer *user_model.User, review *issues_model.Review, _ *issues_model.Comment) {
|
||||
if repo := loadIssueRepo(ctx, review.Issue); repo != nil {
|
||||
RecordAs(ctx, doer, audit_model.PullRequestReviewDismiss, repo, "pull_request", issueLabel(review.Issue), "review_id", review.ID)
|
||||
}
|
||||
}
|
||||
|
||||
// DeleteRef only records tags, branch deletions are as routine as pushes.
|
||||
func (n *auditNotifier) DeleteRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refFullName git.RefName) {
|
||||
if refFullName.IsTag() {
|
||||
RecordAs(ctx, doer, audit_model.RepositoryTagRemove, repo, "tag", refFullName.TagName())
|
||||
}
|
||||
}
|
||||
|
||||
func (n *auditNotifier) PackageDelete(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor) {
|
||||
RecordScoped(WithDoer(ctx, doer), pd.Owner, nil, PackageRemove, "package", pd.Package.Name, "version", pd.Version.Version)
|
||||
}
|
||||
@@ -8,9 +8,11 @@ import (
|
||||
|
||||
audit_model "gitea.dev/models/audit"
|
||||
issues_model "gitea.dev/models/issues"
|
||||
packages_model "gitea.dev/models/packages"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/models/unittest"
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/modules/reqctx"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/test"
|
||||
@@ -62,6 +64,16 @@ func TestAuditNotifier(t *testing.T) {
|
||||
func() { notifier.ChangeDefaultBranch(ctx, repo) },
|
||||
audit_model.Event{Action: audit_model.RepositoryBranchDefault},
|
||||
},
|
||||
{
|
||||
func() {
|
||||
notifier.PullReviewDismiss(ctx, doer, &issues_model.Review{ID: 41, Issue: &issues_model.Issue{Index: 8, Repo: repo}}, nil)
|
||||
},
|
||||
audit_model.Event{Action: audit_model.PullRequestReviewDismiss, ActorID: doer.ID, Message: "Dismissed review 41 of pull request #8 in repository owner/repo."},
|
||||
},
|
||||
{
|
||||
func() { notifier.DeleteRef(ctx, doer, repo, git.RefNameFromTag("v1.0")) },
|
||||
audit_model.Event{Action: audit_model.RepositoryTagRemove, ActorID: doer.ID, Message: "Removed tag v1.0 from repository owner/repo."},
|
||||
},
|
||||
{
|
||||
func() { notifier.MigrateRepository(ctx, migrator, migrator, repo) },
|
||||
audit_model.Event{Action: audit_model.RepositoryCreate, ActorID: migrator.ID, Origin: audit_model.OriginUI},
|
||||
@@ -80,6 +92,15 @@ func TestAuditNotifier(t *testing.T) {
|
||||
tc.event.ScopeID = repo.ID
|
||||
unittest.AssertExistsAndLoadBean(t, &tc.event)
|
||||
}
|
||||
|
||||
notifier.DeleteRef(ctx, doer, repo, git.RefNameFromBranch("feature"))
|
||||
unittest.AssertCount(t, &audit_model.Event{Action: audit_model.RepositoryTagRemove}, 1)
|
||||
|
||||
org := &user_model.User{ID: 3, Name: "org3", Type: user_model.UserTypeOrganization}
|
||||
impersonatedCtx := WithImpersonator(ctx, &user_model.User{ID: 1, Name: "admin"})
|
||||
notifier.PackageDelete(impersonatedCtx, doer, &packages_model.PackageDescriptor{Owner: org, Package: &packages_model.Package{Name: "pkg"}, Version: &packages_model.PackageVersion{Version: "1.0.0"}})
|
||||
unittest.AssertExistsAndLoadBean(t, &audit_model.Event{Action: audit_model.OrganizationPackageRemove, ActorID: doer.ID, ImpersonatorID: 1, ScopeType: audit_model.ScopeOrganization, ScopeID: org.ID})
|
||||
|
||||
notifier.PullRequestReview(ctx, pr, &issues_model.Review{ID: 21, Type: issues_model.ReviewTypeApprove, Reviewer: doer}, &issues_model.Comment{ID: 31}, nil)
|
||||
assert.JSONEq(t, `{"pull_request":"#7","comment_id":31,"review_id":21,"review_type":"approve"}`, unittest.AssertExistsAndLoadBean(t, &audit_model.Event{
|
||||
Action: audit_model.PullRequestCommentCreate, ActorID: doer.ID, Message: "Added comment 31 to pull request #7 in repository owner/repo.",
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
repository_model "gitea.dev/models/repo"
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/setting"
|
||||
)
|
||||
|
||||
// ScopedActions holds the action variants for a resource that can be owned by a
|
||||
@@ -81,6 +82,49 @@ var (
|
||||
User: audit_model.UserWebhookRemove,
|
||||
System: audit_model.SystemWebhookRemove,
|
||||
}
|
||||
|
||||
RunnerToken = ScopedActions{
|
||||
Repo: audit_model.RepositoryRunnerToken,
|
||||
Org: audit_model.OrganizationRunnerToken,
|
||||
User: audit_model.UserRunnerToken,
|
||||
System: audit_model.SystemRunnerToken,
|
||||
}
|
||||
RunnerUpdate = ScopedActions{
|
||||
Repo: audit_model.RepositoryRunnerUpdate,
|
||||
Org: audit_model.OrganizationRunnerUpdate,
|
||||
User: audit_model.UserRunnerUpdate,
|
||||
System: audit_model.SystemRunnerUpdate,
|
||||
}
|
||||
RunnerRemove = ScopedActions{
|
||||
Repo: audit_model.RepositoryRunnerRemove,
|
||||
Org: audit_model.OrganizationRunnerRemove,
|
||||
User: audit_model.UserRunnerRemove,
|
||||
System: audit_model.SystemRunnerRemove,
|
||||
}
|
||||
|
||||
VariableAdd = ScopedActions{
|
||||
Repo: audit_model.RepositoryVariableAdd,
|
||||
Org: audit_model.OrganizationVariableAdd,
|
||||
User: audit_model.UserVariableAdd,
|
||||
System: audit_model.SystemVariableAdd,
|
||||
}
|
||||
VariableUpdate = ScopedActions{
|
||||
Repo: audit_model.RepositoryVariableUpdate,
|
||||
Org: audit_model.OrganizationVariableUpdate,
|
||||
User: audit_model.UserVariableUpdate,
|
||||
System: audit_model.SystemVariableUpdate,
|
||||
}
|
||||
VariableRemove = ScopedActions{
|
||||
Repo: audit_model.RepositoryVariableRemove,
|
||||
Org: audit_model.OrganizationVariableRemove,
|
||||
User: audit_model.UserVariableRemove,
|
||||
System: audit_model.SystemVariableRemove,
|
||||
}
|
||||
|
||||
PackageRemove = ScopedActions{
|
||||
Org: audit_model.OrganizationPackageRemove,
|
||||
User: audit_model.UserPackageRemove,
|
||||
}
|
||||
)
|
||||
|
||||
// resolveScope maps an (owner, repo) pair to the scoped action and audit scope.
|
||||
@@ -113,3 +157,22 @@ func RecordScoped(ctx context.Context, owner *user_model.User, repo *repository_
|
||||
}
|
||||
Record(ctx, action, scope, metadata...)
|
||||
}
|
||||
|
||||
func RecordScopedByID(ctx context.Context, ownerID, repoID int64, actions ScopedActions, metadata ...any) {
|
||||
if !setting.AuditRecordEnabled() {
|
||||
return
|
||||
}
|
||||
var owner *user_model.User
|
||||
var repo *repository_model.Repository
|
||||
var err error
|
||||
if repoID != 0 {
|
||||
repo, err = repository_model.GetRepositoryByID(ctx, repoID)
|
||||
} else if ownerID != 0 {
|
||||
owner, err = user_model.GetUserByID(ctx, ownerID)
|
||||
}
|
||||
if err != nil {
|
||||
log.Error("audit: load scope owner=%d repo=%d: %v", ownerID, repoID, err)
|
||||
return
|
||||
}
|
||||
RecordScoped(ctx, owner, repo, actions, metadata...)
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
asymkey_model "gitea.dev/models/asymkey"
|
||||
audit_model "gitea.dev/models/audit"
|
||||
"gitea.dev/models/auth"
|
||||
user_model "gitea.dev/models/user"
|
||||
@@ -77,7 +76,7 @@ func (source *Source) Authenticate(ctx context.Context, user *user_model.User, u
|
||||
}
|
||||
|
||||
if user != nil {
|
||||
if isAttributeSSHPublicKeySet && asymkey_model.SynchronizePublicKeys(ctx, user, source.AuthSource, sr.SSHPublicKey, source.SSHKeysAreVerified) {
|
||||
if isAttributeSSHPublicKeySet && asymkey_service.SynchronizePublicKeys(ctx, user, source.AuthSource, sr.SSHPublicKey, source.SSHKeysAreVerified) {
|
||||
if err := asymkey_service.RewriteAllPublicKeys(ctx); err != nil {
|
||||
return user, err
|
||||
}
|
||||
@@ -105,7 +104,7 @@ func (source *Source) Authenticate(ctx context.Context, user *user_model.User, u
|
||||
|
||||
audit.Record(ctx, audit_model.UserCreate, user)
|
||||
|
||||
if isAttributeSSHPublicKeySet && asymkey_model.AddPublicKeysBySource(ctx, user, source.AuthSource, sr.SSHPublicKey, source.SSHKeysAreVerified) {
|
||||
if isAttributeSSHPublicKeySet && asymkey_service.AddPublicKeysBySource(ctx, user, source.AuthSource, sr.SSHPublicKey, source.SSHKeysAreVerified) {
|
||||
if err := asymkey_service.RewriteAllPublicKeys(ctx); err != nil {
|
||||
return user, err
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
asymkey_model "gitea.dev/models/asymkey"
|
||||
audit_model "gitea.dev/models/audit"
|
||||
"gitea.dev/models/db"
|
||||
"gitea.dev/models/organization"
|
||||
@@ -143,7 +142,7 @@ func (source *Source) Sync(ctx context.Context, updateExisting bool) error {
|
||||
|
||||
if err == nil && isAttributeSSHPublicKeySet {
|
||||
log.Trace("SyncExternalUsers[%s]: Adding LDAP Public SSH Keys for user %s", source.AuthSource.Name, usr.Name)
|
||||
if asymkey_model.AddPublicKeysBySource(ctx, usr, source.AuthSource, su.SSHPublicKey, source.SSHKeysAreVerified) {
|
||||
if asymkey_service.AddPublicKeysBySource(ctx, usr, source.AuthSource, su.SSHPublicKey, source.SSHKeysAreVerified) {
|
||||
sshKeysNeedUpdate = true
|
||||
}
|
||||
}
|
||||
@@ -153,7 +152,7 @@ func (source *Source) Sync(ctx context.Context, updateExisting bool) error {
|
||||
}
|
||||
} else if updateExisting {
|
||||
// Synchronize SSH Public Key if that attribute is set
|
||||
if isAttributeSSHPublicKeySet && asymkey_model.SynchronizePublicKeys(ctx, usr, source.AuthSource, su.SSHPublicKey, source.SSHKeysAreVerified) {
|
||||
if isAttributeSSHPublicKeySet && asymkey_service.SynchronizePublicKeys(ctx, usr, source.AuthSource, su.SSHPublicKey, source.SSHKeysAreVerified) {
|
||||
sshKeysNeedUpdate = true
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"time"
|
||||
"uuid"
|
||||
|
||||
audit_model "gitea.dev/models/audit"
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/modules/git/gitcmd"
|
||||
@@ -24,6 +25,7 @@ import (
|
||||
"gitea.dev/modules/repository"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/structs"
|
||||
"gitea.dev/services/audit"
|
||||
|
||||
"go.yaml.in/yaml/v4"
|
||||
)
|
||||
@@ -727,5 +729,9 @@ func RestoreRepository(ctx context.Context, baseDir, ownerName, repoName string,
|
||||
}
|
||||
return err
|
||||
}
|
||||
return updateMigrationPosterIDByGitService(ctx, structs.GitServiceType(tp))
|
||||
if err := updateMigrationPosterIDByGitService(ctx, structs.GitServiceType(tp)); err != nil {
|
||||
return err
|
||||
}
|
||||
audit.Record(ctx, audit_model.RepositoryCreate, uploader.repo)
|
||||
return nil
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
audit_model "gitea.dev/models/audit"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
system_model "gitea.dev/models/system"
|
||||
"gitea.dev/modules/git"
|
||||
@@ -22,6 +23,7 @@ import (
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/timeutil"
|
||||
"gitea.dev/modules/util"
|
||||
"gitea.dev/services/audit"
|
||||
"gitea.dev/services/migrations"
|
||||
notify_service "gitea.dev/services/notify"
|
||||
repo_service "gitea.dev/services/repository"
|
||||
@@ -63,8 +65,15 @@ func UpdateAddress(ctx context.Context, m *repo_model.Mirror, addr string) error
|
||||
|
||||
// erase authentication before storing in database
|
||||
u.User = nil
|
||||
oldURL := m.Repo.OriginalURL
|
||||
m.Repo.OriginalURL = u.String()
|
||||
return repo_model.UpdateRepositoryColsNoAutoTime(ctx, m.Repo, "original_url")
|
||||
if err := repo_model.UpdateRepositoryColsNoAutoTime(ctx, m.Repo, "original_url"); err != nil {
|
||||
return err
|
||||
}
|
||||
if m.Repo.OriginalURL != oldURL {
|
||||
audit.Record(ctx, audit_model.RepositoryMirrorPullUpdate, m.Repo, "remote_address", m.Repo.OriginalURL)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func pruneBrokenReferences(ctx context.Context, m *repo_model.Mirror, repoLogName string, gitRepo git.RepositoryFacade, timeout time.Duration) error {
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
audit_model "gitea.dev/models/audit"
|
||||
"gitea.dev/models/db"
|
||||
git_model "gitea.dev/models/git"
|
||||
issues_model "gitea.dev/models/issues"
|
||||
@@ -26,6 +27,7 @@ import (
|
||||
api "gitea.dev/modules/structs"
|
||||
"gitea.dev/modules/timeutil"
|
||||
"gitea.dev/modules/util"
|
||||
"gitea.dev/services/audit"
|
||||
"gitea.dev/services/context/upload"
|
||||
notify_service "gitea.dev/services/notify"
|
||||
)
|
||||
@@ -392,6 +394,7 @@ func UpdateRelease(ctx context.Context, doer *user_model.User, gitRepo *git.Repo
|
||||
|
||||
// DeleteReleaseByID deletes a release and corresponding Git tag by given ID.
|
||||
func DeleteReleaseByID(ctx context.Context, repo *repo_model.Repository, rel *repo_model.Release, doer *user_model.User, delTag bool) error {
|
||||
isRelease := !rel.IsTag
|
||||
if delTag {
|
||||
protectedTags, err := git_model.GetProtectedTags(ctx, rel.RepoID)
|
||||
if err != nil {
|
||||
@@ -459,6 +462,9 @@ func DeleteReleaseByID(ctx context.Context, repo *repo_model.Repository, rel *re
|
||||
}
|
||||
}
|
||||
|
||||
if isRelease {
|
||||
audit.RecordAs(ctx, doer, audit_model.RepositoryReleaseRemove, repo, "release", rel.TagName)
|
||||
}
|
||||
if !rel.IsDraft {
|
||||
notify_service.DeleteRelease(ctx, doer, rel)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
audit_model "gitea.dev/models/audit"
|
||||
"gitea.dev/models/db"
|
||||
issues_model "gitea.dev/models/issues"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
@@ -340,6 +341,20 @@ func TestCreateNewTag(t *testing.T) {
|
||||
"v2.0 is released \n\n BUGFIX: .... \n\n 123"))
|
||||
}
|
||||
|
||||
func TestDeleteReleaseByIDAuditEvents(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
defer test.MockVariableValue(&setting.Audit.RecordOutput, setting.AuditRecordOutputDatabase)()
|
||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
|
||||
for _, id := range []int64{1, 3} {
|
||||
rel := unittest.AssertExistsAndLoadBean(t, &repo_model.Release{ID: id})
|
||||
assert.NoError(t, DeleteReleaseByID(t.Context(), repo, rel, user, rel.IsTag))
|
||||
}
|
||||
unittest.AssertCount(t, &audit_model.Event{Action: audit_model.RepositoryReleaseRemove}, 1)
|
||||
unittest.AssertCount(t, &audit_model.Event{Action: audit_model.RepositoryTagRemove}, 1)
|
||||
}
|
||||
|
||||
func TestCreateReleaseReaction(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
|
||||
@@ -68,6 +68,7 @@ func UpdateUser(ctx context.Context, u *user_model.User, opts *UpdateOptions) er
|
||||
cols := make([]string, 0, 20)
|
||||
|
||||
oldIsActive, oldIsRestricted, oldIsAdmin, oldVisibility, oldType := u.IsActive, u.IsRestricted, u.IsAdmin, u.Visibility, u.Type
|
||||
oldRepoAdminChangeTeamAccess := u.RepoAdminChangeTeamAccess
|
||||
|
||||
if opts.KeepEmailPrivate.Has() {
|
||||
u.KeepEmailPrivate = opts.KeepEmailPrivate.Value()
|
||||
@@ -221,6 +222,9 @@ func UpdateUser(ctx context.Context, u *user_model.User, opts *UpdateOptions) er
|
||||
if u.Type != oldType {
|
||||
audit.Record(ctx, audit_model.UserType, u, "user_type", u.Type.DisplayName())
|
||||
}
|
||||
if u.RepoAdminChangeTeamAccess != oldRepoAdminChangeTeamAccess {
|
||||
audit.Record(ctx, audit_model.OrganizationTeamAccess, u, "repo_admin_change_team_access", u.RepoAdminChangeTeamAccess)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -279,6 +283,7 @@ func UpdateAuth(ctx context.Context, u *user_model.User, opts *UpdateAuthOptions
|
||||
if opts.MustChangePassword.Has() {
|
||||
u.MustChangePassword = opts.MustChangePassword.Value()
|
||||
}
|
||||
oldProhibitLogin := u.ProhibitLogin
|
||||
if opts.ProhibitLogin.Has() {
|
||||
u.ProhibitLogin = opts.ProhibitLogin.Value()
|
||||
}
|
||||
@@ -297,6 +302,9 @@ func UpdateAuth(ctx context.Context, u *user_model.User, opts *UpdateAuthOptions
|
||||
if loginSourceChanged {
|
||||
audit.Record(ctx, audit_model.UserAuthenticationSource, u, "auth_source", authSourceName)
|
||||
}
|
||||
if u.ProhibitLogin != oldProhibitLogin {
|
||||
audit.Record(ctx, audit_model.UserProhibitLogin, u, "prohibit_login", u.ProhibitLogin)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -80,6 +80,11 @@ func TestUpdateUser(t *testing.T) {
|
||||
}
|
||||
assertUpdatedUser(user)
|
||||
assertUpdatedUser(unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 28}))
|
||||
|
||||
defer test.MockVariableValue(&setting.Audit.RecordOutput, setting.AuditRecordOutputDatabase)()
|
||||
org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3})
|
||||
assert.NoError(t, UpdateUser(t.Context(), org, &UpdateOptions{RepoAdminChangeTeamAccess: optional.Some(!org.RepoAdminChangeTeamAccess)}))
|
||||
unittest.AssertExistsAndLoadBean(t, &audit_model.Event{Action: audit_model.OrganizationTeamAccess, ScopeType: audit_model.ScopeOrganization, ScopeID: org.ID})
|
||||
}
|
||||
|
||||
func TestUpdateAuth(t *testing.T) {
|
||||
@@ -101,10 +106,12 @@ func TestUpdateAuth(t *testing.T) {
|
||||
assert.NotEqual(t, userCopy.Passwd, user.Passwd)
|
||||
assert.NotEqual(t, userCopy.Salt, user.Salt)
|
||||
|
||||
defer test.MockVariableValue(&setting.Audit.RecordOutput, setting.AuditRecordOutputDatabase)()
|
||||
assert.NoError(t, UpdateAuth(t.Context(), user, &UpdateAuthOptions{
|
||||
ProhibitLogin: optional.Some(true),
|
||||
}))
|
||||
assert.True(t, user.ProhibitLogin)
|
||||
unittest.AssertExistsAndLoadBean(t, &audit_model.Event{Action: audit_model.UserProhibitLogin, ScopeType: audit_model.ScopeUser, ScopeID: user.ID})
|
||||
|
||||
assert.ErrorIs(t, UpdateAuth(t.Context(), user, &UpdateAuthOptions{
|
||||
Password: optional.Some("aaaa"),
|
||||
|
||||
@@ -178,6 +178,61 @@ func TestAdminAuditLogExport(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestAuditLogAdministrationEvents(t *testing.T) {
|
||||
defer tests.PrepareTestEnv(t)()
|
||||
defer test.MockVariableValue(&setting.Audit.RecordOutput, setting.AuditRecordOutputDatabase)()
|
||||
|
||||
token := getUserToken(t, "user1", auth_model.AccessTokenScopeAll)
|
||||
const repoAPI = "/api/v1/repos/user2/repo1"
|
||||
|
||||
assertEvent := func(t *testing.T, action audit_model.Action, scopeType audit_model.ScopeType, scopeID int64) {
|
||||
t.Helper()
|
||||
unittest.AssertCount(t, &audit_model.Event{Action: action, ScopeType: scopeType, ScopeID: scopeID}, 1)
|
||||
}
|
||||
|
||||
t.Run("ActionsRunners", func(t *testing.T) {
|
||||
MakeRequest(t, NewRequest(t, "POST", repoAPI+"/actions/runners/registration-token").AddTokenAuth(token), http.StatusOK)
|
||||
MakeRequest(t, NewRequestWithJSON(t, "PATCH", repoAPI+"/actions/runners/34348", &api.EditActionRunnerOption{Disabled: new(true)}).AddTokenAuth(token), http.StatusOK)
|
||||
MakeRequest(t, NewRequest(t, "DELETE", repoAPI+"/actions/runners/34348").AddTokenAuth(token), http.StatusNoContent)
|
||||
for _, action := range []audit_model.Action{audit_model.RepositoryRunnerToken, audit_model.RepositoryRunnerUpdate, audit_model.RepositoryRunnerRemove} {
|
||||
assertEvent(t, action, audit_model.ScopeRepository, 1)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ActionsVariables", func(t *testing.T) {
|
||||
MakeRequest(t, NewRequestWithJSON(t, "POST", repoAPI+"/actions/variables/AUDIT_VAR", &api.CreateVariableOption{Value: "a"}).AddTokenAuth(token), http.StatusCreated)
|
||||
MakeRequest(t, NewRequestWithJSON(t, "PUT", repoAPI+"/actions/variables/AUDIT_VAR", &api.UpdateVariableOption{Value: "b"}).AddTokenAuth(token), http.StatusNoContent)
|
||||
MakeRequest(t, NewRequest(t, "DELETE", repoAPI+"/actions/variables/AUDIT_VAR").AddTokenAuth(token), http.StatusNoContent)
|
||||
for _, action := range []audit_model.Action{audit_model.RepositoryVariableAdd, audit_model.RepositoryVariableUpdate, audit_model.RepositoryVariableRemove} {
|
||||
assertEvent(t, action, audit_model.ScopeRepository, 1)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("SystemConfig", func(t *testing.T) {
|
||||
session := loginUser(t, "user1")
|
||||
for range 2 {
|
||||
session.MakeRequest(t, NewRequestWithValues(t, "POST", "/-/admin/config", map[string]string{
|
||||
"key": "instance.web_banner",
|
||||
"value": `{"DisplayEnabled":true,"ContentMessage":"audit"}`,
|
||||
}), http.StatusOK)
|
||||
}
|
||||
assertEvent(t, audit_model.SystemConfigUpdate, audit_model.ScopeSystem, 0)
|
||||
})
|
||||
|
||||
t.Run("PullReviewDelete", func(t *testing.T) {
|
||||
MakeRequest(t, NewRequest(t, "DELETE", repoAPI+"/pulls/2/reviews/1").AddTokenAuth(token), http.StatusNoContent)
|
||||
assertEvent(t, audit_model.PullRequestReviewDelete, audit_model.ScopeRepository, 1)
|
||||
})
|
||||
|
||||
t.Run("OAuth2ApplicationSecret", func(t *testing.T) {
|
||||
option := &api.CreateOAuth2ApplicationOptions{Name: "audit-app", RedirectURIs: []string{"https://example.com/callback"}}
|
||||
resp := MakeRequest(t, NewRequestWithJSON(t, "POST", "/api/v1/user/applications/oauth2", option).AddTokenAuth(token), http.StatusCreated)
|
||||
app := DecodeJSON(t, resp, &api.OAuth2Application{})
|
||||
MakeRequest(t, NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/user/applications/oauth2/%d", app.ID), option).AddTokenAuth(token), http.StatusOK)
|
||||
assertEvent(t, audit_model.UserOAuth2ApplicationSecret, audit_model.ScopeUser, 1)
|
||||
})
|
||||
}
|
||||
|
||||
func TestAuditLogUserEvents(t *testing.T) {
|
||||
defer tests.PrepareTestEnv(t)()
|
||||
defer test.MockVariableValue(&setting.Audit.RecordOutput, setting.AuditRecordOutputDatabase)()
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
audit_model "gitea.dev/models/audit"
|
||||
"gitea.dev/models/db"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/models/unit"
|
||||
@@ -122,7 +123,10 @@ func TestMirrorPull(t *testing.T) {
|
||||
|
||||
mirror = unittest.AssertExistsAndLoadBean(t, &repo_model.Mirror{RepoID: mirrorRepo.ID})
|
||||
lastMirrorSync := mirror.LastSyncUnix
|
||||
defer test.MockVariableValue(&setting.Audit.RecordOutput, setting.AuditRecordOutputDatabase)()
|
||||
assert.NoError(t, mirror_service.UpdateAddress(ctx, mirror, repoPath+"-missing"))
|
||||
assert.NoError(t, mirror_service.UpdateAddress(ctx, mirror, repoPath+"-missing"))
|
||||
unittest.AssertCount(t, &audit_model.Event{Action: audit_model.RepositoryMirrorPullUpdate}, 1)
|
||||
|
||||
ok = mirror_service.SyncPullMirror(ctx, mirrorRepo.ID)
|
||||
assert.False(t, ok)
|
||||
|
||||
Reference in new issue
Block a user