Files
pad/internal/models/activity.go
T
xarmian d3a543db6f feat(attachments): admin per-user storage quota override UI (TASK-883) (#304)
* feat(attachments): admin per-user storage quota override UI (TASK-883)

Surfaces the storage_bytes plan_overrides key in the admin user-detail
page so operators can lift or tighten an individual user's quota
without poking at JSON via the API directly.

Frontend (console/admin/+page.svelte):
- Dedicated "Storage quota override" input below the existing
  overrides grid. Storage is byte-counted, not row-counted, so a
  number input forcing the admin to type 536870912 for 512MB
  would be hostile. Accepts:
    • "10 GB" / "500MB" / "1.5 GB" (IEC shorthand)
    • "1024" (raw bytes)
    • "-1" (unlimited)
    • "" (clear → falls back to plan default)
- Live parse preview ("= 10.0 GB (10,737,418,240 bytes)") so the
  admin can verify the unit was understood.
- "Reset to plan default" button clears the field; save commits
  the absence as a removed override key.
- Pre-fills with the current effective override formatted in the
  largest exact unit so a previously-set "10 GB" doesn't reload as
  "10737418240".

Backend:
- ActionPlanOverridesChanged audit constant.
- handleAdminUpdateUser now logs an audit event with old/new
  override JSONs whenever plan_overrides is patched. Lets operators
  correlate a mysteriously-allowed upload with the override that
  enabled it.

Tests:
- TestAdminUpdateUser_StorageOverrideRoundTrip: PATCH with
  storage_bytes:1073741824 → GET shows the new override → audit
  feed contains plan_overrides_changed event → clearing the
  override removes it.
- TestAdminUpdateUser_NonAdminForbidden: member-role user cannot
  PATCH another user's plan_overrides (regression guard for the
  audit-log path).

Parent: PLAN-866. The Settings → Storage page (TASK-882) reflects
the new effective limit immediately after save because both call
the same WorkspaceStorageInfo helper.

* fix(admin): parse plan_overrides JSON on read, clear via empty string per Codex (round 1)

Two related bugs in the admin user-detail page that Codex caught
in PR #304 round 1:

1. The save path sent JSON null when every override field was
   blank, but the Go handler uses a *string and JSON null decodes
   to a nil pointer — the handler's existing nil-vs-non-nil branch
   then skips the update, meaning "Reset to plan default" reported
   success without actually clearing the override. Fixed by
   sending "" (empty string) which routes through
   SetUserPlanOverrides("") and clears the column.

2. The form-populate path treated u.plan_overrides as an object
   while the API actually returns the raw column value as a JSON
   string. So `'storage_bytes' in ov` was checking string indices
   on a literal '{"storage_bytes":1073741824}' string, returning
   false, and any user with stored overrides loaded a blank form.
   This was a pre-existing bug in the workspaces / api_tokens /
   etc. fields too — fixed for all of them by parsing the JSON in
   parsePlanOverrides() before reading keys, with a defensive
   "future-proof" branch in case the API ever switches to a
   decoded object.

TS type for AdminUser.plan_overrides updated to `string | null`
to match the actual API contract.

Backend regression test added (TestAdminUpdateUser_OmittedOverrides
Preserved) that pins the other half of the contract: PATCH with
plan_overrides absent must NOT clear the column. The test was
straightforward to add because the existing test infrastructure
(bootstrapFirstUser, doRequestWithCookie) already covers the
admin auth path.
2026-04-29 17:56:19 -04:00

118 lines
4.6 KiB
Go

package models
import "time"
// Item-level actions (existing)
var ValidActions = []string{
"created", "updated", "archived", "restored", "moved", "read", "searched",
}
// Audit action constants for auth/admin events
const (
ActionLogin = "login"
ActionLoginFailed = "login_failed"
ActionLogout = "logout"
ActionBootstrap = "bootstrap"
ActionRegister = "register"
ActionPasswordChanged = "password_changed"
ActionPasswordReset = "password_reset"
ActionTokenCreated = "token_created"
ActionTokenRevoked = "token_revoked"
ActionTokenRotated = "token_rotated"
ActionTOTPEnabled = "totp_enabled"
ActionTOTPDisabled = "totp_disabled"
ActionMemberInvited = "member_invited"
ActionMemberRemoved = "member_removed"
ActionRoleChanged = "role_changed"
ActionSettingsChanged = "settings_changed"
ActionOAuthLogin = "oauth_login"
ActionOAuthLoginFailed = "oauth_login_failed"
ActionPlanChanged = "plan_changed"
// ActionPlanOverridesChanged is logged when an admin updates a
// user's plan_overrides JSON via the admin user-detail page.
// Surfaces per-user storage / workspace / API-token quota
// overrides in the audit feed so operators can correlate a
// mysteriously-allowed upload with the override that enabled it.
ActionPlanOverridesChanged = "plan_overrides_changed"
ActionPasswordResetByAdmin = "password_reset_by_admin"
ActionUserDisabled = "user_disabled"
ActionUserEnabled = "user_enabled"
ActionAccountDeleted = "account_deleted"
// ActionSessionIPChanged is logged when a session presents a different
// client IP than the one recorded at creation. We don't strict-check IP
// by default (that breaks legitimate geo shifts — VPN toggle, mobile
// roaming) but surface the change to the audit log for detection. In
// deployments configured with PAD_IP_CHANGE_ENFORCE=strict the middleware
// additionally rejects the request.
ActionSessionIPChanged = "session_ip_changed"
// ActionStripeEventUnmarked is logged when /admin/stripe-event-unmark
// rolls back a row from stripe_processed_events (TASK-736). The
// endpoint intentionally reopens Stripe retry windows, so a persisted
// audit trail is required — a compromised cloud_secret could otherwise
// spam unmarks invisible to the admin /audit-log UI.
ActionStripeEventUnmarked = "stripe_event_unmarked"
// ActionPaymentFailedEmailSent is logged when the sidecar triggers the
// /admin/payment-failed endpoint and pad dispatches a failed-payment
// notification to the user. Audit trail exists so operators can prove
// a customer was notified before a dunning-related plan change.
ActionPaymentFailedEmailSent = "payment_failed_email_sent"
)
type Activity struct {
ID string `json:"id"`
WorkspaceID string `json:"workspace_id,omitempty"`
DocumentID string `json:"document_id,omitempty"`
Action string `json:"action"`
Actor string `json:"actor"`
Source string `json:"source"`
Metadata string `json:"metadata,omitempty"` // JSON
UserID string `json:"user_id,omitempty"`
IPAddress string `json:"ip_address,omitempty"`
UserAgent string `json:"user_agent,omitempty"`
CreatedAt time.Time `json:"created_at"`
// Enrichment fields — populated by handlers, not stored in DB
ItemTitle string `json:"item_title,omitempty"`
ItemSlug string `json:"item_slug,omitempty"`
CollectionSlug string `json:"collection_slug,omitempty"`
ActorName string `json:"actor_name,omitempty"`
}
type ActivityListParams struct {
Action string
Actor string
Source string
Limit int
Offset int
}
// AuditLogParams are query parameters for the audit log endpoint.
type AuditLogParams struct {
Action string
Actor string
WorkspaceID string
Days int
Limit int
Offset int
}
// TimelineEntry represents a single entry in the unified item timeline.
// It wraps one of: a comment, an activity, or a version.
type TimelineEntry struct {
ID string `json:"id"`
Kind string `json:"kind"` // "comment", "activity", "version"
CreatedAt time.Time `json:"created_at"`
Actor string `json:"actor"`
ActorName string `json:"actor_name,omitempty"`
Source string `json:"source"`
Comment *Comment `json:"comment,omitempty"`
Activity *Activity `json:"activity,omitempty"`
Version *Version `json:"version,omitempty"`
}
// TimelineResponse is the paginated response from the timeline endpoint.
type TimelineResponse struct {
Entries []TimelineEntry `json:"entries"`
HasMore bool `json:"has_more"`
}