Go · 7973 bytes Raw Blame History
1 // SPDX-License-Identifier: AGPL-3.0-or-later
2
3 // Package audit writes structured rows into the auth_audit_log table for
4 // security-relevant events. The schema is generic — actor, action, target,
5 // meta JSON — so future sprints reuse this for permission changes,
6 // org-membership changes, admin actions, etc.
7 //
8 // Callers MUST NOT put secret material in the meta JSON. The values land
9 // unredacted in the DB; treat the table contents as confidential but
10 // never sensitive (no plaintext passwords, no TOTP secrets, no PATs).
11 package audit
12
13 import (
14 "context"
15 "encoding/json"
16 "errors"
17 "fmt"
18
19 "github.com/jackc/pgx/v5/pgtype"
20
21 usersdb "github.com/tenseleyFlow/shithub/internal/users/sqlc"
22 )
23
24 // DBTX matches sqlc's DBTX so callers can pass *pgxpool.Pool or a tx.
25 type DBTX = usersdb.DBTX
26
27 // Action is a typed action constant. Reuse these across packages so the
28 // set stays tight and grep-able.
29 type Action string
30
31 const (
32 Action2FAEnabled Action = "2fa_enabled"
33 Action2FADisabled Action = "2fa_disabled"
34 ActionRecoveryCodesIssued Action = "recovery_codes_issued"
35 ActionRecoveryCodeUsed Action = "recovery_code_used"
36 ActionRecoveryRegenerated Action = "recovery_codes_regenerated"
37 ActionAdminCleared2FA Action = "admin_cleared_2fa"
38 ActionPasswordChanged Action = "password_changed"
39 ActionPasswordReset Action = "password_reset_consumed"
40 ActionLoginSucceeded Action = "login_succeeded"
41 ActionLoginFailedThrottled Action = "login_failed_throttled"
42 ActionAccountSuspended Action = "account_suspended"
43 ActionSSHKeyAdded Action = "ssh_key_added"
44 ActionSSHKeyDeleted Action = "ssh_key_deleted"
45 ActionPATCreated Action = "pat_created"
46 ActionPATRevoked Action = "pat_revoked"
47 ActionUsernameChanged Action = "username_changed"
48 ActionAccountDeleted Action = "account_deleted"
49 ActionAccountRestored Action = "account_restored"
50 ActionRepoCreated Action = "repo_created"
51 ActionRepoRenamed Action = "repo_renamed"
52 ActionRepoArchived Action = "repo_archived"
53 ActionRepoUnarchived Action = "repo_unarchived"
54 ActionRepoVisibilityChanged Action = "repo_visibility_changed"
55 ActionRepoSoftDeleted Action = "repo_soft_deleted"
56 ActionRepoRestored Action = "repo_restored"
57 ActionRepoHardDeleted Action = "repo_hard_deleted"
58 ActionRepoTransferRequested Action = "repo_transfer_requested"
59 ActionRepoTransferAccepted Action = "repo_transfer_accepted"
60 ActionRepoTransferDeclined Action = "repo_transfer_declined"
61 ActionRepoTransferCanceled Action = "repo_transfer_canceled"
62 ActionRepoTransferExpired Action = "repo_transfer_expired"
63 ActionIssueStateChanged Action = "issue_state_changed"
64 ActionIssueLockChanged Action = "issue_lock_changed"
65 ActionIssueCommentCreated Action = "issue_comment_created"
66 ActionPullStateChanged Action = "pull_state_changed"
67 ActionPullMerged Action = "pull_merged"
68 ActionStarCreated Action = "star_created"
69 ActionStarDeleted Action = "star_deleted"
70 ActionWatchSet Action = "watch_set"
71 ActionWatchUnset Action = "watch_unset"
72 ActionFollowCreated Action = "follow_created"
73 ActionFollowDeleted Action = "follow_deleted"
74 ActionRepoForked Action = "repo_forked"
75 ActionRepoForkSynced Action = "repo_fork_synced"
76
77 // S33 / SR2 H1 — webhook lifecycle. Pre-SR2 webhook create/update
78 // overloaded ActionRepoCreated; delete/toggle/ping/redeliver were
79 // not audited at all. Each event now has its own enum.
80 ActionWebhookCreated Action = "webhook_created"
81 ActionWebhookUpdated Action = "webhook_updated"
82 ActionWebhookDeleted Action = "webhook_deleted"
83 ActionWebhookActiveSet Action = "webhook_active_set"
84 ActionWebhookActiveUnset Action = "webhook_active_unset"
85 ActionWebhookPinged Action = "webhook_pinged"
86 ActionWebhookRedelivered Action = "webhook_redelivered"
87
88 // S41c — Actions secret/variable lifecycle. Metadata must include
89 // names only, never secret values.
90 ActionActionsSecretSet Action = "actions_secret_set"
91 ActionActionsSecretDeleted Action = "actions_secret_deleted"
92 ActionActionsVariableSet Action = "actions_variable_set"
93 ActionActionsVariableDeleted Action = "actions_variable_deleted"
94 ActionActionsPolicyUpdated Action = "actions_policy_updated"
95
96 // S41h — Actions run/job lifecycle. Metadata must stay structural:
97 // run/job ids, status, conclusion, workflow path/name. Never include
98 // event payloads, env, logs, permissions, tokens, or secret values.
99 ActionWorkflowRunCreated Action = "workflow_run_created"
100 ActionWorkflowRunStarted Action = "workflow_run_started"
101 ActionWorkflowRunCompleted Action = "workflow_run_completed"
102 ActionWorkflowJobCreated Action = "workflow_job_created"
103 ActionWorkflowJobStarted Action = "workflow_job_started"
104 ActionWorkflowJobCompleted Action = "workflow_job_completed"
105 ActionWorkflowJobCancelled Action = "workflow_job_cancelled"
106 ActionWorkflowRunApproved Action = "workflow_run_approved"
107 ActionWorkflowRunRejected Action = "workflow_run_rejected"
108
109 // S34 — site admin actions. Always recorded with the real admin's
110 // id in actor_id; impersonation flows additionally carry the
111 // impersonated user's id in meta.impersonated_user_id.
112 ActionAdminSiteAdminGranted Action = "admin_site_admin_granted"
113 ActionAdminSiteAdminRevoked Action = "admin_site_admin_revoked"
114 ActionAdminUserSuspended Action = "admin_user_suspended"
115 ActionAdminUserUnsuspended Action = "admin_user_unsuspended"
116 ActionAdminUserForceDeleted Action = "admin_user_force_deleted"
117 ActionAdminUserPasswordReset Action = "admin_user_password_reset"
118 ActionAdminRepoForceArchived Action = "admin_repo_force_archived"
119 ActionAdminRepoForceUnarchived Action = "admin_repo_force_unarchived"
120 ActionAdminRepoForceDeleted Action = "admin_repo_force_deleted"
121 ActionAdminJobRetried Action = "admin_job_retried"
122 ActionAdminJobDiscarded Action = "admin_job_discarded"
123 ActionAdminImpersonateStarted Action = "admin_impersonate_started"
124 ActionAdminImpersonateStopped Action = "admin_impersonate_stopped"
125 ActionAdminImpersonateWriteOn Action = "admin_impersonate_write_on"
126 )
127
128 // Target is a typed target-type constant.
129 type Target string
130
131 const (
132 TargetUser Target = "user"
133 TargetRepo Target = "repo"
134 TargetOrg Target = "org"
135 TargetIssue Target = "issue"
136 TargetPull Target = "pull"
137 )
138
139 // Recorder writes audit rows. Bound to the sqlc queries handle.
140 type Recorder struct {
141 q *usersdb.Queries
142 }
143
144 // NewRecorder constructs a recorder.
145 func NewRecorder() *Recorder { return &Recorder{q: usersdb.New()} }
146
147 // Record inserts a single audit-log row. actorID is the user_id of the
148 // actor performing the action (use 0 for system / admin-CLI actions).
149 // targetID is the affected entity (use 0 for actions without a single
150 // concrete target).
151 //
152 // meta MUST be a JSON-serializable map; secrets and PII (tokens, raw
153 // passwords, etc.) MUST NOT appear here.
154 func (r *Recorder) Record(
155 ctx context.Context, db DBTX,
156 actorID int64, action Action, target Target, targetID int64, meta map[string]any,
157 ) error {
158 if action == "" || target == "" {
159 return errors.New("audit: action and target_type required")
160 }
161 if meta == nil {
162 meta = map[string]any{}
163 }
164 metaJSON, err := json.Marshal(meta)
165 if err != nil {
166 return fmt.Errorf("audit: marshal meta: %w", err)
167 }
168 var actorParam pgtype.Int8
169 if actorID != 0 {
170 actorParam = pgtype.Int8{Int64: actorID, Valid: true}
171 }
172 var targetParam pgtype.Int8
173 if targetID != 0 {
174 targetParam = pgtype.Int8{Int64: targetID, Valid: true}
175 }
176 return r.q.InsertAuditLog(ctx, db, usersdb.InsertAuditLogParams{
177 ActorID: actorParam,
178 Action: string(action),
179 TargetType: string(target),
180 TargetID: targetParam,
181 Meta: metaJSON,
182 })
183 }
184