Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
59c72a84ce | ||
|
|
43469ef08d | ||
|
|
35db442cd3 | ||
|
|
e37a46a027 | ||
|
|
50b1649965 |
No files matched your search
+1
-2
@@ -178,8 +178,7 @@ tasks:
|
||||
mutate:
|
||||
desc: Gremlins mutation testing of the use cases → tmp/gremlins.json
|
||||
cmds:
|
||||
- mkdir -p tmp
|
||||
- gremlins unleash --integration --tags nofrontend --coverpkg=./internal/infrastructure/useCases/...,./api/middleware/...,./api/pkg/claims/... --timeout-coefficient 10 --output tmp/gremlins.json ./internal/infrastructure/useCases ./api/middleware ./api/pkg/claims
|
||||
- bash scripts/mutate.sh
|
||||
|
||||
test:web:
|
||||
desc: Run the SPA test suite (Vitest) in run mode
|
||||
|
||||
+62
-25
@@ -3,12 +3,14 @@ package api
|
||||
import (
|
||||
domainAPIKey "RenewCMS/internal/domain/apikey"
|
||||
domainArticle "RenewCMS/internal/domain/article"
|
||||
domainAudit "RenewCMS/internal/domain/audit"
|
||||
domainImage "RenewCMS/internal/domain/image"
|
||||
domainInvite "RenewCMS/internal/domain/invite"
|
||||
domainMail "RenewCMS/internal/domain/mail"
|
||||
domainPurge "RenewCMS/internal/domain/purge"
|
||||
domainUpdate "RenewCMS/internal/domain/update"
|
||||
domainUser "RenewCMS/internal/domain/user"
|
||||
"RenewCMS/internal/infrastructure/auditing"
|
||||
"RenewCMS/internal/infrastructure/config"
|
||||
"RenewCMS/internal/infrastructure/hashing"
|
||||
"RenewCMS/internal/infrastructure/mailer"
|
||||
@@ -19,6 +21,7 @@ import (
|
||||
"RenewCMS/internal/infrastructure/storage"
|
||||
"RenewCMS/internal/infrastructure/update"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"log"
|
||||
"net/http"
|
||||
@@ -36,6 +39,7 @@ type UseCases struct {
|
||||
apiKeyAuthMiddleware func(http.Handler) http.Handler
|
||||
Token *jwtauth.JWTAuth
|
||||
PurgeScheduler *scheduler.Runner
|
||||
ActivityCleanupScheduler *scheduler.Runner
|
||||
CreateArticleUseCase *useCases.CreateArticleUseCase
|
||||
GetArticleUseCase *useCases.GetArticleUseCase
|
||||
ListArticlesUseCase *useCases.ListArticlesUseCase
|
||||
@@ -78,6 +82,26 @@ type UseCases struct {
|
||||
ListAPIKeysUseCase *useCases.ListAPIKeysUseCase
|
||||
RevokeAPIKeyUseCase *useCases.RevokeAPIKeyUseCase
|
||||
AuthenticateAPIKeyUseCase *useCases.AuthenticateAPIKeyUseCase
|
||||
ListActivityUseCase *useCases.ListActivityUseCase
|
||||
GetActivitySummaryUseCase *useCases.GetActivitySummaryUseCase
|
||||
ExportActivityUseCase *useCases.ExportActivityUseCase
|
||||
GetActivityRetentionUseCase *useCases.GetActivityRetentionUseCase
|
||||
UpdateActivityRetentionUseCase *useCases.UpdateActivityRetentionUseCase
|
||||
}
|
||||
|
||||
func (c *UseCases) RunSchedulers(ctx context.Context) {
|
||||
var running sync.WaitGroup
|
||||
for _, runner := range []*scheduler.Runner{c.PurgeScheduler, c.ActivityCleanupScheduler} {
|
||||
if runner == nil {
|
||||
continue
|
||||
}
|
||||
running.Add(1)
|
||||
go func() {
|
||||
defer running.Done()
|
||||
runner.Run(ctx)
|
||||
}()
|
||||
}
|
||||
running.Wait()
|
||||
}
|
||||
|
||||
type Repositories struct {
|
||||
@@ -87,6 +111,8 @@ type Repositories struct {
|
||||
InviteRepo domainInvite.Repository
|
||||
APIKeyRepo domainAPIKey.Repository
|
||||
PurgeSettingsRepo domainPurge.Repository
|
||||
AuditRepo domainAudit.Repository
|
||||
AuditSettingsRepo domainAudit.SettingsRepository
|
||||
MailRepo domainMail.Repository
|
||||
ReleaseFeed domainUpdate.ReleaseFeed
|
||||
UpdateStore domainUpdate.StatusStore
|
||||
@@ -217,6 +243,8 @@ func getRepositories(connection *database.Connection, settings config.Settings)
|
||||
InviteRepo: persistence.NewInviteRepository(db),
|
||||
APIKeyRepo: persistence.NewAPIKeyRepository(db),
|
||||
PurgeSettingsRepo: persistence.NewPurgeSettingsRepository(db),
|
||||
AuditRepo: persistence.NewAuditEventRepository(db),
|
||||
AuditSettingsRepo: persistence.NewAuditSettingsRepository(db),
|
||||
MailRepo: mailer.NewMailRepository(settings.Smtp),
|
||||
ReleaseFeed: update.NewGiteaReleaseFeed(settings.UpdateFeedURL),
|
||||
UpdateStore: update.NewJSONStatusStore(filepath.Join(dataDir, updateStatusFileName)),
|
||||
@@ -236,40 +264,43 @@ func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings
|
||||
hasher := hashing.NewBcryptHasher()
|
||||
renderer := markdown.NewConverter()
|
||||
keyGenerator := hashing.NewSHA256KeyGenerator()
|
||||
mergeMedia := useCases.NewMergeMediaUseCase(repos.ImageRepo, repos.ArticleRepo, imageStorage)
|
||||
recorder := auditing.NewRecorder(repos.AuditRepo, time.Now, log.Default())
|
||||
mergeMedia := useCases.NewMergeMediaUseCase(repos.ImageRepo, repos.ArticleRepo, imageStorage, recorder)
|
||||
|
||||
runPurge := useCases.NewRunPurgeUseCase(repos.ImageRepo, repos.ArticleRepo, mergeMedia, repos.PurgeSettingsRepo, time.Now, log.Default())
|
||||
purgeScheduler := useCases.NewPurgeSchedulerUseCase(repos.PurgeSettingsRepo, runPurge)
|
||||
runPurge := useCases.NewRunPurgeUseCase(repos.ImageRepo, repos.ArticleRepo, mergeMedia, repos.PurgeSettingsRepo, time.Now, log.Default(), recorder)
|
||||
purgeScheduler := useCases.NewPurgeSchedulerUseCase(repos.PurgeSettingsRepo, runPurge, recorder)
|
||||
activityCleanup := useCases.NewCleanupActivityUseCase(repos.AuditRepo, repos.AuditSettingsRepo, recorder)
|
||||
|
||||
return &UseCases{
|
||||
PurgeScheduler: scheduler.NewSystemRunner(purgeScheduler, log.Default()),
|
||||
ActivityCleanupScheduler: scheduler.NewSystemCleanupRunner(activityCleanup, log.Default()),
|
||||
Token: jwtauth.New("HS256", []byte(settings.JWTSecret), nil),
|
||||
CreateArticleUseCase: useCases.NewCreateArticleUseCase(repos.ArticleRepo, renderer),
|
||||
CreateArticleUseCase: useCases.NewCreateArticleUseCase(repos.ArticleRepo, renderer, recorder),
|
||||
GetArticleUseCase: useCases.NewGetArticleUseCase(repos.ArticleRepo, renderer),
|
||||
ListArticlesUseCase: useCases.NewListArticlesUseCase(repos.ArticleRepo, renderer),
|
||||
UpdateArticleUseCase: useCases.NewUpdateArticleUseCase(repos.ArticleRepo, renderer),
|
||||
DeleteArticleUseCase: useCases.NewDeleteArticleUseCase(repos.ArticleRepo),
|
||||
UpdateArticleUseCase: useCases.NewUpdateArticleUseCase(repos.ArticleRepo, renderer, recorder),
|
||||
DeleteArticleUseCase: useCases.NewDeleteArticleUseCase(repos.ArticleRepo, recorder),
|
||||
GetUserUseCase: useCases.NewGetUserUseCase(repos.UserRepo),
|
||||
CreateUserUseCase: useCases.NewCreateUserUseCase(repos.UserRepo, hasher, repos.MailRepo, settings.PublicURL),
|
||||
AuthenticateUserUseCase: useCases.NewAuthenticateUserUseCase(repos.UserRepo, hasher),
|
||||
VerifyUserUseCase: useCases.NewVerifyUserUseCase(repos.UserRepo, hasher),
|
||||
CreateUserUseCase: useCases.NewCreateUserUseCase(repos.UserRepo, hasher, repos.MailRepo, settings.PublicURL, recorder),
|
||||
AuthenticateUserUseCase: useCases.NewAuthenticateUserUseCase(repos.UserRepo, hasher, recorder),
|
||||
VerifyUserUseCase: useCases.NewVerifyUserUseCase(repos.UserRepo, hasher, recorder),
|
||||
CancelRegistrationUseCase: useCases.NewCancelRegistrationUseCase(repos.UserRepo),
|
||||
RequestPasswordResetUseCase: useCases.NewRequestPasswordResetUseCase(repos.UserRepo, hasher, repos.MailRepo, settings.PublicURL),
|
||||
ResetPasswordUseCase: useCases.NewResetPasswordUseCase(repos.UserRepo, hasher, repos.APIKeyRepo, time.Now),
|
||||
UpdateUserProfileUseCase: useCases.NewUpdateUserProfileUseCase(repos.UserRepo),
|
||||
RequestPasswordResetUseCase: useCases.NewRequestPasswordResetUseCase(repos.UserRepo, hasher, repos.MailRepo, settings.PublicURL, recorder),
|
||||
ResetPasswordUseCase: useCases.NewResetPasswordUseCase(repos.UserRepo, hasher, repos.APIKeyRepo, time.Now, recorder),
|
||||
UpdateUserProfileUseCase: useCases.NewUpdateUserProfileUseCase(repos.UserRepo, recorder),
|
||||
ListUsersUseCase: useCases.NewListUsersUseCase(repos.UserRepo),
|
||||
CreateInviteUseCase: useCases.NewCreateInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher, repos.MailRepo, settings.PublicURL),
|
||||
CancelInviteUseCase: useCases.NewCancelInviteUseCase(repos.InviteRepo),
|
||||
RenewInviteUseCase: useCases.NewRenewInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher, repos.MailRepo, settings.PublicURL),
|
||||
CreateInviteUseCase: useCases.NewCreateInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher, repos.MailRepo, settings.PublicURL, recorder),
|
||||
CancelInviteUseCase: useCases.NewCancelInviteUseCase(repos.InviteRepo, recorder),
|
||||
RenewInviteUseCase: useCases.NewRenewInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher, repos.MailRepo, settings.PublicURL, recorder),
|
||||
ListUsersAndInvitesUseCase: useCases.NewListUsersAndInvitesUseCase(repos.UserRepo, repos.InviteRepo),
|
||||
GetInviteUseCase: useCases.NewGetInviteUseCase(repos.InviteRepo, hasher),
|
||||
AcceptInviteUseCase: useCases.NewAcceptInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher),
|
||||
AcceptInviteUseCase: useCases.NewAcceptInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher, recorder),
|
||||
SendMailUseCase: useCases.NewSendMailUseCase(repos.MailRepo),
|
||||
CreateImageUseCase: useCases.NewCreateImageUseCase(repos.ImageRepo, imageStorage),
|
||||
CreateImageUseCase: useCases.NewCreateImageUseCase(repos.ImageRepo, imageStorage, recorder),
|
||||
OpenMediaUseCase: useCases.NewOpenMediaUseCase(imageStorage),
|
||||
ListMediaUseCase: useCases.NewListMediaUseCase(repos.ImageRepo, repos.ArticleRepo, repos.UserRepo),
|
||||
RenameMediaUseCase: useCases.NewRenameMediaUseCase(repos.ImageRepo),
|
||||
DeleteMediaUseCase: useCases.NewDeleteMediaUseCase(repos.ImageRepo, imageStorage),
|
||||
RenameMediaUseCase: useCases.NewRenameMediaUseCase(repos.ImageRepo, recorder),
|
||||
DeleteMediaUseCase: useCases.NewDeleteMediaUseCase(repos.ImageRepo, imageStorage, recorder),
|
||||
MergeMediaUseCase: mergeMedia,
|
||||
GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(repos.ImageRepo, repos.ArticleRepo),
|
||||
GetPurgeSettingsUseCase: useCases.NewGetPurgeSettingsUseCase(repos.PurgeSettingsRepo),
|
||||
@@ -278,18 +309,23 @@ func getUseCases(repos *Repositories, imageStorage domainImage.Storage, settings
|
||||
RunPurgeUseCase: runPurge,
|
||||
GetSettingsUseCase: useCases.NewGetSettingsUseCase(settings.Version),
|
||||
GetUpdateStatusUseCase: useCases.NewGetUpdateStatusUseCase(repos.UpdateStore, repos.UpdateJobs, repos.UpdateHelper, repos.UpdateResults, repos.RestartRequests, settings.Version, settings.Container, time.Now),
|
||||
CheckForUpdateUseCase: useCases.NewCheckForUpdateUseCase(repos.ReleaseFeed, repos.UpdateStore, settings.Version, time.Now),
|
||||
StartUpdateDownloadUseCase: startUpdateDownloadUseCase(repos, settings),
|
||||
RequestRestartUseCase: useCases.NewRequestRestartUseCase(repos.UpdateStore, repos.UpdateJobs, repos.UpdateHelper, repos.UpdateResults, repos.RestartRequests, settings.Version, time.Now),
|
||||
CheckForUpdateUseCase: useCases.NewCheckForUpdateUseCase(repos.ReleaseFeed, repos.UpdateStore, settings.Version, time.Now, recorder),
|
||||
StartUpdateDownloadUseCase: startUpdateDownloadUseCase(repos, settings, recorder),
|
||||
RequestRestartUseCase: useCases.NewRequestRestartUseCase(repos.UpdateStore, repos.UpdateJobs, repos.UpdateHelper, repos.UpdateResults, repos.RestartRequests, settings.Version, time.Now, recorder),
|
||||
RecordRunningInfoUseCase: useCases.NewRecordRunningInfoUseCase(repos.RunningInfo, settings.Version, os.Getpid(), time.Now),
|
||||
CreateAPIKeyUseCase: useCases.NewCreateAPIKeyUseCase(repos.APIKeyRepo, keyGenerator, time.Now),
|
||||
CreateAPIKeyUseCase: useCases.NewCreateAPIKeyUseCase(repos.APIKeyRepo, keyGenerator, time.Now, recorder),
|
||||
ListAPIKeysUseCase: useCases.NewListAPIKeysUseCase(repos.APIKeyRepo, repos.UserRepo, time.Now),
|
||||
RevokeAPIKeyUseCase: useCases.NewRevokeAPIKeyUseCase(repos.APIKeyRepo, repos.UserRepo, time.Now),
|
||||
RevokeAPIKeyUseCase: useCases.NewRevokeAPIKeyUseCase(repos.APIKeyRepo, repos.UserRepo, time.Now, recorder),
|
||||
AuthenticateAPIKeyUseCase: useCases.NewAuthenticateAPIKeyUseCase(repos.APIKeyRepo, keyGenerator, repos.UserRepo, time.Now),
|
||||
ListActivityUseCase: useCases.NewListActivityUseCase(repos.AuditRepo, repos.UserRepo, repos.ArticleRepo, repos.ImageRepo, repos.APIKeyRepo, time.Now),
|
||||
GetActivitySummaryUseCase: useCases.NewGetActivitySummaryUseCase(repos.AuditRepo, time.Now),
|
||||
ExportActivityUseCase: useCases.NewExportActivityUseCase(repos.AuditRepo, time.Now),
|
||||
GetActivityRetentionUseCase: useCases.NewGetActivityRetentionUseCase(repos.AuditSettingsRepo, time.Now),
|
||||
UpdateActivityRetentionUseCase: useCases.NewUpdateActivityRetentionUseCase(repos.AuditSettingsRepo, recorder, time.Now),
|
||||
}
|
||||
}
|
||||
|
||||
func startUpdateDownloadUseCase(repos *Repositories, settings config.Settings) *useCases.StartUpdateDownloadUseCase {
|
||||
func startUpdateDownloadUseCase(repos *Repositories, settings config.Settings, recorder domainAudit.Recorder) *useCases.StartUpdateDownloadUseCase {
|
||||
return useCases.NewStartUpdateDownloadUseCase(useCases.StartUpdateDownloadDependencies{
|
||||
Store: repos.UpdateStore,
|
||||
Jobs: repos.UpdateJobs,
|
||||
@@ -306,6 +342,7 @@ func startUpdateDownloadUseCase(repos *Repositories, settings config.Settings) *
|
||||
Platform: domainUpdate.Platform{OS: runtime.GOOS, Arch: runtime.GOARCH},
|
||||
FeedURL: settings.UpdateFeedURL,
|
||||
Now: time.Now,
|
||||
Recorder: recorder,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
package activity
|
||||
|
||||
import (
|
||||
"RenewCMS/api/pkg/apperr"
|
||||
"RenewCMS/api/pkg/claims"
|
||||
validator "RenewCMS/api/pkg/validator"
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
csvContentType = "text/csv; charset=utf-8"
|
||||
csvContentDisposition = `attachment; filename="activity.csv"`
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
ListUseCase *useCases.ListActivityUseCase
|
||||
SummaryUseCase *useCases.GetActivitySummaryUseCase
|
||||
ExportUseCase *useCases.ExportActivityUseCase
|
||||
}
|
||||
|
||||
type filterQuery struct {
|
||||
Q string `validate:"max=200"`
|
||||
Actor string `validate:"max=40"`
|
||||
Category string `validate:"omitempty,oneof=articles media users api_keys auth system"`
|
||||
Outcome string `validate:"omitempty,oneof=all success failed"`
|
||||
Security string `validate:"omitempty,oneof=true"`
|
||||
Range string `validate:"omitempty,oneof=today 7d 30d custom"`
|
||||
From string `validate:"max=10"`
|
||||
To string `validate:"max=10"`
|
||||
}
|
||||
|
||||
type listQuery struct {
|
||||
filterQuery
|
||||
Page int `validate:"gte=1"`
|
||||
Size int `validate:"oneof=5 25 50 100"`
|
||||
}
|
||||
|
||||
type actorResponse struct {
|
||||
Type audit.ActorType `json:"type"`
|
||||
ID *uint32 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type targetResponse struct {
|
||||
Type string `json:"type"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Exists bool `json:"exists"`
|
||||
}
|
||||
|
||||
type itemResponse struct {
|
||||
ID uint64 `json:"id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Action string `json:"action"`
|
||||
Category audit.Category `json:"category"`
|
||||
Actor actorResponse `json:"actor"`
|
||||
Target *targetResponse `json:"target"`
|
||||
Outcome audit.Outcome `json:"outcome"`
|
||||
FailureReason *string `json:"failure_reason"`
|
||||
Security bool `json:"security"`
|
||||
Source audit.Source `json:"source"`
|
||||
IP *string `json:"ip"`
|
||||
UserAgent *string `json:"user_agent"`
|
||||
Params map[string]any `json:"params"`
|
||||
Changes []audit.Change `json:"changes"`
|
||||
}
|
||||
|
||||
type listResponse struct {
|
||||
Items []itemResponse `json:"items"`
|
||||
Total int `json:"total"`
|
||||
Page int `json:"page"`
|
||||
Size int `json:"size"`
|
||||
}
|
||||
|
||||
func NewHandler(list *useCases.ListActivityUseCase, summary *useCases.GetActivitySummaryUseCase, export *useCases.ExportActivityUseCase) *Handler {
|
||||
return &Handler{ListUseCase: list, SummaryUseCase: summary, ExportUseCase: export}
|
||||
}
|
||||
|
||||
func readFilterQuery(values url.Values) filterQuery {
|
||||
return filterQuery{
|
||||
Q: values.Get("q"),
|
||||
Actor: values.Get("actor"),
|
||||
Category: values.Get("category"),
|
||||
Outcome: values.Get("outcome"),
|
||||
Security: values.Get("security"),
|
||||
Range: values.Get("range"),
|
||||
From: values.Get("from"),
|
||||
To: values.Get("to"),
|
||||
}
|
||||
}
|
||||
|
||||
func readListQuery(values url.Values) (listQuery, error) {
|
||||
page, err := intParam(values, "page", 1)
|
||||
if err != nil {
|
||||
return listQuery{}, err
|
||||
}
|
||||
size, err := intParam(values, "size", 25)
|
||||
if err != nil {
|
||||
return listQuery{}, err
|
||||
}
|
||||
return listQuery{filterQuery: readFilterQuery(values), Page: page, Size: size}, nil
|
||||
}
|
||||
|
||||
func intParam(values url.Values, name string, fallback int) (int, error) {
|
||||
if !values.Has(name) {
|
||||
return fallback, nil
|
||||
}
|
||||
return strconv.Atoi(values.Get(name))
|
||||
}
|
||||
|
||||
func toActivityQuery(query filterQuery) useCases.ActivityQuery {
|
||||
return useCases.ActivityQuery{
|
||||
Q: query.Q,
|
||||
Actor: query.Actor,
|
||||
Category: query.Category,
|
||||
Outcome: query.Outcome,
|
||||
Security: query.Security,
|
||||
Range: query.Range,
|
||||
From: query.From,
|
||||
To: query.To,
|
||||
}
|
||||
}
|
||||
|
||||
func writeActivityError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, audit.ErrInvalidFilter):
|
||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||
case errors.Is(err, audit.ErrActorNotAllowed):
|
||||
http.Error(w, apperr.OwnerOrAdminRequiredErrorMessage, http.StatusForbidden)
|
||||
case errors.Is(err, user.ErrUserNotFound):
|
||||
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||
default:
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
|
||||
query, err := readListQuery(r.URL.Query())
|
||||
if err != nil || validator.Validate.Struct(query) != nil {
|
||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
viewerId, ok := claims.UserId(r)
|
||||
if !ok {
|
||||
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
activityQuery := toActivityQuery(query.filterQuery)
|
||||
activityQuery.Page, activityQuery.Size = query.Page, query.Size
|
||||
page, err := h.ListUseCase.ListActivity(useCases.ListActivityCommand{ViewerID: viewerId, Query: activityQuery})
|
||||
if err != nil {
|
||||
writeActivityError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
items := make([]itemResponse, 0, len(page.Items))
|
||||
for _, entry := range page.Items {
|
||||
items = append(items, toItemResponse(entry))
|
||||
}
|
||||
writeJSON(w, listResponse{Items: items, Total: page.Total, Page: page.Page, Size: page.Size})
|
||||
}
|
||||
|
||||
func toItemResponse(entry useCases.ActivityEntry) itemResponse {
|
||||
event := entry.Event
|
||||
item := itemResponse{
|
||||
ID: event.ID,
|
||||
CreatedAt: event.CreatedAt,
|
||||
Action: event.Action,
|
||||
Category: event.Category,
|
||||
Actor: actorResponse{Type: event.Actor.Type, ID: event.Actor.ID, Name: event.Actor.Name},
|
||||
Outcome: event.Outcome,
|
||||
FailureReason: event.FailureReason,
|
||||
Security: event.Security,
|
||||
Source: event.Source,
|
||||
IP: event.IP,
|
||||
UserAgent: event.UserAgent,
|
||||
Params: event.Params,
|
||||
Changes: event.Changes,
|
||||
}
|
||||
if item.Params == nil {
|
||||
item.Params = map[string]any{}
|
||||
}
|
||||
if item.Changes == nil {
|
||||
item.Changes = []audit.Change{}
|
||||
}
|
||||
if event.Target.Type != "" {
|
||||
item.Target = &targetResponse{Type: event.Target.Type, ID: event.Target.ID, Name: event.Target.Name, Exists: entry.TargetExists}
|
||||
}
|
||||
return item
|
||||
}
|
||||
|
||||
func (h *Handler) Summary(w http.ResponseWriter, r *http.Request) {
|
||||
query := readFilterQuery(r.URL.Query())
|
||||
if validator.Validate.Struct(query) != nil {
|
||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
summary, err := h.SummaryUseCase.GetActivitySummary(toActivityQuery(query))
|
||||
if err != nil {
|
||||
writeActivityError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, summary)
|
||||
}
|
||||
|
||||
func (h *Handler) Export(w http.ResponseWriter, r *http.Request) {
|
||||
query := readFilterQuery(r.URL.Query())
|
||||
if validator.Validate.Struct(query) != nil {
|
||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
prepared, err := h.ExportUseCase.Prepare(toActivityQuery(query))
|
||||
if err != nil {
|
||||
writeActivityError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", csvContentType)
|
||||
w.Header().Set("Content-Disposition", csvContentDisposition)
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
_ = prepared.WriteCSV(w)
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, payload any) {
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
_, _ = w.Write(body)
|
||||
}
|
||||
@@ -71,7 +71,7 @@ func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
created, err := h.CreateUseCase.CreateAPIKey(useCases.CreateAPIKeyCommand{
|
||||
created, err := h.CreateUseCase.CreateAPIKey(r.Context(), useCases.CreateAPIKeyCommand{
|
||||
UserID: userId,
|
||||
Name: request.Name,
|
||||
ExpiresAt: request.ExpiresAt,
|
||||
@@ -161,7 +161,7 @@ func (h *Handler) Revoke(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.RevokeUseCase.RevokeAPIKey(userId, uint32(id)); err != nil {
|
||||
if err := h.RevokeUseCase.RevokeAPIKey(r.Context(), userId, uint32(id)); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrAPIKeyNotFound):
|
||||
http.Error(w, apperr.APIKeyNotFoundErrorMessage, http.StatusNotFound)
|
||||
|
||||
@@ -149,7 +149,7 @@ func (h *Handler) PostArticle(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
createdArticle, err := h.CreateUseCase.CreateArticle(useCases.CreateArticleCommand{
|
||||
createdArticle, err := h.CreateUseCase.CreateArticle(r.Context(), useCases.CreateArticleCommand{
|
||||
Title: localArticle.Title,
|
||||
Body: localArticle.Body,
|
||||
Format: format,
|
||||
@@ -201,7 +201,7 @@ func (h *Handler) setIsOnline(w http.ResponseWriter, r *http.Request, isOnline b
|
||||
return
|
||||
}
|
||||
|
||||
updatedArticle, err := h.UpdateUseCase.UpdateIsOnline(id, isOnline, format)
|
||||
updatedArticle, err := h.UpdateUseCase.UpdateIsOnline(r.Context(), id, isOnline, format)
|
||||
if err != nil {
|
||||
writeArticleErrorResponse(w, err)
|
||||
return
|
||||
@@ -237,7 +237,7 @@ func (h *Handler) UpdateArticleBody(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
updatedArticle, err := h.UpdateUseCase.UpdateBody(id, localArticle.Body, format)
|
||||
updatedArticle, err := h.UpdateUseCase.UpdateBody(r.Context(), id, localArticle.Body, format)
|
||||
if err != nil {
|
||||
writeArticleErrorResponse(w, err)
|
||||
return
|
||||
@@ -314,7 +314,7 @@ func (h *Handler) DeleteArticle(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.DeleteUseCase.DeleteArticle(id); err != nil {
|
||||
if err := h.DeleteUseCase.DeleteArticle(r.Context(), id); err != nil {
|
||||
if errors.Is(err, domain.ErrArticleNotFound) {
|
||||
http.Error(w, apperr.ArticleNotFoundErrorMessage, http.StatusNotFound)
|
||||
return
|
||||
|
||||
@@ -67,7 +67,7 @@ func (h *AcceptInviteHandler) AcceptInvite(w http.ResponseWriter, r *http.Reques
|
||||
return
|
||||
}
|
||||
|
||||
createdUser, err := h.AcceptInviteUseCase.AcceptInvite(useCases.AcceptInviteCommand{
|
||||
createdUser, err := h.AcceptInviteUseCase.AcceptInvite(r.Context(), useCases.AcceptInviteCommand{
|
||||
Code: request.Code,
|
||||
Username: request.Username,
|
||||
Password: request.Password,
|
||||
|
||||
@@ -87,7 +87,7 @@ func (h *LoginHandler) Login(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
dbUser, err := h.AuthenticateUseCase.Authenticate(credentials.Username, credentials.Password)
|
||||
dbUser, err := h.AuthenticateUseCase.Authenticate(r.Context(), credentials.Username, credentials.Password)
|
||||
if err != nil {
|
||||
http.Error(w, apperr.LogsErrorMessage, http.StatusForbidden)
|
||||
return
|
||||
@@ -113,7 +113,7 @@ func (h *LoginHandler) Register(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
createdUser, err := h.CreateUseCase.CreateUser(useCases.CreateUserCommand{
|
||||
createdUser, err := h.CreateUseCase.CreateUser(r.Context(), useCases.CreateUserCommand{
|
||||
Username: credentials.Username,
|
||||
Password: credentials.Password,
|
||||
Email: credentials.Email,
|
||||
@@ -139,7 +139,8 @@ func (h *LoginHandler) RegistrationStatus(w http.ResponseWriter, _ *http.Request
|
||||
_, _ = w.Write(body)
|
||||
}
|
||||
|
||||
func (h *LoginHandler) Logout(w http.ResponseWriter, _ *http.Request) {
|
||||
func (h *LoginHandler) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
h.AuthenticateUseCase.Logout(r.Context())
|
||||
removeJwtCookie(w, h.IsProduction)
|
||||
message, _ := json.Marshal(map[string]any{"message": "User logged out! HTTPonly jwt cookie deleted"})
|
||||
_, _ = w.Write(message)
|
||||
|
||||
@@ -46,7 +46,7 @@ func (h *PasswordResetHandler) RequestPasswordReset(w http.ResponseWriter, r *ht
|
||||
return
|
||||
}
|
||||
|
||||
_ = h.RequestPasswordResetUseCase.RequestPasswordReset(credentials.Email)
|
||||
_ = h.RequestPasswordResetUseCase.RequestPasswordReset(r.Context(), credentials.Email)
|
||||
|
||||
message, _ := json.Marshal(map[string]any{"message": apperr.PasswordResetRequestedMessage})
|
||||
_, _ = w.Write(message)
|
||||
@@ -66,7 +66,7 @@ func (h *PasswordResetHandler) ResetPassword(w http.ResponseWriter, r *http.Requ
|
||||
return
|
||||
}
|
||||
|
||||
err = h.ResetPasswordUseCase.ResetPassword(credentials.Email, credentials.Code, credentials.Password)
|
||||
err = h.ResetPasswordUseCase.ResetPassword(r.Context(), credentials.Email, credentials.Code, credentials.Password)
|
||||
if err != nil {
|
||||
if errors.Is(err, user.ErrInvalidPasswordResetCode) || errors.Is(err, user.ErrPasswordResetCodeExpired) {
|
||||
http.Error(w, apperr.PasswordResetFailedErrorMessage, http.StatusForbidden)
|
||||
|
||||
@@ -50,7 +50,7 @@ func (h *VerificationHandler) Verify(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
verifiedUser, err := h.VerifyUseCase.Verify(userId, credentials.Code)
|
||||
verifiedUser, err := h.VerifyUseCase.Verify(r.Context(), userId, credentials.Code)
|
||||
if err != nil {
|
||||
if errors.Is(err, user.ErrUserNotFound) {
|
||||
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||
|
||||
@@ -213,7 +213,7 @@ func (h *Handler) Upload(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
defer closeFile()
|
||||
|
||||
created, err := h.CreateUseCase.CreateImage(input)
|
||||
created, err := h.CreateUseCase.CreateImage(r.Context(), input)
|
||||
if err != nil {
|
||||
upload.WriteCreateError(w, err)
|
||||
return
|
||||
@@ -247,7 +247,7 @@ func (h *Handler) Rename(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
renamed, err := h.RenameUseCase.Rename(id, request.Filename)
|
||||
renamed, err := h.RenameUseCase.Rename(r.Context(), id, request.Filename)
|
||||
if err != nil {
|
||||
if errors.Is(err, domainImage.ErrInvalidFilename) {
|
||||
http.Error(w, apperr.MediaFilenameErrorMessage, http.StatusBadRequest)
|
||||
@@ -266,7 +266,7 @@ func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.DeleteUseCase.Delete(id); err != nil {
|
||||
if err := h.DeleteUseCase.Delete(r.Context(), id); err != nil {
|
||||
writeImageError(w, err)
|
||||
return
|
||||
}
|
||||
@@ -304,7 +304,7 @@ func (h *Handler) Merge(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.MergeUseCase.Merge(request.KeepID, request.MergeIDs)
|
||||
result, err := h.MergeUseCase.Merge(r.Context(), request.KeepID, request.MergeIDs)
|
||||
if err != nil {
|
||||
writeMergeError(w, err)
|
||||
return
|
||||
|
||||
@@ -154,7 +154,7 @@ func (h *Handler) RunPurge(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
result, err := h.RunPurgeUseCase.Run(request.Fingerprint)
|
||||
result, err := h.RunPurgeUseCase.Run(r.Context(), request.Fingerprint)
|
||||
if err != nil {
|
||||
writePurgeError(w, err)
|
||||
return
|
||||
|
||||
@@ -1,21 +1,78 @@
|
||||
package settings
|
||||
|
||||
import (
|
||||
"RenewCMS/api/pkg/apperr"
|
||||
validator "RenewCMS/api/pkg/validator"
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
GetSettingsUseCase *useCases.GetSettingsUseCase
|
||||
GetActivityRetentionUseCase *useCases.GetActivityRetentionUseCase
|
||||
UpdateActivityRetentionUseCase *useCases.UpdateActivityRetentionUseCase
|
||||
}
|
||||
|
||||
func NewHandler(getSettings *useCases.GetSettingsUseCase) *Handler {
|
||||
return &Handler{GetSettingsUseCase: getSettings}
|
||||
type UpdateSettingsRequest struct {
|
||||
ActivityRetentionDays *int `json:"activity_retention_days" validate:"required,oneof=0 30 90 365"`
|
||||
}
|
||||
|
||||
type settingsResponse struct {
|
||||
Version string `json:"version"`
|
||||
ActivityRetentionDays int `json:"activity_retention_days"`
|
||||
ActivityLastCleanupAt *time.Time `json:"activity_last_cleanup_at"`
|
||||
ActivityLastCleanupRemoved int `json:"activity_last_cleanup_removed"`
|
||||
ActivityNextCleanupAt *time.Time `json:"activity_next_cleanup_at"`
|
||||
}
|
||||
|
||||
func NewHandler(getSettings *useCases.GetSettingsUseCase, getRetention *useCases.GetActivityRetentionUseCase, updateRetention *useCases.UpdateActivityRetentionUseCase) *Handler {
|
||||
return &Handler{GetSettingsUseCase: getSettings, GetActivityRetentionUseCase: getRetention, UpdateActivityRetentionUseCase: updateRetention}
|
||||
}
|
||||
|
||||
func (h *Handler) GetSettings(w http.ResponseWriter, _ *http.Request) {
|
||||
body, err := json.Marshal(h.GetSettingsUseCase.GetSettings())
|
||||
retention, err := h.GetActivityRetentionUseCase.GetActivityRetention()
|
||||
if err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
h.write(w, retention)
|
||||
}
|
||||
|
||||
func (h *Handler) UpdateSettings(w http.ResponseWriter, r *http.Request) {
|
||||
var request UpdateSettingsRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := validator.Validate.Struct(request); err != nil {
|
||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
retention, err := h.UpdateActivityRetentionUseCase.UpdateActivityRetention(r.Context(), *request.ActivityRetentionDays)
|
||||
if err != nil {
|
||||
if errors.Is(err, audit.ErrInvalidRetention) {
|
||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
h.write(w, retention)
|
||||
}
|
||||
|
||||
func (h *Handler) write(w http.ResponseWriter, retention audit.Settings) {
|
||||
body, err := json.Marshal(settingsResponse{
|
||||
Version: h.GetSettingsUseCase.GetSettings().Version,
|
||||
ActivityRetentionDays: retention.RetentionDays,
|
||||
ActivityLastCleanupAt: retention.LastCleanupAt,
|
||||
ActivityLastCleanupRemoved: retention.LastCleanupRemoved,
|
||||
ActivityNextCleanupAt: retention.NextCleanupAt,
|
||||
})
|
||||
if err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
|
||||
@@ -47,7 +47,7 @@ func (h *Handler) GetStatus(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func (h *Handler) Check(w http.ResponseWriter, r *http.Request) {
|
||||
if _, err := h.CheckForUpdateUseCase.Check(); err != nil {
|
||||
if _, err := h.CheckForUpdateUseCase.Check(r.Context()); err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
@@ -58,8 +58,8 @@ func (h *Handler) Check(w http.ResponseWriter, r *http.Request) {
|
||||
writeStatus(w, http.StatusOK, h.GetUpdateStatusUseCase.GetStatus(isOwner))
|
||||
}
|
||||
|
||||
func (h *Handler) Download(w http.ResponseWriter, _ *http.Request) {
|
||||
status, err := h.StartUpdateDownloadUseCase.Start()
|
||||
func (h *Handler) Download(w http.ResponseWriter, r *http.Request) {
|
||||
status, err := h.StartUpdateDownloadUseCase.Start(r.Context())
|
||||
if err != nil {
|
||||
writeDownloadError(w, err)
|
||||
return
|
||||
@@ -77,7 +77,7 @@ func (h *Handler) Restart(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
status, err := h.RequestRestartUseCase.Request(userId, kind)
|
||||
status, err := h.RequestRestartUseCase.Request(r.Context(), userId, kind)
|
||||
if err != nil {
|
||||
writeRestartError(w, err)
|
||||
return
|
||||
|
||||
@@ -82,7 +82,7 @@ func (h *InviteHandler) CreateInvite(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
created, err := h.CreateInviteUseCase.CreateInvite(useCases.CreateInviteCommand{
|
||||
created, err := h.CreateInviteUseCase.CreateInvite(r.Context(), useCases.CreateInviteCommand{
|
||||
Email: request.Email,
|
||||
InvitedBy: userId,
|
||||
})
|
||||
@@ -124,7 +124,7 @@ func (h *InviteHandler) CancelInvite(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.CancelInviteUseCase.CancelInvite(id); err != nil {
|
||||
if err := h.CancelInviteUseCase.CancelInvite(r.Context(), id); err != nil {
|
||||
writeManageInviteError(w, err)
|
||||
return
|
||||
}
|
||||
@@ -144,7 +144,7 @@ func (h *InviteHandler) RenewInvite(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
renewed, err := h.RenewInviteUseCase.RenewInvite(useCases.RenewInviteCommand{ID: id, RenewedBy: userId})
|
||||
renewed, err := h.RenewInviteUseCase.RenewInvite(r.Context(), useCases.RenewInviteCommand{ID: id, RenewedBy: userId})
|
||||
if err != nil {
|
||||
writeManageInviteError(w, err)
|
||||
return
|
||||
|
||||
@@ -46,7 +46,7 @@ func (h *Handler) UpdateMe(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
updatedUser, err := h.UpdateProfileUseCase.UpdateDisplayName(userId, *request.DisplayName)
|
||||
updatedUser, err := h.UpdateProfileUseCase.UpdateDisplayName(r.Context(), userId, *request.DisplayName)
|
||||
if err != nil {
|
||||
if errors.Is(err, user.ErrInvalidDisplayName) {
|
||||
http.Error(w, apperr.DisplayNameErrorMessage, http.StatusBadRequest)
|
||||
|
||||
@@ -19,6 +19,8 @@ const bearerScheme = "bearer "
|
||||
|
||||
type apiKeyIdContextKey struct{}
|
||||
|
||||
type apiKeyNameContextKey struct{}
|
||||
|
||||
func bearerAPIKey(r *http.Request) (string, bool) {
|
||||
header := r.Header.Get("Authorization")
|
||||
if len(header) < len(bearerScheme) || !strings.EqualFold(header[:len(bearerScheme)], bearerScheme) {
|
||||
@@ -34,6 +36,11 @@ func apiKeyIdFrom(r *http.Request) (uint32, bool) {
|
||||
return id, ok
|
||||
}
|
||||
|
||||
func apiKeyNameFrom(r *http.Request) string {
|
||||
name, _ := r.Context().Value(apiKeyNameContextKey{}).(string)
|
||||
return name
|
||||
}
|
||||
|
||||
func RequireSession(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if _, isKey := bearerAPIKey(r); isKey {
|
||||
@@ -70,6 +77,7 @@ func APIKeyAuth(authenticate *useCases.AuthenticateAPIKeyUseCase, maxRequests in
|
||||
|
||||
ctx := jwtauth.NewContext(r.Context(), token, nil)
|
||||
ctx = context.WithValue(ctx, apiKeyIdContextKey{}, authenticated.Key.ID)
|
||||
ctx = context.WithValue(ctx, apiKeyNameContextKey{}, authenticated.Key.Name)
|
||||
limited.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"RenewCMS/api/pkg/claims"
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func AuditContext(getUser *useCases.GetUserUseCase, trustedProxies []string) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
origin := audit.Origin{
|
||||
Actor: auditActor(getUser, r),
|
||||
Source: auditSource(r),
|
||||
IP: clientIP(r, trustedProxies),
|
||||
UserAgent: truncatedUserAgent(r),
|
||||
}
|
||||
next.ServeHTTP(w, r.WithContext(audit.WithOrigin(r.Context(), origin)))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func auditActor(getUser *useCases.GetUserUseCase, r *http.Request) audit.Actor {
|
||||
if id, ok := apiKeyIdFrom(r); ok {
|
||||
return audit.APIKeyActor(id, apiKeyNameFrom(r))
|
||||
}
|
||||
userId, ok := claims.UserId(r)
|
||||
if !ok {
|
||||
return audit.AnonymousActor("")
|
||||
}
|
||||
current, err := getUser.GetUser(userId)
|
||||
if err != nil {
|
||||
return audit.AnonymousActor("")
|
||||
}
|
||||
tokenVersion, ok := claims.TokenVersion(r)
|
||||
if !ok || tokenVersion != current.TokenVersion {
|
||||
return audit.AnonymousActor("")
|
||||
}
|
||||
return audit.UserActor(current)
|
||||
}
|
||||
|
||||
func auditSource(r *http.Request) audit.Source {
|
||||
if _, ok := apiKeyIdFrom(r); ok {
|
||||
return audit.SourceAPIKey
|
||||
}
|
||||
return audit.SourceWeb
|
||||
}
|
||||
|
||||
func clientIP(r *http.Request, trustedProxies []string) string {
|
||||
realIP := r.Header.Get("X-Real-IP")
|
||||
if realIP != "" && isTrustedProxy(r.RemoteAddr, trustedProxies) {
|
||||
return realIP
|
||||
}
|
||||
return hostOf(r.RemoteAddr)
|
||||
}
|
||||
|
||||
func truncatedUserAgent(r *http.Request) string {
|
||||
runes := []rune(r.Header.Get("User-Agent"))
|
||||
if len(runes) > audit.MaxUserAgentLength {
|
||||
runes = runes[:audit.MaxUserAgentLength]
|
||||
}
|
||||
return string(runes)
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"RenewCMS/api/pkg/apperr"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/jwtauth/v5"
|
||||
"github.com/lestrrat-go/jwx/v2/jwt"
|
||||
)
|
||||
|
||||
func RequireSignedIn(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
token, _, err := jwtauth.FromContext(r.Context())
|
||||
if err != nil || token == nil || jwt.Validate(token) != nil {
|
||||
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
+54
-11
@@ -1,6 +1,7 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"RenewCMS/api/handlers/activity"
|
||||
"RenewCMS/api/handlers/apikey"
|
||||
"RenewCMS/api/handlers/article"
|
||||
"RenewCMS/api/handlers/auth"
|
||||
@@ -46,9 +47,10 @@ func (c *UseCases) apiKeyAuth() func(http.Handler) http.Handler {
|
||||
return c.apiKeyAuthMiddleware
|
||||
}
|
||||
|
||||
func NewArticleRouter(container *UseCases) http.Handler {
|
||||
func NewArticleRouter(container *UseCases, trustedProxies []string) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
r.Use(container.apiKeyAuth())
|
||||
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
|
||||
|
||||
articleHandler := article.NewHandler(container.CreateArticleUseCase, container.GetArticleUseCase, container.ListArticlesUseCase, container.DeleteArticleUseCase, container.UpdateArticleUseCase, container.GetUserUseCase)
|
||||
|
||||
@@ -71,6 +73,8 @@ func NewArticleRouter(container *UseCases) http.Handler {
|
||||
|
||||
func NewAuthRouter(container *UseCases, isProduction bool, rateLimit config.AuthRateLimitSettings, trustedProxies []string) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
r.Use(jwtauth.Verifier(container.Token))
|
||||
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
|
||||
|
||||
loginHandler := auth.NewLoginHandler(container.Token, container.CreateUserUseCase, container.AuthenticateUserUseCase, isProduction)
|
||||
verificationHandler := auth.NewVerificationHandler(container.VerifyUserUseCase, container.CancelRegistrationUseCase, isProduction)
|
||||
@@ -124,6 +128,7 @@ func NewUserRouter(container *UseCases, rateLimit config.AuthRateLimitSettings,
|
||||
|
||||
r.Use(jwtauth.Verifier(container.Token))
|
||||
r.Use(container.apiKeyAuth())
|
||||
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
|
||||
r.Use(jwtauth.Authenticator(container.Token))
|
||||
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
||||
@@ -140,17 +145,51 @@ func NewUserRouter(container *UseCases, rateLimit config.AuthRateLimitSettings,
|
||||
return r
|
||||
}
|
||||
|
||||
func NewSettingsRouter(container *UseCases) http.Handler {
|
||||
func NewSettingsRouter(container *UseCases, trustedProxies []string) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
settingsHandler := settings.NewHandler(container.GetSettingsUseCase)
|
||||
settingsHandler := settings.NewHandler(container.GetSettingsUseCase, container.GetActivityRetentionUseCase, container.UpdateActivityRetentionUseCase)
|
||||
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(jwtauth.Verifier(container.Token))
|
||||
r.Use(container.apiKeyAuth())
|
||||
r.Use(jwtauth.Authenticator(container.Token))
|
||||
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
||||
r.Get("/", settingsHandler.GetSettings)
|
||||
})
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(middleware.RequireSession)
|
||||
r.Use(jwtauth.Verifier(container.Token))
|
||||
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
|
||||
r.Use(middleware.RequireSignedIn)
|
||||
r.Use(jwtauth.Authenticator(container.Token))
|
||||
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
||||
r.Use(middleware.RequireOwner(container.GetUserUseCase))
|
||||
r.Patch("/", settingsHandler.UpdateSettings)
|
||||
})
|
||||
return r
|
||||
}
|
||||
|
||||
func NewActivityRouter(container *UseCases, trustedProxies []string) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
activityHandler := activity.NewHandler(container.ListActivityUseCase, container.GetActivitySummaryUseCase, container.ExportActivityUseCase)
|
||||
|
||||
r.Use(middleware.RequireSession)
|
||||
r.Use(jwtauth.Verifier(container.Token))
|
||||
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
|
||||
r.Use(middleware.RequireSignedIn)
|
||||
r.Use(jwtauth.Authenticator(container.Token))
|
||||
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
||||
r.Get("/", activityHandler.List)
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(middleware.RequireOwnerOrAdmin(container.GetUserUseCase))
|
||||
r.Get("/summary", activityHandler.Summary)
|
||||
r.Get("/export", activityHandler.Export)
|
||||
})
|
||||
return r
|
||||
}
|
||||
|
||||
@@ -161,13 +200,14 @@ const (
|
||||
updateDownloadWindow = time.Minute
|
||||
)
|
||||
|
||||
func NewSystemRouter(container *UseCases) http.Handler {
|
||||
func NewSystemRouter(container *UseCases, trustedProxies []string) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
updateHandler := update.NewHandler(container.GetUpdateStatusUseCase, container.CheckForUpdateUseCase, container.StartUpdateDownloadUseCase, container.RequestRestartUseCase, container.GetUserUseCase)
|
||||
|
||||
r.Use(middleware.RequireSession)
|
||||
r.Use(jwtauth.Verifier(container.Token))
|
||||
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
|
||||
r.Use(jwtauth.Authenticator(container.Token))
|
||||
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
||||
@@ -189,13 +229,14 @@ func NewSystemRouter(container *UseCases) http.Handler {
|
||||
return r
|
||||
}
|
||||
|
||||
func NewAPIKeyRouter(container *UseCases) http.Handler {
|
||||
func NewAPIKeyRouter(container *UseCases, trustedProxies []string) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
apiKeyHandler := apikey.NewHandler(container.CreateAPIKeyUseCase, container.ListAPIKeysUseCase, container.RevokeAPIKeyUseCase)
|
||||
|
||||
r.Use(middleware.RequireSession)
|
||||
r.Use(jwtauth.Verifier(container.Token))
|
||||
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
|
||||
r.Use(jwtauth.Authenticator(container.Token))
|
||||
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
||||
@@ -205,13 +246,14 @@ func NewAPIKeyRouter(container *UseCases) http.Handler {
|
||||
return r
|
||||
}
|
||||
|
||||
func NewMediaRouter(container *UseCases) http.Handler {
|
||||
func NewMediaRouter(container *UseCases, trustedProxies []string) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
mediaHandler := media.NewHandler(container.CreateImageUseCase, container.ListMediaUseCase, container.RenameMediaUseCase, container.DeleteMediaUseCase, container.MergeMediaUseCase, container.GetMediaUsageUseCase, container.GetPurgeSettingsUseCase, container.UpdatePurgeSettingsUseCase, container.PreviewPurgeUseCase, container.RunPurgeUseCase)
|
||||
|
||||
r.Use(jwtauth.Verifier(container.Token))
|
||||
r.Use(container.apiKeyAuth())
|
||||
r.Use(middleware.AuditContext(container.GetUserUseCase, trustedProxies))
|
||||
r.Use(jwtauth.Authenticator(container.Token))
|
||||
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
||||
@@ -241,13 +283,14 @@ func InitBackendRoutes(container *UseCases, settings config.Settings) *chi.Mux {
|
||||
r.Get("/", GetHelloWorld)
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(jwtauth.Verifier(container.Token))
|
||||
r.Mount("/article", NewArticleRouter(container))
|
||||
r.Mount("/article", NewArticleRouter(container, settings.TrustedProxies))
|
||||
})
|
||||
r.Mount("/user", NewUserRouter(container, settings.AuthRateLimit, settings.TrustedProxies))
|
||||
r.Mount("/settings", NewSettingsRouter(container))
|
||||
r.Mount("/media", NewMediaRouter(container))
|
||||
r.Mount("/api-key", NewAPIKeyRouter(container))
|
||||
r.Mount("/system", NewSystemRouter(container))
|
||||
r.Mount("/settings", NewSettingsRouter(container, settings.TrustedProxies))
|
||||
r.Mount("/activity", NewActivityRouter(container, settings.TrustedProxies))
|
||||
r.Mount("/media", NewMediaRouter(container, settings.TrustedProxies))
|
||||
r.Mount("/api-key", NewAPIKeyRouter(container, settings.TrustedProxies))
|
||||
r.Mount("/system", NewSystemRouter(container, settings.TrustedProxies))
|
||||
r.Mount("/auth", NewAuthRouter(container, settings.IsProduction(), settings.AuthRateLimit, settings.TrustedProxies))
|
||||
|
||||
return r
|
||||
|
||||
+1
-1
@@ -92,7 +92,7 @@ func run() error {
|
||||
validator.InitValidator()
|
||||
|
||||
server := newServer(api.InitRoutes(container, settings), settings)
|
||||
return serveUntilStopped(server, settings, container.RecordRunningInfoUseCase.Record, container.PurgeScheduler.Run)
|
||||
return serveUntilStopped(server, settings, container.RecordRunningInfoUseCase.Record, container.RunSchedulers)
|
||||
}
|
||||
|
||||
func initEnvVariables() {
|
||||
|
||||
+56
@@ -27,6 +27,62 @@ for example `https://cms.example/v1/article/`.
|
||||
| Users and invites | GET /v1/user/, PATCH /v1/user/me, POST /v1/user/invite (owner only), DELETE /v1/user/invite/{id} (owner only), POST /v1/user/invite/{id}/renew (owner only), GET /v1/auth/me |
|
||||
| Settings | GET /v1/settings |
|
||||
|
||||
## Activity log
|
||||
The activity routes are session only: a key answers 403 "This action needs a real session." and a
|
||||
key never reads the audit trail. Events are append-only; there is no `POST`, `PUT`, `PATCH` or
|
||||
`DELETE` under `/v1/activity`.
|
||||
|
||||
| Route | Who | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `GET /v1/activity` | Any verified user | Filtered, paged events. Owner and admin see every event; any other role is scoped to its own events, and `actor` set to someone else answers 403 "Only owners and admins can do this." |
|
||||
| `GET /v1/activity/summary` | Owner, admin | Counts for the range, the previous period, active people and seven-bucket series. |
|
||||
| `GET /v1/activity/export` | Owner, admin | The same filters as the list without `page` or `size`, as a `text/csv; charset=utf-8` attachment (`when,actor,action,target,outcome,source,ip`). Cells starting with `=`, `+`, `-` or `@` get a leading quote. |
|
||||
|
||||
Query: `q`, `actor` (`user:ID`, `key:ID`, `system`), `category` (`articles`, `media`, `users`,
|
||||
`api_keys`, `auth`, `system`), `outcome` (`all`, `success`, `failed`), `security` (`true`), `range`
|
||||
(`today`, `7d`, `30d`, `custom`; default `7d`), `from` and `to` (dates, with `custom`), `page` (from
|
||||
1) and `size` (25, 50 or 100). Any invalid value answers 400 with the body-mismatch message. Dates
|
||||
are UTC. The list answers `{ items, total, page, size }`, newest first (`created_at`, then `id`).
|
||||
|
||||
`GET /v1/settings` also returns `activity_retention_days` (30, 90, 365 or 0 for forever, default
|
||||
90), `activity_last_cleanup_at` and `activity_last_cleanup_removed`. `PATCH /v1/settings` with
|
||||
`{"activity_retention_days": 30}` is session only and owner only (403 "Only the owner can do this.");
|
||||
any other value answers 400.
|
||||
|
||||
### What is recorded
|
||||
Every real action is recorded by its use case, once, after the change was made (outcome `success`)
|
||||
or after the use case refused it (outcome `failed`, with a plain `failure_reason`). Nothing is
|
||||
recorded for a read (no `GET`, no list, no public article read, no status poll), for a request that
|
||||
fails validation, or for a target that does not exist (404). A failed audit write is logged and
|
||||
never changes the response or the change itself.
|
||||
|
||||
| Category | Actions |
|
||||
| --- | --- |
|
||||
| `articles` | `article.create`, `article.edit`, `article.publish`, `article.unpublish`, `article.delete` |
|
||||
| `media` | `media.upload`, `media.rename`, `media.delete`, `media.merge`, `media.purge` |
|
||||
| `users` | `user.register`, `user.verify`, `user.update_profile`, `invite.create`, `invite.cancel`, `invite.renew`, `invite.accept` |
|
||||
| `system` | `system.media_purge` (scheduled), `system.update_checked`, `system.update_downloaded`, `system.restart_requested`, `system.activity_cleanup`, `system.activity_retention_changed` |
|
||||
|
||||
Target types: `article`, `image`, `user`, `invite`, `api_key` and `release` (id and name are the tag).
|
||||
Only the fields `title`, `online`, `body`, `filename` and `display_name` appear in `changes`, with the
|
||||
kinds `text` and `body`; a body edit carries a signed character count delta and never the text. A
|
||||
change that leaves a value as it was (same body, same publish state, same file name, same display
|
||||
name) records nothing. Params: `media.merge` and `media.purge` and `system.media_purge` carry
|
||||
`merged` and `articles_updated`, plus `failed_groups` when a group failed (still outcome `success`);
|
||||
`system.update_checked` carries `update_available`; `system.restart_requested` carries `kind` and,
|
||||
for an update, `tag` (it has no target). `system.update_downloaded` is recorded when the job reaches
|
||||
`ready` or `failed`, with the origin captured at request time; a refusal at the start is recorded
|
||||
immediately. A failed registration or invite acceptance has an `anonymous` actor named by the
|
||||
attempted username.
|
||||
|
||||
`failure_reason` is one fixed sentence per domain error, matched with `errors.Is`, at most 255
|
||||
characters, for example "The title must be between 3 and 200 characters.", "That file name is not
|
||||
valid.", "The merge request is not valid.", "A purge is already running.", "Registration is closed
|
||||
on this site.", "That invitation has expired.", "The release feed could not be reached." or "The
|
||||
update could not be downloaded.". Any other error becomes "Something went wrong on our side. Please
|
||||
try again."; the text of the error never reaches the event, the API or the CSV. Passwords, hashes,
|
||||
codes, article bodies, file bytes, storage paths and asset urls are never recorded.
|
||||
|
||||
Article routes accept `?format=markdown|html|json` (default `markdown`). `GET /v1/media/` accepts
|
||||
`q`, `hash`, `cursor`, `filter`, `sort` and `limit`.
|
||||
|
||||
|
||||
@@ -55,6 +55,20 @@ The use cases `GetPurgeSettings`, `UpdatePurgeSettings`, `PreviewPurge` and `Run
|
||||
| `GET /v1/media/purge-preview` | Groups, copies, distinct articles, the first 5 groups, `more` and the fingerprint. |
|
||||
| `POST /v1/media/purge` | Runs the purge. Optional `fingerprint`; 409 when stale or when a run is in progress. |
|
||||
|
||||
### Activity log
|
||||
|
||||
`internal/domain/audit` holds the append-only `Event` (actor, target and failure-reason snapshots, outcome, security flag, source, ip, user agent, `params` and `changes`), the closed vocabularies (actor type, category, outcome, source, change kind), the `Filter`, `Summary` and `Settings` types, the `Repository` interface (`Append`, `List`, `Summary`, `DeleteOlderThan`: no way to edit or delete one event), the `SettingsRepository` (`Get`, `SaveRetention`, `SaveLastCleanup`; no row means 90 days) and the sentinels `ErrInvalidFilter`, `ErrInvalidRetention`, `ErrInvalidEvent` and `ErrActorNotAllowed`. The `Recorder` port is `Record(ctx, event)`; it returns nothing, so a caller can never fail on it.
|
||||
|
||||
`internal/infrastructure/auditing.Recorder` is the adapter. It fills a missing actor, source, ip and user agent from the `audit.Origin` carried by the request context, stamps `created_at` from the injected clock in UTC, bounds long names, drops an event outside the vocabulary, and recovers from any error or panic of the repository by writing one line to the process log (the action and the error only). `middleware.AuditContext` builds the origin after the credential middleware: a session gives a `user` actor and source `web`, an API key an `api_key` actor and source `api_key`, no valid credential an `anonymous` actor; the ip is the peer address, or `X-Real-IP` when the peer is a trusted proxy; the user agent is cut to 255 characters. Use cases that produce events (authenticate and logout, password reset request and completion, API key create and revoke, retention change, cleanup) take the context and an `audit.Recorder`; secrets (passwords, raw keys, reset codes, tokens and their hashes) are never put in an event or in its log line.
|
||||
|
||||
Persistence is `models.AuditEvent` (`audit_events`, indexes on `created_at`, `(actor_type, actor_id, created_at)` and `(category, created_at)`; `params` and `changes` are JSON text) and `models.AuditSettings` (one row), both in `AutoMigrate`. The queries use only portable SQL (`LOWER(...) LIKE ... ESCAPE '!'`, `COUNT(DISTINCT ...)`, `CASE` sums), so they run on SQLite, MySQL/MariaDB and PostgreSQL. The summary splits the range into seven equal buckets, oldest first.
|
||||
|
||||
The use cases `ListActivity`, `GetActivitySummary` and `ExportActivity` turn the raw query into a domain filter (`range` defaults to 7 days; `custom` needs two dates, `to` included), scope a caller who is not owner or admin to its own events, and resolve `target.exists` at read time. The export reads the log through `List` in pages of 500 and writes the CSV with `encoding/csv`. `/v1/activity` and the settings `PATCH` sit behind `RequireSession`, the verifier, the current-token and verified-user checks; summary and export also behind `RequireOwnerOrAdmin`, the settings `PATCH` behind `RequireOwner`.
|
||||
|
||||
`CleanupActivityUseCase.Tick(now)` follows the `PurgeScheduler` model. With a retention of 0 it never runs. Otherwise it is due once a day, at or after 03:00 in the location of `now` and when the last cleanup is before today's 03:00. It deletes events older than `now` minus the retention days (never newer than 24 hours), records the run (`activity_last_cleanup_at`, `activity_last_cleanup_removed`) even when nothing was removed, and only then records a `system.activity_cleanup` event when something was removed. A failing delete returns the error and leaves the last-cleanup fields as they were, so the next tick retries. `scheduler.Runner` now wraps a task with a label: `NewRunner` keeps the purge behaviour and log line, and `NewCleanupRunner` ticks the cleanup. `UseCases.RunSchedulers` runs both runners and `cmd/server/main.go` starts it with the server's signal context.
|
||||
|
||||
Producers: `ArticleChanges`, `TextChange` and `BodyChange` in `internal/domain/audit` build the change lists (the body change holds only a signed rune count delta), and `NewTarget` and `ReleaseTarget` build the target snapshots (types `article`, `image`, `user`, `invite`, `api_key`, `release`). The use cases create, edit, publish, unpublish and delete article, upload, rename, delete, merge and purge media, register, verify, update profile, create, cancel, renew and accept invite, check, download and restart take the request context first and an `audit.Recorder` last, and record exactly one event after the change or the refusal (the action catalogue is in `docs/api.md`). Events are never written by handlers, middleware or GORM hooks, and nothing is recorded for reads or for a target that does not exist. `useCases/auditFailures.go` holds the fixed table of failure sentences keyed by domain `Err...` sentinels (matched with `errors.Is`, each at most 255 characters; the restart action overrides `ErrJobInProgress`) with the generic fallback "Something went wrong on our side. Please try again."; raw error text is never stored. The manual purge runs the groups through the non-recording `MergeMediaUseCase.merge`, so only one `media.purge` event is written; `RunPurgeUseCase.Execute` is the non-recording run that `PurgeSchedulerUseCase.Tick(now)` uses to record one `system.media_purge` event with the system actor and `context.Background()`. `StartUpdateDownloadUseCase` hands `context.WithoutCancel(ctx)` to its job goroutine so the `system.update_downloaded` event, written when the job becomes `ready` or `failed`, keeps the origin of the request. `middleware.AuditContext` is mounted on the article, user, media and system routers (after the API key middleware where keys are accepted), so API key calls are attributed to the key.
|
||||
|
||||
### Image metadata backfill
|
||||
|
||||
At boot, `BackfillImageMetadataUseCase` (through `image.Repository.ListMissingMetadata` and `UpdateMetadata`) fills `filename`, `size`, `content_type`, `width`, `height` and `sha256` for image rows that lack them, reading the bytes through `image.Storage` (the files in `UPLOAD_DIR` with the local adapter, the bucket objects with the S3 adapter). It is idempotent, and a row whose file is missing or unreadable is left as it is without stopping the boot. The old `article_id` column and the `article_images` table are kept and never written.
|
||||
|
||||
@@ -103,6 +103,10 @@ Relative paths are resolved against the process's working directory. In producti
|
||||
|
||||
For example, `WorkingDirectory=/var/lib/renewcms` with `DB_FILE=./data/renewcms.db` puts the database in `/var/lib/renewcms/data`. Browser-update `--data-dir` must name that directory, because the app reads helper status and update records beside the database. It is not necessarily `WorkingDirectory` or `ReadWritePaths`. Do not change an existing `DB_FILE` merely to match the helper: that could open a different, empty database. See [browser-update setup](deployment.md#browser-updates).
|
||||
|
||||
## Activity log retention
|
||||
|
||||
The activity log needs no environment variable. Its retention period (30, 90, 365 days or forever, 90 by default) is a setting the owner changes with `PATCH /v1/settings`, and the daily cleanup runs at 03:00 in the server's time zone (`TZ`, or the host's zone).
|
||||
|
||||
## Adding a variable
|
||||
|
||||
1. Read it in the code where it is needed (infrastructure or `api/`, never `internal/domain`).
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
This release adds an activity log that records who did what on your site, and lets RenewCMS run on MySQL, MariaDB or PostgreSQL and keep uploaded images in an S3-compatible bucket.
|
||||
|
||||
## New
|
||||
|
||||
**Activity log**
|
||||
|
||||
- The new Activity page lists every important action as a plain sentence, newest first, grouped by day: articles created, edited, published or deleted, images uploaded, renamed, merged or purged, accounts and invitations, and the system tasks (scheduled purge, update checks and downloads, restarts).
|
||||
- Filter by search text, person, category, outcome and date range, with Today, 7 days, 30 days and a custom range. Click a summary card to apply its filter. Open any row to see its details, including what changed.
|
||||
- Failed actions are recorded with a plain reason, and failed logins and similar events are flagged as security events.
|
||||
- Owners and admins see everyone's activity, a summary strip (total, active people, failed actions, security events) and can export the filtered list as a CSV file. Any other role would only see its own activity.
|
||||
- Article bodies are never recorded, only the change in size. Passwords, codes, file contents and storage paths are never recorded either.
|
||||
- The Home page has a new Recent activity card with the last five events.
|
||||
- Owners choose how long events are kept in the new Retention card in Settings: 30 days, 90 days (the default), 365 days or forever. Shortening the period asks for confirmation first. Older events are removed automatically once a day, and Settings shows the last cleanup and the next one.
|
||||
- The new screens are available in English and French.
|
||||
|
||||
**More ways to run RenewCMS**
|
||||
|
||||
- Use MySQL 8, MariaDB 11 or PostgreSQL 16 and 17 instead of the local SQLite file by setting `DB_DRIVER` to `mysql` or `postgres` and the `DB_*` connection variables. SQLite stays the default.
|
||||
- Keep uploaded images in an S3-compatible bucket (AWS S3, MinIO, Ceph, Cloudflare R2, Backblaze B2 and similar) by setting `STORAGE_DRIVER=s3`. Image URLs do not change and the bucket stays private.
|
||||
- The update backup taken before a download now works with every database: SQLite as before, and a logical dump for MySQL, MariaDB and PostgreSQL. The newest 3 backups are kept.
|
||||
- Docker Compose files for each setup are included: `docker-compose.mysql.yml`, `docker-compose.postgres.yml` and `docker-compose.s3.yml`.
|
||||
|
||||
## API
|
||||
|
||||
- `GET /v1/activity` returns the filtered, paged events as `{ items, total, page, size }`, newest first. It accepts `q`, `actor`, `category`, `outcome`, `security`, `range`, `from`, `to`, `page` and `size`, and any invalid value answers `400`. Owners and admins see every event. Any other role only sees its own, and asking for another actor answers `403`.
|
||||
- `GET /v1/activity/summary` returns the counts for the range, the previous period, the active people and a seven-bucket series. Owners and admins only.
|
||||
- `GET /v1/activity/export` returns the same filters as a CSV attachment (`when,actor,action,target,outcome,source,ip`). Owners and admins only. Cells that start with `=`, `+`, `-` or `@` get a leading quote.
|
||||
- The three routes accept a session only: an API key answers `403` with "This action needs a real session."
|
||||
- There is no `POST`, `PUT`, `PATCH` or `DELETE` under `/v1/activity`. Events can only be removed by the retention period.
|
||||
- `GET /v1/settings` now also returns `activity_retention_days`, `activity_last_cleanup_at`, `activity_last_cleanup_removed` and `activity_next_cleanup_at`.
|
||||
- `PATCH /v1/settings` accepts `activity_retention_days` with `0` (forever), `30`, `90` or `365`. Session and owner only, with `403` "Only the owner can do this." for anyone else. Any other value answers `400`.
|
||||
|
||||
## Under the hood
|
||||
|
||||
- Decouple persistence and image storage behind driver registries: `persistence/database` for the SQL drivers and `internal/infrastructure/storage` for the image adapters, with the domain `image.Storage` port. Repositories no longer touch files.
|
||||
- Add the audit domain, an append-only repository, a recorder that never fails or blocks the caller, and the use cases that record events from inside each action.
|
||||
- Add a scheduler for the activity cleanup, which runs once a day at or after 03:00 server time, alongside the media purge scheduler.
|
||||
- Add the activity, Home card and Retention card specifications and QA procedures to `features/`, the new screens to `docs/design/`, and Go and Vitest suites for each part.
|
||||
- Document the new variables in `docs/configuration.md`, and the new setups in `docs/deployment.md` and `docs/docker.md`.
|
||||
|
||||
## Upgrading
|
||||
|
||||
- Replace the binary, or pull the new image. The activity tables are created automatically at startup.
|
||||
- New environment variables are all optional and default to the previous behaviour: `DB_DRIVER` (`sqlite`), `STORAGE_DRIVER` (`local`), `DATA_DIR` (the directory of `DB_FILE`), and the `DB_*` and `S3_*` variables listed in `docs/configuration.md`. An existing install needs no change.
|
||||
- Activity starts recording after the upgrade, and nothing earlier is added. The first cleanup applies the default retention of 90 days, so owners who want a longer history should change it in Settings.
|
||||
- There is no automatic migration between databases or from the upload directory to a bucket. To move, follow the steps in `docs/configuration.md` and `docs/deployment.md`.
|
||||
- Backups taken before an update cover the database only. With S3, back the bucket up with your provider.
|
||||
@@ -0,0 +1,561 @@
|
||||
Feature: The back-office keeps an append-only activity log that owners can read and retention can prune
|
||||
|
||||
As the owner of a RenewCMS site
|
||||
I want every important action recorded with who, what, when and from where
|
||||
So that I can review activity, spot failed logins and keep the log from growing forever
|
||||
|
||||
Background:
|
||||
Given the spec of record is docs/design/screens/activity.md ("Roles", "API contract", "What is recorded") and docs/design/screens/settings.md ("Activity retention")
|
||||
And this slice is backend only: no SPA, no new env var, no change to the design
|
||||
And error responses are plain text from http.Error and success responses are JSON with snake_case fields
|
||||
And the layering rule holds: internal/domain/audit imports only the stdlib and other domain packages, use cases see only domain interfaces, handlers see only use cases, persistence owns GORM, and no comment is added anywhere
|
||||
And validation of query and body goes through validate tags and validator.Validate.Struct where a struct exists
|
||||
And the error text for a malformed query or body is "The request cannot be processed due to a mismatch in the format of the body."
|
||||
|
||||
Rule: The domain event is a complete snapshot and the repository is append-only
|
||||
|
||||
Scenario: An event carries everything the log needs
|
||||
Given an event is built for the action "article.publish" in category "articles"
|
||||
Then it holds an actor snapshot (type, id, name), the action code and its params, the category, a target snapshot (type, id, name), an outcome, a failure_reason, a security flag, a source, an ip, a user_agent, changes and a created_at
|
||||
|
||||
Scenario Outline: The vocabulary is closed
|
||||
Then the allowed <field> values are exactly <values>
|
||||
|
||||
Examples:
|
||||
| field | values |
|
||||
| actor.type | user, api_key, system, anonymous |
|
||||
| category | articles, media, users, api_keys, auth, system |
|
||||
| outcome | success, failed |
|
||||
| source | web, api_key, system |
|
||||
| change.kind | text, body |
|
||||
|
||||
Scenario: The repository exposes no way to edit or delete one event
|
||||
Then the audit Repository interface has exactly the methods Append, List, Summary and DeleteOlderThan
|
||||
And the persistence implementation exposes no other exported method than those and its constructor
|
||||
And the HTTP surface has no POST, PUT, PATCH or DELETE under /v1/activity
|
||||
|
||||
Scenario: The sentinel errors are matchable
|
||||
Then the audit package declares Err sentinels for an invalid filter and an invalid retention period
|
||||
And each is asserted with errors.Is
|
||||
|
||||
Rule: The recorder never fails or blocks the caller
|
||||
|
||||
Scenario: A failing repository does not change the caller's result
|
||||
Given the audit repository fails on Append with the error "disk full"
|
||||
When a user logs in with valid credentials through POST /v1/auth/login
|
||||
Then the response is 200 with a jwt cookie and the usual JSON message
|
||||
And the process log contains a line naming the failed audit write and "disk full"
|
||||
|
||||
Scenario: A panicking repository does not crash the request
|
||||
Given the audit repository panics on Append
|
||||
When a user logs out through POST /v1/auth/logout
|
||||
Then the response is 200 and the process continues serving
|
||||
|
||||
Scenario: The recorder fills the event from the audit context
|
||||
Given a context holding actor user 3 "marta", source "web", ip "203.0.113.12" and user agent "Mozilla/5.0 test"
|
||||
When the recorder records an event that has no actor, source, ip or user agent
|
||||
Then the stored event has those values
|
||||
And created_at is the injected clock's time in UTC
|
||||
|
||||
Scenario: Secrets never reach the log or the stored event
|
||||
Given actions that handle a password, a raw API key, a reset code and a jwt
|
||||
When they are recorded
|
||||
Then no stored field, no params and no process log line contains any of those values or their hashes
|
||||
|
||||
Rule: The audit context is set by middleware from the credentials and the trusted-proxy IP
|
||||
|
||||
Scenario: A session sets a user actor with source web
|
||||
Given a request with a valid jwt cookie for user 3 "marta"
|
||||
When it passes the audit context middleware
|
||||
Then the context holds actor type "user", id 3, name "marta" and source "web"
|
||||
|
||||
Scenario: An API key sets an api_key actor with source api_key
|
||||
Given a request with "Authorization: Bearer <valid key>" for the key 7 named "Deploy bot"
|
||||
When it passes the audit context middleware
|
||||
Then the context holds actor type "api_key", id 7, name "Deploy bot" and source "api_key"
|
||||
|
||||
Scenario: No credentials sets an anonymous actor
|
||||
Given a request without a cookie or key
|
||||
Then the context holds actor type "anonymous" and source "web"
|
||||
|
||||
Scenario Outline: The ip comes from the trusted-proxy real IP only
|
||||
Given the trusted proxies are "10.0.0.5"
|
||||
And the request peer is "<peer>" and X-Real-IP is "<header>"
|
||||
Then the context ip is "<ip>"
|
||||
|
||||
Examples:
|
||||
| peer | header | ip |
|
||||
| 10.0.0.5:443 | 203.0.113.12 | 203.0.113.12 |
|
||||
| 198.51.100.9:443 | 203.0.113.12 | 198.51.100.9 |
|
||||
| 198.51.100.9:443 | | 198.51.100.9 |
|
||||
|
||||
Scenario: The user agent is stored as sent and bounded
|
||||
Given the User-Agent header is 400 characters long
|
||||
Then the context user agent is its first 255 characters
|
||||
|
||||
Rule: Persistence stores events portably and indexed
|
||||
|
||||
Background:
|
||||
Given the persistence tests run against a real in-memory SQLite database migrated with the model list of migrate.go
|
||||
And the SQL stays portable across SQLite, MySQL/MariaDB and PostgreSQL
|
||||
|
||||
Scenario: The model is migrated with its indexes
|
||||
Then the audit events table exists
|
||||
And it has an index on created_at, an index on (actor_type, actor_id, created_at) and an index on (category, created_at)
|
||||
|
||||
Scenario: An appended event round-trips
|
||||
When an event with params {"merged": 3}, changes and a null failure_reason is appended
|
||||
Then listing returns it with every field equal, params and changes included
|
||||
|
||||
Scenario: List sorts by created_at descending then id descending
|
||||
Given three events with the same created_at and one older
|
||||
Then List returns the three by id descending, then the older one
|
||||
|
||||
Scenario Outline: Filters narrow the list and the total
|
||||
Given events across actors, categories, outcomes and days
|
||||
When List runs with <filter>
|
||||
Then items and total contain exactly <expected>
|
||||
|
||||
Examples:
|
||||
| filter | expected |
|
||||
| actor user:3 | events of user 3 only |
|
||||
| actor key:7 | events of api key 7 only |
|
||||
| actor system | events with actor type system only |
|
||||
| category auth | auth events only |
|
||||
| outcome failed | failed events only |
|
||||
| outcome success | succeeded events only |
|
||||
| security true | events whose security flag is true |
|
||||
| q "SPRING" | events whose actor or target name contains "spring", case-insensitive |
|
||||
| q "50%_" | only names containing the literal text 50%_ |
|
||||
| from 2026-10-01 to 2026-10-03 | events from 2026-10-01T00:00:00Z to the end of 2026-10-03 |
|
||||
|
||||
Scenario: Paging slices the sorted list and total is the unpaged count
|
||||
Given 60 events
|
||||
When List runs with page 2 and size 25
|
||||
Then 25 items are returned, the 26th to 50th of the sorted list, and total is 60
|
||||
|
||||
Scenario: A page past the end is empty
|
||||
When List runs with page 9 and size 25 over 60 events
|
||||
Then items is empty and total is 60
|
||||
|
||||
Scenario: The summary counts the range and the previous period
|
||||
Given events in the last 7 days and in the 7 days before
|
||||
When Summary runs for range 7d
|
||||
Then total, previous_total, failed and security are the counts of those periods
|
||||
And active_people.users counts distinct user actors and active_people.api_keys counts distinct key actors, with anonymous and system excluded
|
||||
And series holds seven daily counts for total, active, failed and security, oldest first
|
||||
|
||||
Scenario: DeleteOlderThan removes only events before the cutoff
|
||||
Given events at 100, 40, 31, 29 and 1 days ago
|
||||
When DeleteOlderThan runs with the cutoff 30 days ago
|
||||
Then it returns 3 and only the 29-day and 1-day events remain
|
||||
|
||||
Rule: Reading the log is session only and scoped by role
|
||||
|
||||
Background:
|
||||
Given the handler is mounted at /v1/activity behind jwtauth.Verifier, jwtauth.Authenticator, the current-token check and the verified-user check
|
||||
And the routes sit behind RequireSession, so no API key reaches them
|
||||
|
||||
Scenario Outline: The credentials gate answers before any data
|
||||
When GET <path> is sent <credentials>
|
||||
Then the response is <status> with body "<body>"
|
||||
And the audit repository was not read
|
||||
|
||||
Examples:
|
||||
| path | credentials | status | body |
|
||||
| /v1/activity | without a jwt cookie | 401 | You must be logged in to access this resource. |
|
||||
| /v1/activity/summary | without a jwt cookie | 401 | You must be logged in to access this resource. |
|
||||
| /v1/activity/export | without a jwt cookie | 401 | You must be logged in to access this resource. |
|
||||
| /v1/activity | with a valid API key | 403 | This action needs a real session. |
|
||||
| /v1/activity/summary | with a valid API key | 403 | This action needs a real session. |
|
||||
| /v1/activity/export | with a valid API key | 403 | This action needs a real session. |
|
||||
| /v1/activity | with an unverified user's cookie | 403 | You must verify your account to access this resource. |
|
||||
|
||||
Scenario Outline: Owner and admin see every event
|
||||
Given events by users 1, 2 and 3, an api key and the system
|
||||
When GET /v1/activity is sent with the cookie of the <role>
|
||||
Then the response is 200 and total counts the events of every actor
|
||||
|
||||
Examples:
|
||||
| role |
|
||||
| owner |
|
||||
| admin |
|
||||
|
||||
Scenario: Another role is scoped to its own events
|
||||
Given a verified user 3 whose role is neither owner nor admin
|
||||
And events by users 1, 2 and 3
|
||||
When GET /v1/activity is sent with user 3's cookie
|
||||
Then every item has actor type "user" and id 3
|
||||
And total counts only user 3's events
|
||||
|
||||
Scenario Outline: A scoped caller cannot ask for another actor
|
||||
Given a verified user 3 whose role is neither owner nor admin
|
||||
When GET /v1/activity?actor=<actor> is sent with user 3's cookie
|
||||
Then the response is <status>
|
||||
|
||||
Examples:
|
||||
| actor | status |
|
||||
| user:3 | 200 |
|
||||
| user:2 | 403 |
|
||||
| key:7 | 403 |
|
||||
| system | 403 |
|
||||
|
||||
Scenario Outline: A scoped caller cannot read the summary or the export
|
||||
Given a verified user 3 whose role is neither owner nor admin
|
||||
When GET <path> is sent with user 3's cookie
|
||||
Then the response is 403 with body "Only owners and admins can do this."
|
||||
|
||||
Examples:
|
||||
| path |
|
||||
| /v1/activity/summary |
|
||||
| /v1/activity/export |
|
||||
|
||||
Rule: GET /v1/activity lists filtered, paged events
|
||||
|
||||
Scenario: The default request
|
||||
Given 30 events over the last 3 days
|
||||
When the owner sends GET /v1/activity
|
||||
Then the response is 200 with {"items": [...], "total": 30, "page": 1, "size": 25}
|
||||
And items has 25 entries, newest first
|
||||
|
||||
Scenario: An item has the documented shape
|
||||
Given user 3 "Marta Alves" published the article 8 "Spring release" at 2026-10-06T10:42:18Z from 203.0.113.12 with "Chrome 129 on Windows"
|
||||
When the owner sends GET /v1/activity
|
||||
Then the first item is
|
||||
"""
|
||||
{"id": 4821, "created_at": "2026-10-06T10:42:18Z", "action": "article.publish", "category": "articles", "actor": {"type": "user", "id": 3, "name": "Marta Alves"}, "target": {"type": "article", "id": "8", "name": "Spring release", "exists": true}, "outcome": "success", "failure_reason": null, "security": false, "source": "web", "ip": "203.0.113.12", "user_agent": "Chrome 129 on Windows", "params": {}, "changes": [{"field": "online", "kind": "text", "before": "false", "after": "true"}]}
|
||||
"""
|
||||
|
||||
Scenario: A system event has no ip or user agent
|
||||
Given a system event "system.activity_cleanup"
|
||||
When the owner sends GET /v1/activity
|
||||
Then its item has actor {"type": "system", "id": null, "name": "System"}, source "system", ip null and user_agent null
|
||||
|
||||
Scenario: A renamed or deleted user still reads correctly
|
||||
Given an event recorded when user 3 was named "Marta Alves"
|
||||
And user 3 has since been renamed "M. Alves" and then deleted
|
||||
When the owner sends GET /v1/activity
|
||||
Then the item's actor.name is still "Marta Alves"
|
||||
|
||||
Scenario Outline: target.exists is resolved when the list is read
|
||||
Given an event whose target is <type> "<id>" named "<name>"
|
||||
And <state>
|
||||
When the owner sends GET /v1/activity
|
||||
Then the item's target.name is "<name>" and target.exists is <exists>
|
||||
|
||||
Examples:
|
||||
| type | id | name | state | exists |
|
||||
| article | 8 | Spring release | the article still exists | true |
|
||||
| article | 8 | Spring release | the article was deleted | false |
|
||||
| user | 3 | Marta Alves | the user was deleted | false |
|
||||
|
||||
Scenario: A body change carries a delta and never text
|
||||
Given an event with a body change of +312 characters
|
||||
Then its change is {"field": "body", "kind": "body", "delta": 312} with no before and no after
|
||||
|
||||
Scenario Outline: The filters are applied through the query
|
||||
When the owner sends GET /v1/activity?<query>
|
||||
Then the response is 200 and items match <expected>
|
||||
|
||||
Examples:
|
||||
| query | expected |
|
||||
| q=spring | the actor or target name contains spring |
|
||||
| actor=user:3 | events of user 3 |
|
||||
| actor=key:7 | events of api key 7 |
|
||||
| actor=system | system events |
|
||||
| category=auth | auth events |
|
||||
| outcome=failed | failed events |
|
||||
| outcome=success | succeeded events |
|
||||
| outcome=all | both outcomes |
|
||||
| security=true | events with the security flag |
|
||||
| range=today | events since 00:00 UTC today |
|
||||
| range=7d | events of the last 7 days |
|
||||
| range=30d | events of the last 30 days |
|
||||
| range=custom&from=2026-09-01&to=2026-09-30 | events from 1 to 30 September 2026 UTC |
|
||||
| page=2&size=50 | the second page of 50 |
|
||||
| size=5 | the first page of 5 |
|
||||
|
||||
Scenario: Omitting range means 7 days
|
||||
Given events 2 days old and 10 days old
|
||||
When the owner sends GET /v1/activity
|
||||
Then only the 2-day-old event is listed
|
||||
|
||||
Scenario Outline: Invalid values answer 400
|
||||
When the owner sends GET /v1/activity?<query>
|
||||
Then the response is 400 with body "The request cannot be processed due to a mismatch in the format of the body."
|
||||
And the audit repository was not read
|
||||
|
||||
Examples:
|
||||
| query |
|
||||
| actor=user:abc |
|
||||
| actor=user:-1 |
|
||||
| actor=group:3 |
|
||||
| category=billing |
|
||||
| outcome=maybe |
|
||||
| security=false |
|
||||
| range=year |
|
||||
| range=custom |
|
||||
| range=custom&from=2026-09-30&to=2026-09-01 |
|
||||
| range=custom&from=yesterday&to=today |
|
||||
| page=0 |
|
||||
| page=abc |
|
||||
| size=10 |
|
||||
| size=200 |
|
||||
|
||||
Rule: GET /v1/activity/summary answers the strip
|
||||
|
||||
Scenario: The summary of the last seven days
|
||||
Given 12 events in the last 7 days, 3 failed, 2 with the security flag, by 2 users and 1 api key
|
||||
And 10 events in the 7 days before
|
||||
When the owner sends GET /v1/activity/summary?range=7d
|
||||
Then the response is 200 and the body is
|
||||
"""
|
||||
{"total": 12, "previous_total": 10, "active_people": {"users": 2, "api_keys": 1}, "failed": 3, "security": 2, "series": {"total": [...7 numbers], "active": [...7], "failed": [...7], "security": [...7]}}
|
||||
"""
|
||||
And each series array has 7 entries, oldest first, and the total series sums to 12
|
||||
|
||||
Scenario: An empty log answers zeros
|
||||
Given no events
|
||||
When the owner sends GET /v1/activity/summary
|
||||
Then every number is 0 and every series array is seven zeros
|
||||
|
||||
Scenario: The summary uses the same filters as the range
|
||||
When the owner sends GET /v1/activity/summary?range=custom&from=2026-09-01&to=2026-09-07
|
||||
Then the counts cover exactly that range and previous_total covers the 7 days immediately before 2026-09-01
|
||||
|
||||
Scenario: An invalid range answers 400
|
||||
When the owner sends GET /v1/activity/summary?range=year
|
||||
Then the response is 400 with the body-mismatch message
|
||||
|
||||
Rule: GET /v1/activity/export streams a safe CSV
|
||||
|
||||
Scenario: The response is a CSV attachment
|
||||
Given 3 events
|
||||
When the owner sends GET /v1/activity/export
|
||||
Then the response is 200 with Content-Type "text/csv; charset=utf-8" and Content-Disposition starting with "attachment"
|
||||
And the first row is "when,actor,action,target,outcome,source,ip"
|
||||
And there are 3 data rows, newest first
|
||||
|
||||
Scenario: A row holds the documented columns only
|
||||
Given user 3 "Marta Alves" published "Spring release" at 2026-10-06T10:42:18Z from 203.0.113.12 with changes and a user agent
|
||||
Then the row is "2026-10-06T10:42:18Z,Marta Alves,article.publish,Spring release,success,web,203.0.113.12"
|
||||
And the file contains no changes and no user agent
|
||||
|
||||
Scenario Outline: Cells that a spreadsheet would evaluate are neutralised
|
||||
Given an event whose <column> is "<value>"
|
||||
Then the cell is "<cell>"
|
||||
|
||||
Examples:
|
||||
| column | value | cell |
|
||||
| actor | =cmd | '=cmd |
|
||||
| target | +1+1 | '+1+1 |
|
||||
| target | -2 | '-2 |
|
||||
| actor | @SUM(A1) | '@SUM(A1) |
|
||||
| target | Spring release | Spring release |
|
||||
| target | a=b | a=b |
|
||||
|
||||
Scenario: Commas, quotes and newlines are quoted
|
||||
Given a target whose name contains a comma, double quotes and a newline
|
||||
Then the cell is quoted with doubled inner quotes and the file still has one row for the event
|
||||
|
||||
Scenario: The export uses the list filters without paging
|
||||
Given 60 events of which 8 failed
|
||||
When the owner sends GET /v1/activity/export?outcome=failed&page=2&size=25
|
||||
Then the file has the 8 failed rows and page and size are ignored
|
||||
|
||||
Scenario: A system event has an empty ip cell
|
||||
Given a system event
|
||||
Then its ip cell is empty
|
||||
|
||||
Scenario: An invalid filter answers 400 before any byte is streamed
|
||||
When the owner sends GET /v1/activity/export?outcome=maybe
|
||||
Then the response is 400 with the body-mismatch message and no CSV header
|
||||
|
||||
Scenario: A large export is read in batches
|
||||
Given 1200 events
|
||||
When the owner exports them
|
||||
Then the file has 1200 rows and the repository was read through List in pages, not all at once
|
||||
|
||||
Rule: The retention period is a setting only the owner can change
|
||||
|
||||
Scenario: The default is 90 days
|
||||
Given no retention row exists
|
||||
When a verified user sends GET /v1/settings
|
||||
Then the body has "activity_retention_days": 90, "activity_last_cleanup_at": null and "activity_last_cleanup_removed": 0
|
||||
And the existing fields of the response are unchanged
|
||||
|
||||
Scenario: The last cleanup is reported
|
||||
Given a cleanup ran at 2026-10-06T03:00:00Z and removed 142 events
|
||||
When a verified user sends GET /v1/settings
|
||||
Then "activity_last_cleanup_at" is "2026-10-06T03:00:00Z" and "activity_last_cleanup_removed" is 142
|
||||
|
||||
Scenario Outline: The owner sets a valid period
|
||||
When the owner sends PATCH /v1/settings with body {"activity_retention_days": <days>}
|
||||
Then the response is 200 and the body has "activity_retention_days": <days>
|
||||
And a following GET /v1/settings returns <days>
|
||||
|
||||
Examples:
|
||||
| days |
|
||||
| 30 |
|
||||
| 90 |
|
||||
| 365 |
|
||||
| 0 |
|
||||
|
||||
Scenario Outline: Any other value answers 400 and changes nothing
|
||||
Given the stored retention is 90
|
||||
When the owner sends PATCH /v1/settings with body <body>
|
||||
Then the response is 400 with body "The request cannot be processed due to a mismatch in the format of the body."
|
||||
And the stored retention is still 90
|
||||
|
||||
Examples:
|
||||
| body |
|
||||
| {"activity_retention_days": 7} |
|
||||
| {"activity_retention_days": -1} |
|
||||
| {"activity_retention_days": 366} |
|
||||
| {"activity_retention_days": 30.5} |
|
||||
| {"activity_retention_days": "30"} |
|
||||
| {"activity_retention_days": null} |
|
||||
| {} |
|
||||
| not json |
|
||||
|
||||
Scenario: An admin cannot change it
|
||||
When an admin sends PATCH /v1/settings with body {"activity_retention_days": 30}
|
||||
Then the response is 403 with body "Only the owner can do this."
|
||||
And the stored retention is unchanged
|
||||
|
||||
Scenario Outline: The gate answers before the body is read
|
||||
When PATCH /v1/settings is sent <credentials> with body {"activity_retention_days": 30}
|
||||
Then the response is <status> with body "<body>"
|
||||
|
||||
Examples:
|
||||
| credentials | status | body |
|
||||
| without a jwt cookie | 401 | You must be logged in to access this resource. |
|
||||
| with an owner's API key | 403 | This action needs a real session. |
|
||||
| with an unverified owner | 403 | You must verify your account to access this resource. |
|
||||
|
||||
Scenario: A change is recorded as a system event by the owner
|
||||
Given the stored retention is 90
|
||||
When the owner sends PATCH /v1/settings with body {"activity_retention_days": 30}
|
||||
Then one event exists with action "system.activity_retention_changed", category "system", actor the owner, source "web", outcome "success", security false and params {"from": 90, "to": 30}
|
||||
|
||||
Scenario: Setting the same value records nothing
|
||||
Given the stored retention is 90
|
||||
When the owner sends PATCH /v1/settings with body {"activity_retention_days": 90}
|
||||
Then the response is 200 and no event is recorded
|
||||
|
||||
Rule: A daily cleanup removes events past the retention period
|
||||
|
||||
Background:
|
||||
Given the cleanup is a use case with a Tick(now) like PurgeScheduler, driven by the scheduler runner with hand-fed channels and an injected clock
|
||||
And the server time zone is the injected clock's location
|
||||
|
||||
Scenario Outline: The cleanup is due once a day at or after 03:00
|
||||
Given the retention is 90 and the last cleanup was at <last>
|
||||
When Tick runs at <now>
|
||||
Then ran is <ran>
|
||||
|
||||
Examples:
|
||||
| last | now | ran |
|
||||
| never | 2026-10-06T02:59:00 | false |
|
||||
| never | 2026-10-06T03:00:00 | true |
|
||||
| never | 2026-10-06T14:00:00 | true |
|
||||
| 2026-10-05T03:00:00 | 2026-10-06T02:59:00 | false |
|
||||
| 2026-10-05T03:00:00 | 2026-10-06T03:00:00 | true |
|
||||
| 2026-10-06T03:00:00 | 2026-10-06T04:00:00 | false |
|
||||
| 2026-10-06T03:00:00 | 2026-10-07T03:00:00 | true |
|
||||
|
||||
Scenario: Forever never runs
|
||||
Given the retention is 0
|
||||
When Tick runs at 2026-10-06T03:00:00
|
||||
Then ran is false and DeleteOlderThan is not called
|
||||
|
||||
Scenario: The cutoff is now minus the retention days
|
||||
Given the retention is 30 and events at 40, 31, 29 and 1 days ago
|
||||
When the cleanup runs at 2026-10-06T03:00:00
|
||||
Then the events 31 and 40 days old are removed and the others remain
|
||||
And the last cleanup time is the clock's time and the removed count is 2
|
||||
|
||||
Scenario: The last 24 hours are never removed
|
||||
Given the cleanup is asked for a cutoff newer than 24 hours ago
|
||||
Then the effective cutoff is 24 hours before now
|
||||
|
||||
Scenario: A cleanup that removes nothing still records the run
|
||||
Given the retention is 90 and no event is older than 90 days
|
||||
When the cleanup runs
|
||||
Then the last cleanup time is the clock's time, the removed count is 0 and no system.activity_cleanup event is recorded
|
||||
|
||||
Scenario: A cleanup that removes events records a system event after deleting
|
||||
Given 142 events older than the retention
|
||||
When the cleanup runs
|
||||
Then one event exists with action "system.activity_cleanup", category "system", actor type "system", source "system", ip null, user_agent null, outcome "success" and params {"removed": 142}
|
||||
And that event is not among the removed ones
|
||||
|
||||
Scenario: A failing delete is retried at the next tick
|
||||
Given DeleteOlderThan fails
|
||||
When Tick runs
|
||||
Then the error is returned and logged, the last cleanup fields are unchanged and the next tick runs the cleanup again
|
||||
|
||||
Scenario: A shortened period applies at the next cleanup
|
||||
Given the retention was 90 and the owner sets 30
|
||||
Then no event is removed by the change itself
|
||||
And the next cleanup removes events older than 30 days
|
||||
|
||||
Scenario: The scheduler stops with the process
|
||||
When the context is cancelled
|
||||
Then the runner returns and no goroutine outlives it
|
||||
|
||||
Rule: The first producers record the right events
|
||||
|
||||
Scenario Outline: Authentication events
|
||||
When <trigger>
|
||||
Then one event exists with action "<action>", category "auth", <actor>, source "web", outcome "<outcome>", security <security>, failure_reason <reason> and the request ip and user agent
|
||||
|
||||
Examples:
|
||||
| trigger | action | actor | outcome | security | reason |
|
||||
| POST /v1/auth/login with the right username and password | auth.login | actor user with the account's name | success | false | null |
|
||||
| POST /v1/auth/login with the right username and a wrong password | auth.login_failed | actor anonymous named by the attempted username | failed | true | "Wrong username or password." |
|
||||
| POST /v1/auth/login with an unknown username | auth.login_failed | actor anonymous named by the attempted username | failed | true | "Wrong username or password." |
|
||||
| POST /v1/auth/logout with a valid jwt cookie | auth.logout | actor user | success | false | null |
|
||||
| POST /v1/auth/password-reset for an existing account | auth.password_reset_requested | actor user | success | true | null |
|
||||
| POST /v1/auth/password-reset/confirm with a valid code | auth.password_reset_completed | actor user | success | true | null |
|
||||
|
||||
Scenario: A failed login reveals no more than the response does
|
||||
Given a wrong password for an existing user and an unknown username
|
||||
Then both events have the same failure_reason, actor type anonymous and no target
|
||||
And neither event holds the password
|
||||
|
||||
Scenario Outline: Nothing is recorded when nothing happened
|
||||
When <trigger>
|
||||
Then no event is recorded and the response is unchanged
|
||||
|
||||
Examples:
|
||||
| trigger |
|
||||
| POST /v1/auth/logout without a jwt cookie |
|
||||
| POST /v1/auth/password-reset for an unknown email |
|
||||
| POST /v1/auth/password-reset/confirm with an invalid code |
|
||||
| POST /v1/auth/login with a body that fails validation |
|
||||
| POST /v1/auth/login answered 429 by the rate limiter |
|
||||
|
||||
Scenario: A reset event never holds the code
|
||||
When a password reset is requested and completed
|
||||
Then neither event nor the process log contains the raw code, its hash or the new password
|
||||
|
||||
Scenario: Creating an API key is recorded
|
||||
When the owner sends POST /v1/api-key with a name "Deploy bot"
|
||||
Then one event exists with action "api_key.create", category "api_keys", actor the owner, source "web", target {"type": "api_key", "id": "<new id>", "name": "Deploy bot"}, outcome "success" and security false
|
||||
And no stored field and no response of the activity API contains the raw key or its hash
|
||||
|
||||
Scenario: Revoking an API key is recorded
|
||||
Given the API key 7 named "Deploy bot"
|
||||
When the owner sends DELETE /v1/api-key/7
|
||||
Then one event exists with action "api_key.revoke", category "api_keys", actor the owner, target {"type": "api_key", "id": "7", "name": "Deploy bot"} and outcome "success"
|
||||
|
||||
Scenario: A revoke of an unknown key records nothing
|
||||
When the owner sends DELETE /v1/api-key/99
|
||||
Then the response is 404 and no event is recorded
|
||||
|
||||
Scenario: The recorded events are readable through the API
|
||||
Given a failed login, an API key creation and a retention change were recorded
|
||||
When the owner sends GET /v1/activity
|
||||
Then the three events are listed newest first with their documented items
|
||||
And GET /v1/activity?security=true lists only the failed login
|
||||
@@ -0,0 +1,72 @@
|
||||
# QA procedure: activity-log-backend
|
||||
|
||||
Go only, no SPA. Package `test` (black-box), new files `test/activity_log_domain_test.go`, `test/activity_log_persistence_test.go`, `test/activity_log_http_test.go` and `test/activity_cleanup_test.go`. Fake and helper type names must be unique across the package. No live server, no real SMTP, no real SQLite file, no real sleeping, no `time.Ticker`. No env var is added. Never put a secret value in a test name or log assertion helper beyond the fixed test strings.
|
||||
|
||||
## Setup shared by every case
|
||||
1. `validator.InitValidator()` once. `jwtauth.New("HS256", []byte("test-secret"), nil)` standing in for `JWT_SECRET`.
|
||||
2. Fakes: `fakeAuditClock` (mutable, `Now()` and `Set(t)`, UTC), `mockAuditRepo` (in-memory slice, `Append`, `List`, `Summary`, `DeleteOlderThan`, failure and panic switches, call counters per method), existing `mockUserRepo` extended with users: owner 1, admin 2, a verified user 3 with role `"editor"` (domain has only owner and admin, so the role is a plain string in the fake), an unverified user 4. Fake API key repo with key 7 "Deploy bot" and a raw key built with `apikey.RawKeyPrefix`.
|
||||
3. Router: a fresh `chi.NewRouter()` mirroring `api/router.go`. Mount `/activity` (RequireSession, `jwtauth.Verifier`, `jwtauth.Authenticator`, `RequireCurrentToken`, `RequireVerifiedUser`, then the audit context middleware), `/settings` with the new PATCH, `/api-key` and `/auth` over the real use cases and the fakes. `httptest.NewRecorder` per request. Cookies are real `jwt` cookies signed with the test token carrying `user_id` and `token_version`.
|
||||
4. Capture the standard log with `log.SetOutput(&buf)` and restore with `t.Cleanup`. No parallel tests except where `-race` is stated.
|
||||
5. Seed helper `seedEvents(repo, n, spec)` building events with explicit `created_at` from the clock.
|
||||
|
||||
## A. Domain (no HTTP)
|
||||
6. Vocabulary table: for each of actor type, category, outcome, source and change kind, the exported constants equal the allowed set from the feature; an invalid value is rejected by the domain constructor or validator with the matching `Err` sentinel (`errors.Is`).
|
||||
7. Append-only guard: `reflect.TypeOf((*audit.Repository)(nil)).Elem()` has exactly `Append`, `List`, `Summary`, `DeleteOlderThan`. The persistence implementation's exported method set (via `reflect`) equals the same four. Router walk (`chi.Walk`) finds only GET under `/v1/activity`.
|
||||
8. Recorder: with `mockAuditRepo` failing (`errors.New("disk full")`), `Record` returns without error, and `buf` names the failed write and `disk full`. A panicking repo is recovered. A context holding actor, source, ip and user agent fills an event that lacks them; an event that already has an actor keeps it. `created_at` equals `fakeAuditClock.Now()` in UTC.
|
||||
|
||||
## B. Persistence (real in-memory SQLite, same model list as `api/dependecyInjection.go` and `migrate.go`)
|
||||
9. Migrate, then query `sqlite_master` and assert the table and three indexes: `created_at`; `(actor_type, actor_id, created_at)`; `(category, created_at)`. Assert the audit model is in the `migrate.go` list (migrate the full list, not just the audit model).
|
||||
10. Round-trip: append an event with params, changes (text and body kinds) and a null failure_reason; `List` returns equal fields. A system event round-trips with null ip and user agent.
|
||||
11. Order: three events with identical `created_at` come back by id descending, older last.
|
||||
12. Filter table from the feature (actor user, key, system, category, outcome, security, `q` case-insensitive, `q` containing `%` and `_` matched literally, date range inclusive of the whole `to` day UTC). Assert items and total for each.
|
||||
13. Paging: 60 events, page 2 size 25 gives items 26-50 and total 60; page 9 gives empty items and total 60.
|
||||
14. Summary: events in the last 7 days and the 7 days before; assert total, previous_total, failed, security, distinct user and key counts (anonymous and system excluded) and the four seven-element series, oldest first.
|
||||
15. `DeleteOlderThan`: events at 100, 40, 31, 29, 1 days; cutoff 30 days; returns 3, remaining ids as expected.
|
||||
16. Portability: assert no raw dialect-specific SQL (`ILIKE`, `strftime`, `date_trunc`, backticks) appears in the repository source. Cross-database run is manual (see below).
|
||||
|
||||
## C. Audit context middleware (probe handler echoing the context as JSON)
|
||||
17. Table: valid cookie for user 3 gives `{type user, id 3, name, source web}`; valid `Authorization: Bearer <key>` gives `{api_key, 7, "Deploy bot", source api_key}`; none gives anonymous and web.
|
||||
18. IP table with `TrustedProxyRealIP([]string{"10.0.0.5"})` in front: trusted peer plus `X-Real-IP` gives the header; untrusted peer ignores it; no header gives the peer. User agent of 400 characters is cut to 255.
|
||||
|
||||
## D. Read endpoints (HTTP)
|
||||
19. Gate table: no cookie 401 `You must be logged in to access this resource.`; API key 403 `This action needs a real session.`; unverified cookie 403 `You must verify your account to access this resource.`, each for list, summary and export, with `mockAuditRepo` List/Summary counters at 0.
|
||||
20. Roles: owner and admin see all actors; user 3 sees only its own with `total` of its own count; `actor=user:3` is 200, `actor=user:2`, `actor=key:7`, `actor=system` are 403 (body `Only owners and admins can do this.`); summary and export for user 3 are 403 with the same body.
|
||||
21. Shape: decode the first item into a map and compare with the JSON in the feature, including `"failure_reason": null`, `"params": {}`, integer `actor.id`, string `target.id`, `exists`. System event has `actor.id` null, `ip` null, `user_agent` null. Renamed and deleted user keeps the snapshot name. `exists` table with fake article repo (present, deleted) and user repo (deleted). A `body` change has `delta` and no `before` or `after`.
|
||||
22. Query table: every row of the filter outline, asserted against the seeded set; default range 7d (2-day event in, 10-day event out); default `page` 1, `size` 25.
|
||||
23. 400 table: every invalid query row gives exactly `The request cannot be processed due to a mismatch in the format of the body.` with the repo read counter at 0.
|
||||
24. Summary: the 7d example (12 / 10 / 2 users + 1 key / 3 / 2 and seven-length series that sum to the total); empty log all zeros; custom range previous period is the 7 days immediately before; invalid range 400.
|
||||
25. Export: status 200, `Content-Type: text/csv; charset=utf-8`, `Content-Disposition` begins `attachment`. Parse with `encoding/csv`: header `when,actor,action,target,outcome,source,ip`, row values as in the feature, no changes and no user agent column, system ip cell empty. Formula table (`=cmd`, `+1+1`, `-2`, `@SUM(A1)` get a leading `'`; `Spring release` and `a=b` untouched). A name with comma, quotes and a newline is one parseable record. `outcome=failed&page=2&size=25` returns only failed rows. 1200 events yield 1200 rows and `mockAuditRepo` saw more than one `List` call with a bounded size. Invalid filter gives 400 with no `Content-Type: text/csv`.
|
||||
|
||||
## E. Retention settings (HTTP)
|
||||
26. `GET /v1/settings` with no stored row: `activity_retention_days` 90, `activity_last_cleanup_at` null, `activity_last_cleanup_removed` 0, existing fields (`version`) unchanged. With a stored cleanup: values echoed (RFC3339 UTC).
|
||||
27. `PATCH` accepts 30, 90, 365, 0 (200, body echoes, a following GET agrees). 400 table: 7, -1, 366, 30.5, `"30"`, null, `{}`, non-JSON, each with the body-mismatch message and the stored value unchanged.
|
||||
28. Gate: admin 403 `Only the owner can do this.`; no cookie 401; owner API key 403 `This action needs a real session.`; unverified owner 403 verification text.
|
||||
29. Event: PATCH 90 to 30 records one `system.activity_retention_changed` event with actor owner, source web and params `{"from":90,"to":30}`; PATCH to the same value records none.
|
||||
|
||||
## F. Cleanup scheduler (no HTTP, hand-fed channels, `fakeAuditClock`)
|
||||
30. Tick table from the feature (never/last cleanup versus now, boundary at exactly 03:00, same-day second tick not due, next-day tick due). Assert `ran` and the `DeleteOlderThan` call count. Retention 0 never calls it.
|
||||
31. Cutoff: retention 30, events at 40, 31, 29, 1 days; run at 03:00; 31 and 40 removed; `last_cleanup_at` equals the clock; removed count 2. A request for a cutoff inside 24 hours is clamped to now minus 24 hours.
|
||||
32. Zero removed: fields updated, no `system.activity_cleanup` event. 142 removed: one event with action `system.activity_cleanup`, actor type system, source system, ip and user agent null, params `{"removed":142}`, and it is not deleted by the run that created it.
|
||||
33. `DeleteOlderThan` failure: Tick returns the error, last-cleanup fields unchanged, the log buffer holds the error, the next Tick runs again after healing.
|
||||
34. Runner: one tick runs one Tick; cancelling the context returns `Run` within a timeout; a done channel proves no goroutine outlives it (`-race`).
|
||||
35. Shortening retention from 90 to 30 deletes nothing at PATCH time (repo `DeleteOlderThan` counter 0); the next due Tick deletes older than 30.
|
||||
|
||||
## G. Producers (HTTP)
|
||||
36. Login: right credentials gives `auth.login` (actor user, source web, security false, failure_reason null, ip and user agent from the request); wrong password and unknown username give `auth.login_failed` with actor anonymous named by the attempted username, outcome failed, security true, failure_reason `Wrong username or password.`, identical for both; validation failure and a rate-limited 429 record nothing. No stored field or log line contains the password.
|
||||
37. Logout with a valid cookie gives `auth.logout`; without a cookie records nothing.
|
||||
38. Password reset: request for an existing account gives `auth.password_reset_requested` (security true); unknown email records nothing and the response is byte-identical to the existing account's response except `Date`; confirm with a valid code gives `auth.password_reset_completed`; invalid code records nothing. Neither the raw code, its hash nor the new password appears in any stored field or in `buf`.
|
||||
39. API key: `POST /v1/api-key` records `api_key.create` with the target `{api_key, <id>, name}`; `DELETE /v1/api-key/7` records `api_key.revoke`; `DELETE /v1/api-key/99` is 404 and records nothing. Marshal every stored event and every `/v1/activity` response and assert the raw key and its hash are absent.
|
||||
40. Recorder failure on each producer: the HTTP status and body equal those of the same request with a healthy repository.
|
||||
41. End to end: record a failed login, a key creation and a retention change, then `GET /v1/activity` lists them newest first, and `?security=true` returns only the failed login.
|
||||
|
||||
## H. Layering and hygiene guards
|
||||
42. Grep-style test: `internal/domain/audit` imports only the stdlib and other `internal/domain/*`; the audit use cases import no `gorm`, `persistence`, `mailer`, `net/http`, chi or `api/...`; handlers import no `persistence`, `models` or `gorm`; the persistence repository asserts `var _ audit.Repository = &X{}`; the GORM model lives in `persistence/models` with a mapper.
|
||||
43. Grep the new and edited files, Go and docs, for comments: none; only tool directives.
|
||||
44. Docs read: `docs/api.md` lists the three activity routes, the query parameters, response shapes, the 400/401/403 answers and the PATCH `/v1/settings` contract with the three new GET fields; `docs/architecture.md` describes `domain/audit`, the recorder and context, the persistence model and indexes, and the retention scheduler; `docs/configuration.md` states that retention is stored in the database (default 90) and that no env var was added.
|
||||
|
||||
## Manual (not automated)
|
||||
45. Real boot with `task dev:api`: log in with a wrong password, log in correctly, create and revoke an API key, PATCH retention as owner (with the session cookie), then read `/v1/activity` and `/v1/activity/export` and open the CSV in a spreadsheet to confirm injected cells show as text.
|
||||
46. Behind a reverse proxy with `TRUSTED_PROXIES` containing the proxy: the stored ip is the client's, not the proxy's. Without it: the proxy's.
|
||||
47. Backdate events in the SQLite file, set retention to 30 and either wait for 03:00 or move the system clock; confirm removed rows and the new Last cleanup values in `GET /v1/settings`.
|
||||
48. Run the persistence suite against a MySQL/MariaDB and a PostgreSQL instance through the documented database settings of `docs/configuration.md`: index creation, case-insensitive `q`, literal `%` and `_`, date-range boundaries, and `DeleteOlderThan` counts.
|
||||
49. SIGINT during a cleanup: the process exits after the run ends, with no database error on close.
|
||||
@@ -0,0 +1,506 @@
|
||||
Feature: Every real action of the back-office is recorded in the activity log from inside its use case
|
||||
|
||||
As the owner of a RenewCMS site
|
||||
I want articles, media, users and invites, and system tasks to leave an activity event
|
||||
So that the Activity screen shows who did what, and a failed attempt says why in plain words
|
||||
|
||||
Background:
|
||||
Given the spec of record is docs/design/screens/activity.md ("What is recorded", "API contract") and the foundation slice features/activity-log-backend.feature
|
||||
And this slice is backend only: no SPA, no new env var, no new table, no change to docs/design
|
||||
And events are recorded by the use cases through audit.Recorder, never by handlers, middleware or GORM hooks
|
||||
And every mutating use case method takes the request context as its first parameter and hands it to Recorder.Record, which fills actor, source, ip and user agent from the audit context
|
||||
And system events set the system actor and source "system" themselves, with ip and user_agent null
|
||||
And an event is recorded once, after the change was made (success) or after the use case decided to refuse or abort it (failed), never before
|
||||
And no read is recorded: no GET, no list, no public article read, no status poll
|
||||
And error responses are plain text from http.Error and success responses are JSON with snake_case fields, unchanged by this slice
|
||||
And the layering rule holds: use cases see only domain interfaces, no comment is added anywhere
|
||||
|
||||
Rule: The audit context reaches every producing route
|
||||
|
||||
Scenario Outline: A producing route carries the origin of the request
|
||||
When <request> is sent with <credentials>
|
||||
Then the stored event has actor <actor>, source "<source>" and the request ip and user agent
|
||||
|
||||
Examples:
|
||||
| request | credentials | actor | source |
|
||||
| POST /v1/article | the owner's jwt cookie | the owner, named by display name | web |
|
||||
| POST /v1/article | an API key "Deploy bot"| api_key id 7 named "Deploy bot" | api_key |
|
||||
| POST /v1/media | an API key "Deploy bot"| api_key id 7 named "Deploy bot" | api_key |
|
||||
| POST /v1/system/update/check | the owner's jwt cookie | the owner | web |
|
||||
|
||||
Rule: A failed audit write never changes the user's action
|
||||
|
||||
Scenario Outline: A failing or panicking repository leaves the response untouched
|
||||
Given the audit repository <fault> on Append
|
||||
When <request> succeeds
|
||||
Then the response status and body equal those of the same request with a healthy repository
|
||||
And the change itself was applied
|
||||
And the process log names the failed audit write
|
||||
|
||||
Examples:
|
||||
| fault | request |
|
||||
| fails | POST /v1/article |
|
||||
| fails | DELETE /v1/article/8 |
|
||||
| panics | PATCH /v1/article/8/publish |
|
||||
| fails | POST /v1/media |
|
||||
| fails | POST /v1/media/merge |
|
||||
| fails | POST /v1/user/invite |
|
||||
| fails | POST /v1/system/update/restart |
|
||||
|
||||
Rule: Articles
|
||||
|
||||
Scenario: Creating an article is recorded
|
||||
When the owner sends POST /v1/article with {"title": "Spring release", "body": "Hello"}
|
||||
Then one event exists with action "article.create", category "articles", actor the owner, source "web", target {"type": "article", "id": "<new id>", "name": "Spring release"}, outcome "success", failure_reason null and no changes
|
||||
And the stored event holds no article body
|
||||
|
||||
Scenario: Editing the body records a size delta and never the text
|
||||
Given the article 8 "Spring release" has a body of 100 characters
|
||||
When the owner sends PATCH /v1/article/8 with a body of 412 characters
|
||||
Then one event exists with action "article.edit", target {"type": "article", "id": "8", "name": "Spring release"} and changes [{"field": "body", "kind": "body", "delta": 312}]
|
||||
And no stored field and no /v1/activity response contains any text of either body
|
||||
|
||||
Scenario Outline: The delta is signed and counts characters
|
||||
Given the article 8 has a body of <before> characters
|
||||
When its body is replaced by one of <after> characters
|
||||
Then the change delta is <delta>
|
||||
|
||||
Examples:
|
||||
| before | after | delta |
|
||||
| 100 | 412 | 312 |
|
||||
| 412 | 100 | -312 |
|
||||
| 5 | 5 | 0 |
|
||||
|
||||
Scenario: A body with multi-byte characters is counted in characters
|
||||
Given the article 8 has the body "héllo"
|
||||
When its body is replaced by "héllo wörld"
|
||||
Then the change delta is 6
|
||||
|
||||
Scenario: Saving an identical body records nothing
|
||||
Given the article 8 has the body "Same text"
|
||||
When the owner sends PATCH /v1/article/8 with the body "Same text"
|
||||
Then the response is 200 and no event is recorded
|
||||
|
||||
Scenario: A title change is recorded as a text diff when a title edit exists
|
||||
Given a use case that changes an article's title from "Spring release" to "Spring release 2"
|
||||
Then its event has action "article.edit" and changes [{"field": "title", "kind": "text", "before": "Spring release", "after": "Spring release 2"}]
|
||||
And only the fields title, online and body can ever appear in an article event's changes
|
||||
|
||||
Scenario: Publishing is recorded with the publish state
|
||||
Given the article 8 "Spring release" is offline
|
||||
When the owner sends PATCH /v1/article/8/publish
|
||||
Then one event exists with action "article.publish", category "articles" and changes [{"field": "online", "kind": "text", "before": "false", "after": "true"}]
|
||||
|
||||
Scenario: Unpublishing is recorded with the publish state
|
||||
Given the article 8 is online
|
||||
When the owner sends PATCH /v1/article/8/unpublish
|
||||
Then one event exists with action "article.unpublish" and changes [{"field": "online", "kind": "text", "before": "true", "after": "false"}]
|
||||
|
||||
Scenario Outline: A publish state that does not change records nothing
|
||||
Given the article 8 is <state>
|
||||
When the owner sends PATCH /v1/article/8/<path>
|
||||
Then the response is 200 and no event is recorded
|
||||
|
||||
Examples:
|
||||
| state | path |
|
||||
| online | publish |
|
||||
| offline | unpublish |
|
||||
|
||||
Scenario: Deleting an article is recorded with its name snapshot
|
||||
Given the article 8 "Spring release" exists
|
||||
When the owner sends DELETE /v1/article/8
|
||||
Then one event exists with action "article.delete", target {"type": "article", "id": "8", "name": "Spring release"} and outcome "success"
|
||||
And GET /v1/activity shows that target with exists false
|
||||
|
||||
Scenario Outline: A refused article action is recorded as failed with a plain reason
|
||||
Given <state>
|
||||
When <request>
|
||||
Then one event exists with action "<action>", outcome "failed" and failure_reason "<reason>"
|
||||
And the response is unchanged
|
||||
|
||||
Examples:
|
||||
| state | request | action | reason |
|
||||
| no article has this title | POST /v1/article with a 2 character title | article.create | The title must be between 3 and 200 characters. |
|
||||
| the repository fails with "db is locked" | POST /v1/article with a valid title | article.create | Something went wrong on our side. Please try again. |
|
||||
| the repository fails with "db is locked" | PATCH /v1/article/8/publish | article.publish | Something went wrong on our side. Please try again. |
|
||||
|
||||
Scenario: An article that does not exist records nothing
|
||||
When the owner sends DELETE /v1/article/99, PATCH /v1/article/99, PATCH /v1/article/99/publish and PATCH /v1/article/99/unpublish
|
||||
Then every response is 404 and no event is recorded
|
||||
|
||||
Scenario: A request that fails validation records nothing
|
||||
When the owner sends POST /v1/article with an empty body or a malformed id such as /v1/article/abc
|
||||
Then the response is 400 and no event is recorded
|
||||
|
||||
Scenario Outline: Reads are never recorded
|
||||
When <request> is sent
|
||||
Then no event is recorded
|
||||
|
||||
Examples:
|
||||
| request |
|
||||
| GET /v1/article |
|
||||
| GET /v1/article/8 |
|
||||
| GET /v1/article/8 as the public |
|
||||
|
||||
Rule: Media
|
||||
|
||||
Scenario: Uploading an image is recorded
|
||||
When the owner sends POST /v1/media with the PNG "spring-banner.png"
|
||||
Then one event exists with action "media.upload", category "media", actor the owner, target {"type": "image", "id": "<new id>", "name": "spring-banner.png"} and outcome "success"
|
||||
And the stored event holds no file content and no storage path
|
||||
|
||||
Scenario Outline: A refused upload is recorded as failed
|
||||
When the owner uploads <file>
|
||||
Then one event exists with action "media.upload", outcome "failed" and failure_reason "<reason>"
|
||||
And the target name is the file name as sent, normalised the way a stored upload would be named, or empty when it is unusable
|
||||
And the response is unchanged
|
||||
|
||||
Examples:
|
||||
| file | reason |
|
||||
| a GIF | The file must be a PNG, JPEG, WEBP or SVG image. |
|
||||
| a PNG larger than the limit | The file is too large to upload. |
|
||||
| a corrupt PNG | The image could not be read. |
|
||||
|
||||
Scenario: Renaming an image records the filename diff
|
||||
Given the image 5 "banner.png"
|
||||
When the owner sends PATCH /v1/media/5 with {"filename": "spring-banner"}
|
||||
Then one event exists with action "media.rename", target {"type": "image", "id": "5", "name": "spring-banner.png"} and changes [{"field": "filename", "kind": "text", "before": "banner.png", "after": "spring-banner.png"}]
|
||||
|
||||
Scenario: Renaming to the same name records nothing
|
||||
Given the image 5 "banner.png"
|
||||
When the owner renames it to "banner"
|
||||
Then no event is recorded
|
||||
|
||||
Scenario: A refused rename is recorded as failed
|
||||
Given the image 5 "banner.png"
|
||||
When the owner sends PATCH /v1/media/5 with an invalid filename
|
||||
Then one event exists with action "media.rename", outcome "failed", failure_reason "That file name is not valid." and target {"type": "image", "id": "5", "name": "banner.png"}
|
||||
|
||||
Scenario: Deleting an image is recorded with its name snapshot
|
||||
Given the image 5 "banner.png"
|
||||
When the owner sends DELETE /v1/media/5
|
||||
Then one event exists with action "media.delete", target {"type": "image", "id": "5", "name": "banner.png"} and outcome "success"
|
||||
And GET /v1/activity shows that target with exists false
|
||||
|
||||
Scenario: Merging images is recorded once with its counts
|
||||
Given the images 5 "banner.png", 6 "banner-copy.png" and 7 "banner-copy-2.png" share one content hash
|
||||
And two articles reference the copies
|
||||
When the owner sends POST /v1/media/merge keeping 5 and merging [6, 7]
|
||||
Then one event exists with action "media.merge", target {"type": "image", "id": "5", "name": "banner.png"} and params {"merged": 2, "articles_updated": 2}
|
||||
And no event names a removed copy as a separate action
|
||||
|
||||
Scenario Outline: A refused merge is recorded as failed
|
||||
When the owner sends POST /v1/media/merge that fails with <error>
|
||||
Then one event exists with action "media.merge", outcome "failed" and failure_reason "<reason>"
|
||||
|
||||
Examples:
|
||||
| error | reason |
|
||||
| ErrInvalidMergeRequest | The merge request is not valid. |
|
||||
| ErrMergeCopyMissing | One of the copies no longer exists. |
|
||||
| ErrMergeHashMismatch | The images are not identical copies.|
|
||||
|
||||
Scenario: A manual purge is recorded once and not as separate merges
|
||||
Given a purge plan with 2 groups, 3 copies and 5 articles to update
|
||||
When the owner sends POST /v1/media/purge
|
||||
Then one event exists with action "media.purge", category "media", actor the owner, source "web", outcome "success" and params {"merged": 3, "articles_updated": 5}
|
||||
And no "media.merge" event is recorded for its groups
|
||||
|
||||
Scenario: A partly failed manual purge is a success with the failed group count
|
||||
Given a purge plan with 3 groups where 1 group fails
|
||||
When the owner sends POST /v1/media/purge
|
||||
Then one event exists with action "media.purge", outcome "success" and params that include "failed_groups": 1
|
||||
|
||||
Scenario Outline: A refused manual purge is recorded as failed
|
||||
When the owner sends POST /v1/media/purge and the use case returns <error>
|
||||
Then one event exists with action "media.purge", outcome "failed" and failure_reason "<reason>"
|
||||
|
||||
Examples:
|
||||
| error | reason |
|
||||
| ErrPurgeConflict | The library changed since the preview. Review it again. |
|
||||
| ErrPurgeBusy | A purge is already running. |
|
||||
|
||||
Scenario: The scheduled purge is a system event
|
||||
Given the purge is due and merges 3 copies and updates 5 articles
|
||||
When PurgeSchedulerUseCase.Tick runs
|
||||
Then one event exists with action "system.media_purge", category "system", actor type system named "System", source "system", ip null, user_agent null, outcome "success" and params {"merged": 3, "articles_updated": 5}
|
||||
|
||||
Scenario: A scheduled purge with a failed group records the failed group count
|
||||
Given the purge is due and 1 group fails while others merge
|
||||
When Tick runs
|
||||
Then one event exists with action "system.media_purge", outcome "success" and params that include "failed_groups": 1
|
||||
|
||||
Scenario: A scheduled purge that is not due or merges nothing records nothing
|
||||
Given the purge is not due, or is due and finds no duplicate
|
||||
When Tick runs
|
||||
Then no event is recorded
|
||||
|
||||
Scenario: A scheduled purge that cannot record its run is a failed system event
|
||||
Given the purge is due and the run result cannot be saved
|
||||
When Tick runs
|
||||
Then one event exists with action "system.media_purge", outcome "failed" and failure_reason "Something went wrong on our side. Please try again."
|
||||
|
||||
Scenario: Browsing and the media usage lookup are never recorded
|
||||
When the owner sends GET /v1/media, GET /v1/media/5/usage, GET /v1/media/purge-preview and GET /v1/media/purge-settings
|
||||
Then no event is recorded
|
||||
|
||||
Rule: Users and invites
|
||||
|
||||
Scenario: Registering is recorded with the new account as actor
|
||||
Given registration is open
|
||||
When POST /v1/auth/register is sent with the username "marta"
|
||||
Then one event exists with action "user.register", category "users", actor user "marta" with the new id, source "web", target {"type": "user", "id": "<new id>", "name": "marta"} and outcome "success"
|
||||
And the stored event holds no password, no hash and no verification code
|
||||
|
||||
Scenario Outline: A refused registration is recorded as failed
|
||||
When POST /v1/auth/register is sent and <cause>
|
||||
Then one event exists with action "user.register", outcome "failed", failure_reason "<reason>", actor anonymous named by the attempted username and no target
|
||||
And the response is unchanged
|
||||
|
||||
Examples:
|
||||
| cause | reason |
|
||||
| registration is closed | Registration is closed on this site. |
|
||||
| the verification email cannot be sent | The verification email could not be sent. |
|
||||
|
||||
Scenario: Verifying an account is recorded
|
||||
Given the unverified user 4 "lea" with a valid code
|
||||
When user 4 sends POST /v1/auth/verify with that code
|
||||
Then one event exists with action "user.verify", category "users", actor user 4, target {"type": "user", "id": "4", "name": "lea"} and outcome "success"
|
||||
And the stored event does not hold the code or its hash
|
||||
|
||||
Scenario Outline: A refused verification is recorded as failed
|
||||
Given the unverified user 4 "lea"
|
||||
When user 4 sends POST /v1/auth/verify and the use case returns <error>
|
||||
Then one event exists with action "user.verify", outcome "failed" and failure_reason "<reason>"
|
||||
|
||||
Examples:
|
||||
| error | reason |
|
||||
| ErrInvalidVerificationCode | The verification code is not valid. |
|
||||
| ErrVerificationCodeExpired | The verification code has expired. |
|
||||
|
||||
Scenario: Changing the display name records a before and after
|
||||
Given user 3 has the display name "Marta"
|
||||
When user 3 sends PATCH /v1/user/me with {"display_name": "Marta Alves"}
|
||||
Then one event exists with action "user.update_profile", category "users", target {"type": "user", "id": "3", "name": "Marta Alves"} and changes [{"field": "display_name", "kind": "text", "before": "Marta", "after": "Marta Alves"}]
|
||||
And the actor snapshot name is the name held when the request began
|
||||
|
||||
Scenario Outline: Setting a display name that does not change records nothing
|
||||
Given user 3 has the display name "<current>"
|
||||
When user 3 sends PATCH /v1/user/me with {"display_name": "<sent>"}
|
||||
Then no event is recorded
|
||||
|
||||
Examples:
|
||||
| current | sent |
|
||||
| Marta | Marta |
|
||||
| Marta | Marta |
|
||||
| | |
|
||||
|
||||
Scenario: A display name that is too long is recorded as failed
|
||||
When user 3 sends PATCH /v1/user/me with a 61 character name
|
||||
Then one event exists with action "user.update_profile", outcome "failed" and failure_reason "That display name is too long."
|
||||
And the stored event holds no changes
|
||||
|
||||
Scenario: Creating an invite is recorded
|
||||
When the owner sends POST /v1/user/invite with {"email": "new@example.com"}
|
||||
Then one event exists with action "invite.create", category "users", actor the owner, target {"type": "invite", "id": "<invite id>", "name": "new@example.com"} and outcome "success"
|
||||
And the stored event holds no invite code and no hash
|
||||
|
||||
Scenario Outline: A refused invite action is recorded as failed
|
||||
When the owner <request> and the use case returns <error>
|
||||
Then one event exists with action "<action>", outcome "failed" and failure_reason "<reason>"
|
||||
|
||||
Examples:
|
||||
| request | error | action | reason |
|
||||
| sends POST /v1/user/invite | ErrEmailHasAccount | invite.create | That email already has an account. |
|
||||
| sends POST /v1/user/invite | ErrPendingInvite | invite.create | An invitation is already pending for that email. |
|
||||
| sends POST /v1/user/invite | ErrInviteEmailNotSent | invite.create | The invitation email could not be sent. |
|
||||
| sends POST /v1/user/invite/4/renew | ErrInviteEmailNotSent | invite.renew | The invitation email could not be sent. |
|
||||
| sends POST /v1/user/invite/4/renew | ErrInviteAlreadyAccepted | invite.renew | That invitation was already accepted. |
|
||||
| sends DELETE /v1/user/invite/4 | ErrInviteAlreadyAccepted | invite.cancel | That invitation was already accepted. |
|
||||
|
||||
Scenario: Cancelling an invite is recorded
|
||||
Given the pending invite 4 for "new@example.com"
|
||||
When the owner sends DELETE /v1/user/invite/4
|
||||
Then one event exists with action "invite.cancel", target {"type": "invite", "id": "4", "name": "new@example.com"} and outcome "success"
|
||||
|
||||
Scenario: Renewing an invite is recorded
|
||||
Given the pending invite 4 for "new@example.com"
|
||||
When the owner sends POST /v1/user/invite/4/renew
|
||||
Then one event exists with action "invite.renew", target {"type": "invite", "id": "4", "name": "new@example.com"} and outcome "success"
|
||||
And a renewal whose email fails is rolled back and recorded only as failed
|
||||
|
||||
Scenario: Accepting an invite is recorded with the new account as actor
|
||||
Given the pending invite 4 for "new@example.com"
|
||||
When POST /v1/auth/invite/accept is sent with a valid code and the username "sam"
|
||||
Then one event exists with action "invite.accept", category "users", actor user "sam" with the new id, source "web", target {"type": "invite", "id": "4", "name": "new@example.com"} and outcome "success"
|
||||
And the stored event holds no code, no hash and no password
|
||||
|
||||
Scenario Outline: A refused acceptance is recorded as failed
|
||||
When POST /v1/auth/invite/accept is sent and the use case returns <error>
|
||||
Then one event exists with action "invite.accept", outcome "failed", failure_reason "<reason>" and actor anonymous named by the attempted username
|
||||
And the stored event has no target when the invite could not be identified
|
||||
|
||||
Examples:
|
||||
| error | reason |
|
||||
| ErrInviteInvalid | That invitation is not valid. |
|
||||
| ErrInviteExpired | That invitation has expired. |
|
||||
| ErrInviteAlreadyAccepted | That invitation was already accepted. |
|
||||
| ErrUsernameTaken | That username is already taken. |
|
||||
| ErrEmailHasAccount | That email already has an account. |
|
||||
|
||||
Scenario: An invite or user that does not exist records nothing
|
||||
When the owner sends DELETE /v1/user/invite/99 or POST /v1/user/invite/99/renew
|
||||
Then every response is 404 and no event is recorded
|
||||
|
||||
Scenario Outline: Reads and checks are never recorded
|
||||
When <request> is sent
|
||||
Then no event is recorded
|
||||
|
||||
Examples:
|
||||
| request |
|
||||
| GET /v1/user |
|
||||
| GET /v1/auth/me |
|
||||
| GET /v1/auth/invite?code=<code> |
|
||||
| GET /v1/auth/registration |
|
||||
|
||||
Rule: System tasks
|
||||
|
||||
Scenario: Checking for an update is recorded
|
||||
Given the release feed answers v1.4.0 while the running version is v1.3.2
|
||||
When the owner sends POST /v1/system/update/check
|
||||
Then one event exists with action "system.update_checked", category "system", actor the owner, source "web", target {"type": "release", "id": "v1.4.0", "name": "v1.4.0"}, outcome "success" and params {"update_available": true}
|
||||
|
||||
Scenario Outline: A failed update check is recorded with a plain reason
|
||||
When the owner sends POST /v1/system/update/check and the use case returns <error>
|
||||
Then one event exists with action "system.update_checked", outcome "failed", failure_reason "<reason>" and no target
|
||||
|
||||
Examples:
|
||||
| error | reason |
|
||||
| ErrFeedUnavailable | The release feed could not be reached. |
|
||||
| ErrNoRelease | No release was found. |
|
||||
|
||||
Scenario: The status poll is never recorded
|
||||
When the owner sends GET /v1/system/update
|
||||
Then no event is recorded
|
||||
|
||||
Scenario: A download that completes is recorded when the job is ready
|
||||
Given a newer release v1.4.0 is available and the update helper is installed
|
||||
When the owner sends POST /v1/system/update/download
|
||||
Then the response is returned before the job ends and no event exists yet
|
||||
And when the job reaches the ready state one event exists with action "system.update_downloaded", actor the owner, source "web", target {"type": "release", "id": "v1.4.0", "name": "v1.4.0"} and outcome "success"
|
||||
And the origin (actor, ip, user agent) is the one captured at request time
|
||||
|
||||
Scenario Outline: A download that fails is recorded with a reason that hides the cause
|
||||
Given a newer release v1.4.0 is available and the job fails with the error kind "<kind>"
|
||||
Then one event exists with action "system.update_downloaded", outcome "failed" and failure_reason "<reason>"
|
||||
And the stored event holds no url, no path and no raw error text
|
||||
|
||||
Examples:
|
||||
| kind | reason |
|
||||
| download | The update could not be downloaded. |
|
||||
| verification | The downloaded update failed its integrity check. |
|
||||
|
||||
Scenario Outline: A download refused at the start is recorded as failed
|
||||
When the owner sends POST /v1/system/update/download and the use case returns <error>
|
||||
Then one event exists with action "system.update_downloaded", outcome "failed" and failure_reason "<reason>"
|
||||
And the response is unchanged
|
||||
|
||||
Examples:
|
||||
| error | reason |
|
||||
| ErrNotPrepared | This server cannot apply updates. |
|
||||
| ErrJobInProgress | An update is already being downloaded. |
|
||||
| ErrRestartPending | A restart is already pending. |
|
||||
| ErrNothingToUpdate | There is nothing to update. |
|
||||
| ErrPreflightRefused | The update cannot be downloaded. |
|
||||
|
||||
Scenario: A restart request is recorded
|
||||
Given the update helper is installed and no job is running
|
||||
When the owner sends POST /v1/system/update/restart
|
||||
Then one event exists with action "system.restart_requested", category "system", actor the owner, source "web", outcome "success" and params {"kind": "restart"}
|
||||
|
||||
Scenario: A restart that applies a downloaded update records the kind and version
|
||||
Given a downloaded update v1.4.0 is ready
|
||||
When the owner sends POST /v1/system/update/restart
|
||||
Then the event has params {"kind": "update", "tag": "v1.4.0"}
|
||||
|
||||
Scenario Outline: A refused restart is recorded as failed
|
||||
When the owner sends POST /v1/system/update/restart and the use case returns <error>
|
||||
Then one event exists with action "system.restart_requested", outcome "failed" and failure_reason "<reason>"
|
||||
|
||||
Examples:
|
||||
| error | reason |
|
||||
| ErrNotPrepared | This server cannot apply updates. |
|
||||
| ErrJobInProgress | An update is still being downloaded. |
|
||||
| ErrRestartPending | A restart is already pending. |
|
||||
| ErrRestartKindMismatch | The requested restart does not match the server state. |
|
||||
|
||||
Rule: A failed outcome never exposes more than the plain-language reason
|
||||
|
||||
Scenario: Failure reasons are mapped from domain sentinels
|
||||
Given a table that maps each domain Err sentinel above to a fixed sentence
|
||||
When a use case fails with an error that wraps one of them
|
||||
Then failure_reason is that sentence, matched with errors.Is
|
||||
|
||||
Scenario Outline: Unmapped errors become the generic sentence
|
||||
When a use case fails with <error>
|
||||
Then failure_reason is "Something went wrong on our side. Please try again."
|
||||
And neither the event, the activity API nor the CSV export holds the text of the error
|
||||
|
||||
Examples:
|
||||
| error |
|
||||
| errors.New("db is locked") |
|
||||
| an error carrying an SMTP host and password |
|
||||
| an error carrying a file system path |
|
||||
| an error wrapping a sentinel and a raw cause |
|
||||
|
||||
Scenario: Every failure reason fits the stored limit
|
||||
Then every mapped sentence is at most 255 characters
|
||||
|
||||
Scenario: A failed event keeps its target when the target is known
|
||||
Given the image 5 "banner.png" exists
|
||||
When a rename of image 5 is refused
|
||||
Then the failed event keeps the target snapshot of image 5
|
||||
|
||||
Rule: Secrets and bodies never reach the log
|
||||
|
||||
Scenario Outline: Sensitive values are absent everywhere
|
||||
Given the action <action> handled <secret>
|
||||
When it is recorded, listed through GET /v1/activity and exported through GET /v1/activity/export
|
||||
Then no stored field, no params, no change, no response, no CSV cell and no process log line contains <secret>
|
||||
|
||||
Examples:
|
||||
| action | secret |
|
||||
| user.register | the password, its hash and the verification code |
|
||||
| user.verify | the verification code and its hash |
|
||||
| invite.create | the invite code and its hash |
|
||||
| invite.accept | the invite code, its hash and the password |
|
||||
| article.edit | the old and the new article body |
|
||||
| media.upload | the file bytes and the storage path |
|
||||
| system.update_downloaded | the asset url and the staging path |
|
||||
|
||||
Scenario: Only allowlisted fields appear in changes
|
||||
Then the only change fields any producer emits are title, online, body, filename and display_name
|
||||
And the only change kinds are text and body
|
||||
|
||||
Rule: The recorded events read back through the existing API
|
||||
|
||||
Scenario: Producer events are listed with their documented shape
|
||||
Given an article was created, edited, published and deleted by the owner
|
||||
When the owner sends GET /v1/activity?category=articles
|
||||
Then the four events are listed newest first, with category "articles", the documented item shape and the article target exists false after the delete
|
||||
|
||||
Scenario Outline: Categories filter the producers
|
||||
Given one event of each producer was recorded
|
||||
When the owner sends GET /v1/activity?category=<category>
|
||||
Then the items are exactly the events listed in <actions>
|
||||
|
||||
Examples:
|
||||
| category | actions |
|
||||
| articles | article.create, article.edit, article.publish, article.unpublish, article.delete |
|
||||
| media | media.upload, media.rename, media.delete, media.merge, media.purge |
|
||||
| users | user.register, user.verify, user.update_profile, invite.create, invite.cancel, invite.renew, invite.accept |
|
||||
| system | system.media_purge, system.update_checked, system.update_downloaded, system.restart_requested |
|
||||
|
||||
Scenario: A failed producer event is filterable
|
||||
Given a refused merge and a successful rename were recorded
|
||||
When the owner sends GET /v1/activity?outcome=failed
|
||||
Then only the refused merge is listed with its failure_reason
|
||||
@@ -0,0 +1,67 @@
|
||||
# QA procedure: activity-log-producers
|
||||
|
||||
Go only, no SPA. Package `test` (black-box). New files: `test/activity_producers_articles_test.go`, `test/activity_producers_media_test.go`, `test/activity_producers_users_test.go`, `test/activity_producers_system_test.go`, `test/activity_producers_reasons_test.go`. Reuse the foundation helpers in `test/activity_support_test.go` (`mockAuditRepo`, `fakeAuditClock`, `seedEvents`). Extend the existing hand-written fakes (`mockArticleRepo`, the image, user, invite, purge, update and status fakes) with failure switches and call counters. New fake type names must be unique across the package. No live server, no real SMTP, no real SQLite file, no real sleeping, no `time.Ticker`. Secrets in tests are fixed test strings only.
|
||||
|
||||
## Setup shared by every case
|
||||
1. `validator.InitValidator()` once. `jwtauth.New("HS256", []byte("test-secret"), nil)` stands in for `JWT_SECRET`.
|
||||
2. One `auditing.NewRecorder(mockAuditRepo, fakeAuditClock.Now, logger)` shared by every use case. `logger` writes to a `bytes.Buffer` (restore with `t.Cleanup`).
|
||||
3. Users: owner 1, admin 2, verified user 3 "Marta", unverified user 4 "lea" (with a hashed code). API key 7 "Deploy bot" in the fake key repo.
|
||||
4. A fresh `chi.NewRouter()` per test that mirrors `api/router.go` for the article, user, media, system and auth routers, with `middleware.AuditContext(getUser, trustedProxies)` placed exactly where the router wires it (after `apiKeyAuth()` on the article, user and media routers). Cookies are real signed `jwt` cookies with `user_id` and `token_version`. `httptest.NewRecorder` per request.
|
||||
5. Helpers: `eventsOf(repo)`, `onlyEvent(t, repo)` (fails unless exactly one event), `assertNoEvent(t, repo)`.
|
||||
6. Each mutating use case method takes `ctx context.Context` first. A method called with a context holding no origin still works.
|
||||
|
||||
## A. Origin and routing
|
||||
7. Table (feature rule 1): each request with the cookie or the API key yields the expected actor type, id, name and source, plus the request ip and user agent. Proves `AuditContext` is mounted on the article, user, media and system routers.
|
||||
8. A route without credentials, or answered 401/403/429, records nothing.
|
||||
|
||||
## B. Articles
|
||||
9. Create: one `article.create` event, target id string, name as typed, no changes, no body anywhere (marshal the event and assert absence).
|
||||
10. Edit: table `(before, after, delta)`: 100 to 412 (312), 412 to 100 (-312), 5 to 5 with different content (0, still recorded), `héllo` to `héllo wörld` (6, characters not bytes). Identical body records nothing. Change kind `body`, `Delta` set, `Before` and `After` nil.
|
||||
11. Publish and unpublish: `online` text change (`"false"`/`"true"`). Repeating the same state records nothing and returns 200.
|
||||
12. Delete: event keeps the name snapshot. After it, `GET /v1/activity` shows `target.exists` false.
|
||||
13. Title diff: unit-test the change builder with title, online and body only; any other field name is rejected.
|
||||
14. Failure table: 2 character title, repository failing with `errors.New("db is locked")` (generic reason). 404 on delete, edit, publish, unpublish of id 99 and 400 on malformed id or body record nothing.
|
||||
15. Reads (list, get, public get) record nothing.
|
||||
|
||||
## C. Media
|
||||
16. Upload: in-memory PNG, target name equals the normalised filename, no bytes and no path. Failed upload table: GIF, oversize, corrupt PNG, each with its mapped reason.
|
||||
17. Rename: `filename` text change `banner.png` to `spring-banner.png`. Same name records nothing. Invalid stem records a failed event keeping the target. Missing image records nothing (404).
|
||||
18. Delete: event with name snapshot. Missing image records nothing.
|
||||
19. Merge: three images with one hash, two articles referencing the copies. One `media.merge` event with `{"merged":2,"articles_updated":2}`, target the kept image. Failure table: `ErrInvalidMergeRequest`, `ErrMergeCopyMissing`, `ErrMergeHashMismatch`.
|
||||
20. Manual purge: plan with 2 groups, 3 copies, 5 articles. Exactly one `media.purge` event with `{"merged":3,"articles_updated":5}` and zero `media.merge` events. A plan with one failing group: outcome success with `failed_groups` 1. `ErrPurgeConflict` and `ErrPurgeBusy` give failed events. Preview, usage, list and settings GETs record nothing.
|
||||
21. Scheduled purge: drive `PurgeSchedulerUseCase.Tick(now)` with the fake purge repo and clock. Due and merging 3: one `system.media_purge` event with system actor, source system, ip nil, user agent nil. Due with a failed group: success with `failed_groups`. Not due, or no duplicates: none. A fake `SaveLastRun` failure: failed event with the generic reason.
|
||||
22. Manual purge after the scheduler in the same test yields two events with sources `web` and `system`.
|
||||
|
||||
## D. Users and invites
|
||||
23. Register: open registration records `user.register` with the new account as actor and target. Closed registration and a failing mailer (error carrying a fake SMTP password) record failed events with the mapped reason, anonymous actor named by the attempted username, no raw text. Marshal the event and assert password, hash and code are absent.
|
||||
24. Verify: success, invalid code, expired code.
|
||||
25. Display name: before/after diff, trimmed no-op records nothing, empty to empty records nothing, 61 characters records a failed event with no changes. Actor snapshot name is the pre-change name.
|
||||
26. Invites: create, cancel, renew, accept each record the documented event with the invited email as target name. Failure table covers every error in the feature. A renew whose mail fails is rolled back and records one failed event only. Unknown ids (404) record nothing.
|
||||
27. Accept: actor is the new account, source `web`; failed accept actor is anonymous with the attempted username.
|
||||
28. Reads (`GET /v1/user`, `/v1/auth/me`, `/v1/auth/invite`, `/v1/auth/registration`) record nothing.
|
||||
|
||||
## E. System tasks
|
||||
29. Check: success event with `{"update_available":true}` and a release target. `ErrFeedUnavailable` and `ErrNoRelease` give failed events without target. Status `GET` records nothing.
|
||||
30. Download: fakes complete the job through a hand-fed channel (no `time.Sleep`). No event before the job ends, one after `ready`; actor, ip and user agent are those captured at request time even though the request context was cancelled. Failure kinds `download` and `verification` give the two reasons, no URL or path. Start-time refusals give failed events. Run with `-race`.
|
||||
31. Restart: `{"kind":"restart"}` and `{"kind":"update","tag":"v1.4.0"}`. Refusals for `ErrNotPrepared`, `ErrJobInProgress`, `ErrRestartPending`, `ErrRestartKindMismatch`.
|
||||
|
||||
## F. Reasons, secrets and recorder faults
|
||||
32. Reason table: wrap each sentinel with `fmt.Errorf("%w: %w", sentinel, errors.New("secret detail"))`, assert the sentence equals the table and the extra text is absent. Unmapped errors give the generic sentence. Every sentence is at most 255 characters.
|
||||
33. Recorder fault: for each producer row of the fault table, run with failing, panicking and healthy `mockAuditRepo`. Identical status and body, change applied, log line naming the failed write.
|
||||
34. Secret sweep: after exercising every producer, marshal every stored event, the `/v1/activity` response and the `/v1/activity/export` file; assert none contains the password, hash, verification code, invite code, raw API key, article body, file bytes, asset URL or staging path. The log buffer is free of them too.
|
||||
35. Allowlist: every `Change.Field` is in `{title, online, body, filename, display_name}` and every kind is `text` or `body`.
|
||||
36. Read-back: list by `category=articles|media|users|system` and `outcome=failed`; compare action sets with the feature tables.
|
||||
|
||||
## G. Mutation guard (gremlins stays clean)
|
||||
37. `task mutate` scope is `./internal/infrastructure/useCases`. Each new branch needs a killing assertion: every no-op guard (body, online, filename, display name) with equal and differing values; delta sign and rune-versus-byte count; success versus failed outcome and recorded once after the change (event count and order against the repository call); every `errors.Is` row of the reason map plus the generic fallback; every `ctx` forwarding; the system-actor defaults. Bare-bool conditions produce no mutant, so cover both branches with tests regardless.
|
||||
|
||||
## H. Layering and hygiene
|
||||
38. Touched use cases import no `gorm`, `persistence`, `mailer`, `net/http`, chi or `api/...`; handlers only pass `r.Context()`; `internal/domain/audit` imports only stdlib and domain packages.
|
||||
39. No comments in new or edited Go files, test files and docs, except tool directives.
|
||||
40. Docs (`docs/api.md`, `docs/architecture.md`) list the action catalogue, target types, reason sentences and the rule that no read is recorded.
|
||||
|
||||
## Manual (not automated)
|
||||
41. Real boot with `task dev:api` and SMTP: register, verify, invite, renew, accept and cancel an invite, change display name, create/edit/publish/unpublish/delete an article, upload/rename/merge/delete images, manual purge; read `/v1/activity` and the CSV export and read every sentence.
|
||||
42. Real update helper on Linux systemd (or the Docker QA flow): check, download until `ready`, restart; one event each, real asset names absent. Skip in a container.
|
||||
43. Leave the scheduled purge due and wait for the hourly tick: a single `system.media_purge` event, source `system`, no ip or user agent.
|
||||
44. Remove the database file's write access during one article edit: edit result unchanged, process log names the audit write failure.
|
||||
@@ -0,0 +1,349 @@
|
||||
Feature: Recent activity card on Home and Retention card on Settings
|
||||
|
||||
As a RenewCMS user
|
||||
I want Home to show my last five activity events and the owner to choose how long activity is kept on Settings
|
||||
So that I see what happened without opening the Activity page, and the log does not grow without bound
|
||||
|
||||
Background:
|
||||
Given the activity API (features/activity-log-backend.feature, activity-log-producers.feature, activity_screen.feature) and the settings retention fields already exist
|
||||
And this slice adds one field to the settings API, activity_next_cleanup_at, and wires the SPA to the existing endpoints; there is no other Go change
|
||||
And the Home card and the Settings "Retention" card are the two items activity_screen.feature left out of scope; the spec of record is docs/design/screens/home.md ("Recent activity card") and docs/design/screens/settings.md ("Activity retention"), groups "Home card" and "Settings retention" of RenewCMS Screens Activity.dc.html
|
||||
And both boards draw the existing cards as dashed placeholders, so neither card is pixel-compared and Vitest is the SPA coverage
|
||||
And "owner" and "admin" are the full Home view; any other or absent session role is the regular-user view
|
||||
And every new English string has a French entry in messages.ts
|
||||
And GET /v1/settings (every verified user) and PATCH /v1/settings (owner only, behind RequireOwner) both answer with the JSON object {"version", "activity_retention_days", "activity_last_cleanup_at", "activity_last_cleanup_removed", "activity_next_cleanup_at"}, snake_case, nothing else
|
||||
And this supersedes the statement of features/settings_page.feature that the body is exactly {"version": "<value>"}; the version field and the verified-user access of that feature are unchanged
|
||||
And activity_next_cleanup_at is an RFC 3339 timestamp with the server's offset, or null when activity_retention_days is 0 (Forever)
|
||||
And otherwise it is the next 03:00 (audit.CleanupHour) in the server's time zone strictly after the server's current time
|
||||
And the value is computed in the domain (audit.Settings) from the clock the use cases are built with, never in the handler and never in the SPA
|
||||
And the cleanup it announces is the existing daily job, which never touches the last 24 hours (audit.KeepRecentHours)
|
||||
And GetActivityRetentionUseCase and UpdateActivityRetentionUseCase both return the value, so a PATCH response carries the next cleanup of the new period (null after switching to Forever, a timestamp after leaving Forever)
|
||||
And the existing validation, 400 with the text of apperr.BodyErrorMessage for any value outside 0, 30, 90, 365 or a malformed body, and 403 for a non-owner are unchanged
|
||||
And the domain package stays free of GORM, HTTP and the clock source (the clock is passed in)
|
||||
And on /home a card "Recent activity" (RecentActivityCard) sits in a 420 px column to the right of the existing cards from the lg breakpoint up, with a 16 px gap, in a grid (minmax(0,1fr) 420px, items aligned to the start) that spans the full content width, with no max-width, as the board frame draws it
|
||||
And the greeting header and the update banner stay above the grid at full width
|
||||
And below lg the card is stacked above the stat tiles and the recent article list, below the banner, with a 16 px gap
|
||||
And the card is --ui-bg with a 1 px --ui-border and a header row (12px 16px padding, 1 px bottom border) holding the title (14 px semibold, --ui-text-highlighted) and, at the right, the link "View all" with an arrow-right icon (14 px; 44 px touch height below lg) to /activity
|
||||
And the title is "Recent activity", and "Your recent activity" in the regular-user view
|
||||
And on mount the card sends exactly one GET /v1/activity?size=5 with no other parameter and never an actor parameter; it never calls /summary or /export; the server returns own events only for a regular user
|
||||
And no range is sent, so the server's default of 7 days applies and a site quiet for more than a week reads "No activity yet"
|
||||
And the card loads independently of GET /v1/article/: neither waits for or blocks the other, and an error or empty card leaves the stat tiles, the recent article list, the articles' own empty and error states and "Connect your website" as they are
|
||||
And each row (up to 5, in API order) has a 24 px avatar, the sentence clamped to two lines with the target name in semibold (composed by ActivitySentence exactly as on /activity, never stored text), then a muted 12 px line: "{actor name} · {time}" in the full view and only "{time}" in the regular-user view
|
||||
And the avatar is the same as the Actor cell of /activity (initials for a user, key-round for an API key, cog for the system, user-round-x for an anonymous actor)
|
||||
And the time of an event of today is "{n} min ago" or "{n} h ago" (lib/activityTime), an event of yesterday reads "Yesterday, 14:20" and an older one "3 Oct 2026, 14:20" (French "Hier, 14:20", "3 oct. 2026, 14:20"); the full local time with seconds is its title attribute
|
||||
And a failed event shows a "Failed" badge at the right of its row; a successful event with security true shows a small shield icon (14 px, --ui-warning) and no badge; a failed security event shows the badge only
|
||||
And rows are not interactive; only "View all" navigates
|
||||
And while the request is in flight for longer than 150 ms the card body shows five skeleton rows (24 px circle, two bars) and aria-busy="true"; nothing is drawn in the body for the first 150 ms
|
||||
And on a 500, any other non-401 status or a network failure the body is an inline role="alert" error with icon circle-x, title "Couldn't load recent activity", no description, and a "Try again" button that sends the same GET /v1/activity?size=5 again; a 401 is handled globally by useApi
|
||||
And when total is 0 the body is the empty state: icon history, "No activity yet" and "Actions on your site will appear here." (regular user: "Your actions will appear here.")
|
||||
And on /settings, for the owner only, a third card (RetentionCard) follows UpdatesCard and MediaCleanupCard and has the same width as its sibling cards; for an admin, a regular user or an absent role it is not rendered at all
|
||||
And the card reads GET /v1/settings, the single call SettingsView already makes, whose typed response is widened with the four activity_* fields; the page still sends exactly one GET /v1/settings per navigation
|
||||
And the header is "Retention" (14 px semibold) over "How long activity is kept." (12 px muted) with a status area at the right, aria-live="polite": "Saving…" (loader-circle) while a PATCH is in flight, "Saved" (check, --ui-success) for 2 s after it succeeds
|
||||
And the body has the label "Keep activity for" over a USelectMenu (at most 260 px wide) with the items "30 days", "90 days", "365 days", "Forever" (values 30, 90, 365, 0) and a 12 px muted helper: "Older events are removed automatically." or, for Forever, "Nothing is removed automatically. The log grows over time."
|
||||
And an info UAlert with icon lock is always shown: "Activity logs are append-only" / "Events can't be edited or deleted from the app. Only the retention period removes them."
|
||||
And after a divider two read-only lines (120 px label then value; stacked on mobile) are shown in the user's local time: "Last cleanup" reads "6 Oct 2026, 03:00 · 142 events removed" ("1 event removed" for 1), or "Never" when activity_last_cleanup_at is null; "Next cleanup" reads "7 Oct 2026, 03:00" from activity_next_cleanup_at, or "Not scheduled" when it is null
|
||||
And for Forever the last-cleanup line still shows the real last cleanup when one exists, and "Never" otherwise
|
||||
And the periods are ordered 30 < 90 < 365 < Forever, and "shorter" means a lower rank than the saved period
|
||||
And choosing a longer period, including Forever, sends PATCH /v1/settings with {"activity_retention_days": <value>} at once
|
||||
And choosing a shorter period sends nothing and shows a warning UAlert with icon triangle-alert, title "Events older than {n} days will be removed", text "This happens at the next cleanup on {date}. It can't be undone." (the date is the saved settings' activity_next_cleanup_at, formatted like the line above) and the buttons "Apply {n} days" and "Cancel"
|
||||
And a PATCH 200 returns the full settings, which refresh the select and the last and next lines
|
||||
And any non-401 PATCH failure (400, 403, 500, network) shows an error UAlert with icon circle-x, title "Couldn't save the retention period", text "Your previous setting is still in place." and a "Try again" button, reverts the select to the saved value and leaves the lines unchanged; a 403 additionally refreshes the session, after which the card is gone
|
||||
And "Try again" re-sends the failed value without asking for the shortening confirmation again
|
||||
And while GET /v1/settings is loading for longer than 150 ms the card shows skeleton lines with aria-busy="true"
|
||||
And when GET /v1/settings fails the card shows the Media cleanup card's alert, "Couldn't reach RenewCMS. Check your connection and try again." with "Try again", which re-runs the shared load
|
||||
And while the browser is offline the select, "Apply" and "Cancel" are disabled; the page's offline banner copy is unchanged
|
||||
|
||||
Scenario Outline: Settings API, GET returns the next cleanup of the saved period
|
||||
Given the saved retention is <days> days and the server time is <now> in a server zone of +02:00
|
||||
When a verified user sends GET /v1/settings
|
||||
Then the status is 200
|
||||
And the body has "activity_next_cleanup_at" <next> and the other four fields
|
||||
|
||||
Examples:
|
||||
| days | now | next |
|
||||
| 90 | 2026-10-06T10:00:00+02:00 | "2026-10-07T03:00:00+02:00" |
|
||||
| 90 | 2026-10-06T02:59:59+02:00 | "2026-10-06T03:00:00+02:00" |
|
||||
| 90 | 2026-10-06T03:00:00+02:00 | "2026-10-07T03:00:00+02:00" |
|
||||
| 30 | 2026-12-31T23:30:00+02:00 | "2027-01-01T03:00:00+02:00" |
|
||||
| 365 | 2026-10-06T10:00:00+02:00 | "2026-10-07T03:00:00+02:00" |
|
||||
| 0 | 2026-10-06T10:00:00+02:00 | null |
|
||||
|
||||
Scenario: Settings API, GET keeps the existing fields and adds exactly one
|
||||
Given the saved retention is 90 days, the last cleanup is 2026-10-06T01:00:00Z with 142 events removed
|
||||
When a verified user sends GET /v1/settings
|
||||
Then the body is a JSON object with exactly the keys version, activity_retention_days, activity_last_cleanup_at, activity_last_cleanup_removed and activity_next_cleanup_at
|
||||
|
||||
Scenario: Settings API, GET is open to every verified user
|
||||
Given a verified admin or editor sends GET /v1/settings
|
||||
Then the status is 200 and the body includes activity_next_cleanup_at
|
||||
|
||||
Scenario Outline: Settings API, PATCH returns the next cleanup of the new period
|
||||
Given the saved retention is <from> days and the user is the owner
|
||||
When the owner sends PATCH /v1/settings with {"activity_retention_days": <to>}
|
||||
Then the status is 200 and activity_retention_days is <to>
|
||||
And activity_next_cleanup_at is <next>
|
||||
|
||||
Examples:
|
||||
| from | to | next |
|
||||
| 90 | 30 | the next 03:00 server time |
|
||||
| 90 | 0 | null |
|
||||
| 0 | 365 | the next 03:00 server time |
|
||||
| 90 | 90 | the next 03:00 server time |
|
||||
|
||||
Scenario: Settings API, PATCH with the saved value changes nothing
|
||||
Given the saved retention is 90 days
|
||||
When the owner sends PATCH /v1/settings with {"activity_retention_days": 90}
|
||||
Then the status is 200, nothing is saved and no audit event is recorded
|
||||
|
||||
Scenario: Settings API, PATCH by a non-owner is refused and changes nothing
|
||||
Given a verified admin
|
||||
When the admin sends PATCH /v1/settings with {"activity_retention_days": 30}
|
||||
Then the status is 403 with the text "Only the owner can do this." and the saved retention is unchanged
|
||||
|
||||
Scenario Outline: Settings API, PATCH rejects invalid input
|
||||
When the owner sends PATCH /v1/settings with <body>
|
||||
Then the status is 400 with the text of apperr.BodyErrorMessage and nothing is saved
|
||||
|
||||
Examples:
|
||||
| body |
|
||||
| {"activity_retention_days": 7} |
|
||||
| {"activity_retention_days": "30"} |
|
||||
| {} |
|
||||
| not json |
|
||||
|
||||
Scenario: Settings use cases compute the next cleanup from their clock
|
||||
Given GetActivityRetentionUseCase and UpdateActivityRetentionUseCase are built with a fake settings repository and a fixed clock
|
||||
Then GetActivityRetention returns Settings whose NextCleanupAt is the next 03:00 after the clock, or nil for Forever
|
||||
And UpdateActivityRetention returns the new period with its own NextCleanupAt
|
||||
And UpdateActivityRetention(7) returns an error satisfying errors.Is(err, audit.ErrInvalidRetention) and saves nothing
|
||||
|
||||
Scenario Outline: Home, owner or admin, the last five events with the actor name
|
||||
Given the session role is "<role>" and GET /v1/activity?size=5 resolves 200 with 5 events, the first being Marta Alves publishing the article "Spring release" 2 minutes ago
|
||||
When the user navigates to /home
|
||||
Then the card title is "Recent activity" and "View all" links to /activity
|
||||
And row 1 reads "Published the article Spring release" with "Spring release" in semibold, over "Marta Alves · 2 min ago", with a 24 px avatar "MA"
|
||||
And exactly 5 rows are shown and GET /v1/activity was requested once with size=5 and no other parameter
|
||||
|
||||
Examples:
|
||||
| role |
|
||||
| owner |
|
||||
| admin |
|
||||
|
||||
Scenario Outline: Home, regular user, own events only and no actor name
|
||||
Given the session role is "<role>" and GET /v1/activity?size=5 resolves 200 with 3 own events
|
||||
When the user navigates to /home
|
||||
Then the card title is "Your recent activity"
|
||||
And each row's meta line is only the time, for example "2 min ago"
|
||||
And no actor parameter was sent
|
||||
|
||||
Examples:
|
||||
| role |
|
||||
| editor |
|
||||
| absent |
|
||||
|
||||
Scenario Outline: Home rows, failure and security markers
|
||||
Given an event with outcome "<outcome>" and security <security>
|
||||
Then its row shows <marker>
|
||||
|
||||
Examples:
|
||||
| outcome | security | marker |
|
||||
| success | false | no badge and no shield |
|
||||
| failed | false | a "Failed" badge |
|
||||
| success | true | a shield icon and no badge |
|
||||
| failed | true | a "Failed" badge and no shield |
|
||||
|
||||
Scenario Outline: Home rows, the time label follows the day
|
||||
Given the current time is 2026-10-06 15:00 local and an event created <when>
|
||||
Then the meta time reads "<label>"
|
||||
|
||||
Examples:
|
||||
| when | label |
|
||||
| 2026-10-06 14:58 | 2 min ago |
|
||||
| 2026-10-06 12:00 | 3 h ago |
|
||||
| 2026-10-05 14:20 | Yesterday, 14:20 |
|
||||
| 2026-10-03 14:20 | 3 Oct 2026, 14:20 |
|
||||
|
||||
Scenario: Home rows, a long sentence is clamped to two lines
|
||||
Given an event on an article whose title has 150 characters
|
||||
Then the sentence is clamped to two lines with the title in semibold and the meta line stays on one line
|
||||
|
||||
Scenario: Home rows, an unknown action and a failed login
|
||||
Given an event with action "article.archive" and an "auth.login_failed" event for "alex@example.com"
|
||||
Then the first row shows "article.archive", the second "Failed login attempt for alex@example.com" with a "Failed" badge and the user-round-x avatar, and nothing throws
|
||||
|
||||
Scenario: Home rows are not interactive
|
||||
Then a click on a row navigates nowhere and opens nothing
|
||||
|
||||
Scenario: Home card, skeleton rows only after 150 ms
|
||||
Given GET /v1/activity?size=5 has not resolved
|
||||
When the user navigates to /home
|
||||
Then nothing is drawn in the card body for the first 150 ms
|
||||
And after 150 ms five skeleton rows are shown and the card is aria-busy="true"
|
||||
When the request resolves 200 with 5 events
|
||||
Then the skeletons are replaced by 5 rows
|
||||
And a response in under 150 ms never shows a skeleton
|
||||
|
||||
Scenario Outline: Home card, error shows a retryable alert that leaves the page alone
|
||||
Given GET /v1/activity?size=5 <failure> and GET /v1/article/ resolves 200 with 6 articles
|
||||
When the user navigates to /home
|
||||
Then the card shows an alert "Couldn't load recent activity" with a "Try again" button
|
||||
And the stat tiles "6" "articles", "4" "online", "2" "drafts", the recent article list and "Connect your website" are shown as in home.feature's Default state
|
||||
When the user activates "Try again"
|
||||
Then GET /v1/activity?size=5 is sent again and, on 200 with events, the rows replace the alert
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| resolves with a 500 response |
|
||||
| resolves with a 403 response |
|
||||
| never reaches the server |
|
||||
|
||||
Scenario Outline: Home card, empty when there are no events yet
|
||||
Given GET /v1/activity?size=5 resolves 200 with items [] and total 0 and the role is "<role>"
|
||||
When the user navigates to /home
|
||||
Then the card shows the history icon, "No activity yet" and "<text>"
|
||||
And "View all" is still shown
|
||||
|
||||
Examples:
|
||||
| role | text |
|
||||
| owner | Actions on your site will appear here. |
|
||||
| editor | Your actions will appear here. |
|
||||
|
||||
Scenario: Home card and article list are independent
|
||||
Given GET /v1/article/ fails with a 500 and GET /v1/activity?size=5 resolves 200 with 5 events
|
||||
Then the articles alert "Couldn't load your articles" and the 5 activity rows are both shown
|
||||
And with GET /v1/article/ resolving [] and GET /v1/activity?size=5 failing, the articles' Empty state and the card's error are both shown
|
||||
|
||||
Scenario: Home layout is two columns from lg and stacked below
|
||||
Given the viewport is lg or wider
|
||||
Then the header and the update banner span the full content width and the grid below them spans the same full width with the article cards on the left and the activity card 420 px wide in the far-right column, 16 px apart, its top aligned with the top of the article cards
|
||||
Given the viewport is below lg
|
||||
Then the card sits above the stat tiles, below the banner, at full width
|
||||
|
||||
Scenario: Home card, "View all" opens the activity page
|
||||
When the user activates "View all"
|
||||
Then the router navigates to /activity
|
||||
|
||||
Scenario: Settings retention is hidden for everyone but the owner
|
||||
Given GET /v1/settings resolves 200 with activity_retention_days 90
|
||||
When an "admin" (or an "editor", or an absent role) navigates to /settings
|
||||
Then no "Retention" card and no "Keep activity for" select is in the page
|
||||
And the Version, Updates and Media cleanup cards are unchanged
|
||||
And GET /v1/settings was requested once
|
||||
|
||||
Scenario: Settings retention, Default with 90 days
|
||||
Given the role is "owner" and GET /v1/settings resolves 200 with activity_retention_days 90, activity_last_cleanup_at 6 Oct 2026 03:00 local, activity_last_cleanup_removed 142 and activity_next_cleanup_at 7 Oct 2026 03:00 local
|
||||
When the owner navigates to /settings
|
||||
Then the third card reads "Retention" and "How long activity is kept."
|
||||
And the select shows "90 days" with the helper "Older events are removed automatically."
|
||||
And the lock alert "Activity logs are append-only" is shown
|
||||
And the lines read "Last cleanup" "6 Oct 2026, 03:00 · 142 events removed" and "Next cleanup" "7 Oct 2026, 03:00"
|
||||
And no "Saved" is shown, no PATCH was sent and GET /v1/settings was requested once
|
||||
|
||||
Scenario: Settings retention, before the first cleanup
|
||||
Given activity_last_cleanup_at is null and activity_next_cleanup_at is set
|
||||
Then "Last cleanup" reads "Never" and "Next cleanup" shows the date
|
||||
|
||||
Scenario: Settings retention, skeleton lines after 150 ms
|
||||
Given GET /v1/settings has not resolved and the role is "owner"
|
||||
When the owner navigates to /settings
|
||||
Then nothing is drawn in the card body for the first 150 ms, then skeleton lines with aria-busy="true"
|
||||
|
||||
Scenario: Settings retention, the settings request fails
|
||||
Given GET /v1/settings fails with a 500
|
||||
Then the card shows "Couldn't reach RenewCMS. Check your connection and try again." with a "Try again" button that re-runs the shared GET /v1/settings
|
||||
|
||||
Scenario Outline: Settings retention, a longer period saves at once
|
||||
Given the saved period is <from> and the owner chooses "<to>"
|
||||
When PATCH /v1/settings resolves 200 with activity_retention_days <value> and the matching activity_next_cleanup_at
|
||||
Then PATCH was sent once with {"activity_retention_days": <value>} and no warning alert is shown
|
||||
And the status reads "Saving…" while in flight and "Saved" with a check afterwards, fading after 2 s
|
||||
And the select shows "<to>" and the "Next cleanup" line shows the returned value
|
||||
|
||||
Examples:
|
||||
| from | to | value |
|
||||
| 90 days | 365 days | 365 |
|
||||
| 30 days | 90 days | 90 |
|
||||
| 90 days | Forever | 0 |
|
||||
|
||||
Scenario: Settings retention, Forever changes the helper and the lines
|
||||
Given the saved period is 90 days and the owner chooses "Forever" and PATCH resolves 200 with activity_retention_days 0, activity_next_cleanup_at null and a last cleanup of 6 Oct 2026 03:00 with 142 removed
|
||||
Then the helper reads "Nothing is removed automatically. The log grows over time."
|
||||
And "Next cleanup" reads "Not scheduled" and "Last cleanup" still reads "6 Oct 2026, 03:00 · 142 events removed"
|
||||
|
||||
Scenario: Settings retention, Forever and never cleaned
|
||||
Given GET /v1/settings resolves 200 with activity_retention_days 0, activity_last_cleanup_at null and activity_next_cleanup_at null
|
||||
Then "Last cleanup" reads "Never" and "Next cleanup" reads "Not scheduled"
|
||||
|
||||
Scenario: Settings retention, shortening asks first
|
||||
Given the saved period is 90 days and activity_next_cleanup_at is 7 Oct 2026 03:00 local
|
||||
When the owner chooses "30 days"
|
||||
Then no PATCH is sent and the select shows "30 days"
|
||||
And a warning alert shows "Events older than 30 days will be removed" and "This happens at the next cleanup on 7 Oct 2026, 03:00. It can't be undone." with "Apply 30 days" and "Cancel"
|
||||
When the owner activates "Apply 30 days" and PATCH resolves 200 with activity_retention_days 30
|
||||
Then PATCH was sent once with {"activity_retention_days": 30}, the alert is gone and "Saved" shows
|
||||
|
||||
Scenario: Settings retention, shortening cancelled
|
||||
Given the warning for 30 days is shown on a saved 90
|
||||
When the owner activates "Cancel"
|
||||
Then the alert is gone, the select reads "90 days" again and no PATCH was ever sent
|
||||
|
||||
Scenario Outline: Settings retention, shortening is relative to the saved period
|
||||
Given the saved period is <saved>
|
||||
When the owner chooses "<chosen>"
|
||||
Then <outcome>
|
||||
|
||||
Examples:
|
||||
| saved | chosen | outcome |
|
||||
| Forever | 365 days | the warning "Events older than 365 days will be removed" shows |
|
||||
| 365 days | 90 days | the warning "Events older than 90 days will be removed" shows |
|
||||
| 90 days | 90 days | nothing happens and no request is sent |
|
||||
| 30 days | Forever | PATCH is sent at once |
|
||||
|
||||
Scenario: Settings retention, choosing a longer period while the warning is open drops it
|
||||
Given the warning for 30 days is shown on a saved 90
|
||||
When the owner chooses "365 days"
|
||||
Then the warning disappears and PATCH is sent once with 365
|
||||
When the owner then chooses "30 days" and again "365 days" before the first request settles or after it
|
||||
Then no stale warning is ever left on screen
|
||||
|
||||
Scenario Outline: Settings retention, save error reverts the control and Try again retries
|
||||
Given the saved period is 90 days and the owner chooses "365 days"
|
||||
When PATCH /v1/settings <failure>
|
||||
Then an error alert shows "Couldn't save the retention period" and "Your previous setting is still in place." with "Try again"
|
||||
And the select shows "90 days" again, the lines are unchanged and no "Saved" appears
|
||||
When the owner activates "Try again" and PATCH resolves 200 with 365
|
||||
Then PATCH was sent a second time with 365 and "Saved" replaces the alert
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| resolves with a 500 response |
|
||||
| resolves with a 400 response |
|
||||
| resolves with a 403 response |
|
||||
| never reaches the server |
|
||||
|
||||
Scenario: Settings retention, Try again after Apply does not ask again
|
||||
Given the warning for 30 days is shown and the owner activates "Apply 30 days"
|
||||
When PATCH resolves 500
|
||||
Then the warning is gone, the error alert is shown and the select reads the saved period
|
||||
When the owner activates "Try again" and PATCH resolves 200 with 30
|
||||
Then PATCH was sent a second time with 30 and no warning reappears
|
||||
|
||||
Scenario: Settings retention, an owner demoted while the page is open
|
||||
Given PATCH /v1/settings resolves 403 and GET /v1/auth/me then resolves with role "admin"
|
||||
Then the error alert is shown and, after the session refresh, the Retention card is no longer rendered
|
||||
|
||||
Scenario: Settings retention, offline disables the controls
|
||||
Given the owner is on /settings and the browser goes offline
|
||||
Then the select, and "Apply" and "Cancel" when shown, are disabled and nothing is sent
|
||||
And the page's offline banner keeps its existing copy
|
||||
|
||||
Scenario: Settings retention, a 401 is global
|
||||
Given GET or PATCH /v1/settings resolves 401
|
||||
Then useApi redirects to /login?redirect=/settings&reason=expired and no card alert is shown
|
||||
|
||||
Scenario: The French interface
|
||||
Given the language is French
|
||||
Then every string of both cards is French and the Home rows use the French sentence templates of activity_screen.feature
|
||||
|
||||
Scenario: Existing behaviour is unchanged
|
||||
Then every scenario of home.feature, settings_page.feature (except its exact-body statement, superseded above) and the Media cleanup scenarios still holds with GET /v1/activity?size=5 mocked and the settings mock widened with the four activity_* fields
|
||||
@@ -0,0 +1,74 @@
|
||||
# QA: Recent activity card on Home and Retention card on Settings
|
||||
|
||||
## Implementation note for coder (informational, not a QA assertion)
|
||||
|
||||
- Backend: add NextCleanupAt (nullable time) to the audit settings entity with a domain method computing the next 03:00 (audit.CleanupHour) strictly after a given time, in that time's location; nil when RetentionDays is audit.ForeverRetentionDays. GetActivityRetentionUseCase and UpdateActivityRetentionUseCase get an injected `now func() time.Time` (wired in api/dependecyInjection.go) and populate it. settingsResponse in api/handlers/settings gains `activity_next_cleanup_at` (`*time.Time`, RFC 3339, null when nil). No logic in the handler, none in the SPA.
|
||||
- Home: HomeView mounts a RecentActivityCard calling GET /v1/activity?size=5 once, reusing ActivityActor, ActivitySentence and lib/activityTime.
|
||||
- Settings: widen WorkspaceSettings with the four activity_* fields, add a PATCH helper to useSettings, render RetentionCard after MediaCleanupCard for session.role === 'owner' only. No second GET /v1/settings.
|
||||
- features/settings_page.feature and its qa.md say the body is exactly {"version"}; this feature supersedes that statement, so update those tests to the new five-key body.
|
||||
|
||||
## Automated, Go (httptest, in-memory fakes, `task test`)
|
||||
|
||||
Build `settings.NewHandler(GetSettingsUseCase, GetActivityRetentionUseCase, UpdateActivityRetentionUseCase)` over a fake audit.SettingsRepository (records saved retention and last cleanup) and a fake audit.Recorder, with a fixed fake clock. Mount on a fresh chi.NewRouter mirroring NewSettingsRouter: GET "/" behind jwtauth.Verifier + Authenticator (test jwtauth.New("HS256", ...)); PATCH "/" additionally behind the owner check using a fake user repository holding an owner, an admin and an editor. Call validator.InitValidator() first. No live server, no SQLite file. Fake type names must be unique across test files.
|
||||
|
||||
- G1. GET table (clock in a +02:00 zone): retention 90 at 10:00 gives next = next day 03:00+02:00; at 02:59:59 gives same day 03:00; at exactly 03:00:00 gives next day 03:00; 30 at 2026-12-31T23:30 gives 2027-01-01T03:00; 365 at 10:00 gives next day; retention 0 gives JSON null (assert the key is present with value null, not absent).
|
||||
- G2. GET body has exactly the five keys (decode into map[string]any, assert the key set); last cleanup 2026-10-06T01:00:00Z and 142 preserved.
|
||||
- G3. GET is 200 for owner, admin and editor tokens; 401 without a cookie.
|
||||
- G4. PATCH owner 90->30: 200, activity_retention_days 30, next cleanup non-null at the next 03:00; the fake repository holds 30; one audit event with params from 90, to 30.
|
||||
- G5. PATCH owner 90->0: 200, next null. PATCH 0->365: next non-null.
|
||||
- G6. PATCH owner 90->90: 200, next non-null, no repository save, no audit event.
|
||||
- G7. Ownership: PATCH as admin and as editor: 403 with "Only the owner can do this."; repository unchanged; no audit event. PATCH without a cookie: 401.
|
||||
- G8. Invalid: {"activity_retention_days": 7}, "30" (string), {}, malformed JSON: each 400 with the apperr.BodyErrorMessage text (plain text via http.Error), repository unchanged.
|
||||
- G9. Use-case level (no HTTP): GetActivityRetention returns NextCleanupAt per G1 rows; UpdateActivityRetention(7) returns an error satisfying errors.Is(err, audit.ErrInvalidRetention) and saves nothing; a repository Get error propagates and the handler answers 500 "Internal server error".
|
||||
- G10. Domain: NextCleanupAt table including a DST-change day in a named zone (for example Europe/Paris, 2026-10-25), asserting it is still 03:00 local on the right date.
|
||||
|
||||
## Automated, SPA (Vitest + Vue Test Utils, `task test:web`)
|
||||
|
||||
Suggested files: web/src/views/__tests__/HomeActivityCard.spec.ts and SettingsRetention.spec.ts. Mock useApi per case; no real backend. Freeze the clock with vi.setSystemTime only where a time label is asserted (these specs are not visual).
|
||||
|
||||
Home (mount HomeView with a resolved session; GET /v1/article/ mocked with the 6-article fixture):
|
||||
|
||||
1. Owner and admin: 5 events, title "Recent activity", "View all" links to /activity; row 1 text with semibold target, "Marta Alves · 2 min ago", avatar "MA"; the activity mock was called once with exactly size=5 and no other parameter; /summary and /export never called.
|
||||
2. Regular user (editor, absent role): "Your recent activity"; meta lines are time only; no actor parameter.
|
||||
3. Marker table over outcome x security (no badge and no shield, Failed badge, shield only, badge only).
|
||||
4. Time label table (2 min ago, 3 h ago, "Yesterday, 14:20", "3 Oct 2026, 14:20") with fixed time; the title attribute holds the full local time.
|
||||
5. Clamp class on a 150-character title; unknown action "article.archive" renders the code; auth.login_failed sentence with Failed badge and user-round-x avatar.
|
||||
6. Rows are inert: clicking one changes no route and opens nothing.
|
||||
7. Skeleton only after 150 ms (fake timers): none before, 5 skeleton rows and aria-busy after, replaced on resolve; a fast response never shows one.
|
||||
8. Error table (500, 403, network): role="alert", title "Couldn't load recent activity", no description, "Try again"; stat tiles, article list and "Connect your website" still rendered; retry sends a second GET and recovers.
|
||||
9. Empty: both copies by role; "View all" still present.
|
||||
10. Independence in both directions (articles 500 + activity 200; articles [] + activity 500).
|
||||
11. "View all" navigates to /activity (test router).
|
||||
12. Layout classes: grid with the lg two-column template and the 420 px column, and no max-width class on the Home wrapper or the grid (the grid spans the full content width); DOM order puts the card first below lg (real pixels are manual).
|
||||
13. Existing home specs (HomeView, HomeUpdateBanner, HomeUpdateReady) keep passing with the activity mock added to the shared mount helper.
|
||||
|
||||
Settings (mount SettingsView, GET /v1/settings mocked with the five-key body):
|
||||
|
||||
14. Hidden for admin, editor and absent role; GET /v1/settings called once.
|
||||
15. Owner Default: header, "90 days", helper, lock alert, "Last cleanup 6 Oct 2026, 03:00 · 142 events removed", "Next cleanup 7 Oct 2026, 03:00" (from activity_next_cleanup_at; the SPA computes nothing); no PATCH; "1 event removed" singular.
|
||||
16. last_cleanup_at null: "Never". Forever with null/null: "Never" and "Not scheduled". Forever with a past cleanup: the real last line and "Not scheduled".
|
||||
17. Skeleton after 150 ms with aria-busy; load error alert and "Try again" re-runs the shared GET.
|
||||
18. Longer periods (90->365, 30->90, 90->Forever): one PATCH with {"activity_retention_days": N}, "Saving…" then "Saved", gone after 2 s (fake timers), no warning; the returned next cleanup replaces the line; a Forever response with next null shows "Not scheduled".
|
||||
19. Shortening: no PATCH, warning copy with the date taken from the loaded activity_next_cleanup_at; Apply sends once; Cancel reverts the select with no PATCH; table Forever->365, 365->90, 90->90 (no-op), 30->Forever (immediate); a longer choice while the warning is open drops it and leaves no stale warning after 30 days then 365 days again.
|
||||
20. Save error x (500, 400, 403, network): alert copy, select reverts, lines unchanged; Try again re-sends the same value without re-confirming; success shows "Saved"; error after Apply also clears the warning; a 403 triggers a session refresh and the card disappears when the role is no longer owner.
|
||||
21. Offline (mock useOnline false): select, Apply and Cancel disabled; nothing sent; page offline banner text unchanged.
|
||||
22. 401 handled globally: no local alert.
|
||||
23. French key parity: every new string has a messages.ts entry.
|
||||
24. Keyboard: the select opens with Enter or Space, arrows and Enter choose, Escape closes; Apply then Cancel reachable in order after the select.
|
||||
25. Existing SettingsView, SettingsMediaCleanup and Settings update specs keep passing with the widened mock body.
|
||||
|
||||
## Visual (task visual:check)
|
||||
|
||||
- Neither card can be pixel-compared (dashed placeholders); no new visual state is added. The card sub-states are not `###` headings in home.md or settings.md, so the tool should not iterate them; confirm on the first run.
|
||||
- Existing Home states and owner-session Settings states must still pass at 10 % with the card present. Every Home setup in web/visual/states.ts needs GET /v1/activity?size=5 mocked (an unmocked /v1 call fails the gate), and every owner Settings setup needs the widened GET /v1/settings body. Layout changes may exceed the gate: measure first, then ask the user for a per-state `exception` (needs approvedBy). Do not add any exception beforehand.
|
||||
- Time-dependent states stay `skip: 'clock-sensitive'`; no Vitest spec freezes the date for a visual claim.
|
||||
|
||||
## Manual verification
|
||||
|
||||
- [ ] Real GET /v1/settings and PATCH /v1/settings against `task dev` with a live SQLite file: five keys, next cleanup at the next 03:00 server time, null after switching to Forever, a timestamp after leaving Forever; as an admin PATCH is 403, as the owner a bad value is 400.
|
||||
- [ ] Browser in a time zone different from the server's: the "Next cleanup" and "Last cleanup" lines both show the user's local time of the same instants; the warning date matches the "Next cleanup" line.
|
||||
- [ ] Real daily cleanup (or a forced run) updates "Last cleanup" and moves "Next cleanup" a day forward.
|
||||
- [ ] Real GET /v1/activity?size=5 as owner, admin and editor (server-side own-event scoping), including a site with only events older than 7 days (reads "No activity yet").
|
||||
- [ ] Home at 1440 and 390 px, light and dark: 420 px column in the far-right of the full content width, 16 px gap, row clamping, "View all" 44 px touch target; the article column fills the remaining width and still reads well.
|
||||
- [ ] Keyboard and focus: Home tab order "New article", article rows, "View all"; Settings select, Apply, Cancel in order and focus back on the select after Cancel.
|
||||
- [ ] Hover, focus rings, the 2 s "Saved" fade and reduced motion.
|
||||
@@ -0,0 +1,693 @@
|
||||
Feature: Activity screen, details slide-over and My activity
|
||||
|
||||
As a verified RenewCMS user
|
||||
I want /activity to read as a plain-language timeline of who did what and when, with filters,
|
||||
a summary strip, CSV export and a details panel for each event
|
||||
So that an owner can audit the site without reading a log, and any other role sees its own history
|
||||
|
||||
Background:
|
||||
Given /activity is a verified route (meta.auth "verified", meta.title "Activity") rendered as
|
||||
ActivityView (views/ActivityView.vue, the "ActivityPage" of docs/design/components.md) inside
|
||||
DashboardShell, per docs/design/routes.md and docs/design/screens/activity.md
|
||||
And the activity API already exists (features/activity-log-backend.feature and
|
||||
features/activity-log-producers.feature) and this slice wires the SPA to it unchanged, with
|
||||
no Go change
|
||||
And the Home card and the Settings "Retention" card of the same board are not in this slice
|
||||
And where docs/design prose and the board frame ActivityFrame.dc.html differ, the frame is
|
||||
followed
|
||||
And the views read the session role from GET /v1/auth/me: "owner" and "admin" are the full
|
||||
view; any other or absent value is the regular-user view ("My activity"), which no real
|
||||
account can reach today and is covered by Vitest and one visual state only
|
||||
And a full view loads, in parallel, GET /v1/activity?range=7d&page=1&size=25 and GET
|
||||
/v1/activity/summary?range=7d; a regular-user view loads only GET /v1/activity with the same
|
||||
query and never calls /summary or /export, and never sends an actor parameter
|
||||
And the list query always sends range, page and size explicitly, and adds q, actor, category,
|
||||
outcome, security, from and to only when set (outcome "all" is not sent, from and to only
|
||||
with range=custom); the summary query sends only range, from and to; the export query sends
|
||||
the list query without page and size
|
||||
And filters and the page live in component state, not in the URL, and reset when the user
|
||||
leaves /activity
|
||||
And useApi's global handling covers 401 and the unverified 403
|
||||
(features/api_client_global_error_handling.feature); this screen maps every other failure
|
||||
And DashboardShell's navigation gains "Activity" (icon i-lucide-history, linking to /activity)
|
||||
between "Users" and "Integration", in the sidebar and in the mobile drawer, so it lists Home,
|
||||
Articles, Media, Users, Activity, Integration, Settings in that order, for every verified
|
||||
user; "Activity" has aria-current="page" on /activity; the specs that list the destinations
|
||||
are amended accordingly (named in the QA file)
|
||||
And the PageHeader breadcrumb and the mobile title read the page title: "Activity", or
|
||||
"My activity" for the regular-user view
|
||||
And the page padding is 24 px on desktop and 16 px on mobile with a 16 px gap between the
|
||||
header, the strip, the filter bar, the chips, the table and the pager
|
||||
And the header is the title "Activity" (regular user: "My activity") with the subtitle "Who
|
||||
did what, and when, across your site." (regular user: "Everything you've done on this
|
||||
site."), and, in the full view except Forbidden, an outline button with icon download and
|
||||
the label "Export CSV" at the right, aligned to the bottom of the title block
|
||||
And sentences are composed in the SPA from the event's action code, its outcome, its params
|
||||
and its target name through the existing i18n (English keys, French in messages.ts), never
|
||||
stored as text; the target name is user content, is inserted untranslated as a semibold
|
||||
segment, and is the last slot of every template, so a missing target name drops the slot
|
||||
with its leading space and colon
|
||||
And the success sentences are, in English and French (the actor sits in its own column, so
|
||||
sentences start with the verb; {0} is the target name):
|
||||
| action | English | French |
|
||||
| article.create | Created the article {0} | Article créé : {0} |
|
||||
| article.edit | Edited the article {0} | Article modifié : {0} |
|
||||
| article.publish | Published the article {0} | Article publié : {0} |
|
||||
| article.unpublish | Unpublished the article {0} | Article dépublié : {0} |
|
||||
| article.delete | Deleted the article {0} | Article supprimé : {0} |
|
||||
| media.upload | Uploaded the image {0} | Image téléversée : {0} |
|
||||
| media.rename | Renamed the image {0} | Image renommée : {0} |
|
||||
| media.delete | Deleted the image {0} | Image supprimée : {0} |
|
||||
| media.merge | Merged duplicates into the image {0} | Doublons fusionnés dans l'image {0} |
|
||||
| media.purge | Purged duplicate images: {0} merged, {1} articles updated | Doublons purgés : {0} fusionnés, {1} articles mis à jour |
|
||||
| system.media_purge | Ran the scheduled duplicate purge: {0} merged, {1} articles updated | Purge automatique des doublons : {0} fusionnés, {1} articles mis à jour |
|
||||
| user.register | Registered the account {0} | Compte créé : {0} |
|
||||
| user.verify | Verified the account {0} | Compte vérifié : {0} |
|
||||
| user.update_profile | Updated the profile of {0} | Profil mis à jour : {0} |
|
||||
| invite.create | Invited {0} | Invitation envoyée à {0} |
|
||||
| invite.cancel | Cancelled the invite for {0} | Invitation annulée : {0} |
|
||||
| invite.renew | Renewed the invite for {0} | Invitation renouvelée : {0} |
|
||||
| invite.accept | Accepted the invite for {0} | Invitation acceptée : {0} |
|
||||
| api_key.create | Created API key {0} | Clé d'API créée : {0} |
|
||||
| api_key.revoke | Revoked API key {0} | Clé d'API révoquée : {0} |
|
||||
| auth.login | Logged in | Connexion |
|
||||
| auth.logout | Logged out | Déconnexion |
|
||||
| auth.password_reset_requested | Requested a password reset | Réinitialisation du mot de passe demandée |
|
||||
| auth.password_reset_completed | Reset the password | Mot de passe réinitialisé |
|
||||
| system.update_checked | Checked for updates | Recherche de mises à jour |
|
||||
| system.update_downloaded | Downloaded the update {0} | Mise à jour téléchargée : {0} |
|
||||
| system.restart_requested (kind restart) | Requested a restart | Redémarrage demandé |
|
||||
| system.restart_requested (kind update) | Restarted to apply the update {0} | Redémarrage pour appliquer la mise à jour {0} |
|
||||
| system.activity_retention_changed | Changed the activity retention from {0} to {1} | Durée de conservation de l'activité modifiée : {0} → {1} |
|
||||
| system.activity_cleanup | Removed {0} old events from the activity log | {0} anciens événements supprimés du journal d'activité |
|
||||
And the failed sentences, used when outcome is "failed", are:
|
||||
| action | English | French |
|
||||
| article.create | Failed to create the article {0} | Échec de la création de l'article {0} |
|
||||
| article.edit | Failed to edit the article {0} | Échec de la modification de l'article {0} |
|
||||
| article.publish | Failed to publish the article {0} | Échec de la publication de l'article {0} |
|
||||
| article.unpublish | Failed to unpublish the article {0} | Échec de la dépublication de l'article {0} |
|
||||
| article.delete | Failed to delete the article {0} | Échec de la suppression de l'article {0} |
|
||||
| media.upload | Failed to upload the image {0} | Échec du téléversement de l'image {0} |
|
||||
| media.rename | Failed to rename the image {0} | Échec du renommage de l'image {0} |
|
||||
| media.delete | Failed to delete the image {0} | Échec de la suppression de l'image {0} |
|
||||
| media.merge | Failed to merge duplicates into the image {0} | Échec de la fusion des doublons dans l'image {0} |
|
||||
| media.purge | Failed to purge duplicate images | Échec de la purge des doublons |
|
||||
| system.media_purge | Failed to run the scheduled duplicate purge | Échec de la purge automatique des doublons |
|
||||
| user.register | Failed to register the account {0} | Échec de la création du compte {0} |
|
||||
| user.verify | Failed to verify the account {0} | Échec de la vérification du compte {0} |
|
||||
| user.update_profile | Failed to update the profile of {0} | Échec de la mise à jour du profil de {0} |
|
||||
| invite.create | Failed to invite {0} | Échec de l'invitation de {0} |
|
||||
| invite.cancel | Failed to cancel the invite for {0} | Échec de l'annulation de l'invitation de {0} |
|
||||
| invite.renew | Failed to renew the invite for {0} | Échec du renouvellement de l'invitation de {0} |
|
||||
| invite.accept | Failed to accept the invite for {0} | Échec de l'acceptation de l'invitation de {0} |
|
||||
| api_key.create | Failed to create API key {0} | Échec de la création de la clé d'API {0} |
|
||||
| api_key.revoke | Failed to revoke API key {0} | Échec de la révocation de la clé d'API {0} |
|
||||
| auth.login_failed | Failed login attempt for {0} | Échec de connexion pour {0} |
|
||||
| system.update_checked | Failed to check for updates | Échec de la recherche de mises à jour |
|
||||
| system.update_downloaded | Failed to download the update {0} | Échec du téléchargement de la mise à jour {0} |
|
||||
| system.restart_requested | Failed to restart | Échec du redémarrage |
|
||||
And an action whose failed sentence is not listed (for example auth.login) renders its success
|
||||
sentence with the Failed badge; an action code that is not in the catalogue renders the raw
|
||||
code (for example "article.archive") and never throws
|
||||
And for auth.login_failed the slot {0} is the actor's name (the attempted username, since the
|
||||
event has no target), while the Actor column reads "Not signed in"
|
||||
And counts in params are shown with the locale's number format; "{0} old events" and "{1}
|
||||
articles updated" use the singular form for 1 ("1 old event", "1 article updated"); a
|
||||
media.purge or system.media_purge event with params.failed_groups appends ", {2} groups
|
||||
failed" ("1 group failed") in English and ", {2} groupes en échec" in French;
|
||||
system.activity_retention_changed shows days as "{n} days" and 0 as "Forever" ("{n} jours",
|
||||
"Toujours")
|
||||
And the category icons are: articles file-text, media image, users users, api_keys key-round,
|
||||
auth shield-check, system server-cog; the category labels are Articles, Media, Users and
|
||||
invites, API keys, Authentication, System
|
||||
And the Actor cell is the actor's name with: a UAvatar of initials (first letters of the first
|
||||
two words, upper case) for type "user"; a key-round icon avatar and an "API key" badge for
|
||||
"api_key"; a cog icon avatar and a "System" badge for "system"; a user-round-x icon avatar
|
||||
and the text "Not signed in" for "anonymous"
|
||||
And the Target cell is "—" (muted) when target is null; when target.exists it is the name as an
|
||||
underlined link with an arrow-up-right icon, plus the target type as a muted second line
|
||||
(Article, Image, User, Invite, API key, Release); when it does not exist the name is struck
|
||||
through, muted, with a "Deleted" badge (icon trash-2) and the type line; the link goes to
|
||||
/article/{id}/edit for article, /media for image, /users for user and invite,
|
||||
/integration/api-keys for api_key, and a target type with no page (release) is plain text
|
||||
And the Outcome cell is a badge with icon and word, never colour alone: "Succeeded" (check,
|
||||
bordered) or "Failed" (circle-x, --rc-error-soft background, --ui-error text)
|
||||
And a row whose event has security true shows a shield-alert icon in --ui-warning after the
|
||||
sentence and a 2 px inset --ui-warning edge on its left side; on mobile it also shows a
|
||||
"Security" badge (shield-alert, --rc-warning-soft, --ui-warning)
|
||||
And the table (md and up) has the columns When, Actor, Action, Target, Outcome in a grid
|
||||
96px 210px minmax(0,1fr) 230px 120px (regular user: When, Action, Target, Outcome in 96px
|
||||
minmax(0,1fr) 230px 120px), a 36 px header on --ui-bg-elevated with an arrow-down icon on
|
||||
When, day separator rows of 32 px on --ui-bg-muted with the label in 12 px semibold, and
|
||||
rows at least 52 px high with a top border; a selected row (details open) and a hovered row
|
||||
use --ui-bg-elevated
|
||||
And rows are grouped by the user's local calendar day under a separator labelled "Today",
|
||||
"Yesterday" or the date as "3 Oct 2026" (French "3 oct. 2026"), in the order the API
|
||||
returns them (newest first); the When cell shows the time as drawn, relative within today
|
||||
("2 min ago", "29 min ago", "1 h ago") and the local clock time "HH:mm" on earlier days,
|
||||
and carries the full local time "3 Oct 2026, 14:20:05" as its title attribute
|
||||
And below md the table is replaced by a stacked list of cards (ActivityCardList) with the same
|
||||
separators: a first line with the actor (avatar, name, badge; hidden for the regular user)
|
||||
and the time at the right, the category icon and the sentence (15 px, up to 3 lines), then a
|
||||
line of badges: the Outcome badge, "Security" when flagged, and "Target deleted" when the
|
||||
target is gone; each card is at least 44 px high as a touch target
|
||||
And rows and cards are focusable, open the details on click and on Enter, and a click on the
|
||||
target link navigates to the target without opening the details
|
||||
And the summary strip (ActivitySummaryStrip, full view only) has four cards that are real
|
||||
buttons: "Total actions", "Active people", "Failed actions", "Security events", each with
|
||||
the number (locale-formatted), a sub-line, and a seven-bar sparkline of seven div bars,
|
||||
4 px wide, 2 px apart, oldest at the left, bar height round(value / max(series, 1) * H)
|
||||
with a 2 px minimum and H of 20 px on desktop and 16 px on mobile, drawn from
|
||||
series.total, series.active, series.failed and series.security
|
||||
And on desktop the strip is a 4-column grid with a 12 px gap; below md it is, as drawn in
|
||||
ActivityFrame.dc.html, a single row of 156 px cards with an 8 px gap that is clipped at the
|
||||
page edge
|
||||
And the Total sub-line is "{pct}% vs previous 7 days" with icon trending-up when total is at
|
||||
least previous_total and trending-down otherwise, pct being the rounded absolute change
|
||||
against previous_total; for the ranges Today, 30 days and Custom the words read "vs previous
|
||||
day", "vs previous 30 days" and "vs previous period"; when previous_total is 0 the sub-line
|
||||
is "No earlier data" and when the two totals are equal it is "No change", both without an
|
||||
icon (French "Aucune donnée antérieure", "Aucun changement")
|
||||
And the Active people number is active_people.users plus active_people.api_keys with the
|
||||
sub-line "{users} people, {api_keys} API keys" ("1 person", "1 API key")
|
||||
And the Failed sub-line is "{pct}% of all actions" (one decimal, "0.5%") with icon circle-x
|
||||
and the --rc-error-soft background and --ui-error number
|
||||
And the Security sub-line is "{n} flagged" (French "{n} signalés", "1 signalé"), n being
|
||||
summary.security, with icon shield-alert and the --rc-warning-soft background and
|
||||
--ui-warning number
|
||||
And a Failed or Security count of 0 reads "0" with "Nothing failed" or "Nothing to flag" and
|
||||
icon circle-check in --ui-success, drops the emphasis fill and draws its bars in
|
||||
--ui-border-accented; with total 0 Total and Active people read "0" with "No data yet"
|
||||
And the strip follows only the date range; q, person, category, outcome and security never
|
||||
change it, and it is not requested again when they change
|
||||
And when the summary request fails with any status or never reaches the server, the strip is
|
||||
not rendered and nothing is shown in its place
|
||||
And the filter bar (ActivityFilterBar) has: a UInput (icon search, clearable, placeholder
|
||||
"Search activity", 240 px) that applies 300 ms after the last keystroke or at once on Enter;
|
||||
a Person USelectMenu (icon user-round, "All people", 168 px, full view only) with the groups
|
||||
users, API keys and "System"; a Category USelectMenu (icon layout-list, "All categories",
|
||||
176 px); an Outcome button group "All / Succeeded / Failed" (soft is the selected one,
|
||||
outline the others); and the date presets "Today / 7 days / 30 days / Custom" (Custom has
|
||||
icon calendar and opens a date-range popover) at the right; controls are 32 px high
|
||||
And the Person options come from GET /v1/user/ (accepted users, shown by display name or
|
||||
username) and GET /v1/api-key/, requested once, the first time the Person menu opens, so a
|
||||
page load makes no other call than the two above
|
||||
And choosing a Person sends actor=user:{id}, actor=key:{id} or actor=system; a Category sends
|
||||
category=articles|media|users|api_keys|auth|system; Outcome Succeeded sends outcome=success
|
||||
and Failed outcome=failed; Today, 7 days and 30 days send range=today|7d|30d; Custom sends
|
||||
range=custom&from=YYYY-MM-DD&to=YYYY-MM-DD once both dates are chosen; any filter change
|
||||
resets the page to 1 and sends a new list request, and the page size is kept
|
||||
And the active filter chips (UBadge subtle with a trailing ghost x button) read "Search:
|
||||
spring", "Person: Marta Alves", "Category: Authentication", "Outcome: Failed", "Security
|
||||
events", "Dates: 30 days" or "Dates: 1 – 30 Sep 2026" (same month "1 – 30 Sep 2026", across
|
||||
months "28 Sep – 3 Oct 2026"), followed by a link button "Clear all"; the default range 7
|
||||
days is never a chip; removing a chip resets that filter; "Clear all" resets every filter to
|
||||
the default (range 7d)
|
||||
And below md the bar is a search field and a "Filters" button (icon sliders-horizontal) with a
|
||||
count badge (the number of chips, hidden at 0); it opens a bottom sheet titled "Filters"
|
||||
with Person (full view only), Category, Outcome, Dates (two date fields when Custom is
|
||||
chosen) and a footer "Clear all" (disabled at 0 filters) and "Show {total} results" ("Show 1
|
||||
result"); the sheet applies each change at once, so the footer count is the current total,
|
||||
and "Show … results" closes the sheet
|
||||
And the pager (full width under the table) reads "Showing {from}–{to} of {total}" with
|
||||
locale-formatted numbers, a UPagination (previous, 1, 2, 3, …, last, next; previous
|
||||
disabled on page 1), and "Rows per page" with a select of 25, 50 and 100; changing the size
|
||||
resets the page to 1; below md it reads "Page {page} of {pages}" above "{from}–{to} of
|
||||
{total}", with previous and next buttons and the size select
|
||||
And while a list request is in flight for longer than 150 ms, 9 skeleton rows (desktop) or 5
|
||||
skeleton cards (below md) replace the rows and the pager is hidden; the strip shows 4
|
||||
skeleton cards while the summary request is in flight for longer than 150 ms; nothing is
|
||||
drawn in their place for the first 150 ms
|
||||
And the list is "empty" when total is 0: with no chip it is "No activity yet" (icon history,
|
||||
"Actions on articles, media, users and API keys will appear here.", regular user: "Your
|
||||
actions will appear here once you start working on the site."), with at least one chip it is
|
||||
"No activity matches these filters" (icon search-x, action "Clear filters")
|
||||
And the error, empty and forbidden panels are drawn as in ActivityFrame.dc.html: "Couldn't
|
||||
load activity" is an error alert with icon circle-x, the text and an outline "Try again"
|
||||
button, and "You can't view this activity" (no trailing period) uses icon lock and the
|
||||
action "Back to home"
|
||||
And "Export CSV" is disabled in "No activity yet" and while the list is in the Error state,
|
||||
and enabled otherwise
|
||||
And ActivityDetailsPanel is a USlideover: 480 px wide from the right on desktop, an 88 %-high
|
||||
bottom sheet with a 36×4 px handle below md; its header reads "Activity details" with a
|
||||
close button (and "{position} of {total}" below md); it opens from a row or card, closes
|
||||
with Escape, the close button or the scrim, and focus returns to the row that opened it
|
||||
And the panel body has, in this order: the full sentence (18 px semibold, target in semibold)
|
||||
with the Outcome badge, a "Security" badge when flagged and the category icon and label; an
|
||||
error alert "Why it failed" with failure_reason, only when outcome is "failed" and the
|
||||
reason is present; the grid When, Actor, Source, IP address, Browser; a Target section;
|
||||
a Changes section
|
||||
And When shows the local time as "6 Oct 2026, 10:42:18 (your time)" and under it, muted, the
|
||||
UTC time as "6 Oct 2026, 10:42:18 UTC"; Actor is the avatar, the name and the same badges
|
||||
as the table; Source is "Web app" for web, "API key" for api_key and "System task" for
|
||||
system; IP address (IBM Plex Mono 12 px) and Browser read "Not applicable" (muted) when ip
|
||||
or user_agent is null
|
||||
And the Target section shows the name (a link with arrow-up-right when it exists, otherwise
|
||||
struck through with a "Deleted" badge and the line "This item was deleted. Its name is kept
|
||||
for reference."), and the line "{type} · {id}"; it is absent when target is null
|
||||
And the Changes section (ActivityDiff) is absent when changes is empty; each change is a row
|
||||
headed by its field label: a "text" change shows Before and After boxes (side by side with
|
||||
an arrow-right on desktop, stacked with an arrow-down below md), a "body" change shows only
|
||||
the line "Body edited (+312 characters)" with icon file-pen-line ("-48", "+1 character")
|
||||
and never any text
|
||||
And the field labels are title "Title", online "Publish state", body "Body", filename "File
|
||||
name", display_name "Display name" (French "Titre", "État de publication", "Corps", "Nom du
|
||||
fichier", "Nom d'affichage"), an unknown field shows its raw code, and for online the
|
||||
values "false" and "true" read "Draft" and "Published" ("Brouillon", "Publié")
|
||||
And a Before or After value taller than two lines is clamped to two lines and a "Show more"
|
||||
link button appears under that row; it toggles to "Show less"; shorter values show no toggle
|
||||
And the panel footer has "Previous event" (icon chevron-up) and "Next event" (icon
|
||||
chevron-down) buttons that move through the current filtered list, and on desktop the
|
||||
muted text "Event {position} of {total}" with position = (page − 1) × size + index + 1;
|
||||
below md the two buttons are full width and there is no footer text
|
||||
And when Previous or Next crosses a page boundary the list page follows, and a failed request
|
||||
for the neighbour page keeps the panel on the current event with no message
|
||||
|
||||
Scenario: Navigation — "Activity" sits between Users and Integration
|
||||
Given the user is on /activity
|
||||
When DashboardShell mounts
|
||||
Then the sidebar and the mobile drawer list Home, Articles, Media, Users, Activity,
|
||||
Integration, Settings in that order
|
||||
And "Activity" has the history icon, links to /activity and has aria-current="page"
|
||||
And the breadcrumb reads "Activity" (mobile title "Activity")
|
||||
|
||||
Scenario: Default — an owner sees the strip, the filter bar and a day-grouped table
|
||||
Given GET /v1/activity resolves 200 with 25 items and total 1284, and GET /v1/activity/summary
|
||||
resolves 200 with total 1284, previous_total 1146, active_people {users 7, api_keys 2},
|
||||
failed 6, security 11 and seven-day series, and the session role is "owner"
|
||||
When the user navigates to /activity
|
||||
Then the header shows "Activity", "Who did what, and when, across your site." and an enabled
|
||||
"Export CSV"
|
||||
And the strip reads "1,284" "12% vs previous 7 days" with trending-up; "9" "7 people, 2 API
|
||||
keys"; "6" "0.5% of all actions"; "11" "11 flagged"
|
||||
And the filter bar shows "Search activity", "All people", "All categories", All selected in
|
||||
the Outcome group, and 7 days selected, with no chip
|
||||
And the table rows follow the API order under day separators
|
||||
And the pager reads "Showing 1–25 of 1,284" and "Rows per page" 25
|
||||
And GET /v1/activity was requested once with range=7d, page=1, size=25 and no other
|
||||
parameter, and GET /v1/activity/summary once with range=7d
|
||||
|
||||
Scenario Outline: Rows — the Actor cell and the sentence follow the event
|
||||
Given a row for an event with actor type "<type>" named "<name>", action "<action>", outcome
|
||||
"<outcome>" and security <security>
|
||||
Then the Actor cell shows <actor>
|
||||
And the Action cell shows "<sentence>" with the target name in semibold, and <marker>
|
||||
And the Outcome cell shows "<badge>"
|
||||
|
||||
Examples:
|
||||
| type | name | action | outcome | security | actor | sentence | marker | badge |
|
||||
| user | Marta Alves | article.publish | success | false | an avatar "MA" and "Marta Alves" | Published the article Spring release | no shield | Succeeded |
|
||||
| api_key | Website sync | media.upload | success | false | a key icon, "Website sync", "API key" | Uploaded the image north-wall.jpg | no shield | Succeeded |
|
||||
| system | System | system.media_purge | success | false | a cog icon, "System", "System" | Ran the scheduled duplicate purge: 3 merged, 5 articles updated | no shield | Succeeded |
|
||||
| anonymous | alex@example.com | auth.login_failed | failed | true | a user-round-x icon, "Not signed in" | Failed login attempt for alex@example.com | a shield-alert marker | Failed |
|
||||
| user | Inès Duarte | article.publish | failed | false | an avatar "ID" and "Inès Duarte" | Failed to publish the article Spring release | no shield | Failed |
|
||||
| user | Jonas Weber | api_key.revoke | success | true | an avatar "JW" and "Jonas Weber" | Revoked API key Mobile app | a shield-alert marker | Succeeded |
|
||||
|
||||
Scenario: Rows — a deleted target is struck through, a living one is a link
|
||||
Given an event of target {"type": "image", "id": "9", "name": "old-banner.png", "exists": false}
|
||||
and an event of target {"type": "article", "id": "8", "name": "Spring release", "exists": true}
|
||||
Then the first Target cell shows "old-banner.png" struck through with a "Deleted" badge and
|
||||
"Image"
|
||||
And the second Target cell shows "Spring release" as a link to /article/8/edit and "Article"
|
||||
And clicking that link navigates to /article/8/edit and does not open the details
|
||||
|
||||
Scenario: Rows — an event with no target shows a dash
|
||||
Given an event whose target is null
|
||||
Then its Target cell shows a muted "—"
|
||||
|
||||
Scenario: Rows — an unknown action code renders the code
|
||||
Given an event with action "article.archive"
|
||||
Then its Action cell shows "article.archive" and the row still opens the details
|
||||
|
||||
Scenario Outline: Sentences — English and French come from the same code and params
|
||||
Given an event with action "<action>", outcome "<outcome>", params <params> and target
|
||||
"<target>"
|
||||
When the language is <language>
|
||||
Then the sentence reads "<sentence>" with "<target>" untranslated
|
||||
|
||||
Examples:
|
||||
| action | outcome | params | target | language | sentence |
|
||||
| article.publish | success | {} | Spring release | English | Published the article Spring release |
|
||||
| article.publish | success | {} | Spring release | French | Article publié : Spring release |
|
||||
| article.publish | failed | {} | Spring release | French | Échec de la publication de l'article Spring release |
|
||||
| media.purge | success | {"merged": 3, "articles_updated": 5} | | English | Purged duplicate images: 3 merged, 5 articles updated |
|
||||
| media.purge | success | {"merged": 3, "articles_updated": 5, "failed_groups": 1} | | English | Purged duplicate images: 3 merged, 5 articles updated, 1 group failed |
|
||||
| system.activity_cleanup | success | {"removed": 1} | | English | Removed 1 old event from the activity log |
|
||||
| system.activity_retention_changed | success | {"from": 90, "to": 0} | | English | Changed the activity retention from 90 days to Forever |
|
||||
| system.restart_requested | success | {"kind": "update", "tag": "v1.4.0"} | v1.4.0 | English | Restarted to apply the update v1.4.0 |
|
||||
| media.upload | failed | {} | | English | Failed to upload the image |
|
||||
|
||||
Scenario: Loading — skeletons after 150 ms while both requests are in flight
|
||||
Given GET /v1/activity and GET /v1/activity/summary have not resolved
|
||||
When the user navigates to /activity
|
||||
Then the header, the filter bar and an enabled "Export CSV" are drawn at once
|
||||
And nothing is drawn in place of the strip and the table for the first 150 ms
|
||||
And after 150 ms 4 skeleton cards replace the strip and 9 skeleton rows (5 cards below md)
|
||||
replace the table, the pager is hidden and the table container is aria-busy="true"
|
||||
When both requests resolve 200 with the Default data
|
||||
Then the skeletons are replaced by the Default state's strip, rows and pager
|
||||
|
||||
Scenario: Zero-value summary strip — a quiet period shows a calm 0
|
||||
Given GET /v1/activity/summary resolves 200 with total 214, previous_total 223, active_people
|
||||
{users 4, api_keys 1}, failed 0, security 0 and series of zeros for failed and security
|
||||
And GET /v1/activity resolves 200 with 25 items
|
||||
When the user navigates to /activity
|
||||
Then the Total card reads "214" "4% vs previous 7 days" with trending-down
|
||||
And the Active people card reads "5" "4 people, 1 API key"
|
||||
And the Failed card reads "0" "Nothing failed" with circle-check and no error fill
|
||||
And the Security card reads "0" "Nothing to flag" with circle-check and no warning fill
|
||||
And their bars are 2 px high
|
||||
|
||||
Scenario Outline: The Total sub-line when there is nothing to compare
|
||||
Given GET /v1/activity/summary resolves 200 with total <total> and previous_total <previous>
|
||||
When the user navigates to /activity
|
||||
Then the Total card reads "<total>" and "<subline>" without a trend icon
|
||||
|
||||
Examples:
|
||||
| total | previous | subline |
|
||||
| 40 | 0 | No earlier data |
|
||||
| 40 | 40 | No change |
|
||||
|
||||
Scenario: Empty, no activity yet — a new site
|
||||
Given GET /v1/activity resolves 200 with items [] and total 0, and GET /v1/activity/summary
|
||||
resolves 200 with every number 0
|
||||
And no filter chip is shown
|
||||
When the user navigates to /activity
|
||||
Then the strip reads "0" "No data yet" for Total and Active people, "0" "Nothing failed" and
|
||||
"0" "Nothing to flag"
|
||||
And an empty panel with icon history shows "No activity yet" and "Actions on articles,
|
||||
media, users and API keys will appear here."
|
||||
And "Export CSV" is disabled and no table header or pager is shown
|
||||
|
||||
Scenario: Empty, filters match nothing — the panel offers Clear filters
|
||||
Given the Default state has loaded
|
||||
When the user types "sitemap" in Search, chooses Category "Media" and Outcome "Failed", and
|
||||
GET /v1/activity resolves 200 with items [] and total 0
|
||||
Then the chips read "Search: sitemap", "Category: Media", "Outcome: Failed" and "Clear all"
|
||||
And an empty panel with icon search-x shows "No activity matches these filters" and "Try a
|
||||
different search or a wider date range." with the action "Clear filters"
|
||||
And "Export CSV" stays enabled and the strip is unchanged
|
||||
When the user activates "Clear filters"
|
||||
Then every filter is reset, GET /v1/activity is sent with range=7d, page=1, size=25 only and
|
||||
the rows come back
|
||||
|
||||
Scenario Outline: Error with retry — a 500, a 400 or a network failure replaces the table
|
||||
Given GET /v1/activity <failure> and GET /v1/activity/summary resolves 200
|
||||
When the user navigates to /activity
|
||||
Then the strip and the filter bar are shown
|
||||
And an error alert shows "Couldn't load activity" and "Check your connection and try again."
|
||||
with the action "Try again"
|
||||
And "Export CSV" is disabled and no table or pager is shown
|
||||
When the user activates "Try again"
|
||||
Then the Loading state shows for the list and GET /v1/activity is sent again with the same
|
||||
query
|
||||
When it then resolves 200 with the Default data
|
||||
Then the Default rows replace the alert
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| resolves with a 500 response |
|
||||
| resolves with a 400 response |
|
||||
| never reaches the server |
|
||||
|
||||
Scenario Outline: The summary alone fails — the strip is not drawn and the list still works
|
||||
Given GET /v1/activity resolves 200 with the Default items and GET /v1/activity/summary
|
||||
<failure>
|
||||
When the user navigates to /activity
|
||||
Then the strip is not rendered, with no error shown for it
|
||||
And the filter bar, the rows and the pager are shown as in Default
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| resolves with a 500 response |
|
||||
| resolves with a 403 response |
|
||||
| never reaches the server |
|
||||
|
||||
Scenario: Forbidden (403) — the page itself is refused
|
||||
Given GET /v1/activity resolves 403 and GET /v1/auth/me resolves 200 with a verified user
|
||||
When the user navigates to /activity
|
||||
Then the header shows "Activity" and no "Export CSV"
|
||||
And no strip, filter bar, chips, table or pager is shown
|
||||
And an empty panel with icon lock shows "You can't view this activity" and "Your role
|
||||
doesn't include this page. Ask an owner or admin if you need access." with the action "Back
|
||||
to home"
|
||||
When the user activates "Back to home"
|
||||
Then the router navigates to /home
|
||||
|
||||
Scenario: An unverified 403 and a 401 are handled globally
|
||||
Given GET /v1/activity resolves 401 (or 403 for an unverified session)
|
||||
When the user navigates to /activity
|
||||
Then useApi redirects to /login?redirect=/activity&reason=expired (or to /register/pending)
|
||||
And no Forbidden or Error panel is shown
|
||||
|
||||
Scenario Outline: Strip cards — each card applies its filter
|
||||
Given the Default state has loaded with the 7 days range
|
||||
When the user activates the "<card>" card
|
||||
Then <effect>
|
||||
And <state>
|
||||
|
||||
Examples:
|
||||
| card | effect | state |
|
||||
| Total actions | every filter is cleared and GET /v1/activity is sent with range=7d | no card is marked active |
|
||||
| Active people | nothing changes and no request is sent | no card is marked active |
|
||||
| Failed actions | GET /v1/activity is sent with outcome=failed and the page 1 | the chip "Outcome: Failed" and "Clear all" appear and the card has aria-pressed="true" with a --ui-primary border |
|
||||
| Security events | GET /v1/activity is sent with security=true and the page 1 | the chip "Security events" and "Clear all" appear and the card has aria-pressed="true" with a --ui-primary border |
|
||||
|
||||
Scenario: Filtered, card applied — the Failed card on top of other filters
|
||||
Given the user has chosen Category "Authentication" and 30 days
|
||||
When the user activates the "Failed actions" card and GET /v1/activity resolves 200 with 1
|
||||
item and total 6
|
||||
Then the chips read "Category: Authentication", "Outcome: Failed", "Dates: 30 days" and
|
||||
"Clear all"
|
||||
And GET /v1/activity/summary was requested for range=30d and is not requested again
|
||||
And the pager reads "Showing 1–6 of 6"
|
||||
And below md the "Filters" button shows the count badge "3"
|
||||
|
||||
Scenario Outline: Filter bar — each control sends its query parameter and resets the page
|
||||
Given the user is on page 3 of the Default list
|
||||
When <action>
|
||||
Then GET /v1/activity is sent with <query>, page=1 and size=25
|
||||
|
||||
Examples:
|
||||
| action | query |
|
||||
| the user types "spring" and waits 300 ms | q=spring and range=7d |
|
||||
| the user types "spring" and presses Enter at once | q=spring and range=7d |
|
||||
| the user chooses Person "Marta Alves" (user 3) | actor=user:3 and range=7d |
|
||||
| the user chooses Person "Website sync" (API key 7) | actor=key:7 and range=7d |
|
||||
| the user chooses Person "System" | actor=system and range=7d |
|
||||
| the user chooses Category "Users and invites" | category=users and range=7d |
|
||||
| the user chooses Outcome "Succeeded" | outcome=success and range=7d |
|
||||
| the user chooses "Today" | range=today |
|
||||
| the user chooses "30 days" | range=30d |
|
||||
|
||||
Scenario: Filter bar — Custom opens a date-range popover and applies on the second date
|
||||
Given the Default state has loaded
|
||||
When the user chooses "Custom" and picks 1 Sep 2026 then 30 Sep 2026 in the popover
|
||||
Then GET /v1/activity and GET /v1/activity/summary are sent with range=custom, from=2026-09-01
|
||||
and to=2026-09-30
|
||||
And the chip reads "Dates: 1 – 30 Sep 2026"
|
||||
And no request is sent after the first date alone
|
||||
|
||||
Scenario: Chips — removing one resets only that filter, Clear all resets everything
|
||||
Given the chips "Search: spring", "Outcome: Failed" and "Dates: 30 days" are shown
|
||||
When the user activates the x of "Outcome: Failed"
|
||||
Then GET /v1/activity is sent with q=spring and range=30d and without outcome
|
||||
When the user activates "Clear all"
|
||||
Then GET /v1/activity is sent with range=7d only, and the summary is requested for range=7d
|
||||
And no chip and no "Clear all" is shown
|
||||
|
||||
Scenario: The Person menu loads its options once, on first open
|
||||
Given the Default state has loaded
|
||||
Then GET /v1/user/ and GET /v1/api-key/ have not been requested
|
||||
When the user opens the Person menu
|
||||
Then both are requested once and the menu lists the users, then the API keys, then "System"
|
||||
And opening it again does not request them again
|
||||
|
||||
Scenario: Pagination — next page, page size and totals
|
||||
Given the Default state has loaded with total 1284
|
||||
When the user activates page "2" of the pager
|
||||
Then GET /v1/activity is sent with page=2 and size=25 and the pager reads "Showing 26–50 of
|
||||
1,284"
|
||||
When the user chooses "50" in "Rows per page"
|
||||
Then GET /v1/activity is sent with page=1 and size=50 and the pager reads "Showing 1–50 of
|
||||
1,284"
|
||||
And on the last page 52 of size 25 the pager reads "Showing 1,276–1,284 of 1,284" and next is
|
||||
disabled
|
||||
|
||||
Scenario: Mobile — the list is cards and the controls collapse into a sheet
|
||||
Given the Default state has loaded below md with the filters Category "Authentication" and
|
||||
Outcome "Failed" applied and GET /v1/activity resolves with total 6
|
||||
Then the page shows the search field and "Filters" with the badge "2", and no Person,
|
||||
Category, Outcome or date control
|
||||
And the table is replaced by cards, each with its actor, time, sentence and badges
|
||||
And the pager reads "Page 1 of 1" with "1–6 of 6"
|
||||
When the user activates "Filters"
|
||||
Then a bottom sheet titled "Filters" shows Person, Category, Outcome, Dates, "Clear all" and
|
||||
"Show 6 results"
|
||||
When the user chooses "Custom"
|
||||
Then two date fields appear in the sheet
|
||||
When the user activates "Show 6 results"
|
||||
Then the sheet closes and the list stays filtered
|
||||
|
||||
Scenario: Export — the file is prepared, then downloads
|
||||
Given the Default state has loaded with the filters Category "Authentication" and 30 days
|
||||
When the user activates "Export CSV"
|
||||
Then GET /v1/activity/export is sent with category=auth and range=30d and without page or size
|
||||
And while it is in flight the button reads "Preparing file…" and is disabled
|
||||
When it resolves 200 with a text/csv body
|
||||
Then the file is downloaded as "activity.csv" and a toast appears: color success, icon
|
||||
i-lucide-circle-check, title "Export started. Your file will download shortly."
|
||||
And the button returns to "Export CSV", enabled
|
||||
|
||||
Scenario Outline: Export — a failure raises an error toast and re-enables the button
|
||||
Given the Default state has loaded
|
||||
When the user activates "Export CSV" and GET /v1/activity/export <failure>
|
||||
Then a toast appears: color error, icon i-lucide-circle-x, title "Couldn't export activity.
|
||||
Try again."
|
||||
And nothing is downloaded and the button returns to "Export CSV", enabled
|
||||
|
||||
Examples:
|
||||
| failure |
|
||||
| resolves with a 500 response |
|
||||
| resolves with a 403 response |
|
||||
| never reaches the server |
|
||||
|
||||
Scenario: Details — a row opens the slide-over and focus returns on close
|
||||
Given the Default state has loaded
|
||||
When the user activates the second row (click, or Enter with the row focused)
|
||||
Then the slide-over opens with the title "Activity details", the row is marked selected and
|
||||
the footer reads "Event 2 of 1,284"
|
||||
When the user presses Escape (or activates the close button, or the scrim)
|
||||
Then the slide-over closes and focus is on that row
|
||||
|
||||
Scenario: Details — the Edit with a diff event
|
||||
Given the event "Why we reuse original floorboards" has action "article.edit" with changes
|
||||
[{"field": "title", "kind": "text", "before": "Why we reuse floorboards", "after": "Why we
|
||||
reuse original floorboards"}, {"field": "body", "kind": "body", "delta": 312}]
|
||||
When its details open
|
||||
Then the sentence reads "Edited the article Why we reuse original floorboards"
|
||||
And the Changes section shows a "Title" row with Before "Why we reuse floorboards" and After
|
||||
"Why we reuse original floorboards", then a "Body" row with "Body edited (+312 characters)"
|
||||
And no body text appears anywhere in the panel
|
||||
|
||||
Scenario: Details — long values clamp to two lines with Show more
|
||||
Given an event with a text change whose Before and After are 170-character values, and
|
||||
another text change with short values
|
||||
When its details open and the long values overflow two lines
|
||||
Then the long row's values are clamped and "Show more" appears under that row only
|
||||
When the user activates "Show more"
|
||||
Then the values are fully shown and the link reads "Show less"
|
||||
|
||||
Scenario: Details — a failed action with a very long target title shows its reason
|
||||
Given an event with action "article.publish", outcome "failed", failure_reason "The article
|
||||
has no cover image. Add one, then publish again." and a 150-character target name
|
||||
When its details open
|
||||
Then the sentence wraps with the title in semibold, the "Failed" badge is shown and an error
|
||||
alert "Why it failed" reads the reason
|
||||
And the Target section wraps the long name
|
||||
|
||||
Scenario: Details — a deleted target has no diff
|
||||
Given an event of action "media.delete" with target {"type": "image", "id": "9", "name":
|
||||
"old-banner.png", "exists": false} and no changes
|
||||
When its details open
|
||||
Then the Target section shows "old-banner.png" struck through, a "Deleted" badge and "This
|
||||
item was deleted. Its name is kept for reference."
|
||||
And there is no Changes section
|
||||
|
||||
Scenario: Details — a system-initiated event has no human actor
|
||||
Given an event with actor {"type": "system", "id": null, "name": "System"}, source "system",
|
||||
ip null and user_agent null
|
||||
When its details open
|
||||
Then Actor shows the cog avatar, "System" and a "System" badge, Source reads "System task",
|
||||
and IP address and Browser read "Not applicable"
|
||||
|
||||
Scenario: Details — a failed login shows the actor as not signed in
|
||||
Given an event with action "auth.login_failed", actor {"type": "anonymous", "id": null,
|
||||
"name": "alex@example.com"}, security true, outcome "failed", failure_reason "Wrong username
|
||||
or password.", ip "198.51.100.77" and user_agent "Chrome 129 on Windows"
|
||||
When its details open
|
||||
Then the sentence reads "Failed login attempt for alex@example.com" with a "Security" badge
|
||||
and a "Failed" badge
|
||||
And Actor reads "Not signed in", the alert "Why it failed" shows the reason, and the IP
|
||||
address and the Browser are shown
|
||||
|
||||
Scenario: Details — the times are shown in local time and in UTC
|
||||
Given an event created_at "2026-10-06T10:42:18Z"
|
||||
When its details open
|
||||
Then the When line ends with "(your time)" and the muted line below reads "6 Oct 2026,
|
||||
10:42:18 UTC"
|
||||
|
||||
Scenario Outline: Details — Source reads the event's source
|
||||
Given an event with source "<source>"
|
||||
When its details open
|
||||
Then Source reads "<label>"
|
||||
|
||||
Examples:
|
||||
| source | label |
|
||||
| web | Web app |
|
||||
| api_key | API key |
|
||||
| system | System task |
|
||||
|
||||
Scenario: Details — Previous and Next move through the filtered list across pages
|
||||
Given the list is on page 1 of size 25 with total 1284 and the first row's details are open
|
||||
Then "Previous event" is disabled and the footer reads "Event 1 of 1,284"
|
||||
When the user activates "Next event" 24 times
|
||||
Then the footer reads "Event 25 of 1,284" with no extra request
|
||||
When the user activates "Next event" once more
|
||||
Then GET /v1/activity is sent with the same filters, page=2 and size=25
|
||||
And the panel shows the first item of page 2, the footer reads "Event 26 of 1,284" and the
|
||||
pager under the table reads "Showing 26–50 of 1,284"
|
||||
When the user activates "Previous event"
|
||||
Then GET /v1/activity is sent with page=1 and the panel shows the last item of page 1 as
|
||||
"Event 25 of 1,284"
|
||||
And on the last event "Next event" is disabled
|
||||
|
||||
Scenario: Details — a failed neighbour page keeps the panel on the current event
|
||||
Given the last item of page 1 is open
|
||||
When the user activates "Next event" and GET /v1/activity resolves 500
|
||||
Then the panel still shows the same event, the button is enabled again and the list is
|
||||
unchanged
|
||||
|
||||
Scenario: Details — below md the slide-over is a bottom sheet
|
||||
Given the Default state has loaded below md
|
||||
When the user activates the second card
|
||||
Then a bottom sheet opens, 88 % high, with a handle, the title "Activity details", "2 of
|
||||
1,284" in the header, and full-width "Previous event" and "Next event" buttons
|
||||
And there is no "Event 2 of 1,284" footer text
|
||||
|
||||
Scenario: My activity — a role that is not owner or admin sees its own events
|
||||
Given the session role is "editor" (or absent) and GET /v1/activity resolves 200 with 25
|
||||
items and total 41
|
||||
When the user navigates to /activity
|
||||
Then the title reads "My activity", the subtitle "Everything you've done on this site." and
|
||||
the breadcrumb "My activity"
|
||||
And no summary strip, no Person filter and no "Export CSV" are rendered
|
||||
And the table has the columns When, Action, Target, Outcome and no Actor column
|
||||
And the cards show no actor line below md
|
||||
And GET /v1/activity is sent with range=7d, page=1, size=25 and no actor parameter, and
|
||||
GET /v1/activity/summary is never sent
|
||||
And the pager reads "Showing 1–25 of 41"
|
||||
|
||||
Scenario: My activity, empty — the user has not done anything yet
|
||||
Given the session role is "editor" and GET /v1/activity resolves 200 with items [] and total 0
|
||||
When the user navigates to /activity
|
||||
Then an empty panel with icon history shows "No activity yet" and "Your actions will appear
|
||||
here once you start working on the site."
|
||||
|
||||
Scenario: My activity, details — the slide-over on one of the user's own events
|
||||
Given the session role is "editor" and the Default list has loaded
|
||||
When the first row's details open
|
||||
Then the footer reads "Event 1 of 41", "Previous event" is disabled and the panel is the same
|
||||
as for an owner, with the Actor row showing the user's own name
|
||||
|
||||
Scenario: The French interface composes sentences and chrome in French
|
||||
Given the language is French and the Default state has loaded as owner
|
||||
Then the title reads "Activité", the strip labels, filter placeholders, badges, pager and
|
||||
"Exporter en CSV" are in French, the sentences use the French templates and day
|
||||
separators read "Aujourd'hui", "Hier" or "3 oct. 2026"
|
||||
And the Security sub-line reads "11 signalés"
|
||||
And every new English string of this screen has a French entry in messages.ts
|
||||
|
||||
Scenario: Hover shows the exact time
|
||||
Given the Default state has loaded
|
||||
Then each When cell has a title attribute holding the full local time with seconds
|
||||
@@ -0,0 +1,257 @@
|
||||
# QA: Activity screen, details slide-over and My activity
|
||||
|
||||
## Implementation note for coder (informational, not a QA assertion)
|
||||
|
||||
The activity API is already built and covered by features/activity-log-backend.qa.md and
|
||||
features/activity-log-producers.qa.md: this slice has no Go change and no HTTP-level Go section.
|
||||
|
||||
The shell specs that list the navigation are amended to seven destinations (Home, Articles, Media,
|
||||
Users, Activity, Integration, Settings): features/dashboard_shell_branding.feature,
|
||||
features/media_browse.feature, features/users_screen.feature and .qa.md,
|
||||
features/settings_page.feature and .qa.md, features/profile_page.feature. Their Vitest tests
|
||||
(DashboardShell.spec.ts, where Settings moves from index 5 to 6) must be updated in the same change.
|
||||
|
||||
Export needs the response body as a file, which `useApi().request` does not return (it calls
|
||||
`response.json()`). Add a raw or blob read to `useApi` that keeps the global 401 handling, builds
|
||||
an object URL and clicks a temporary anchor with `download="activity.csv"`. The toasts use
|
||||
`useToast().add({ color, icon, title })` with the one sentence as the title.
|
||||
|
||||
The page needs a date-range popover and a Custom date pair in the mobile sheet. The clamp ("Show
|
||||
more") is measured from the rendered element, so tests stub `scrollHeight` and `clientHeight`.
|
||||
|
||||
Every new English string needs a French entry in `web/src/i18n/messages.ts`. Sentences are
|
||||
composed by a composable (`useActivitySentence`) that returns segments so the target name can be
|
||||
rendered semibold. The Security sub-line is "{n} flagged" with n = `summary.security`, French
|
||||
"{n} signalés".
|
||||
|
||||
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
||||
|
||||
Mock `useApi`'s `request` (and the export transport) per case, matching on method, path and parsed
|
||||
query (`URLSearchParams`); no real backend. Mount ActivityView inside DashboardShell with a
|
||||
resolved verified session (id 2, username "ines", display_name "Inès Duarte", role "owner") and a
|
||||
test router at /activity; the regular-user cases use role "editor" (and one with no role). Run
|
||||
each layout case at a desktop and a below-md width (mock `matchMedia`, see
|
||||
`components/__tests__/viewport.ts`). Timers: use `vi.useFakeTimers({ toFake: ['setTimeout',
|
||||
'clearTimeout'] })` so the 150 ms skeleton delay and the 300 ms search debounce can be advanced
|
||||
while `Date` stays real. No test freezes or asserts the system date.
|
||||
|
||||
Clock-independence rules for fixtures: every event in the Vitest fixtures is dated 3 Oct 2026 or
|
||||
earlier, created at 12:00 to 13:00 UTC so its local day is the same in any time zone from UTC-11
|
||||
to UTC+11; assert day separators with the absolute label "3 Oct 2026" and When cells only against
|
||||
the pattern `^\d{2}:\d{2}$` and a non-empty `title`; never assert "Today", "Yesterday" or a
|
||||
relative "N min ago". UTC lines can be asserted exactly; the local time line only with its
|
||||
"(your time)" suffix.
|
||||
|
||||
Fixtures: `activityItems` (a 15-item list built from the board's events, mapped to the API shape
|
||||
with the action codes of the "Visual" section), `summaryDefault` (total 1284, previous_total
|
||||
1146, active_people {users 7, api_keys 2}, failed 6, security 11, series total [4,6,5,8,7,9,6],
|
||||
active [5,6,6,7,7,8,9], failed [0,1,0,2,1,0,2], security [1,0,2,1,3,2,2]), `summaryZero` (total
|
||||
214, previous_total 223, active_people {4, 1}, failed 0, security 0, series failed and security
|
||||
zeros) and `summaryNone` (all zeros). The list response is `{ items, total, page, size }`.
|
||||
|
||||
1. **Navigation** — sidebar and drawer list Home, Articles, Media, Users, Activity, Integration,
|
||||
Settings in order; "Activity" has the `i-lucide-history` icon, links to /activity, has
|
||||
aria-current="page" on /activity and none elsewhere; breadcrumb and mobile title "Activity".
|
||||
2. **Default (owner)** — assert header texts, enabled "Export CSV", the four strip cards (labels,
|
||||
"1,284", "9", "6", "11", sub-lines "12% vs previous 7 days" with the trending-up icon, "7
|
||||
people, 2 API keys", "0.5% of all actions" with icon `circle-x`, "11 flagged" with icon
|
||||
`shield-alert`), the filter bar (placeholder, "All people", "All categories", Outcome All
|
||||
selected, 7 days selected), no chip, the pager text "Showing 1–25 of 1,284", and that `request`
|
||||
was called exactly twice at mount with the expected queries (`range=7d&page=1&size=25` and
|
||||
`range=7d`).
|
||||
3. **Rows, Examples-driven** — one fixture row per Examples row of the feature; assert the
|
||||
Actor cell (initials, key or cog or user-round-x icon, badge, "Not signed in"), the sentence
|
||||
text and that the target name is in a semibold element, the shield marker only on security
|
||||
rows, and the Outcome badge word.
|
||||
4. **Target cell** — deleted (struck-through class, "Deleted" badge, type line), living (link
|
||||
with `href` "/article/8/edit", "/media", "/users", "/integration/api-keys" per type, plain text
|
||||
for "release"), and null ("—"); clicking the link navigates and does not open the details.
|
||||
5. **Day grouping and When cell** — fixture across 3 Oct and 2 Oct 2026; assert two separators
|
||||
"3 Oct 2026" and "2 Oct 2026" in order, the When cell pattern and `title`.
|
||||
6. **Sentences, Examples-driven** — for each Examples row set the locale (`setLocale`), render
|
||||
and assert the exact sentence, including plurals, `failed_groups`, "Forever", the dropped slot
|
||||
for a missing target name, the unknown code `article.archive`, and the success sentence used
|
||||
for an unlisted failed action (`auth.login` failed). Add a completeness test: every action in
|
||||
the catalogue has an English and a French template, and every key used on the page exists in
|
||||
`messages.ts`.
|
||||
7. **Loading** — unresolved requests; at 149 ms nothing in place of strip and table; at 150 ms 4
|
||||
skeleton cards, 9 skeleton rows (5 cards below md), `aria-busy="true"`, no pager; resolve and
|
||||
assert the Default content.
|
||||
8. **Zero-value strip** — `summaryZero`; assert "214" "4% vs previous 7 days" with the
|
||||
trending-down icon, "5" "4 people, 1 API key", "0" "Nothing failed" and "0" "Nothing to flag"
|
||||
with `circle-check`, no error or warning fill class, bars at 2 px.
|
||||
9. **Total sub-line without a comparison, Examples-driven** — previous_total 0 gives "No earlier
|
||||
data" and equal totals give "No change", both without a trend icon; French "Aucune donnée
|
||||
antérieure" and "Aucun changement"; ranges Today, 30 days and Custom give "vs previous day",
|
||||
"vs previous 30 days" and "vs previous period".
|
||||
10. **Empty, no activity yet** — `summaryNone`, items []; assert "No data yet" on two cards, the
|
||||
calm lines on the other two, the empty panel copy and icon, a disabled "Export CSV", no table
|
||||
header and no pager.
|
||||
11. **Empty, filters match nothing** — type "sitemap", choose Category "Media" and Outcome
|
||||
"Failed", resolve items []; assert chips, empty panel copy, "Clear filters", enabled export;
|
||||
click "Clear filters" and assert a request with `range=7d&page=1&size=25` only.
|
||||
12. **Error, Examples-driven** — list rejects with `ApiError(500)`, `ApiError(400)`, then
|
||||
`NetworkError`, summary resolves; assert the strip, the alert copy, "Try again", a disabled
|
||||
export and no table; click "Try again"; assert the list request is repeated and the Default
|
||||
rows replace the alert.
|
||||
13. **Summary alone fails** — summary rejects with `ApiError(500)`, `ApiError(403)`, then
|
||||
`NetworkError`; assert the strip is absent, nothing is drawn in its place, and the list is
|
||||
fully rendered.
|
||||
14. **Forbidden** — list rejects with `ApiError(403)` and a verified session; assert no export
|
||||
button, no strip, no filter bar, the lock panel copy, and that "Back to home" navigates to
|
||||
/home. Also `ApiError(401)` triggers the global redirect and no panel.
|
||||
15. **Strip cards, Examples-driven** — click each card; assert the effect and `aria-pressed`
|
||||
(Failed: request with `outcome=failed&page=1`, chip "Outcome: Failed"; Security: request with
|
||||
`security=true`, chip "Security events"; Total: filters cleared; Active people: no request)
|
||||
and that the summary is not requested again.
|
||||
16. **Filtered, card applied** — Category "Authentication", 30 days, then the Failed card; assert
|
||||
the chip texts and order, "Clear all", the summary requested only once for `range=30d`, the
|
||||
pager "Showing 1–6 of 6", and below md the Filters badge "3".
|
||||
17. **Filter bar, Examples-driven** — for each Examples row assert the exact query, `page=1` after
|
||||
starting on page 3, and the 300 ms debounce with fake timers (no request at 299 ms, one at
|
||||
300 ms; Enter applies at once and the pending debounce does not send a second request).
|
||||
18. **Custom dates** — pick two dates in the popover (stub the calendar's model); assert no request
|
||||
after the first date, then `range=custom&from=2026-09-01&to=2026-09-30` on the list and the
|
||||
summary, and the chip "Dates: 1 – 30 Sep 2026"; also "28 Sep – 3 Oct 2026".
|
||||
19. **Chips** — remove one chip, then "Clear all"; assert the queries and that the summary is
|
||||
requested again only when the range changes back.
|
||||
20. **Person options** — assert no `GET /v1/user/` or `GET /v1/api-key/` call at mount, both on
|
||||
first open of the menu, none on the second; assert group order and the three query values.
|
||||
21. **Pagination** — next page, size 50, last page "Showing 1,276–1,284 of 1,284" with next
|
||||
disabled; mobile "Page 1 of 52" and previous and next.
|
||||
22. **Mobile list and sheet** — below md assert cards (actor line, sentence, badges, "Target
|
||||
deleted"), "Filters" with the badge count, the sheet content and footer ("Show 6 results", "Show
|
||||
1 result"), two date fields for Custom, and that "Show … results" closes it.
|
||||
23. **Export success** — click "Export CSV" with filters applied; assert one request to
|
||||
`/v1/activity/export` with the list filters and no `page` or `size`, "Preparing file…" and
|
||||
disabled while pending, an object URL created and an anchor clicked with
|
||||
`download="activity.csv"`, the success toast (color success, icon `i-lucide-circle-check`,
|
||||
title "Export started. Your file will download shortly."), and the button back to "Export CSV".
|
||||
24. **Export failure, Examples-driven** — 500, 403 and `NetworkError`; assert the error toast
|
||||
(color error, icon `i-lucide-circle-x`, title "Couldn't export activity. Try again."), no
|
||||
download, button re-enabled.
|
||||
25. **Details open and close** — click, then Enter on a focused row; assert the title, the selected
|
||||
row class, the footer "Event 2 of 1,284"; close with Escape, the close button and the scrim and
|
||||
assert focus on the row.
|
||||
26. **Details content, Examples-driven** — the six board events: Edit with a diff (Title row with
|
||||
both values and the "Body edited (+312 characters)" row, "(+1 character)", "(-48 characters)"),
|
||||
long text (stub overflow; "Show more" on that row only, toggles to "Show less"), failed with a
|
||||
long title (alert "Why it failed", wrapping), deleted target (struck-through name, "Deleted"
|
||||
badge, explanation, no Changes), system event ("System" badge, "System task", two "Not
|
||||
applicable"), failed login ("Not signed in", "Security" badge, reason, IP and Browser). Assert
|
||||
the field labels and the Draft and Published values for `online`, the raw code for an unknown
|
||||
field, and that no body text is ever rendered.
|
||||
27. **Details times** — `created_at` "2026-10-06T10:42:18Z": the UTC line is exactly "6 Oct 2026,
|
||||
10:42:18 UTC" and the local line ends with "(your time)".
|
||||
28. **Previous and Next across pages** — first item: previous disabled, "Event 1 of 1,284"; 24
|
||||
nexts without a request; the 25th next sends `page=2&size=25` with the same filters, shows
|
||||
page 2's first item, "Event 26 of 1,284" and the pager "Showing 26–50 of 1,284"; previous
|
||||
sends `page=1` and shows "Event 25 of 1,284"; the last event disables next; a 500 on the
|
||||
neighbour page keeps the panel on the current event and re-enables the button; the position
|
||||
also follows a non-default size (size 50, page 2, index 0 is "Event 51").
|
||||
29. **Details below md** — the bottom-sheet variant: header "2 of 1,284", full-width buttons, no
|
||||
footer text.
|
||||
30. **My activity, Examples-driven** — role "editor" then no role: title, subtitle, breadcrumb "My
|
||||
activity", no strip, no Person filter, no export, no Actor column or card actor line; assert no
|
||||
request to `/summary` or `/export` and no `actor` parameter; pager "Showing 1–25 of 41"; empty
|
||||
state copy; details "Event 1 of 41" with previous disabled.
|
||||
31. **French** — `setLocale('fr')`; assert the chrome strings (Activity "Activité", My activity
|
||||
"Mon activité", Export CSV "Exporter en CSV", Preparing file… "Préparation du fichier…",
|
||||
Total actions "Actions au total", Active people "Personnes actives", Failed actions "Actions
|
||||
en échec", Security events "Événements de sécurité", Succeeded "Réussie", Failed "Échec", Not
|
||||
signed in "Non connecté", Activity details "Détails de l'activité", Previous event and Next
|
||||
event "Événement précédent" and "Événement suivant", "11 signalés"), the French sentences, the
|
||||
plural and "Forever" ("Toujours") forms, and the day separator format.
|
||||
32. **Hover time** — each When cell has a `title` that is non-empty and contains seconds.
|
||||
|
||||
## Visual (task visual:check -- activity, desktop and mobile, light and dark)
|
||||
|
||||
Reference: `docs/design/screens/activity.md`, board `docs/design/source/RenewCMS Screens
|
||||
Activity.dc.html`, groups "Activity, owner and admin", "Details slide-over" and "My activity"
|
||||
(the last two are already declared as `extraSources` in `web/visual/check.ts`); exact values in
|
||||
`docs/design/source/ActivityFrame.dc.html`. Add each state to `visualStates.activity` in
|
||||
`web/visual/states.ts` with the board's own sample data. The gate is hard: every capture of every
|
||||
non-skipped state must be within 10 %, for both viewports and both themes (6 gated states, 24
|
||||
captures). No state uses the `now` option or a frozen clock. Mocks are keyed by method and path
|
||||
(`GET /v1/activity`, `GET /v1/activity/summary`, `GET /v1/auth/me`); use `bodyFor` to read the
|
||||
query. Do not mock or call `/v1/user/` or `/v1/api-key/` (Person options load only when the menu
|
||||
opens, which no state does), so there is no unmocked request.
|
||||
|
||||
Sessions: add `activityOwnerSession` (id 2, display_name "Inès Duarte", role "owner") and
|
||||
`activityEditorSession` (id 3, display_name "Marta Alves", role "editor"), as the board draws them
|
||||
in its sidebar chip. The board draws a 4-item sidebar for the regular user as illustrative; the
|
||||
real shell keeps all 7 items, a known small difference in the My activity Empty capture.
|
||||
|
||||
Fixtures (all taken from the frame's script): `activityBoardEvents`, the 15 events of the frame in
|
||||
its order, mapped to API items. Where the frame's sample has no real producer the nearest real
|
||||
code is used and the sentence differs from the board (accepted; those rows only appear in skipped
|
||||
states): 1 `article.publish`, 2 `article.edit` with title and body (+312) changes, 3
|
||||
`auth.login_failed` (anonymous, name "alex@example.com", reason from the frame), 4
|
||||
`api_key.revoke`, 5 `system.media_purge` (system, ip and user_agent null), 6 `invite.accept`
|
||||
(replaces "Changed the role"), 7 `media.upload` by the API key "Website sync", 8 `media.delete`
|
||||
(target not existing), 9 `article.publish` failed with the 150-character title, 10
|
||||
`system.activity_cleanup`, 11 `article.edit` with long title values (replaces the "Site
|
||||
description" setting diff), 12 `api_key.create`, 13 `user.update_profile`, 14 `media.upload`, 15
|
||||
`auth.password_reset_completed`; times are the frame's local times minus one hour as UTC
|
||||
(`created_at`), IPs and browsers as in the frame, security as in the frame. Summary fixtures are
|
||||
the three in the Automated section; the strip of the Default state is "1,284 / 9 / 6 / 11" with
|
||||
the sub-line "11 flagged". Total is 1284 with page size 25 for the owner and 41 for the editor.
|
||||
|
||||
- [ ] Loading: both requests with `hang: true`; the setup waits 150 ms or more so the skeleton
|
||||
strip and rows are drawn before the capture.
|
||||
- [ ] Empty, no activity yet: list `items: [], total: 0`, summary `summaryNone`; "Export CSV"
|
||||
disabled.
|
||||
- [ ] Empty, filters match nothing: the board applies Search "sitemap", Category "Media", Outcome
|
||||
"Failed" (steps type and select them, or the mock answers with the filtered query), list
|
||||
`items: [], total: 0`, summary Default.
|
||||
- [ ] Error with retry: list 500, summary Default; the alert, disabled export, strip drawn.
|
||||
- [ ] Forbidden (403): list 403, summary 403; session with a non-admin role as the board does
|
||||
(`role: 'user'`), so no "Export CSV".
|
||||
- [ ] My activity, Empty: `activityEditorSession`, list `items: [], total: 0`.
|
||||
- [ ] skip: clock-sensitive. Default, large dataset: `skip: 'clock-sensitive'` (day separators and
|
||||
"2 min ago" depend on the real clock). Prints SKIP, never investigated or date-frozen.
|
||||
- [ ] skip: clock-sensitive. Zero-value summary strip, Filtered card applied and Mobile filters
|
||||
sheet (all draw Today rows behind the strip or sheet).
|
||||
- [ ] skip: clock-sensitive. The six Details slide-over states (Edit with a diff, Settings diff
|
||||
long text, Failed action very long target title, Deleted target no diff, System-initiated no
|
||||
human actor, Security event failed login) and the My activity states Default and Details:
|
||||
the rows behind the scrim show relative times and the panel shows the browser's local
|
||||
time. Their Vitest coverage is cases 3, 5, 25 to 30.
|
||||
- [ ] Layout, from `ActivityFrame.dc.html`, not `components.md`: header row is the title block
|
||||
(20 px/28 px title) on the left and the 32 px (44 px mobile) "Export CSV" button on the right,
|
||||
aligned to the bottom; the strip is 4 columns with a 12 px gap on desktop and a clipped row
|
||||
of 156 px cards with an 8 px gap on mobile; the table header is 36 px, day rows 32 px, rows at
|
||||
least 52 px; the slide-over is 480 px wide on desktop, the bottom sheet 88 % high.
|
||||
- [ ] Error is drawn as the frame's alert (error soft background, circle-x, title, text, 28 px
|
||||
outline "Try again"), the empty states as the frame's centred panel (44 px icon box, 15 px
|
||||
semibold title, muted text up to 340 px).
|
||||
- [ ] Not covered by screenshots: keyboard and focus order (Tab reaches Export CSV, the strip
|
||||
cards, the search, the selects, the groups, a row; Enter opens the details; focus is trapped
|
||||
in the slide-over and returns to the row on close; Escape closes it); hover (the row, the
|
||||
native `title` tooltip), the 240 ms slide-over and sheet motion and the skeleton pulse, all
|
||||
stopped under reduced motion; the date-range popover.
|
||||
|
||||
## Manual verification
|
||||
|
||||
- **Real round trips against `task dev`** — Vitest only mocks `useApi`. As owner: perform an
|
||||
article publish, an image upload and a failed login, then confirm they appear newest first with
|
||||
the right sentences, the shield marker on the failed login, the Succeeded and Failed badges, the
|
||||
summary numbers and the sparkline bars; apply each filter and each card; page through with size
|
||||
25, 50 and 100; open the details across a page boundary.
|
||||
- **Real CSV** — click "Export CSV" with and without filters and open `activity.csv`: columns
|
||||
`when,actor,action,target,outcome,source,ip`, the filtered rows only, no page or size applied,
|
||||
neutralised cells that start with `=`, `+`, `-` or `@`; confirm the browser download prompt and
|
||||
the two toasts.
|
||||
- **Admin session** — sign in as an admin: the same full view as the owner.
|
||||
- **Time zones** — set the OS time zone to UTC-8 and UTC+9, reload, and confirm the day
|
||||
separators, the clock times, the "(your time)" line and the UTC line are consistent.
|
||||
- **Regular user** — no real account can reach "My activity" today; confirm by a mocked
|
||||
`/v1/auth/me` in the browser (or a future role) that the view has no strip, no Person filter and
|
||||
no export, and that the server answers 403 for `actor=user:2` and for the summary and export.
|
||||
- **API key** — calling `GET /v1/activity` with an API key answers 403 "This action needs a real
|
||||
session." and the SPA never does it.
|
||||
- **"Today", "Yesterday" and relative times** — confirm them against the real clock, since
|
||||
visual:check skips every state that shows them.
|
||||
- **French** — switch the language and read every state, the sentences and the toasts.
|
||||
- **Real screen readers and zoom** — row selection, the sparkline buttons (labelled by the card
|
||||
text), the sheet focus trap.
|
||||
@@ -0,0 +1,30 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/article"
|
||||
"strconv"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
func TextChange(field string, before string, after string) Change {
|
||||
return Change{Field: field, Kind: ChangeText, Before: &before, After: &after}
|
||||
}
|
||||
|
||||
func BodyChange(before string, after string) Change {
|
||||
delta := utf8.RuneCountInString(after) - utf8.RuneCountInString(before)
|
||||
return Change{Field: FieldBody, Kind: ChangeBody, Delta: &delta}
|
||||
}
|
||||
|
||||
func ArticleChanges(before article.Article, after article.Article) []Change {
|
||||
changes := []Change{}
|
||||
if before.Title != after.Title {
|
||||
changes = append(changes, TextChange(FieldTitle, before.Title, after.Title))
|
||||
}
|
||||
if before.IsOnline != after.IsOnline {
|
||||
changes = append(changes, TextChange(FieldOnline, strconv.FormatBool(before.IsOnline), strconv.FormatBool(after.IsOnline)))
|
||||
}
|
||||
if before.Body != after.Body {
|
||||
changes = append(changes, BodyChange(before.Body, after.Body))
|
||||
}
|
||||
return changes
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/user"
|
||||
"errors"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrInvalidFilter = errors.New("invalid activity filter")
|
||||
var ErrInvalidRetention = errors.New("invalid activity retention period")
|
||||
var ErrInvalidEvent = errors.New("invalid activity event")
|
||||
var ErrActorNotAllowed = errors.New("activity of another actor is not allowed")
|
||||
|
||||
type ActorType string
|
||||
|
||||
const (
|
||||
ActorUser ActorType = "user"
|
||||
ActorAPIKey ActorType = "api_key"
|
||||
ActorSystem ActorType = "system"
|
||||
ActorAnonymous ActorType = "anonymous"
|
||||
)
|
||||
|
||||
type Category string
|
||||
|
||||
const (
|
||||
CategoryArticles Category = "articles"
|
||||
CategoryMedia Category = "media"
|
||||
CategoryUsers Category = "users"
|
||||
CategoryAPIKeys Category = "api_keys"
|
||||
CategoryAuth Category = "auth"
|
||||
CategorySystem Category = "system"
|
||||
)
|
||||
|
||||
type Outcome string
|
||||
|
||||
const (
|
||||
OutcomeSuccess Outcome = "success"
|
||||
OutcomeFailed Outcome = "failed"
|
||||
)
|
||||
|
||||
type Source string
|
||||
|
||||
const (
|
||||
SourceWeb Source = "web"
|
||||
SourceAPIKey Source = "api_key"
|
||||
SourceSystem Source = "system"
|
||||
)
|
||||
|
||||
type ChangeKind string
|
||||
|
||||
const (
|
||||
ChangeText ChangeKind = "text"
|
||||
ChangeBody ChangeKind = "body"
|
||||
)
|
||||
|
||||
const (
|
||||
ActionLogin = "auth.login"
|
||||
ActionLoginFailed = "auth.login_failed"
|
||||
ActionLogout = "auth.logout"
|
||||
ActionPasswordResetRequest = "auth.password_reset_requested"
|
||||
ActionPasswordResetDone = "auth.password_reset_completed"
|
||||
ActionAPIKeyCreate = "api_key.create"
|
||||
ActionAPIKeyRevoke = "api_key.revoke"
|
||||
ActionRetentionChanged = "system.activity_retention_changed"
|
||||
ActionCleanup = "system.activity_cleanup"
|
||||
ActionArticleCreate = "article.create"
|
||||
ActionArticleEdit = "article.edit"
|
||||
ActionArticlePublish = "article.publish"
|
||||
ActionArticleUnpublish = "article.unpublish"
|
||||
ActionArticleDelete = "article.delete"
|
||||
ActionMediaUpload = "media.upload"
|
||||
ActionMediaRename = "media.rename"
|
||||
ActionMediaDelete = "media.delete"
|
||||
ActionMediaMerge = "media.merge"
|
||||
ActionMediaPurge = "media.purge"
|
||||
ActionUserRegister = "user.register"
|
||||
ActionUserVerify = "user.verify"
|
||||
ActionUserUpdateProfile = "user.update_profile"
|
||||
ActionInviteCreate = "invite.create"
|
||||
ActionInviteCancel = "invite.cancel"
|
||||
ActionInviteRenew = "invite.renew"
|
||||
ActionInviteAccept = "invite.accept"
|
||||
ActionMediaPurgeScheduled = "system.media_purge"
|
||||
ActionUpdateChecked = "system.update_checked"
|
||||
ActionUpdateDownloaded = "system.update_downloaded"
|
||||
ActionRestartRequested = "system.restart_requested"
|
||||
)
|
||||
|
||||
const (
|
||||
TargetAPIKey = "api_key"
|
||||
TargetUser = "user"
|
||||
TargetArticle = "article"
|
||||
TargetImage = "image"
|
||||
TargetInvite = "invite"
|
||||
TargetRelease = "release"
|
||||
)
|
||||
|
||||
const (
|
||||
SystemActorName = "System"
|
||||
ReasonWrongLogin = "Wrong username or password."
|
||||
MaxUserAgentLength = 255
|
||||
ParamRemoved = "removed"
|
||||
ParamFrom = "from"
|
||||
ParamTo = "to"
|
||||
ParamMerged = "merged"
|
||||
ParamArticlesUpdated = "articles_updated"
|
||||
ParamFailedGroups = "failed_groups"
|
||||
ParamUpdateAvailable = "update_available"
|
||||
ParamKind = "kind"
|
||||
ParamTag = "tag"
|
||||
FieldTitle = "title"
|
||||
FieldOnline = "online"
|
||||
FieldBody = "body"
|
||||
FieldFilename = "filename"
|
||||
FieldDisplayName = "display_name"
|
||||
maxNameLength = 255
|
||||
maxActionLength = 64
|
||||
maxFailureReasonSize = 255
|
||||
)
|
||||
|
||||
func ActorTypes() []ActorType {
|
||||
return []ActorType{ActorUser, ActorAPIKey, ActorSystem, ActorAnonymous}
|
||||
}
|
||||
|
||||
func Categories() []Category {
|
||||
return []Category{CategoryArticles, CategoryMedia, CategoryUsers, CategoryAPIKeys, CategoryAuth, CategorySystem}
|
||||
}
|
||||
|
||||
func Outcomes() []Outcome {
|
||||
return []Outcome{OutcomeSuccess, OutcomeFailed}
|
||||
}
|
||||
|
||||
func Sources() []Source {
|
||||
return []Source{SourceWeb, SourceAPIKey, SourceSystem}
|
||||
}
|
||||
|
||||
func ChangeKinds() []ChangeKind {
|
||||
return []ChangeKind{ChangeText, ChangeBody}
|
||||
}
|
||||
|
||||
type Actor struct {
|
||||
Type ActorType `json:"type"`
|
||||
ID *uint32 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type Target struct {
|
||||
Type string `json:"type"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type Change struct {
|
||||
Field string `json:"field"`
|
||||
Kind ChangeKind `json:"kind"`
|
||||
Before *string `json:"before,omitempty"`
|
||||
After *string `json:"after,omitempty"`
|
||||
Delta *int `json:"delta,omitempty"`
|
||||
}
|
||||
|
||||
type Event struct {
|
||||
ID uint64 `json:"id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Action string `json:"action"`
|
||||
Category Category `json:"category"`
|
||||
Actor Actor `json:"actor"`
|
||||
Target Target `json:"target"`
|
||||
Outcome Outcome `json:"outcome"`
|
||||
FailureReason *string `json:"failure_reason"`
|
||||
Security bool `json:"security"`
|
||||
Source Source `json:"source"`
|
||||
IP *string `json:"ip"`
|
||||
UserAgent *string `json:"user_agent"`
|
||||
Params map[string]any `json:"params"`
|
||||
Changes []Change `json:"changes"`
|
||||
}
|
||||
|
||||
func NewEvent(action string, category Category) Event {
|
||||
return Event{
|
||||
Action: action,
|
||||
Category: category,
|
||||
Outcome: OutcomeSuccess,
|
||||
Params: map[string]any{},
|
||||
Changes: []Change{},
|
||||
}
|
||||
}
|
||||
|
||||
func SystemActor() Actor {
|
||||
return Actor{Type: ActorSystem, Name: SystemActorName}
|
||||
}
|
||||
|
||||
func UserActor(u user.User) Actor {
|
||||
id := u.ID
|
||||
name := strings.TrimSpace(u.DisplayName)
|
||||
if name == "" {
|
||||
name = u.Username
|
||||
}
|
||||
return Actor{Type: ActorUser, ID: &id, Name: name}
|
||||
}
|
||||
|
||||
func AnonymousActor(name string) Actor {
|
||||
return Actor{Type: ActorAnonymous, Name: name}
|
||||
}
|
||||
|
||||
func APIKeyActor(id uint32, name string) Actor {
|
||||
return Actor{Type: ActorAPIKey, ID: &id, Name: name}
|
||||
}
|
||||
|
||||
func APIKeyTarget(id uint32, name string) Target {
|
||||
return Target{Type: TargetAPIKey, ID: strconv.FormatUint(uint64(id), 10), Name: name}
|
||||
}
|
||||
|
||||
func (e Event) Validate() error {
|
||||
if e.Action == "" || len(e.Action) > maxActionLength {
|
||||
return ErrInvalidEvent
|
||||
}
|
||||
if !slices.Contains(Categories(), e.Category) || !slices.Contains(Outcomes(), e.Outcome) || !slices.Contains(Sources(), e.Source) || !slices.Contains(ActorTypes(), e.Actor.Type) {
|
||||
return ErrInvalidEvent
|
||||
}
|
||||
if e.FailureReason != nil && len(*e.FailureReason) > maxFailureReasonSize {
|
||||
return ErrInvalidEvent
|
||||
}
|
||||
for _, change := range e.Changes {
|
||||
if change.Kind != ChangeText && change.Kind != ChangeBody {
|
||||
return ErrInvalidEvent
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e Event) Truncated() Event {
|
||||
e.Actor.Name = truncate(e.Actor.Name, maxNameLength)
|
||||
e.Target.Name = truncate(e.Target.Name, maxNameLength)
|
||||
return e
|
||||
}
|
||||
|
||||
func truncate(value string, limit int) string {
|
||||
runes := []rune(value)
|
||||
return string(runes[:min(len(runes), limit)])
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const SeriesBuckets = 7
|
||||
|
||||
type ActorRef struct {
|
||||
Type ActorType
|
||||
ID *uint32
|
||||
}
|
||||
|
||||
const (
|
||||
userActorPrefix = "user:"
|
||||
apiKeyActorPrefix = "key:"
|
||||
systemActorRef = "system"
|
||||
)
|
||||
|
||||
func ParseActor(raw string) (ActorRef, error) {
|
||||
if raw == systemActorRef {
|
||||
return ActorRef{Type: ActorSystem}, nil
|
||||
}
|
||||
if rest, ok := strings.CutPrefix(raw, userActorPrefix); ok {
|
||||
return parseActorID(ActorUser, rest)
|
||||
}
|
||||
if rest, ok := strings.CutPrefix(raw, apiKeyActorPrefix); ok {
|
||||
return parseActorID(ActorAPIKey, rest)
|
||||
}
|
||||
return ActorRef{}, ErrInvalidFilter
|
||||
}
|
||||
|
||||
func parseActorID(actorType ActorType, raw string) (ActorRef, error) {
|
||||
id, err := strconv.ParseUint(raw, 10, 32)
|
||||
if err != nil {
|
||||
return ActorRef{}, ErrInvalidFilter
|
||||
}
|
||||
value := uint32(id)
|
||||
return ActorRef{Type: actorType, ID: &value}, nil
|
||||
}
|
||||
|
||||
func ParseCategory(raw string) (Category, error) {
|
||||
category := Category(raw)
|
||||
if !slices.Contains(Categories(), category) {
|
||||
return "", ErrInvalidFilter
|
||||
}
|
||||
return category, nil
|
||||
}
|
||||
|
||||
type Filter struct {
|
||||
Query string
|
||||
Actor *ActorRef
|
||||
Category Category
|
||||
Outcome Outcome
|
||||
Security bool
|
||||
From *time.Time
|
||||
To *time.Time
|
||||
Page int
|
||||
Size int
|
||||
}
|
||||
|
||||
type Page struct {
|
||||
Items []Event
|
||||
Total int
|
||||
}
|
||||
|
||||
type SummaryQuery struct {
|
||||
From time.Time
|
||||
To time.Time
|
||||
}
|
||||
|
||||
func (q SummaryQuery) Previous() SummaryQuery {
|
||||
return SummaryQuery{From: q.From.Add(-q.To.Sub(q.From)), To: q.From}
|
||||
}
|
||||
|
||||
type ActivePeople struct {
|
||||
Users int `json:"users"`
|
||||
APIKeys int `json:"api_keys"`
|
||||
}
|
||||
|
||||
type Series struct {
|
||||
Total []int `json:"total"`
|
||||
Active []int `json:"active"`
|
||||
Failed []int `json:"failed"`
|
||||
Security []int `json:"security"`
|
||||
}
|
||||
|
||||
type Summary struct {
|
||||
Total int `json:"total"`
|
||||
PreviousTotal int `json:"previous_total"`
|
||||
ActivePeople ActivePeople `json:"active_people"`
|
||||
Failed int `json:"failed"`
|
||||
Security int `json:"security"`
|
||||
Series Series `json:"series"`
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package audit
|
||||
|
||||
import "context"
|
||||
|
||||
type Recorder interface {
|
||||
Record(ctx context.Context, event Event)
|
||||
}
|
||||
|
||||
type discardRecorder struct{}
|
||||
|
||||
func (discardRecorder) Record(context.Context, Event) {}
|
||||
|
||||
var Discard Recorder = discardRecorder{}
|
||||
|
||||
type Origin struct {
|
||||
Actor Actor
|
||||
Source Source
|
||||
IP string
|
||||
UserAgent string
|
||||
}
|
||||
|
||||
type originContextKey struct{}
|
||||
|
||||
func WithOrigin(ctx context.Context, origin Origin) context.Context {
|
||||
return context.WithValue(ctx, originContextKey{}, origin)
|
||||
}
|
||||
|
||||
func OriginFrom(ctx context.Context) (Origin, bool) {
|
||||
origin, ok := ctx.Value(originContextKey{}).(Origin)
|
||||
return origin, ok
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package audit
|
||||
|
||||
import "time"
|
||||
|
||||
type Repository interface {
|
||||
Append(event Event) (Event, error)
|
||||
List(filter Filter) (Page, error)
|
||||
Summary(query SummaryQuery) (Summary, error)
|
||||
DeleteOlderThan(cutoff time.Time) (int, error)
|
||||
}
|
||||
|
||||
type SettingsRepository interface {
|
||||
Get() (Settings, error)
|
||||
SaveRetention(days int) error
|
||||
SaveLastCleanup(at time.Time, removed int) error
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package audit
|
||||
|
||||
import "time"
|
||||
|
||||
const (
|
||||
DefaultRetentionDays = 90
|
||||
ForeverRetentionDays = 0
|
||||
CleanupHour = 3
|
||||
KeepRecentHours = 24
|
||||
)
|
||||
|
||||
func RetentionOptions() []int {
|
||||
return []int{30, 90, 365, ForeverRetentionDays}
|
||||
}
|
||||
|
||||
func ValidateRetentionDays(days int) error {
|
||||
for _, option := range RetentionOptions() {
|
||||
if option == days {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return ErrInvalidRetention
|
||||
}
|
||||
|
||||
type Settings struct {
|
||||
RetentionDays int `json:"activity_retention_days"`
|
||||
LastCleanupAt *time.Time `json:"activity_last_cleanup_at"`
|
||||
LastCleanupRemoved int `json:"activity_last_cleanup_removed"`
|
||||
NextCleanupAt *time.Time `json:"activity_next_cleanup_at"`
|
||||
}
|
||||
|
||||
func DefaultSettings() Settings {
|
||||
return Settings{RetentionDays: DefaultRetentionDays}
|
||||
}
|
||||
|
||||
func (s Settings) CleanupDue(now time.Time) bool {
|
||||
todayRun := time.Date(now.Year(), now.Month(), now.Day(), CleanupHour, 0, 0, 0, now.Location())
|
||||
if now.Before(todayRun) {
|
||||
return false
|
||||
}
|
||||
return s.LastCleanupAt == nil || s.LastCleanupAt.Before(todayRun)
|
||||
}
|
||||
|
||||
func (s Settings) WithNextCleanup(now time.Time) Settings {
|
||||
s.NextCleanupAt = nil
|
||||
if s.RetentionDays == ForeverRetentionDays {
|
||||
return s
|
||||
}
|
||||
next := time.Date(now.Year(), now.Month(), now.Day(), CleanupHour, 0, 0, 0, now.Location())
|
||||
if !next.After(now) {
|
||||
next = time.Date(now.Year(), now.Month(), now.Day()+1, CleanupHour, 0, 0, 0, now.Location())
|
||||
}
|
||||
s.NextCleanupAt = &next
|
||||
return s
|
||||
}
|
||||
|
||||
func ClampCutoff(now time.Time, cutoff time.Time) time.Time {
|
||||
newest := now.Add(-KeepRecentHours * time.Hour)
|
||||
if cutoff.After(newest) {
|
||||
return newest
|
||||
}
|
||||
return cutoff
|
||||
}
|
||||
|
||||
func RetentionCutoff(now time.Time, retentionDays int) time.Time {
|
||||
return ClampCutoff(now, now.Add(-time.Duration(retentionDays)*24*time.Hour))
|
||||
}
|
||||
|
||||
type CleanupResult struct {
|
||||
Removed int
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package audit
|
||||
|
||||
import "strconv"
|
||||
|
||||
func NewTarget(targetType string, id uint32, name string) Target {
|
||||
return Target{Type: targetType, ID: strconv.FormatUint(uint64(id), 10), Name: name}
|
||||
}
|
||||
|
||||
func ReleaseTarget(tag string) Target {
|
||||
return Target{Type: TargetRelease, ID: tag, Name: tag}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ var ErrInvalidPasswordResetCode = errors.New("invalid password reset code")
|
||||
var ErrPasswordResetCodeExpired = errors.New("password reset code expired")
|
||||
var ErrInvalidDisplayName = errors.New("invalid display name")
|
||||
var ErrUsernameTaken = errors.New("username taken")
|
||||
var ErrVerificationEmailNotSent = errors.New("verification email not sent")
|
||||
|
||||
type Role string
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package auditing
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Recorder struct {
|
||||
repository audit.Repository
|
||||
now func() time.Time
|
||||
logger *log.Logger
|
||||
}
|
||||
|
||||
var _ audit.Recorder = &Recorder{}
|
||||
|
||||
func NewRecorder(repository audit.Repository, now func() time.Time, logger *log.Logger) *Recorder {
|
||||
return &Recorder{repository, now, logger}
|
||||
}
|
||||
|
||||
func (r *Recorder) Record(ctx context.Context, event audit.Event) {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
r.logger.Printf("audit: writing the %s event panicked: %v", event.Action, recovered)
|
||||
}
|
||||
}()
|
||||
|
||||
event = r.complete(ctx, event).Truncated()
|
||||
if err := event.Validate(); err != nil {
|
||||
r.logger.Printf("audit: dropped the %s event: %v", event.Action, err)
|
||||
return
|
||||
}
|
||||
if _, err := r.repository.Append(event); err != nil {
|
||||
r.logger.Printf("audit: failed to write the %s event: %v", event.Action, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Recorder) complete(ctx context.Context, event audit.Event) audit.Event {
|
||||
origin, _ := audit.OriginFrom(ctx)
|
||||
if event.Actor.Type == "" {
|
||||
event.Actor = origin.Actor
|
||||
}
|
||||
if event.Source == "" {
|
||||
event.Source = origin.Source
|
||||
}
|
||||
if event.IP == nil && origin.IP != "" {
|
||||
ip := origin.IP
|
||||
event.IP = &ip
|
||||
}
|
||||
if event.UserAgent == nil && origin.UserAgent != "" {
|
||||
userAgent := origin.UserAgent
|
||||
event.UserAgent = &userAgent
|
||||
}
|
||||
event.CreatedAt = r.now().UTC()
|
||||
return event
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
)
|
||||
|
||||
func Migrate(db *gorm.DB) error {
|
||||
err := tableOptionsFor(db).AutoMigrate(&models.Article{}, &models.Image{}, &models.User{}, &models.Invite{}, &models.APIKey{}, &models.PurgeSettings{})
|
||||
err := tableOptionsFor(db).AutoMigrate(&models.Article{}, &models.Image{}, &models.User{}, &models.Invite{}, &models.APIKey{}, &models.PurgeSettings{}, &models.AuditEvent{}, &models.AuditSettings{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
package mappers
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/infrastructure/persistence/models"
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
const (
|
||||
emptyParams = "{}"
|
||||
emptyChanges = "[]"
|
||||
)
|
||||
|
||||
func AuditEventToModel(e audit.Event) (models.AuditEvent, error) {
|
||||
params, err := encodeJSON(e.Params, emptyParams)
|
||||
if err != nil {
|
||||
return models.AuditEvent{}, err
|
||||
}
|
||||
changes, err := encodeJSON(e.Changes, emptyChanges)
|
||||
if err != nil {
|
||||
return models.AuditEvent{}, err
|
||||
}
|
||||
return models.AuditEvent{
|
||||
ID: e.ID,
|
||||
CreatedAt: e.CreatedAt.UTC(),
|
||||
Action: e.Action,
|
||||
Category: string(e.Category),
|
||||
ActorType: string(e.Actor.Type),
|
||||
ActorID: e.Actor.ID,
|
||||
ActorName: e.Actor.Name,
|
||||
TargetType: e.Target.Type,
|
||||
TargetID: e.Target.ID,
|
||||
TargetName: e.Target.Name,
|
||||
Outcome: string(e.Outcome),
|
||||
FailureReason: e.FailureReason,
|
||||
Security: e.Security,
|
||||
Source: string(e.Source),
|
||||
IP: e.IP,
|
||||
UserAgent: e.UserAgent,
|
||||
Params: params,
|
||||
Changes: changes,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func AuditEventToDomain(m models.AuditEvent) (audit.Event, error) {
|
||||
params := map[string]any{}
|
||||
if err := json.Unmarshal([]byte(m.Params), ¶ms); err != nil {
|
||||
return audit.Event{}, err
|
||||
}
|
||||
changes := []audit.Change{}
|
||||
if err := json.Unmarshal([]byte(m.Changes), &changes); err != nil {
|
||||
return audit.Event{}, err
|
||||
}
|
||||
return audit.Event{
|
||||
ID: m.ID,
|
||||
CreatedAt: m.CreatedAt.UTC(),
|
||||
Action: m.Action,
|
||||
Category: audit.Category(m.Category),
|
||||
Actor: audit.Actor{Type: audit.ActorType(m.ActorType), ID: m.ActorID, Name: m.ActorName},
|
||||
Target: audit.Target{Type: m.TargetType, ID: m.TargetID, Name: m.TargetName},
|
||||
Outcome: audit.Outcome(m.Outcome),
|
||||
FailureReason: m.FailureReason,
|
||||
Security: m.Security,
|
||||
Source: audit.Source(m.Source),
|
||||
IP: m.IP,
|
||||
UserAgent: m.UserAgent,
|
||||
Params: params,
|
||||
Changes: changes,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func encodeJSON(value any, empty string) (string, error) {
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if string(encoded) == "null" {
|
||||
return empty, nil
|
||||
}
|
||||
return string(encoded), nil
|
||||
}
|
||||
|
||||
func AuditSettingsToDomain(m models.AuditSettings) audit.Settings {
|
||||
return audit.Settings{
|
||||
RetentionDays: m.RetentionDays,
|
||||
LastCleanupAt: m.LastCleanupAt,
|
||||
LastCleanupRemoved: m.LastCleanupRemoved,
|
||||
}
|
||||
}
|
||||
|
||||
func AuditSettingsToModel(s audit.Settings) models.AuditSettings {
|
||||
return models.AuditSettings{
|
||||
RetentionDays: s.RetentionDays,
|
||||
LastCleanupAt: s.LastCleanupAt,
|
||||
LastCleanupRemoved: s.LastCleanupRemoved,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type AuditEvent struct {
|
||||
ID uint64 `gorm:"primaryKey;autoIncrement"`
|
||||
CreatedAt time.Time `gorm:"not null;index:idx_audit_events_created_at;index:idx_audit_events_actor,priority:3;index:idx_audit_events_category,priority:2"`
|
||||
Action string `gorm:"not null;size:64"`
|
||||
Category string `gorm:"not null;size:16;index:idx_audit_events_category,priority:1"`
|
||||
ActorType string `gorm:"not null;size:16;index:idx_audit_events_actor,priority:1"`
|
||||
ActorID *uint32 `gorm:"index:idx_audit_events_actor,priority:2"`
|
||||
ActorName string `gorm:"not null;size:255"`
|
||||
TargetType string `gorm:"not null;size:32"`
|
||||
TargetID string `gorm:"not null;size:64"`
|
||||
TargetName string `gorm:"not null;size:255"`
|
||||
Outcome string `gorm:"not null;size:16"`
|
||||
FailureReason *string `gorm:"size:255"`
|
||||
Security bool `gorm:"not null"`
|
||||
Source string `gorm:"not null;size:16"`
|
||||
IP *string `gorm:"size:64"`
|
||||
UserAgent *string `gorm:"size:255"`
|
||||
Params string `gorm:"not null;type:text"`
|
||||
Changes string `gorm:"not null;type:text"`
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type AuditSettings struct {
|
||||
ID uint32 `gorm:"primaryKey"`
|
||||
RetentionDays int `gorm:"not null"`
|
||||
LastCleanupAt *time.Time
|
||||
LastCleanupRemoved int `gorm:"not null"`
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package persistence
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/infrastructure/persistence/mappers"
|
||||
entity "RenewCMS/internal/infrastructure/persistence/models"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const likeEscape = " ESCAPE '!'"
|
||||
|
||||
type AuditEventRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
var _ audit.Repository = &AuditEventRepository{}
|
||||
|
||||
func NewAuditEventRepository(db *gorm.DB) *AuditEventRepository {
|
||||
return &AuditEventRepository{db}
|
||||
}
|
||||
|
||||
func (a *AuditEventRepository) Append(event audit.Event) (audit.Event, error) {
|
||||
model, err := mappers.AuditEventToModel(event)
|
||||
if err != nil {
|
||||
return audit.Event{}, err
|
||||
}
|
||||
model.ID = 0
|
||||
if err := a.db.Create(&model).Error; err != nil {
|
||||
return audit.Event{}, err
|
||||
}
|
||||
return mappers.AuditEventToDomain(model)
|
||||
}
|
||||
|
||||
func (a *AuditEventRepository) List(filter audit.Filter) (audit.Page, error) {
|
||||
var total int64
|
||||
if err := a.filtered(filter).Count(&total).Error; err != nil {
|
||||
return audit.Page{}, err
|
||||
}
|
||||
|
||||
query := a.filtered(filter).Order("created_at DESC, id DESC")
|
||||
if filter.Size > 0 {
|
||||
query = query.Limit(filter.Size).Offset(offsetOf(filter))
|
||||
}
|
||||
var found []entity.AuditEvent
|
||||
if err := query.Find(&found).Error; err != nil {
|
||||
return audit.Page{}, err
|
||||
}
|
||||
|
||||
items := make([]audit.Event, 0, len(found))
|
||||
for _, model := range found {
|
||||
event, err := mappers.AuditEventToDomain(model)
|
||||
if err != nil {
|
||||
return audit.Page{}, err
|
||||
}
|
||||
items = append(items, event)
|
||||
}
|
||||
return audit.Page{Items: items, Total: int(total)}, nil
|
||||
}
|
||||
|
||||
func offsetOf(filter audit.Filter) int {
|
||||
if filter.Page < 1 {
|
||||
return 0
|
||||
}
|
||||
return (filter.Page - 1) * filter.Size
|
||||
}
|
||||
|
||||
func (a *AuditEventRepository) filtered(filter audit.Filter) *gorm.DB {
|
||||
query := a.db.Model(&entity.AuditEvent{})
|
||||
if filter.Actor != nil {
|
||||
query = query.Where("actor_type = ?", string(filter.Actor.Type))
|
||||
if filter.Actor.ID != nil {
|
||||
query = query.Where("actor_id = ?", *filter.Actor.ID)
|
||||
}
|
||||
}
|
||||
if filter.Category != "" {
|
||||
query = query.Where("category = ?", string(filter.Category))
|
||||
}
|
||||
if filter.Outcome != "" {
|
||||
query = query.Where("outcome = ?", string(filter.Outcome))
|
||||
}
|
||||
if filter.Security {
|
||||
query = query.Where("security = ?", true)
|
||||
}
|
||||
if filter.From != nil {
|
||||
query = query.Where("created_at >= ?", filter.From.UTC())
|
||||
}
|
||||
if filter.To != nil {
|
||||
query = query.Where("created_at < ?", filter.To.UTC())
|
||||
}
|
||||
if filter.Query != "" {
|
||||
pattern := containsPattern(strings.ToLower(filter.Query))
|
||||
query = query.Where("(LOWER(actor_name) LIKE ?"+likeEscape+" OR LOWER(target_name) LIKE ?"+likeEscape+")", pattern, pattern)
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
func (a *AuditEventRepository) Summary(query audit.SummaryQuery) (audit.Summary, error) {
|
||||
var summary audit.Summary
|
||||
totals, err := a.countsBetween(query.From, query.To)
|
||||
if err != nil {
|
||||
return audit.Summary{}, err
|
||||
}
|
||||
summary.Total, summary.Failed, summary.Security = totals.Total, totals.Failed, totals.Security
|
||||
|
||||
previous := query.Previous()
|
||||
previousTotals, err := a.countsBetween(previous.From, previous.To)
|
||||
if err != nil {
|
||||
return audit.Summary{}, err
|
||||
}
|
||||
summary.PreviousTotal = previousTotals.Total
|
||||
|
||||
if summary.ActivePeople.Users, err = a.distinctActors(audit.ActorUser, query.From, query.To); err != nil {
|
||||
return audit.Summary{}, err
|
||||
}
|
||||
if summary.ActivePeople.APIKeys, err = a.distinctActors(audit.ActorAPIKey, query.From, query.To); err != nil {
|
||||
return audit.Summary{}, err
|
||||
}
|
||||
summary.Series, err = a.series(query)
|
||||
return summary, err
|
||||
}
|
||||
|
||||
type countsRow struct {
|
||||
Total int
|
||||
Failed int
|
||||
Security int
|
||||
}
|
||||
|
||||
func (a *AuditEventRepository) countsBetween(from time.Time, to time.Time) (countsRow, error) {
|
||||
var row countsRow
|
||||
err := a.db.Model(&entity.AuditEvent{}).
|
||||
Select("COUNT(*) AS total, "+
|
||||
"COALESCE(SUM(CASE WHEN outcome = ? THEN 1 ELSE 0 END), 0) AS failed, "+
|
||||
"COALESCE(SUM(CASE WHEN security = ? THEN 1 ELSE 0 END), 0) AS security", string(audit.OutcomeFailed), true).
|
||||
Where("created_at >= ? AND created_at < ?", from.UTC(), to.UTC()).
|
||||
Scan(&row).Error
|
||||
return row, err
|
||||
}
|
||||
|
||||
func (a *AuditEventRepository) distinctActors(actorType audit.ActorType, from time.Time, to time.Time) (int, error) {
|
||||
var count int64
|
||||
err := a.db.Model(&entity.AuditEvent{}).
|
||||
Where("actor_type = ? AND created_at >= ? AND created_at < ?", string(actorType), from.UTC(), to.UTC()).
|
||||
Distinct("actor_id").
|
||||
Count(&count).Error
|
||||
return int(count), err
|
||||
}
|
||||
|
||||
func (a *AuditEventRepository) series(query audit.SummaryQuery) (audit.Series, error) {
|
||||
series := audit.Series{
|
||||
Total: make([]int, audit.SeriesBuckets),
|
||||
Active: make([]int, audit.SeriesBuckets),
|
||||
Failed: make([]int, audit.SeriesBuckets),
|
||||
Security: make([]int, audit.SeriesBuckets),
|
||||
}
|
||||
width := query.To.Sub(query.From) / audit.SeriesBuckets
|
||||
if width <= 0 {
|
||||
return series, nil
|
||||
}
|
||||
for i := 0; i < audit.SeriesBuckets; i++ {
|
||||
from := query.From.Add(time.Duration(i) * width)
|
||||
to := from.Add(width)
|
||||
if i == audit.SeriesBuckets-1 {
|
||||
to = query.To
|
||||
}
|
||||
counts, err := a.countsBetween(from, to)
|
||||
if err != nil {
|
||||
return audit.Series{}, err
|
||||
}
|
||||
users, err := a.distinctActors(audit.ActorUser, from, to)
|
||||
if err != nil {
|
||||
return audit.Series{}, err
|
||||
}
|
||||
keys, err := a.distinctActors(audit.ActorAPIKey, from, to)
|
||||
if err != nil {
|
||||
return audit.Series{}, err
|
||||
}
|
||||
series.Total[i], series.Failed[i], series.Security[i], series.Active[i] = counts.Total, counts.Failed, counts.Security, users+keys
|
||||
}
|
||||
return series, nil
|
||||
}
|
||||
|
||||
func (a *AuditEventRepository) DeleteOlderThan(cutoff time.Time) (int, error) {
|
||||
result := a.db.Where("created_at < ?", cutoff.UTC()).Delete(&entity.AuditEvent{})
|
||||
return int(result.RowsAffected), result.Error
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package persistence
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/infrastructure/persistence/mappers"
|
||||
entity "RenewCMS/internal/infrastructure/persistence/models"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const auditSettingsRowID uint32 = 1
|
||||
|
||||
type AuditSettingsRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
var _ audit.SettingsRepository = &AuditSettingsRepository{}
|
||||
|
||||
func NewAuditSettingsRepository(db *gorm.DB) *AuditSettingsRepository {
|
||||
return &AuditSettingsRepository{db}
|
||||
}
|
||||
|
||||
func (a *AuditSettingsRepository) Get() (audit.Settings, error) {
|
||||
var model entity.AuditSettings
|
||||
err := a.db.First(&model, auditSettingsRowID).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return audit.DefaultSettings(), nil
|
||||
}
|
||||
if err != nil {
|
||||
return audit.Settings{}, err
|
||||
}
|
||||
return mappers.AuditSettingsToDomain(model), nil
|
||||
}
|
||||
|
||||
func (a *AuditSettingsRepository) SaveRetention(days int) error {
|
||||
return a.update(map[string]any{"retention_days": days}, func(settings *audit.Settings) {
|
||||
settings.RetentionDays = days
|
||||
})
|
||||
}
|
||||
|
||||
func (a *AuditSettingsRepository) SaveLastCleanup(at time.Time, removed int) error {
|
||||
utc := at.UTC()
|
||||
return a.update(map[string]any{"last_cleanup_at": utc, "last_cleanup_removed": removed}, func(settings *audit.Settings) {
|
||||
settings.LastCleanupAt = &utc
|
||||
settings.LastCleanupRemoved = removed
|
||||
})
|
||||
}
|
||||
|
||||
func (a *AuditSettingsRepository) update(columns map[string]any, apply func(*audit.Settings)) error {
|
||||
result := a.db.Model(&entity.AuditSettings{}).Where("id = ?", auditSettingsRowID).Updates(columns)
|
||||
if result.Error != nil || result.RowsAffected > 0 {
|
||||
return result.Error
|
||||
}
|
||||
settings := audit.DefaultSettings()
|
||||
apply(&settings)
|
||||
model := mappers.AuditSettingsToModel(settings)
|
||||
model.ID = auditSettingsRowID
|
||||
return a.db.Create(&model).Error
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
package scheduler
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/purge"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
@@ -17,8 +19,39 @@ type Job interface {
|
||||
Tick(now time.Time) (purge.RunResult, bool, error)
|
||||
}
|
||||
|
||||
type Runner struct {
|
||||
type CleanupJob interface {
|
||||
Tick(now time.Time) (audit.CleanupResult, bool, error)
|
||||
}
|
||||
|
||||
type task interface {
|
||||
tick(now time.Time) (summary string, ran bool, err error)
|
||||
}
|
||||
|
||||
type purgeTask struct {
|
||||
job Job
|
||||
}
|
||||
|
||||
func (p purgeTask) tick(now time.Time) (string, bool, error) {
|
||||
result, ran, err := p.job.Tick(now)
|
||||
if errors.Is(err, purge.ErrPurgeBusy) {
|
||||
return "", false, nil
|
||||
}
|
||||
summary := fmt.Sprintf("groups_purged=%d merged=%d articles_updated=%d failed_groups=%d", result.GroupsPurged, result.Merged, result.ArticlesUpdated, result.FailedGroups)
|
||||
return summary, ran, err
|
||||
}
|
||||
|
||||
type cleanupTask struct {
|
||||
job CleanupJob
|
||||
}
|
||||
|
||||
func (c cleanupTask) tick(now time.Time) (string, bool, error) {
|
||||
result, ran, err := c.job.Tick(now)
|
||||
return fmt.Sprintf("removed=%d", result.Removed), ran, err
|
||||
}
|
||||
|
||||
type Runner struct {
|
||||
label string
|
||||
task task
|
||||
now func() time.Time
|
||||
ticks <-chan time.Time
|
||||
startup <-chan time.Time
|
||||
@@ -26,14 +59,39 @@ type Runner struct {
|
||||
release func()
|
||||
}
|
||||
|
||||
const (
|
||||
purgeLabel = "automatic purge"
|
||||
cleanupLabel = "activity cleanup"
|
||||
)
|
||||
|
||||
func newRunner(label string, task task, now func() time.Time, ticks <-chan time.Time, startup <-chan time.Time, logger *log.Logger) *Runner {
|
||||
return &Runner{label: label, task: task, now: now, ticks: ticks, startup: startup, logger: logger, release: func() {}}
|
||||
}
|
||||
|
||||
func NewRunner(job Job, now func() time.Time, ticks <-chan time.Time, startup <-chan time.Time, logger *log.Logger) *Runner {
|
||||
return &Runner{job: job, now: now, ticks: ticks, startup: startup, logger: logger, release: func() {}}
|
||||
return newRunner(purgeLabel, purgeTask{job}, now, ticks, startup, logger)
|
||||
}
|
||||
|
||||
func NewCleanupRunner(job CleanupJob, now func() time.Time, ticks <-chan time.Time, startup <-chan time.Time, logger *log.Logger) *Runner {
|
||||
return newRunner(cleanupLabel, cleanupTask{job}, now, ticks, startup, logger)
|
||||
}
|
||||
|
||||
func NewSystemRunner(job Job, logger *log.Logger) *Runner {
|
||||
return withSystemTimers(func(now func() time.Time, ticks <-chan time.Time, startup <-chan time.Time) *Runner {
|
||||
return NewRunner(job, now, ticks, startup, logger)
|
||||
})
|
||||
}
|
||||
|
||||
func NewSystemCleanupRunner(job CleanupJob, logger *log.Logger) *Runner {
|
||||
return withSystemTimers(func(now func() time.Time, ticks <-chan time.Time, startup <-chan time.Time) *Runner {
|
||||
return NewCleanupRunner(job, now, ticks, startup, logger)
|
||||
})
|
||||
}
|
||||
|
||||
func withSystemTimers(build func(now func() time.Time, ticks <-chan time.Time, startup <-chan time.Time) *Runner) *Runner {
|
||||
ticker := time.NewTicker(TickInterval)
|
||||
startup := time.NewTimer(StartupDelay)
|
||||
runner := NewRunner(job, time.Now, ticker.C, startup.C, logger)
|
||||
runner := build(time.Now, ticker.C, startup.C)
|
||||
runner.release = func() {
|
||||
ticker.Stop()
|
||||
startup.Stop()
|
||||
@@ -61,15 +119,12 @@ func (r *Runner) tick(ctx context.Context) {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
result, ran, err := r.job.Tick(r.now())
|
||||
if errors.Is(err, purge.ErrPurgeBusy) {
|
||||
return
|
||||
}
|
||||
summary, ran, err := r.task.tick(r.now())
|
||||
if err != nil {
|
||||
r.logger.Printf("scheduler: automatic purge failed: %v", err)
|
||||
r.logger.Printf("scheduler: %s failed: %v", r.label, err)
|
||||
return
|
||||
}
|
||||
if ran {
|
||||
r.logger.Printf("scheduler: automatic purge completed: groups_purged=%d merged=%d articles_updated=%d failed_groups=%d", result.GroupsPurged, result.Merged, result.ArticlesUpdated, result.FailedGroups)
|
||||
r.logger.Printf("scheduler: %s completed: %s", r.label, summary)
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/hash"
|
||||
"RenewCMS/internal/domain/invite"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -13,6 +15,7 @@ type AcceptInviteUseCase struct {
|
||||
userRepository user.Repository
|
||||
inviteRepository invite.Repository
|
||||
hasher hash.Hasher
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
type AcceptInviteCommand struct {
|
||||
@@ -21,18 +24,37 @@ type AcceptInviteCommand struct {
|
||||
Password string
|
||||
}
|
||||
|
||||
func NewAcceptInviteUseCase(userRepository user.Repository, inviteRepository invite.Repository, hasher hash.Hasher) *AcceptInviteUseCase {
|
||||
return &AcceptInviteUseCase{userRepository, inviteRepository, hasher}
|
||||
func NewAcceptInviteUseCase(userRepository user.Repository, inviteRepository invite.Repository, hasher hash.Hasher, recorder audit.Recorder) *AcceptInviteUseCase {
|
||||
return &AcceptInviteUseCase{userRepository, inviteRepository, hasher, recorder}
|
||||
}
|
||||
|
||||
func (a *AcceptInviteUseCase) AcceptInvite(command AcceptInviteCommand) (user.User, error) {
|
||||
func (a *AcceptInviteUseCase) AcceptInvite(ctx context.Context, command AcceptInviteCommand) (user.User, error) {
|
||||
event := audit.NewEvent(audit.ActionInviteAccept, audit.CategoryUsers)
|
||||
now := time.Now()
|
||||
|
||||
pending, err := findUsableInvite(a.inviteRepository, a.hasher, command.Code, now)
|
||||
if err != nil {
|
||||
a.recordRefusal(ctx, event, command, err)
|
||||
return user.User{}, err
|
||||
}
|
||||
event.Target = inviteTarget(pending)
|
||||
|
||||
created, err := a.accept(command, pending, now)
|
||||
if err != nil {
|
||||
a.recordRefusal(ctx, event, command, err)
|
||||
return user.User{}, err
|
||||
}
|
||||
event.Actor = audit.UserActor(created)
|
||||
a.recorder.Record(ctx, event)
|
||||
return created, nil
|
||||
}
|
||||
|
||||
func (a *AcceptInviteUseCase) recordRefusal(ctx context.Context, event audit.Event, command AcceptInviteCommand, cause error) {
|
||||
event.Actor = audit.AnonymousActor(command.Username)
|
||||
recordFailure(ctx, a.recorder, event, cause)
|
||||
}
|
||||
|
||||
func (a *AcceptInviteUseCase) accept(command AcceptInviteCommand, pending invite.Invite, now time.Time) (user.User, error) {
|
||||
if a.emailHasAccount(pending.Email) {
|
||||
if _, err := findUsableInvite(a.inviteRepository, a.hasher, command.Code, now); err != nil {
|
||||
return user.User{}, err
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
type GetActivityRetentionUseCase struct {
|
||||
settings audit.SettingsRepository
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewGetActivityRetentionUseCase(settings audit.SettingsRepository, now func() time.Time) *GetActivityRetentionUseCase {
|
||||
return &GetActivityRetentionUseCase{settings, now}
|
||||
}
|
||||
|
||||
func (g *GetActivityRetentionUseCase) GetActivityRetention() (audit.Settings, error) {
|
||||
current, err := g.settings.Get()
|
||||
if err != nil {
|
||||
return audit.Settings{}, err
|
||||
}
|
||||
return current.WithNextCleanup(g.now()), nil
|
||||
}
|
||||
|
||||
type UpdateActivityRetentionUseCase struct {
|
||||
settings audit.SettingsRepository
|
||||
recorder audit.Recorder
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewUpdateActivityRetentionUseCase(settings audit.SettingsRepository, recorder audit.Recorder, now func() time.Time) *UpdateActivityRetentionUseCase {
|
||||
return &UpdateActivityRetentionUseCase{settings, recorder, now}
|
||||
}
|
||||
|
||||
func (u *UpdateActivityRetentionUseCase) UpdateActivityRetention(ctx context.Context, days int) (audit.Settings, error) {
|
||||
if err := audit.ValidateRetentionDays(days); err != nil {
|
||||
return audit.Settings{}, err
|
||||
}
|
||||
current, err := u.settings.Get()
|
||||
if err != nil {
|
||||
return audit.Settings{}, err
|
||||
}
|
||||
if current.RetentionDays == days {
|
||||
return current.WithNextCleanup(u.now()), nil
|
||||
}
|
||||
if err := u.settings.SaveRetention(days); err != nil {
|
||||
return audit.Settings{}, err
|
||||
}
|
||||
|
||||
event := audit.NewEvent(audit.ActionRetentionChanged, audit.CategorySystem)
|
||||
event.Params = map[string]any{audit.ParamFrom: current.RetentionDays, audit.ParamTo: days}
|
||||
u.recorder.Record(ctx, event)
|
||||
|
||||
current.RetentionDays = days
|
||||
return current.WithNextCleanup(u.now()), nil
|
||||
}
|
||||
@@ -1,20 +1,37 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/hash"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"context"
|
||||
"errors"
|
||||
)
|
||||
|
||||
type AuthenticateUserUseCase struct {
|
||||
userRepository user.Repository
|
||||
hasher hash.Hasher
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
func NewAuthenticateUserUseCase(userRepository user.Repository, hasher hash.Hasher) *AuthenticateUserUseCase {
|
||||
return &AuthenticateUserUseCase{userRepository, hasher}
|
||||
func NewAuthenticateUserUseCase(userRepository user.Repository, hasher hash.Hasher, recorder audit.Recorder) *AuthenticateUserUseCase {
|
||||
return &AuthenticateUserUseCase{userRepository, hasher, recorder}
|
||||
}
|
||||
|
||||
func (a *AuthenticateUserUseCase) Authenticate(username string, password string) (user.User, error) {
|
||||
func (a *AuthenticateUserUseCase) Authenticate(ctx context.Context, username string, password string) (user.User, error) {
|
||||
dbUser, err := a.verifyCredentials(username, password)
|
||||
if err != nil {
|
||||
a.recordRejectedLogin(ctx, username, err)
|
||||
return user.User{}, err
|
||||
}
|
||||
|
||||
event := audit.NewEvent(audit.ActionLogin, audit.CategoryAuth)
|
||||
event.Actor = audit.UserActor(dbUser)
|
||||
a.recorder.Record(ctx, event)
|
||||
return dbUser, nil
|
||||
}
|
||||
|
||||
func (a *AuthenticateUserUseCase) verifyCredentials(username string, password string) (user.User, error) {
|
||||
dbUser, err := a.userRepository.GetByUsername(username)
|
||||
if err != nil {
|
||||
return user.User{}, err
|
||||
@@ -26,3 +43,24 @@ func (a *AuthenticateUserUseCase) Authenticate(username string, password string)
|
||||
|
||||
return dbUser, nil
|
||||
}
|
||||
|
||||
func (a *AuthenticateUserUseCase) recordRejectedLogin(ctx context.Context, username string, cause error) {
|
||||
if !errors.Is(cause, user.ErrUserNotFound) && !errors.Is(cause, user.ErrInvalidCredentials) {
|
||||
return
|
||||
}
|
||||
reason := audit.ReasonWrongLogin
|
||||
event := audit.NewEvent(audit.ActionLoginFailed, audit.CategoryAuth)
|
||||
event.Actor = audit.AnonymousActor(username)
|
||||
event.Outcome = audit.OutcomeFailed
|
||||
event.FailureReason = &reason
|
||||
event.Security = true
|
||||
a.recorder.Record(ctx, event)
|
||||
}
|
||||
|
||||
func (a *AuthenticateUserUseCase) Logout(ctx context.Context) {
|
||||
origin, ok := audit.OriginFrom(ctx)
|
||||
if !ok || origin.Actor.Type != audit.ActorUser {
|
||||
return
|
||||
}
|
||||
a.recorder.Record(ctx, audit.NewEvent(audit.ActionLogout, audit.CategoryAuth))
|
||||
}
|
||||
@@ -1,18 +1,36 @@
|
||||
package useCases
|
||||
|
||||
import "RenewCMS/internal/domain/invite"
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/invite"
|
||||
"context"
|
||||
)
|
||||
|
||||
type CancelInviteUseCase struct {
|
||||
inviteRepository invite.Repository
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
func NewCancelInviteUseCase(inviteRepository invite.Repository) *CancelInviteUseCase {
|
||||
return &CancelInviteUseCase{inviteRepository}
|
||||
func NewCancelInviteUseCase(inviteRepository invite.Repository, recorder audit.Recorder) *CancelInviteUseCase {
|
||||
return &CancelInviteUseCase{inviteRepository, recorder}
|
||||
}
|
||||
|
||||
func (c *CancelInviteUseCase) CancelInvite(id uint32) error {
|
||||
if _, err := findManageableInvite(c.inviteRepository, id); err != nil {
|
||||
func (c *CancelInviteUseCase) CancelInvite(ctx context.Context, id uint32) error {
|
||||
event := audit.NewEvent(audit.ActionInviteCancel, audit.CategoryUsers)
|
||||
pending, err := findManageableInvite(c.inviteRepository, id)
|
||||
if err != nil {
|
||||
recordFailure(ctx, c.recorder, event, err)
|
||||
return err
|
||||
}
|
||||
return c.inviteRepository.Delete(id)
|
||||
event.Target = inviteTarget(pending)
|
||||
if err := c.inviteRepository.Delete(id); err != nil {
|
||||
recordFailure(ctx, c.recorder, event, err)
|
||||
return err
|
||||
}
|
||||
c.recorder.Record(ctx, event)
|
||||
return nil
|
||||
}
|
||||
|
||||
func inviteTarget(i invite.Invite) audit.Target {
|
||||
return audit.NewTarget(audit.TargetInvite, i.ID, i.Email)
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/update"
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -10,13 +12,27 @@ type CheckForUpdateUseCase struct {
|
||||
store update.StatusStore
|
||||
currentVersion string
|
||||
now func() time.Time
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
func NewCheckForUpdateUseCase(feed update.ReleaseFeed, store update.StatusStore, currentVersion string, now func() time.Time) *CheckForUpdateUseCase {
|
||||
return &CheckForUpdateUseCase{feed: feed, store: store, currentVersion: currentVersion, now: now}
|
||||
func NewCheckForUpdateUseCase(feed update.ReleaseFeed, store update.StatusStore, currentVersion string, now func() time.Time, recorder audit.Recorder) *CheckForUpdateUseCase {
|
||||
return &CheckForUpdateUseCase{feed: feed, store: store, currentVersion: currentVersion, now: now, recorder: recorder}
|
||||
}
|
||||
|
||||
func (c *CheckForUpdateUseCase) Check() (update.UpdateStatus, error) {
|
||||
func (c *CheckForUpdateUseCase) Check(ctx context.Context) (update.UpdateStatus, error) {
|
||||
event := audit.NewEvent(audit.ActionUpdateChecked, audit.CategorySystem)
|
||||
status, err := c.check()
|
||||
if err != nil {
|
||||
recordFailure(ctx, c.recorder, event, err)
|
||||
return update.UpdateStatus{}, err
|
||||
}
|
||||
event.Target = audit.ReleaseTarget(status.Latest)
|
||||
event.Params = map[string]any{audit.ParamUpdateAvailable: status.Available}
|
||||
c.recorder.Record(ctx, event)
|
||||
return status, nil
|
||||
}
|
||||
|
||||
func (c *CheckForUpdateUseCase) check() (update.UpdateStatus, error) {
|
||||
release, err := c.feed.Latest()
|
||||
if err != nil {
|
||||
return update.UpdateStatus{}, err
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
type CleanupActivityUseCase struct {
|
||||
events audit.Repository
|
||||
settings audit.SettingsRepository
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
func NewCleanupActivityUseCase(events audit.Repository, settings audit.SettingsRepository, recorder audit.Recorder) *CleanupActivityUseCase {
|
||||
return &CleanupActivityUseCase{events, settings, recorder}
|
||||
}
|
||||
|
||||
func (c *CleanupActivityUseCase) Tick(now time.Time) (audit.CleanupResult, bool, error) {
|
||||
settings, err := c.settings.Get()
|
||||
if err != nil {
|
||||
return audit.CleanupResult{}, false, err
|
||||
}
|
||||
if settings.RetentionDays == audit.ForeverRetentionDays || !settings.CleanupDue(now) {
|
||||
return audit.CleanupResult{}, false, nil
|
||||
}
|
||||
|
||||
removed, err := c.events.DeleteOlderThan(audit.RetentionCutoff(now, settings.RetentionDays))
|
||||
if err != nil {
|
||||
return audit.CleanupResult{}, false, err
|
||||
}
|
||||
if err := c.settings.SaveLastCleanup(now, removed); err != nil {
|
||||
return audit.CleanupResult{}, false, err
|
||||
}
|
||||
if removed > 0 {
|
||||
c.recordCleanup(removed)
|
||||
}
|
||||
return audit.CleanupResult{Removed: removed}, true, nil
|
||||
}
|
||||
|
||||
func (c *CleanupActivityUseCase) recordCleanup(removed int) {
|
||||
event := audit.NewEvent(audit.ActionCleanup, audit.CategorySystem)
|
||||
event.Actor = audit.SystemActor()
|
||||
event.Source = audit.SourceSystem
|
||||
event.Params = map[string]any{audit.ParamRemoved: removed}
|
||||
c.recorder.Record(context.Background(), event)
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/apikey"
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -9,6 +11,7 @@ type CreateAPIKeyUseCase struct {
|
||||
apiKeyRepository apikey.Repository
|
||||
keyGenerator apikey.KeyGenerator
|
||||
now func() time.Time
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
type CreateAPIKeyCommand struct {
|
||||
@@ -22,11 +25,11 @@ type CreatedAPIKey struct {
|
||||
RawKey string
|
||||
}
|
||||
|
||||
func NewCreateAPIKeyUseCase(apiKeyRepository apikey.Repository, keyGenerator apikey.KeyGenerator, now func() time.Time) *CreateAPIKeyUseCase {
|
||||
return &CreateAPIKeyUseCase{apiKeyRepository, keyGenerator, now}
|
||||
func NewCreateAPIKeyUseCase(apiKeyRepository apikey.Repository, keyGenerator apikey.KeyGenerator, now func() time.Time, recorder audit.Recorder) *CreateAPIKeyUseCase {
|
||||
return &CreateAPIKeyUseCase{apiKeyRepository, keyGenerator, now, recorder}
|
||||
}
|
||||
|
||||
func (c *CreateAPIKeyUseCase) CreateAPIKey(command CreateAPIKeyCommand) (CreatedAPIKey, error) {
|
||||
func (c *CreateAPIKeyUseCase) CreateAPIKey(ctx context.Context, command CreateAPIKeyCommand) (CreatedAPIKey, error) {
|
||||
now := c.now()
|
||||
if command.ExpiresAt != nil && !command.ExpiresAt.After(now) {
|
||||
return CreatedAPIKey{}, apikey.ErrExpiryNotInFuture
|
||||
@@ -45,5 +48,9 @@ func (c *CreateAPIKeyUseCase) CreateAPIKey(command CreateAPIKeyCommand) (Created
|
||||
return CreatedAPIKey{}, err
|
||||
}
|
||||
|
||||
event := audit.NewEvent(audit.ActionAPIKeyCreate, audit.CategoryAPIKeys)
|
||||
event.Target = audit.APIKeyTarget(stored.ID, stored.Name)
|
||||
c.recorder.Record(ctx, event)
|
||||
|
||||
return CreatedAPIKey{Key: stored, RawKey: rawKey}, nil
|
||||
}
|
||||
@@ -2,11 +2,14 @@ package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/article"
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"context"
|
||||
)
|
||||
|
||||
type CreateArticleUseCase struct {
|
||||
articleRepository article.Repository
|
||||
bodyRenderer article.BodyRenderer
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
type CreateArticleCommand struct {
|
||||
@@ -15,12 +18,14 @@ type CreateArticleCommand struct {
|
||||
Format article.BodyFormat
|
||||
}
|
||||
|
||||
func NewCreateArticleUseCase(articleRepository article.Repository, bodyRenderer article.BodyRenderer) *CreateArticleUseCase {
|
||||
return &CreateArticleUseCase{articleRepository, bodyRenderer}
|
||||
func NewCreateArticleUseCase(articleRepository article.Repository, bodyRenderer article.BodyRenderer, recorder audit.Recorder) *CreateArticleUseCase {
|
||||
return &CreateArticleUseCase{articleRepository, bodyRenderer, recorder}
|
||||
}
|
||||
|
||||
func (g *CreateArticleUseCase) CreateArticle(createArticle CreateArticleCommand) (article.Article, error) {
|
||||
func (g *CreateArticleUseCase) CreateArticle(ctx context.Context, createArticle CreateArticleCommand) (article.Article, error) {
|
||||
event := audit.NewEvent(audit.ActionArticleCreate, audit.CategoryArticles)
|
||||
if err := article.ValidateTitle(createArticle.Title); err != nil {
|
||||
recordFailure(ctx, g.recorder, event, err)
|
||||
return article.Article{}, err
|
||||
}
|
||||
|
||||
@@ -30,7 +35,15 @@ func (g *CreateArticleUseCase) CreateArticle(createArticle CreateArticleCommand)
|
||||
IsOnline: false,
|
||||
})
|
||||
if err != nil {
|
||||
recordFailure(ctx, g.recorder, event, err)
|
||||
return article.Article{}, err
|
||||
}
|
||||
|
||||
event.Target = articleTarget(created)
|
||||
g.recorder.Record(ctx, event)
|
||||
return renderArticle(g.bodyRenderer, created, createArticle.Format)
|
||||
}
|
||||
|
||||
func articleTarget(a article.Article) audit.Target {
|
||||
return audit.NewTarget(audit.TargetArticle, a.ID, a.Title)
|
||||
}
|
||||
@@ -1,13 +1,16 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/image"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/xml"
|
||||
stdimage "image"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
_ "golang.org/x/image/webp"
|
||||
_ "image/jpeg"
|
||||
@@ -25,13 +28,38 @@ var rasterFormats = map[string]string{
|
||||
type CreateImageUseCase struct {
|
||||
imageRepository image.Repository
|
||||
storage image.Storage
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
func NewCreateImageUseCase(imageRepository image.Repository, storage image.Storage) *CreateImageUseCase {
|
||||
return &CreateImageUseCase{imageRepository, storage}
|
||||
func NewCreateImageUseCase(imageRepository image.Repository, storage image.Storage, recorder audit.Recorder) *CreateImageUseCase {
|
||||
return &CreateImageUseCase{imageRepository, storage, recorder}
|
||||
}
|
||||
|
||||
func (g *CreateImageUseCase) CreateImage(input image.ImageInput) (image.Image, error) {
|
||||
func (g *CreateImageUseCase) CreateImage(ctx context.Context, input image.ImageInput) (image.Image, error) {
|
||||
created, err := g.create(input)
|
||||
event := audit.NewEvent(audit.ActionMediaUpload, audit.CategoryMedia)
|
||||
if err != nil {
|
||||
event.Target = attemptedUploadTarget(input)
|
||||
recordFailure(ctx, g.recorder, event, err)
|
||||
return image.Image{}, err
|
||||
}
|
||||
event.Target = imageTarget(created)
|
||||
g.recorder.Record(ctx, event)
|
||||
return created, nil
|
||||
}
|
||||
|
||||
func imageTarget(img image.Image) audit.Target {
|
||||
return audit.NewTarget(audit.TargetImage, img.ID, img.Filename)
|
||||
}
|
||||
|
||||
func attemptedUploadTarget(input image.ImageInput) audit.Target {
|
||||
if strings.TrimSpace(input.Filename) == "" {
|
||||
return audit.Target{}
|
||||
}
|
||||
return audit.Target{Type: audit.TargetImage, Name: image.NormalizeUploadFilename(input.Filename, input.ContentType)}
|
||||
}
|
||||
|
||||
func (g *CreateImageUseCase) create(input image.ImageInput) (image.Image, error) {
|
||||
if !image.IsAllowedContentType(input.ContentType) {
|
||||
return image.Image{}, image.ErrImageTypeNotAllowed
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/hash"
|
||||
"RenewCMS/internal/domain/invite"
|
||||
"RenewCMS/internal/domain/mail"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -15,6 +17,7 @@ type CreateInviteUseCase struct {
|
||||
inviteRepository invite.Repository
|
||||
hasher hash.Hasher
|
||||
mailer inviteMailer
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
type CreateInviteCommand struct {
|
||||
@@ -22,11 +25,23 @@ type CreateInviteCommand struct {
|
||||
InvitedBy uint32
|
||||
}
|
||||
|
||||
func NewCreateInviteUseCase(userRepository user.Repository, inviteRepository invite.Repository, hasher hash.Hasher, mailRepository mail.Repository, publicURL string) *CreateInviteUseCase {
|
||||
return &CreateInviteUseCase{userRepository, inviteRepository, hasher, inviteMailer{mailRepository, publicURL}}
|
||||
func NewCreateInviteUseCase(userRepository user.Repository, inviteRepository invite.Repository, hasher hash.Hasher, mailRepository mail.Repository, publicURL string, recorder audit.Recorder) *CreateInviteUseCase {
|
||||
return &CreateInviteUseCase{userRepository, inviteRepository, hasher, inviteMailer{mailRepository, publicURL}, recorder}
|
||||
}
|
||||
|
||||
func (g *CreateInviteUseCase) CreateInvite(command CreateInviteCommand) (invite.Invite, error) {
|
||||
func (g *CreateInviteUseCase) CreateInvite(ctx context.Context, command CreateInviteCommand) (invite.Invite, error) {
|
||||
event := audit.NewEvent(audit.ActionInviteCreate, audit.CategoryUsers)
|
||||
created, err := g.create(command)
|
||||
if err != nil {
|
||||
recordFailure(ctx, g.recorder, event, err)
|
||||
return invite.Invite{}, err
|
||||
}
|
||||
event.Target = inviteTarget(created)
|
||||
g.recorder.Record(ctx, event)
|
||||
return created, nil
|
||||
}
|
||||
|
||||
func (g *CreateInviteUseCase) create(command CreateInviteCommand) (invite.Invite, error) {
|
||||
email := strings.ToLower(command.Email)
|
||||
now := time.Now()
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/hash"
|
||||
"RenewCMS/internal/domain/mail"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
@@ -16,6 +18,7 @@ type CreateUserUseCase struct {
|
||||
hasher hash.Hasher
|
||||
mailRepository mail.Repository
|
||||
publicURL string
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
type CreateUserCommand struct {
|
||||
@@ -29,11 +32,25 @@ type MailValidationData struct {
|
||||
VerificationCode string
|
||||
}
|
||||
|
||||
func NewCreateUserUseCase(userRepository user.Repository, hasher hash.Hasher, mailRepository mail.Repository, publicURL string) *CreateUserUseCase {
|
||||
return &CreateUserUseCase{userRepository, hasher, mailRepository, publicURL}
|
||||
func NewCreateUserUseCase(userRepository user.Repository, hasher hash.Hasher, mailRepository mail.Repository, publicURL string, recorder audit.Recorder) *CreateUserUseCase {
|
||||
return &CreateUserUseCase{userRepository, hasher, mailRepository, publicURL, recorder}
|
||||
}
|
||||
|
||||
func (g *CreateUserUseCase) CreateUser(createUser CreateUserCommand) (user.User, error) {
|
||||
func (g *CreateUserUseCase) CreateUser(ctx context.Context, createUser CreateUserCommand) (user.User, error) {
|
||||
event := audit.NewEvent(audit.ActionUserRegister, audit.CategoryUsers)
|
||||
created, err := g.create(createUser)
|
||||
if err != nil {
|
||||
event.Actor = audit.AnonymousActor(createUser.Username)
|
||||
recordFailure(ctx, g.recorder, event, err)
|
||||
return user.User{}, err
|
||||
}
|
||||
event.Actor = audit.UserActor(created)
|
||||
event.Target = audit.NewTarget(audit.TargetUser, created.ID, created.Username)
|
||||
g.recorder.Record(ctx, event)
|
||||
return created, nil
|
||||
}
|
||||
|
||||
func (g *CreateUserUseCase) create(createUser CreateUserCommand) (user.User, error) {
|
||||
if g.registrationClosed() {
|
||||
return user.User{}, user.ErrRegistrationClosed
|
||||
}
|
||||
@@ -70,7 +87,7 @@ func (g *CreateUserUseCase) CreateUser(createUser CreateUserCommand) (user.User,
|
||||
Host: g.publicURL,
|
||||
VerificationCode: rawUuid,
|
||||
}); err != nil {
|
||||
sendErr := fmt.Errorf("failed to send verification email: %w", err)
|
||||
sendErr := fmt.Errorf("%w: %w", user.ErrVerificationEmailNotSent, err)
|
||||
if deleteErr := g.userRepository.Delete(createdUser.ID); deleteErr != nil {
|
||||
return user.User{}, errors.Join(sendErr, deleteErr)
|
||||
}
|
||||
|
||||
@@ -1,15 +1,32 @@
|
||||
package useCases
|
||||
|
||||
import "RenewCMS/internal/domain/article"
|
||||
import (
|
||||
"RenewCMS/internal/domain/article"
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"context"
|
||||
)
|
||||
|
||||
type DeleteArticleUseCase struct {
|
||||
articleRepository article.Repository
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
func NewDeleteArticleUseCase(articleRepository article.Repository) *DeleteArticleUseCase {
|
||||
return &DeleteArticleUseCase{articleRepository}
|
||||
func NewDeleteArticleUseCase(articleRepository article.Repository, recorder audit.Recorder) *DeleteArticleUseCase {
|
||||
return &DeleteArticleUseCase{articleRepository, recorder}
|
||||
}
|
||||
|
||||
func (g *DeleteArticleUseCase) DeleteArticle(id uint32) error {
|
||||
return g.articleRepository.Delete(id)
|
||||
func (g *DeleteArticleUseCase) DeleteArticle(ctx context.Context, id uint32) error {
|
||||
target, err := g.articleRepository.Get(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
event := audit.NewEvent(audit.ActionArticleDelete, audit.CategoryArticles)
|
||||
event.Target = articleTarget(target)
|
||||
if err := g.articleRepository.Delete(id); err != nil {
|
||||
recordFailure(ctx, g.recorder, event, err)
|
||||
return err
|
||||
}
|
||||
g.recorder.Record(ctx, event)
|
||||
return nil
|
||||
}
|
||||
@@ -1,20 +1,33 @@
|
||||
package useCases
|
||||
|
||||
import "RenewCMS/internal/domain/image"
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/image"
|
||||
"context"
|
||||
)
|
||||
|
||||
type DeleteMediaUseCase struct {
|
||||
imageRepository image.Repository
|
||||
remover mediaRemover
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
func NewDeleteMediaUseCase(imageRepository image.Repository, storage image.Storage) *DeleteMediaUseCase {
|
||||
return &DeleteMediaUseCase{imageRepository, mediaRemover{imageRepository, storage}}
|
||||
func NewDeleteMediaUseCase(imageRepository image.Repository, storage image.Storage, recorder audit.Recorder) *DeleteMediaUseCase {
|
||||
return &DeleteMediaUseCase{imageRepository, mediaRemover{imageRepository, storage}, recorder}
|
||||
}
|
||||
|
||||
func (u *DeleteMediaUseCase) Delete(id uint32) error {
|
||||
func (u *DeleteMediaUseCase) Delete(ctx context.Context, id uint32) error {
|
||||
img, err := u.imageRepository.Get(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return u.remover.remove(img)
|
||||
|
||||
event := audit.NewEvent(audit.ActionMediaDelete, audit.CategoryMedia)
|
||||
event.Target = imageTarget(img)
|
||||
if err := u.remover.remove(img); err != nil {
|
||||
recordFailure(ctx, u.recorder, event, err)
|
||||
return err
|
||||
}
|
||||
u.recorder.Record(ctx, event)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"encoding/csv"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const exportBatchSize = 500
|
||||
|
||||
const formulaGuard = "'"
|
||||
const formulaStarts = "=+-@"
|
||||
|
||||
var exportHeader = []string{"when", "actor", "action", "target", "outcome", "source", "ip"}
|
||||
|
||||
type ExportActivityUseCase struct {
|
||||
events audit.Repository
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
type ActivityExport struct {
|
||||
events audit.Repository
|
||||
filter audit.Filter
|
||||
}
|
||||
|
||||
func NewExportActivityUseCase(events audit.Repository, now func() time.Time) *ExportActivityUseCase {
|
||||
return &ExportActivityUseCase{events, now}
|
||||
}
|
||||
|
||||
func (e *ExportActivityUseCase) Prepare(query ActivityQuery) (*ActivityExport, error) {
|
||||
filter, err := buildActivityFilter(query, e.now())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ActivityExport{events: e.events, filter: filter}, nil
|
||||
}
|
||||
|
||||
func (a *ActivityExport) WriteCSV(w io.Writer) error {
|
||||
writer := csv.NewWriter(w)
|
||||
if err := writer.Write(exportHeader); err != nil {
|
||||
return err
|
||||
}
|
||||
for page := 1; ; page++ {
|
||||
filter := a.filter
|
||||
filter.Page, filter.Size = page, exportBatchSize
|
||||
found, err := a.events.List(filter)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, event := range found.Items {
|
||||
if err := writer.Write(exportRow(event)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
writer.Flush()
|
||||
if err := writer.Error(); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(found.Items) < exportBatchSize || page*exportBatchSize >= found.Total {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func exportRow(event audit.Event) []string {
|
||||
ip := ""
|
||||
if event.IP != nil {
|
||||
ip = *event.IP
|
||||
}
|
||||
return []string{
|
||||
event.CreatedAt.UTC().Format(time.RFC3339),
|
||||
guardCell(event.Actor.Name),
|
||||
guardCell(event.Action),
|
||||
guardCell(event.Target.Name),
|
||||
string(event.Outcome),
|
||||
string(event.Source),
|
||||
guardCell(ip),
|
||||
}
|
||||
}
|
||||
|
||||
func guardCell(value string) string {
|
||||
if value != "" && strings.ContainsRune(formulaStarts, rune(value[0])) {
|
||||
return formulaGuard + value
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"time"
|
||||
)
|
||||
|
||||
type GetActivitySummaryUseCase struct {
|
||||
events audit.Repository
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewGetActivitySummaryUseCase(events audit.Repository, now func() time.Time) *GetActivitySummaryUseCase {
|
||||
return &GetActivitySummaryUseCase{events, now}
|
||||
}
|
||||
|
||||
func (g *GetActivitySummaryUseCase) GetActivitySummary(query ActivityQuery) (audit.Summary, error) {
|
||||
window, err := resolveActivityWindow(query, g.now())
|
||||
if err != nil {
|
||||
return audit.Summary{}, err
|
||||
}
|
||||
return g.events.Summary(audit.SummaryQuery{From: window.from, To: window.to})
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/apikey"
|
||||
"RenewCMS/internal/domain/article"
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/image"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"errors"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ListActivityUseCase struct {
|
||||
events audit.Repository
|
||||
users user.Repository
|
||||
articles article.Repository
|
||||
images image.Repository
|
||||
apiKeys apikey.Repository
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
type ListActivityCommand struct {
|
||||
ViewerID uint32
|
||||
Query ActivityQuery
|
||||
}
|
||||
|
||||
type ActivityEntry struct {
|
||||
Event audit.Event
|
||||
TargetExists bool
|
||||
}
|
||||
|
||||
type ActivityPage struct {
|
||||
Items []ActivityEntry
|
||||
Total int
|
||||
Page int
|
||||
Size int
|
||||
}
|
||||
|
||||
func NewListActivityUseCase(events audit.Repository, users user.Repository, articles article.Repository, images image.Repository, apiKeys apikey.Repository, now func() time.Time) *ListActivityUseCase {
|
||||
return &ListActivityUseCase{events, users, articles, images, apiKeys, now}
|
||||
}
|
||||
|
||||
func (l *ListActivityUseCase) ListActivity(command ListActivityCommand) (ActivityPage, error) {
|
||||
filter, err := buildActivityFilter(command.Query, l.now())
|
||||
if err != nil {
|
||||
return ActivityPage{}, err
|
||||
}
|
||||
if filter.Page, filter.Size, err = resolveActivityPaging(command.Query); err != nil {
|
||||
return ActivityPage{}, err
|
||||
}
|
||||
if err := l.scopeToViewer(&filter, command.ViewerID); err != nil {
|
||||
return ActivityPage{}, err
|
||||
}
|
||||
|
||||
found, err := l.events.List(filter)
|
||||
if err != nil {
|
||||
return ActivityPage{}, err
|
||||
}
|
||||
entries, err := l.withTargetState(found.Items)
|
||||
if err != nil {
|
||||
return ActivityPage{}, err
|
||||
}
|
||||
return ActivityPage{Items: entries, Total: found.Total, Page: filter.Page, Size: filter.Size}, nil
|
||||
}
|
||||
|
||||
func (l *ListActivityUseCase) scopeToViewer(filter *audit.Filter, viewerID uint32) error {
|
||||
viewer, err := l.users.Get(viewerID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if viewer.Role == user.RoleOwner || viewer.Role == user.RoleAdmin {
|
||||
return nil
|
||||
}
|
||||
own := audit.ActorRef{Type: audit.ActorUser, ID: &viewer.ID}
|
||||
if filter.Actor != nil && !sameActor(*filter.Actor, own) {
|
||||
return audit.ErrActorNotAllowed
|
||||
}
|
||||
filter.Actor = &own
|
||||
return nil
|
||||
}
|
||||
|
||||
func sameActor(a audit.ActorRef, b audit.ActorRef) bool {
|
||||
return a.Type == b.Type && a.ID != nil && b.ID != nil && *a.ID == *b.ID
|
||||
}
|
||||
|
||||
type targetKey struct {
|
||||
kind string
|
||||
id string
|
||||
}
|
||||
|
||||
func (l *ListActivityUseCase) withTargetState(events []audit.Event) ([]ActivityEntry, error) {
|
||||
known := map[targetKey]bool{}
|
||||
entries := make([]ActivityEntry, 0, len(events))
|
||||
for _, event := range events {
|
||||
key := targetKey{event.Target.Type, event.Target.ID}
|
||||
exists, resolved := known[key]
|
||||
if !resolved {
|
||||
var err error
|
||||
if exists, err = l.targetExists(event.Target); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
known[key] = exists
|
||||
}
|
||||
entries = append(entries, ActivityEntry{Event: event, TargetExists: exists})
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
func (l *ListActivityUseCase) targetExists(target audit.Target) (bool, error) {
|
||||
id, err := strconv.ParseUint(target.ID, 10, 32)
|
||||
if err != nil {
|
||||
return true, nil
|
||||
}
|
||||
switch target.Type {
|
||||
case audit.TargetArticle:
|
||||
_, err = l.articles.Get(uint32(id))
|
||||
return existsUnless(err, article.ErrArticleNotFound)
|
||||
case audit.TargetUser:
|
||||
_, err = l.users.Get(uint32(id))
|
||||
return existsUnless(err, user.ErrUserNotFound)
|
||||
case audit.TargetAPIKey:
|
||||
_, err = l.apiKeys.Get(uint32(id))
|
||||
return existsUnless(err, apikey.ErrAPIKeyNotFound)
|
||||
case audit.TargetImage:
|
||||
_, err = l.images.Get(uint32(id))
|
||||
return existsUnless(err, image.ErrImageNotFound)
|
||||
default:
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
func existsUnless(err error, notFound error) (bool, error) {
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if errors.Is(err, notFound) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
@@ -2,8 +2,10 @@ package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/article"
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/image"
|
||||
"cmp"
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
@@ -19,10 +21,11 @@ type MergeMediaUseCase struct {
|
||||
imageRepository image.Repository
|
||||
articleRepository article.Repository
|
||||
remover mediaRemover
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
func NewMergeMediaUseCase(imageRepository image.Repository, articleRepository article.Repository, storage image.Storage) *MergeMediaUseCase {
|
||||
return &MergeMediaUseCase{imageRepository, articleRepository, mediaRemover{imageRepository, storage}}
|
||||
func NewMergeMediaUseCase(imageRepository image.Repository, articleRepository article.Repository, storage image.Storage, recorder audit.Recorder) *MergeMediaUseCase {
|
||||
return &MergeMediaUseCase{imageRepository, articleRepository, mediaRemover{imageRepository, storage}, recorder}
|
||||
}
|
||||
|
||||
type bodyRewrite struct {
|
||||
@@ -31,7 +34,30 @@ type bodyRewrite struct {
|
||||
rewritten string
|
||||
}
|
||||
|
||||
func (u *MergeMediaUseCase) Merge(keepId uint32, mergeIds []uint32) (MergeMediaResult, error) {
|
||||
func (u *MergeMediaUseCase) Merge(ctx context.Context, keepId uint32, mergeIds []uint32) (MergeMediaResult, error) {
|
||||
result, err := u.merge(keepId, mergeIds)
|
||||
event := audit.NewEvent(audit.ActionMediaMerge, audit.CategoryMedia)
|
||||
if kept, found := u.keptImage(keepId); found {
|
||||
event.Target = imageTarget(kept)
|
||||
}
|
||||
if err != nil {
|
||||
recordFailure(ctx, u.recorder, event, err)
|
||||
return MergeMediaResult{}, err
|
||||
}
|
||||
event.Params = map[string]any{audit.ParamMerged: result.Merged, audit.ParamArticlesUpdated: result.ArticlesUpdated}
|
||||
u.recorder.Record(ctx, event)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (u *MergeMediaUseCase) keptImage(keepId uint32) (image.Image, bool) {
|
||||
if keepId == 0 {
|
||||
return image.Image{}, false
|
||||
}
|
||||
kept, err := u.imageRepository.Get(keepId)
|
||||
return kept, err == nil
|
||||
}
|
||||
|
||||
func (u *MergeMediaUseCase) merge(keepId uint32, mergeIds []uint32) (MergeMediaResult, error) {
|
||||
if err := validateMergeRequest(keepId, mergeIds); err != nil {
|
||||
return MergeMediaResult{}, err
|
||||
}
|
||||
|
||||
@@ -1,21 +1,25 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/purge"
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
type PurgeRunner interface {
|
||||
Run(fingerprint *string) (purge.RunResult, error)
|
||||
Execute(fingerprint *string) (purge.RunResult, error)
|
||||
}
|
||||
|
||||
type PurgeSchedulerUseCase struct {
|
||||
repository purge.Repository
|
||||
runner PurgeRunner
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
func NewPurgeSchedulerUseCase(repository purge.Repository, runner PurgeRunner) *PurgeSchedulerUseCase {
|
||||
return &PurgeSchedulerUseCase{repository, runner}
|
||||
func NewPurgeSchedulerUseCase(repository purge.Repository, runner PurgeRunner, recorder audit.Recorder) *PurgeSchedulerUseCase {
|
||||
return &PurgeSchedulerUseCase{repository, runner, recorder}
|
||||
}
|
||||
|
||||
func (u *PurgeSchedulerUseCase) Tick(now time.Time) (purge.RunResult, bool, error) {
|
||||
@@ -27,9 +31,29 @@ func (u *PurgeSchedulerUseCase) Tick(now time.Time) (purge.RunResult, bool, erro
|
||||
if next == nil || now.Before(*next) {
|
||||
return purge.RunResult{}, false, nil
|
||||
}
|
||||
result, err := u.runner.Run(nil)
|
||||
result, err := u.runner.Execute(nil)
|
||||
if err != nil {
|
||||
u.recordFailedRun(err)
|
||||
return purge.RunResult{}, false, err
|
||||
}
|
||||
if result.GroupsTotal > 0 {
|
||||
event := systemPurgeEvent()
|
||||
event.Params = purgeParams(result)
|
||||
u.recorder.Record(context.Background(), event)
|
||||
}
|
||||
return result, true, nil
|
||||
}
|
||||
|
||||
func (u *PurgeSchedulerUseCase) recordFailedRun(err error) {
|
||||
if errors.Is(err, purge.ErrPurgeBusy) {
|
||||
return
|
||||
}
|
||||
failFrom(context.Background(), u.recorder, systemPurgeEvent(), reasonFor(err))
|
||||
}
|
||||
|
||||
func systemPurgeEvent() audit.Event {
|
||||
event := audit.NewEvent(audit.ActionMediaPurgeScheduled, audit.CategorySystem)
|
||||
event.Actor = audit.SystemActor()
|
||||
event.Source = audit.SourceSystem
|
||||
return event
|
||||
}
|
||||
@@ -1,25 +1,43 @@
|
||||
package useCases
|
||||
|
||||
import "RenewCMS/internal/domain/image"
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/image"
|
||||
"context"
|
||||
)
|
||||
|
||||
type RenameMediaUseCase struct {
|
||||
imageRepository image.Repository
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
func NewRenameMediaUseCase(imageRepository image.Repository) *RenameMediaUseCase {
|
||||
return &RenameMediaUseCase{imageRepository}
|
||||
func NewRenameMediaUseCase(imageRepository image.Repository, recorder audit.Recorder) *RenameMediaUseCase {
|
||||
return &RenameMediaUseCase{imageRepository, recorder}
|
||||
}
|
||||
|
||||
func (u *RenameMediaUseCase) Rename(id uint32, stem string) (image.Image, error) {
|
||||
validStem, err := image.ValidateFilenameStem(stem)
|
||||
if err != nil {
|
||||
return image.Image{}, err
|
||||
}
|
||||
|
||||
func (u *RenameMediaUseCase) Rename(ctx context.Context, id uint32, stem string) (image.Image, error) {
|
||||
current, err := u.imageRepository.Get(id)
|
||||
if err != nil {
|
||||
return image.Image{}, err
|
||||
}
|
||||
|
||||
return u.imageRepository.Rename(id, validStem+image.ExtensionOf(current.Filename))
|
||||
event := audit.NewEvent(audit.ActionMediaRename, audit.CategoryMedia)
|
||||
event.Target = imageTarget(current)
|
||||
validStem, err := image.ValidateFilenameStem(stem)
|
||||
if err != nil {
|
||||
recordFailure(ctx, u.recorder, event, err)
|
||||
return image.Image{}, err
|
||||
}
|
||||
|
||||
renamed, err := u.imageRepository.Rename(id, validStem+image.ExtensionOf(current.Filename))
|
||||
if err != nil {
|
||||
recordFailure(ctx, u.recorder, event, err)
|
||||
return image.Image{}, err
|
||||
}
|
||||
if renamed.Filename != current.Filename {
|
||||
event.Target = imageTarget(renamed)
|
||||
event.Changes = []audit.Change{audit.TextChange(audit.FieldFilename, current.Filename, renamed.Filename)}
|
||||
u.recorder.Record(ctx, event)
|
||||
}
|
||||
return renamed, nil
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/hash"
|
||||
"RenewCMS/internal/domain/invite"
|
||||
"RenewCMS/internal/domain/mail"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
@@ -14,6 +16,7 @@ type RenewInviteUseCase struct {
|
||||
inviteRepository invite.Repository
|
||||
hasher hash.Hasher
|
||||
mailer inviteMailer
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
type RenewInviteCommand struct {
|
||||
@@ -21,11 +24,23 @@ type RenewInviteCommand struct {
|
||||
RenewedBy uint32
|
||||
}
|
||||
|
||||
func NewRenewInviteUseCase(userRepository user.Repository, inviteRepository invite.Repository, hasher hash.Hasher, mailRepository mail.Repository, publicURL string) *RenewInviteUseCase {
|
||||
return &RenewInviteUseCase{userRepository, inviteRepository, hasher, inviteMailer{mailRepository, publicURL}}
|
||||
func NewRenewInviteUseCase(userRepository user.Repository, inviteRepository invite.Repository, hasher hash.Hasher, mailRepository mail.Repository, publicURL string, recorder audit.Recorder) *RenewInviteUseCase {
|
||||
return &RenewInviteUseCase{userRepository, inviteRepository, hasher, inviteMailer{mailRepository, publicURL}, recorder}
|
||||
}
|
||||
|
||||
func (u *RenewInviteUseCase) RenewInvite(command RenewInviteCommand) (invite.Invite, error) {
|
||||
func (u *RenewInviteUseCase) RenewInvite(ctx context.Context, command RenewInviteCommand) (invite.Invite, error) {
|
||||
event := audit.NewEvent(audit.ActionInviteRenew, audit.CategoryUsers)
|
||||
renewed, err := u.renew(command)
|
||||
if err != nil {
|
||||
recordFailure(ctx, u.recorder, event, err)
|
||||
return invite.Invite{}, err
|
||||
}
|
||||
event.Target = inviteTarget(renewed)
|
||||
u.recorder.Record(ctx, event)
|
||||
return renewed, nil
|
||||
}
|
||||
|
||||
func (u *RenewInviteUseCase) renew(command RenewInviteCommand) (invite.Invite, error) {
|
||||
now := time.Now()
|
||||
|
||||
renewer, err := u.userRepository.Get(command.RenewedBy)
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/hash"
|
||||
"RenewCMS/internal/domain/mail"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
@@ -15,6 +17,7 @@ type RequestPasswordResetUseCase struct {
|
||||
hasher hash.Hasher
|
||||
mailRepository mail.Repository
|
||||
publicURL string
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
type MailPasswordResetData struct {
|
||||
@@ -23,11 +26,11 @@ type MailPasswordResetData struct {
|
||||
Email string
|
||||
}
|
||||
|
||||
func NewRequestPasswordResetUseCase(userRepository user.Repository, hasher hash.Hasher, mailRepository mail.Repository, publicURL string) *RequestPasswordResetUseCase {
|
||||
return &RequestPasswordResetUseCase{userRepository, hasher, mailRepository, publicURL}
|
||||
func NewRequestPasswordResetUseCase(userRepository user.Repository, hasher hash.Hasher, mailRepository mail.Repository, publicURL string, recorder audit.Recorder) *RequestPasswordResetUseCase {
|
||||
return &RequestPasswordResetUseCase{userRepository, hasher, mailRepository, publicURL, recorder}
|
||||
}
|
||||
|
||||
func (g *RequestPasswordResetUseCase) RequestPasswordReset(email string) error {
|
||||
func (g *RequestPasswordResetUseCase) RequestPasswordReset(ctx context.Context, email string) error {
|
||||
foundUser, err := g.userRepository.GetByEmail(email)
|
||||
if err != nil {
|
||||
return nil
|
||||
@@ -46,6 +49,8 @@ func (g *RequestPasswordResetUseCase) RequestPasswordReset(email string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
g.recordRequest(ctx, foundUser)
|
||||
|
||||
if err := g.mailRepository.Send(foundUser.Email, "password-reset", MailPasswordResetData{
|
||||
Host: g.publicURL,
|
||||
VerificationCode: rawCode,
|
||||
@@ -57,3 +62,10 @@ func (g *RequestPasswordResetUseCase) RequestPasswordReset(email string) error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *RequestPasswordResetUseCase) recordRequest(ctx context.Context, requester user.User) {
|
||||
event := audit.NewEvent(audit.ActionPasswordResetRequest, audit.CategoryAuth)
|
||||
event.Actor = audit.UserActor(requester)
|
||||
event.Security = true
|
||||
g.recorder.Record(ctx, event)
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/update"
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
@@ -13,10 +15,11 @@ type RequestRestartUseCase struct {
|
||||
requests update.RestartRequestStore
|
||||
status updateStatusBuilder
|
||||
now func() time.Time
|
||||
recorder audit.Recorder
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func NewRequestRestartUseCase(store update.StatusStore, jobs update.JobStore, helper update.HelperDetector, results update.ResultStore, requests update.RestartRequestStore, currentVersion string, now func() time.Time) *RequestRestartUseCase {
|
||||
func NewRequestRestartUseCase(store update.StatusStore, jobs update.JobStore, helper update.HelperDetector, results update.ResultStore, requests update.RestartRequestStore, currentVersion string, now func() time.Time, recorder audit.Recorder) *RequestRestartUseCase {
|
||||
return &RequestRestartUseCase{
|
||||
jobs: jobs,
|
||||
helper: helper,
|
||||
@@ -24,12 +27,33 @@ func NewRequestRestartUseCase(store update.StatusStore, jobs update.JobStore, he
|
||||
requests: requests,
|
||||
status: updateStatusBuilder{store: store, jobs: jobs, results: results, requests: requests, currentVersion: currentVersion, now: now},
|
||||
now: now,
|
||||
recorder: recorder,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *RequestRestartUseCase) Request(userId uint32, kind string) (update.UpdateStatus, error) {
|
||||
func (r *RequestRestartUseCase) Request(ctx context.Context, userId uint32, kind string) (update.UpdateStatus, error) {
|
||||
event := audit.NewEvent(audit.ActionRestartRequested, audit.CategorySystem)
|
||||
status, request, err := r.request(userId, kind)
|
||||
if err != nil {
|
||||
recordFailure(ctx, r.recorder, event, err, restartFailureReasons...)
|
||||
return update.UpdateStatus{}, err
|
||||
}
|
||||
event.Params = restartParams(request)
|
||||
r.recorder.Record(ctx, event)
|
||||
return status, nil
|
||||
}
|
||||
|
||||
func restartParams(request update.RestartRequest) map[string]any {
|
||||
params := map[string]any{audit.ParamKind: request.Kind}
|
||||
if request.Kind == update.RestartKindUpdate {
|
||||
params[audit.ParamTag] = request.Tag
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func (r *RequestRestartUseCase) request(userId uint32, kind string) (update.UpdateStatus, update.RestartRequest, error) {
|
||||
if !r.helper.Installed() {
|
||||
return update.UpdateStatus{}, update.ErrNotPrepared
|
||||
return update.UpdateStatus{}, update.RestartRequest{}, update.ErrNotPrepared
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
@@ -37,19 +61,19 @@ func (r *RequestRestartUseCase) Request(userId uint32, kind string) (update.Upda
|
||||
|
||||
current := r.status.build(true)
|
||||
if err := refuseWhileBusy(current); err != nil {
|
||||
return update.UpdateStatus{}, err
|
||||
return update.UpdateStatus{}, update.RestartRequest{}, err
|
||||
}
|
||||
request, err := r.requestFor(kind, userId)
|
||||
if err != nil {
|
||||
return update.UpdateStatus{}, err
|
||||
return update.UpdateStatus{}, update.RestartRequest{}, err
|
||||
}
|
||||
if err := r.results.Delete(); err != nil {
|
||||
return update.UpdateStatus{}, err
|
||||
return update.UpdateStatus{}, update.RestartRequest{}, err
|
||||
}
|
||||
if err := r.requests.Write(request); err != nil {
|
||||
return update.UpdateStatus{}, err
|
||||
return update.UpdateStatus{}, update.RestartRequest{}, err
|
||||
}
|
||||
return r.status.build(true), nil
|
||||
return r.status.build(true), request, nil
|
||||
}
|
||||
|
||||
func refuseWhileBusy(status update.UpdateStatus) error {
|
||||
|
||||
@@ -2,8 +2,10 @@ package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/apikey"
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/hash"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -12,13 +14,14 @@ type ResetPasswordUseCase struct {
|
||||
hasher hash.Hasher
|
||||
apiKeys apikey.Repository
|
||||
now func() time.Time
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
func NewResetPasswordUseCase(userRepository user.Repository, hasher hash.Hasher, apiKeys apikey.Repository, now func() time.Time) *ResetPasswordUseCase {
|
||||
return &ResetPasswordUseCase{userRepository, hasher, apiKeys, now}
|
||||
func NewResetPasswordUseCase(userRepository user.Repository, hasher hash.Hasher, apiKeys apikey.Repository, now func() time.Time, recorder audit.Recorder) *ResetPasswordUseCase {
|
||||
return &ResetPasswordUseCase{userRepository, hasher, apiKeys, now, recorder}
|
||||
}
|
||||
|
||||
func (r *ResetPasswordUseCase) ResetPassword(email string, code string, newPassword string) error {
|
||||
func (r *ResetPasswordUseCase) ResetPassword(ctx context.Context, email string, code string, newPassword string) error {
|
||||
dbUser, err := r.userRepository.GetByEmail(email)
|
||||
if err != nil {
|
||||
return user.ErrInvalidPasswordResetCode
|
||||
@@ -41,5 +44,13 @@ func (r *ResetPasswordUseCase) ResetPassword(email string, code string, newPassw
|
||||
return err
|
||||
}
|
||||
|
||||
return r.apiKeys.RevokeAllByUser(dbUser.ID, r.now())
|
||||
if err := r.apiKeys.RevokeAllByUser(dbUser.ID, r.now()); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
event := audit.NewEvent(audit.ActionPasswordResetDone, audit.CategoryAuth)
|
||||
event.Actor = audit.UserActor(dbUser)
|
||||
event.Security = true
|
||||
r.recorder.Record(ctx, event)
|
||||
return nil
|
||||
}
|
||||
@@ -2,7 +2,9 @@ package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/apikey"
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -10,13 +12,14 @@ type RevokeAPIKeyUseCase struct {
|
||||
apiKeyRepository apikey.Repository
|
||||
userRepository user.Repository
|
||||
now func() time.Time
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
func NewRevokeAPIKeyUseCase(apiKeyRepository apikey.Repository, userRepository user.Repository, now func() time.Time) *RevokeAPIKeyUseCase {
|
||||
return &RevokeAPIKeyUseCase{apiKeyRepository, userRepository, now}
|
||||
func NewRevokeAPIKeyUseCase(apiKeyRepository apikey.Repository, userRepository user.Repository, now func() time.Time, recorder audit.Recorder) *RevokeAPIKeyUseCase {
|
||||
return &RevokeAPIKeyUseCase{apiKeyRepository, userRepository, now, recorder}
|
||||
}
|
||||
|
||||
func (r *RevokeAPIKeyUseCase) RevokeAPIKey(requesterId uint32, keyId uint32) error {
|
||||
func (r *RevokeAPIKeyUseCase) RevokeAPIKey(ctx context.Context, requesterId uint32, keyId uint32) error {
|
||||
key, err := r.apiKeyRepository.Get(keyId)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -35,5 +38,12 @@ func (r *RevokeAPIKeyUseCase) RevokeAPIKey(requesterId uint32, keyId uint32) err
|
||||
return nil
|
||||
}
|
||||
|
||||
return r.apiKeyRepository.Revoke(key.ID, r.now())
|
||||
if err := r.apiKeyRepository.Revoke(key.ID, r.now()); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
event := audit.NewEvent(audit.ActionAPIKeyRevoke, audit.CategoryAPIKeys)
|
||||
event.Target = audit.APIKeyTarget(key.ID, key.Name)
|
||||
r.recorder.Record(ctx, event)
|
||||
return nil
|
||||
}
|
||||
@@ -2,8 +2,10 @@ package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/article"
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/image"
|
||||
"RenewCMS/internal/domain/purge"
|
||||
"context"
|
||||
"log"
|
||||
"slices"
|
||||
"sync"
|
||||
@@ -16,20 +18,42 @@ type RunPurgeUseCase struct {
|
||||
repository purge.Repository
|
||||
now func() time.Time
|
||||
logger *log.Logger
|
||||
recorder audit.Recorder
|
||||
guard sync.Mutex
|
||||
}
|
||||
|
||||
func NewRunPurgeUseCase(imageRepository image.Repository, articleRepository article.Repository, merge *MergeMediaUseCase, repository purge.Repository, now func() time.Time, logger *log.Logger) *RunPurgeUseCase {
|
||||
func NewRunPurgeUseCase(imageRepository image.Repository, articleRepository article.Repository, merge *MergeMediaUseCase, repository purge.Repository, now func() time.Time, logger *log.Logger, recorder audit.Recorder) *RunPurgeUseCase {
|
||||
return &RunPurgeUseCase{
|
||||
planner: &purgePlanner{imageRepository, articleRepository},
|
||||
merge: merge,
|
||||
repository: repository,
|
||||
now: now,
|
||||
logger: logger,
|
||||
recorder: recorder,
|
||||
}
|
||||
}
|
||||
|
||||
func (u *RunPurgeUseCase) Run(fingerprint *string) (purge.RunResult, error) {
|
||||
func (u *RunPurgeUseCase) Run(ctx context.Context, fingerprint *string) (purge.RunResult, error) {
|
||||
result, err := u.Execute(fingerprint)
|
||||
event := audit.NewEvent(audit.ActionMediaPurge, audit.CategoryMedia)
|
||||
if err != nil {
|
||||
recordFailure(ctx, u.recorder, event, err)
|
||||
return purge.RunResult{}, err
|
||||
}
|
||||
event.Params = purgeParams(result)
|
||||
u.recorder.Record(ctx, event)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func purgeParams(result purge.RunResult) map[string]any {
|
||||
params := map[string]any{audit.ParamMerged: result.Merged, audit.ParamArticlesUpdated: result.ArticlesUpdated}
|
||||
if result.FailedGroups > 0 {
|
||||
params[audit.ParamFailedGroups] = result.FailedGroups
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func (u *RunPurgeUseCase) Execute(fingerprint *string) (purge.RunResult, error) {
|
||||
if !u.guard.TryLock() {
|
||||
return purge.RunResult{}, purge.ErrPurgeBusy
|
||||
}
|
||||
@@ -55,7 +79,7 @@ func (u *RunPurgeUseCase) mergeGroups(plan purgePlan) purge.RunResult {
|
||||
result := purge.RunResult{GroupsTotal: len(plan.groups)}
|
||||
updated := map[uint32]bool{}
|
||||
for _, group := range plan.groups {
|
||||
merged, err := u.merge.Merge(group.kept.ID, slices.Clone(group.mergedIds))
|
||||
merged, err := u.merge.merge(group.kept.ID, slices.Clone(group.mergedIds))
|
||||
if err != nil {
|
||||
result.FailedGroups++
|
||||
continue
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/update"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
@@ -24,6 +26,7 @@ type StartUpdateDownloadUseCase struct {
|
||||
platform update.Platform
|
||||
feedHost string
|
||||
now func() time.Time
|
||||
recorder audit.Recorder
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
@@ -43,6 +46,7 @@ type StartUpdateDownloadDependencies struct {
|
||||
Platform update.Platform
|
||||
FeedURL string
|
||||
Now func() time.Time
|
||||
Recorder audit.Recorder
|
||||
}
|
||||
|
||||
type jobFailure struct {
|
||||
@@ -78,10 +82,19 @@ func NewStartUpdateDownloadUseCase(dependencies StartUpdateDownloadDependencies)
|
||||
platform: dependencies.Platform,
|
||||
feedHost: update.HostOf(dependencies.FeedURL),
|
||||
now: dependencies.Now,
|
||||
recorder: dependencies.Recorder,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *StartUpdateDownloadUseCase) Start() (update.UpdateStatus, error) {
|
||||
func (s *StartUpdateDownloadUseCase) Start(ctx context.Context) (update.UpdateStatus, error) {
|
||||
status, err := s.start(ctx)
|
||||
if err != nil {
|
||||
recordFailure(ctx, s.recorder, audit.NewEvent(audit.ActionUpdateDownloaded, audit.CategorySystem), err)
|
||||
}
|
||||
return status, err
|
||||
}
|
||||
|
||||
func (s *StartUpdateDownloadUseCase) start(ctx context.Context) (update.UpdateStatus, error) {
|
||||
if !s.helper.Installed() {
|
||||
return update.UpdateStatus{}, update.ErrNotPrepared
|
||||
}
|
||||
@@ -118,7 +131,7 @@ func (s *StartUpdateDownloadUseCase) Start() (update.UpdateStatus, error) {
|
||||
return update.UpdateStatus{}, err
|
||||
}
|
||||
status := s.status.build(true)
|
||||
go s.run(job, binary, checksums, signature)
|
||||
go s.run(context.WithoutCancel(ctx), job, binary, checksums, signature)
|
||||
|
||||
return status, nil
|
||||
}
|
||||
@@ -139,15 +152,19 @@ func (s *StartUpdateDownloadUseCase) preflight(result update.CheckResult) (binar
|
||||
return found[0], found[1], found[2], nil
|
||||
}
|
||||
|
||||
func (s *StartUpdateDownloadUseCase) run(job update.Job, binary, checksums, signature update.Asset) {
|
||||
func (s *StartUpdateDownloadUseCase) run(ctx context.Context, job update.Job, binary, checksums, signature update.Asset) {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
s.fail(job, downloadFailure(fmt.Errorf("panic: %v", recovered)))
|
||||
s.fail(ctx, job, downloadFailure(fmt.Errorf("panic: %v", recovered)))
|
||||
}
|
||||
}()
|
||||
if err := s.execute(&job, binary, checksums, signature); err != nil {
|
||||
s.fail(job, err)
|
||||
s.fail(ctx, job, err)
|
||||
return
|
||||
}
|
||||
event := audit.NewEvent(audit.ActionUpdateDownloaded, audit.CategorySystem)
|
||||
event.Target = audit.ReleaseTarget(job.Tag)
|
||||
s.recorder.Record(ctx, event)
|
||||
}
|
||||
|
||||
func (s *StartUpdateDownloadUseCase) execute(job *update.Job, binary, checksums, signature update.Asset) error {
|
||||
@@ -263,7 +280,7 @@ func downloadFailure(err error) error {
|
||||
return jobFailure{kind: update.ErrorKindDownload, reason: err}
|
||||
}
|
||||
|
||||
func (s *StartUpdateDownloadUseCase) fail(job update.Job, err error) {
|
||||
func (s *StartUpdateDownloadUseCase) fail(ctx context.Context, job update.Job, err error) {
|
||||
kind := update.ErrorKindDownload
|
||||
var failure jobFailure
|
||||
if errors.As(err, &failure) {
|
||||
@@ -279,4 +296,7 @@ func (s *StartUpdateDownloadUseCase) fail(job update.Job, err error) {
|
||||
if saveErr := s.jobs.Save(job); saveErr != nil {
|
||||
s.logger.Printf("update job record could not be saved: %v", saveErr)
|
||||
}
|
||||
event := audit.NewEvent(audit.ActionUpdateDownloaded, audit.CategorySystem)
|
||||
event.Target = audit.ReleaseTarget(job.Tag)
|
||||
failFrom(ctx, s.recorder, event, downloadFailureReasons[kind])
|
||||
}
|
||||
@@ -1,28 +1,69 @@
|
||||
package useCases
|
||||
|
||||
import "RenewCMS/internal/domain/article"
|
||||
import (
|
||||
"RenewCMS/internal/domain/article"
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"context"
|
||||
)
|
||||
|
||||
type UpdateArticleUseCase struct {
|
||||
articleRepository article.Repository
|
||||
bodyRenderer article.BodyRenderer
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
func NewUpdateArticleUseCase(articleRepository article.Repository, bodyRenderer article.BodyRenderer) *UpdateArticleUseCase {
|
||||
return &UpdateArticleUseCase{articleRepository, bodyRenderer}
|
||||
func NewUpdateArticleUseCase(articleRepository article.Repository, bodyRenderer article.BodyRenderer, recorder audit.Recorder) *UpdateArticleUseCase {
|
||||
return &UpdateArticleUseCase{articleRepository, bodyRenderer, recorder}
|
||||
}
|
||||
|
||||
func (g *UpdateArticleUseCase) UpdateBody(id uint32, body string, format article.BodyFormat) (article.Article, error) {
|
||||
func (g *UpdateArticleUseCase) UpdateBody(ctx context.Context, id uint32, body string, format article.BodyFormat) (article.Article, error) {
|
||||
before, err := g.articleRepository.Get(id)
|
||||
if err != nil {
|
||||
return article.Article{}, err
|
||||
}
|
||||
updated, err := g.articleRepository.UpdateBody(id, body)
|
||||
if err != nil {
|
||||
g.recordFailure(ctx, audit.ActionArticleEdit, before, err)
|
||||
return article.Article{}, err
|
||||
}
|
||||
g.recordChange(ctx, audit.ActionArticleEdit, before, updated)
|
||||
return renderArticle(g.bodyRenderer, updated, format)
|
||||
}
|
||||
|
||||
func (g *UpdateArticleUseCase) UpdateIsOnline(id uint32, isOnline bool, format article.BodyFormat) (article.Article, error) {
|
||||
updated, err := g.articleRepository.UpdateIsOnline(id, isOnline)
|
||||
func (g *UpdateArticleUseCase) UpdateIsOnline(ctx context.Context, id uint32, isOnline bool, format article.BodyFormat) (article.Article, error) {
|
||||
before, err := g.articleRepository.Get(id)
|
||||
if err != nil {
|
||||
return article.Article{}, err
|
||||
}
|
||||
updated, err := g.articleRepository.UpdateIsOnline(id, isOnline)
|
||||
if err != nil {
|
||||
g.recordFailure(ctx, publishAction(isOnline), before, err)
|
||||
return article.Article{}, err
|
||||
}
|
||||
g.recordChange(ctx, publishAction(isOnline), before, updated)
|
||||
return renderArticle(g.bodyRenderer, updated, format)
|
||||
}
|
||||
|
||||
func publishAction(isOnline bool) string {
|
||||
if isOnline {
|
||||
return audit.ActionArticlePublish
|
||||
}
|
||||
return audit.ActionArticleUnpublish
|
||||
}
|
||||
|
||||
func (g *UpdateArticleUseCase) recordChange(ctx context.Context, action string, before article.Article, after article.Article) {
|
||||
changes := audit.ArticleChanges(before, after)
|
||||
if len(changes) == 0 {
|
||||
return
|
||||
}
|
||||
event := audit.NewEvent(action, audit.CategoryArticles)
|
||||
event.Target = articleTarget(after)
|
||||
event.Changes = changes
|
||||
g.recorder.Record(ctx, event)
|
||||
}
|
||||
|
||||
func (g *UpdateArticleUseCase) recordFailure(ctx context.Context, action string, before article.Article, cause error) {
|
||||
event := audit.NewEvent(action, audit.CategoryArticles)
|
||||
event.Target = articleTarget(before)
|
||||
recordFailure(ctx, g.recorder, event, cause)
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"context"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
@@ -10,16 +12,40 @@ const maxDisplayNameRunes = 60
|
||||
|
||||
type UpdateUserProfileUseCase struct {
|
||||
userRepository user.Repository
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
func NewUpdateUserProfileUseCase(userRepository user.Repository) *UpdateUserProfileUseCase {
|
||||
return &UpdateUserProfileUseCase{userRepository}
|
||||
func NewUpdateUserProfileUseCase(userRepository user.Repository, recorder audit.Recorder) *UpdateUserProfileUseCase {
|
||||
return &UpdateUserProfileUseCase{userRepository, recorder}
|
||||
}
|
||||
|
||||
func (u *UpdateUserProfileUseCase) UpdateDisplayName(userId uint32, displayName string) (user.User, error) {
|
||||
func (u *UpdateUserProfileUseCase) UpdateDisplayName(ctx context.Context, userId uint32, displayName string) (user.User, error) {
|
||||
before, err := u.userRepository.Get(userId)
|
||||
if err != nil {
|
||||
return user.User{}, err
|
||||
}
|
||||
|
||||
event := audit.NewEvent(audit.ActionUserUpdateProfile, audit.CategoryUsers)
|
||||
event.Target = userTarget(before)
|
||||
trimmed := strings.TrimSpace(displayName)
|
||||
if utf8.RuneCountInString(trimmed) > maxDisplayNameRunes {
|
||||
recordFailure(ctx, u.recorder, event, user.ErrInvalidDisplayName)
|
||||
return user.User{}, user.ErrInvalidDisplayName
|
||||
}
|
||||
return u.userRepository.UpdateDisplayName(userId, trimmed)
|
||||
|
||||
updated, err := u.userRepository.UpdateDisplayName(userId, trimmed)
|
||||
if err != nil {
|
||||
recordFailure(ctx, u.recorder, event, err)
|
||||
return user.User{}, err
|
||||
}
|
||||
if updated.DisplayName != before.DisplayName {
|
||||
event.Target = userTarget(updated)
|
||||
event.Changes = []audit.Change{audit.TextChange(audit.FieldDisplayName, before.DisplayName, updated.DisplayName)}
|
||||
u.recorder.Record(ctx, event)
|
||||
}
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
func userTarget(u user.User) audit.Target {
|
||||
return audit.NewTarget(audit.TargetUser, u.ID, audit.UserActor(u).Name)
|
||||
}
|
||||
@@ -1,26 +1,42 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/hash"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
type VerifyUserUseCase struct {
|
||||
userRepository user.Repository
|
||||
hasher hash.Hasher
|
||||
recorder audit.Recorder
|
||||
}
|
||||
|
||||
func NewVerifyUserUseCase(userRepository user.Repository, hasher hash.Hasher) *VerifyUserUseCase {
|
||||
return &VerifyUserUseCase{userRepository, hasher}
|
||||
func NewVerifyUserUseCase(userRepository user.Repository, hasher hash.Hasher, recorder audit.Recorder) *VerifyUserUseCase {
|
||||
return &VerifyUserUseCase{userRepository, hasher, recorder}
|
||||
}
|
||||
|
||||
func (v *VerifyUserUseCase) Verify(userId uint32, code string) (user.User, error) {
|
||||
func (v *VerifyUserUseCase) Verify(ctx context.Context, userId uint32, code string) (user.User, error) {
|
||||
dbUser, err := v.userRepository.Get(userId)
|
||||
if err != nil {
|
||||
return user.User{}, err
|
||||
}
|
||||
|
||||
event := audit.NewEvent(audit.ActionUserVerify, audit.CategoryUsers)
|
||||
event.Actor = audit.UserActor(dbUser)
|
||||
event.Target = audit.NewTarget(audit.TargetUser, dbUser.ID, dbUser.Username)
|
||||
verified, err := v.verify(dbUser, code)
|
||||
if err != nil {
|
||||
recordFailure(ctx, v.recorder, event, err)
|
||||
return user.User{}, err
|
||||
}
|
||||
v.recorder.Record(ctx, event)
|
||||
return verified, nil
|
||||
}
|
||||
|
||||
func (v *VerifyUserUseCase) verify(dbUser user.User, code string) (user.User, error) {
|
||||
if dbUser.VerificationCode == "" || v.hasher.Compare(dbUser.VerificationCode, code) != nil {
|
||||
return user.User{}, user.ErrInvalidVerificationCode
|
||||
}
|
||||
@@ -29,5 +45,5 @@ func (v *VerifyUserUseCase) Verify(userId uint32, code string) (user.User, error
|
||||
return user.User{}, user.ErrVerificationCodeExpired
|
||||
}
|
||||
|
||||
return v.userRepository.ClearVerificationCode(userId)
|
||||
return v.userRepository.ClearVerificationCode(dbUser.ID)
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
activityRangeToday = "today"
|
||||
activityRange7Days = "7d"
|
||||
activityRange30Days = "30d"
|
||||
activityRangeCustom = "custom"
|
||||
activityDateLayout = "2006-01-02"
|
||||
activityDefaultSize = 25
|
||||
outcomeAll = "all"
|
||||
securityOnly = "true"
|
||||
)
|
||||
|
||||
var activityPageSizes = []int{5, 25, 50, 100}
|
||||
|
||||
type ActivityQuery struct {
|
||||
Q string
|
||||
Actor string
|
||||
Category string
|
||||
Outcome string
|
||||
Security string
|
||||
Range string
|
||||
From string
|
||||
To string
|
||||
Page int
|
||||
Size int
|
||||
}
|
||||
|
||||
type activityWindow struct {
|
||||
from time.Time
|
||||
to time.Time
|
||||
explicit bool
|
||||
}
|
||||
|
||||
func resolveActivityWindow(query ActivityQuery, now time.Time) (activityWindow, error) {
|
||||
utc := now.UTC()
|
||||
end := utc.Add(time.Second)
|
||||
switch query.Range {
|
||||
case "", activityRange7Days:
|
||||
return activityWindow{from: end.AddDate(0, 0, -7), to: end}, nil
|
||||
case activityRange30Days:
|
||||
return activityWindow{from: end.AddDate(0, 0, -30), to: end}, nil
|
||||
case activityRangeToday:
|
||||
return activityWindow{from: time.Date(utc.Year(), utc.Month(), utc.Day(), 0, 0, 0, 0, time.UTC), to: end}, nil
|
||||
case activityRangeCustom:
|
||||
return resolveCustomWindow(query)
|
||||
default:
|
||||
return activityWindow{}, audit.ErrInvalidFilter
|
||||
}
|
||||
}
|
||||
|
||||
func resolveCustomWindow(query ActivityQuery) (activityWindow, error) {
|
||||
from, err := time.Parse(activityDateLayout, query.From)
|
||||
if err != nil {
|
||||
return activityWindow{}, audit.ErrInvalidFilter
|
||||
}
|
||||
last, err := time.Parse(activityDateLayout, query.To)
|
||||
if err != nil || last.Before(from) {
|
||||
return activityWindow{}, audit.ErrInvalidFilter
|
||||
}
|
||||
return activityWindow{from: from, to: last.AddDate(0, 0, 1), explicit: true}, nil
|
||||
}
|
||||
|
||||
func buildActivityFilter(query ActivityQuery, now time.Time) (audit.Filter, error) {
|
||||
window, err := resolveActivityWindow(query, now)
|
||||
if err != nil {
|
||||
return audit.Filter{}, err
|
||||
}
|
||||
filter := audit.Filter{Query: query.Q, From: &window.from}
|
||||
if window.explicit {
|
||||
filter.To = &window.to
|
||||
}
|
||||
if filter.Outcome, err = parseActivityOutcome(query.Outcome); err != nil {
|
||||
return audit.Filter{}, err
|
||||
}
|
||||
if filter.Security, err = parseActivitySecurity(query.Security); err != nil {
|
||||
return audit.Filter{}, err
|
||||
}
|
||||
if query.Category != "" {
|
||||
if filter.Category, err = audit.ParseCategory(query.Category); err != nil {
|
||||
return audit.Filter{}, err
|
||||
}
|
||||
}
|
||||
if query.Actor != "" {
|
||||
actor, err := audit.ParseActor(query.Actor)
|
||||
if err != nil {
|
||||
return audit.Filter{}, err
|
||||
}
|
||||
filter.Actor = &actor
|
||||
}
|
||||
return filter, nil
|
||||
}
|
||||
|
||||
func parseActivityOutcome(raw string) (audit.Outcome, error) {
|
||||
switch raw {
|
||||
case "", outcomeAll:
|
||||
return "", nil
|
||||
case string(audit.OutcomeSuccess):
|
||||
return audit.OutcomeSuccess, nil
|
||||
case string(audit.OutcomeFailed):
|
||||
return audit.OutcomeFailed, nil
|
||||
default:
|
||||
return "", audit.ErrInvalidFilter
|
||||
}
|
||||
}
|
||||
|
||||
func parseActivitySecurity(raw string) (bool, error) {
|
||||
switch raw {
|
||||
case "":
|
||||
return false, nil
|
||||
case securityOnly:
|
||||
return true, nil
|
||||
default:
|
||||
return false, audit.ErrInvalidFilter
|
||||
}
|
||||
}
|
||||
|
||||
func resolveActivityPaging(query ActivityQuery) (int, int, error) {
|
||||
page, size := query.Page, query.Size
|
||||
if page == 0 {
|
||||
page = 1
|
||||
}
|
||||
if size == 0 {
|
||||
size = activityDefaultSize
|
||||
}
|
||||
if page < 1 || !containsInt(activityPageSizes, size) {
|
||||
return 0, 0, audit.ErrInvalidFilter
|
||||
}
|
||||
return page, size, nil
|
||||
}
|
||||
|
||||
func containsInt(values []int, wanted int) bool {
|
||||
for _, value := range values {
|
||||
if value == wanted {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/article"
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/image"
|
||||
"RenewCMS/internal/domain/invite"
|
||||
"RenewCMS/internal/domain/purge"
|
||||
"RenewCMS/internal/domain/update"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
)
|
||||
|
||||
const GenericFailureReason = "Something went wrong on our side. Please try again."
|
||||
|
||||
type failureReason struct {
|
||||
cause error
|
||||
reason string
|
||||
}
|
||||
|
||||
var failureReasons = []failureReason{
|
||||
{article.ErrInvalidTitle, "The title must be between 3 and 200 characters."},
|
||||
{image.ErrImageTypeNotAllowed, "The file must be a PNG, JPEG, WEBP or SVG image."},
|
||||
{image.ErrImageTooLarge, "The file is too large to upload."},
|
||||
{image.ErrImageUnreadable, "The image could not be read."},
|
||||
{image.ErrInvalidFilename, "That file name is not valid."},
|
||||
{image.ErrInvalidMergeRequest, "The merge request is not valid."},
|
||||
{image.ErrMergeCopyMissing, "One of the copies no longer exists."},
|
||||
{image.ErrMergeHashMismatch, "The images are not identical copies."},
|
||||
{purge.ErrPurgeConflict, "The library changed since the preview. Review it again."},
|
||||
{purge.ErrPurgeBusy, "A purge is already running."},
|
||||
{user.ErrRegistrationClosed, "Registration is closed on this site."},
|
||||
{user.ErrVerificationEmailNotSent, "The verification email could not be sent."},
|
||||
{user.ErrInvalidVerificationCode, "The verification code is not valid."},
|
||||
{user.ErrVerificationCodeExpired, "The verification code has expired."},
|
||||
{user.ErrInvalidDisplayName, "That display name is too long."},
|
||||
{user.ErrUsernameTaken, "That username is already taken."},
|
||||
{invite.ErrEmailHasAccount, "That email already has an account."},
|
||||
{invite.ErrPendingInvite, "An invitation is already pending for that email."},
|
||||
{invite.ErrInviteEmailNotSent, "The invitation email could not be sent."},
|
||||
{invite.ErrInviteAlreadyAccepted, "That invitation was already accepted."},
|
||||
{invite.ErrInviteInvalid, "That invitation is not valid."},
|
||||
{invite.ErrInviteExpired, "That invitation has expired."},
|
||||
{update.ErrFeedUnavailable, "The release feed could not be reached."},
|
||||
{update.ErrNoRelease, "No release was found."},
|
||||
{update.ErrNotPrepared, "This server cannot apply updates."},
|
||||
{update.ErrJobInProgress, "An update is already being downloaded."},
|
||||
{update.ErrRestartPending, "A restart is already pending."},
|
||||
{update.ErrNothingToUpdate, "There is nothing to update."},
|
||||
{update.ErrPreflightRefused, "The update cannot be downloaded."},
|
||||
{update.ErrRestartKindMismatch, "The requested restart does not match the server state."},
|
||||
}
|
||||
|
||||
var restartFailureReasons = []failureReason{
|
||||
{update.ErrJobInProgress, "An update is still being downloaded."},
|
||||
}
|
||||
|
||||
var downloadFailureReasons = map[string]string{
|
||||
update.ErrorKindDownload: "The update could not be downloaded.",
|
||||
update.ErrorKindVerification: "The downloaded update failed its integrity check.",
|
||||
}
|
||||
|
||||
var notFoundCauses = []error{
|
||||
article.ErrArticleNotFound,
|
||||
image.ErrImageNotFound,
|
||||
invite.ErrInviteNotFound,
|
||||
user.ErrUserNotFound,
|
||||
}
|
||||
|
||||
func reasonFor(err error, overrides ...failureReason) string {
|
||||
for _, candidate := range slices.Concat(overrides, failureReasons) {
|
||||
if errors.Is(err, candidate.cause) {
|
||||
return candidate.reason
|
||||
}
|
||||
}
|
||||
return GenericFailureReason
|
||||
}
|
||||
|
||||
func isNotFound(err error) bool {
|
||||
for _, cause := range notFoundCauses {
|
||||
if errors.Is(err, cause) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func recordFailure(ctx context.Context, recorder audit.Recorder, event audit.Event, err error, overrides ...failureReason) {
|
||||
if isNotFound(err) {
|
||||
return
|
||||
}
|
||||
failFrom(ctx, recorder, event, reasonFor(err, overrides...))
|
||||
}
|
||||
|
||||
func failFrom(ctx context.Context, recorder audit.Recorder, event audit.Event, reason string) {
|
||||
event.Outcome = audit.OutcomeFailed
|
||||
event.FailureReason = &reason
|
||||
recorder.Record(ctx, event)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
work="$(mktemp -d)"
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
|
||||
native() {
|
||||
if command -v cygpath >/dev/null 2>&1; then
|
||||
cygpath -m "$1"
|
||||
else
|
||||
printf '%s' "$1"
|
||||
fi
|
||||
}
|
||||
|
||||
repo="$work/repo"
|
||||
mkdir -p "$repo" "$work/tmp" "$root/tmp"
|
||||
|
||||
tar -C "$root" -c \
|
||||
--exclude=./bin --exclude=./web --exclude=./node_modules --exclude=./.git \
|
||||
--exclude=./.task --exclude=./tmp --exclude=./data --exclude=./.claude \
|
||||
--exclude=./internal/infrastructure/assets/dist --exclude='*.exe' --exclude='*.db' . |
|
||||
tar -C "$repo" -x
|
||||
|
||||
export GOCACHE="$(native "$work/gocache")"
|
||||
export TEMP="$(native "$work/tmp")"
|
||||
export TMP="$TEMP"
|
||||
export TMPDIR="$TEMP"
|
||||
|
||||
cd "$repo"
|
||||
code=0
|
||||
gremlins unleash --integration --tags nofrontend --workers 4 \
|
||||
--coverpkg=./internal/infrastructure/useCases/...,./api/middleware/...,./api/pkg/claims/... \
|
||||
--timeout-coefficient 10 --output "$(native "$root/tmp/gremlins.json")" \
|
||||
./internal/infrastructure/useCases ./api/middleware ./api/pkg/claims || code=$?
|
||||
go clean -cache >/dev/null 2>&1 || true
|
||||
exit "$code"
|
||||
@@ -116,7 +116,7 @@ func newAtomicAcceptFixture(t *testing.T, wrap func(db *gorm.DB, repo invite.Rep
|
||||
hasher := atomicPlainHasher{}
|
||||
handler := auth.NewAcceptInviteHandler(
|
||||
useCases.NewGetInviteUseCase(invites, hasher),
|
||||
useCases.NewAcceptInviteUseCase(users, invites, hasher),
|
||||
useCases.NewAcceptInviteUseCase(users, invites, hasher, discardRecorder),
|
||||
jwtauth.New("HS256", []byte("test-secret"), nil),
|
||||
true,
|
||||
)
|
||||
|
||||
@@ -56,21 +56,21 @@ func newAcceptInviteFixture(t *testing.T, maxAttempts int) *acceptInviteFixture
|
||||
getUser := useCases.NewGetUserUseCase(f.users)
|
||||
acceptHandler := auth.NewAcceptInviteHandler(
|
||||
useCases.NewGetInviteUseCase(f.invites, f.hasher),
|
||||
useCases.NewAcceptInviteUseCase(f.users, f.invites, f.hasher),
|
||||
useCases.NewAcceptInviteUseCase(f.users, f.invites, f.hasher, discardRecorder),
|
||||
f.token,
|
||||
true,
|
||||
)
|
||||
meHandler := auth.NewMeHandler(getUser)
|
||||
listHandler := userhandler.NewInviteHandler(
|
||||
useCases.NewCreateInviteUseCase(f.users, f.invites, f.hasher, f.mail, invitePublicURL),
|
||||
useCases.NewCreateInviteUseCase(f.users, f.invites, f.hasher, f.mail, invitePublicURL, discardRecorder),
|
||||
nil,
|
||||
nil,
|
||||
useCases.NewListUsersAndInvitesUseCase(f.users, f.invites),
|
||||
)
|
||||
registerHandler := auth.NewLoginHandler(
|
||||
f.token,
|
||||
useCases.NewCreateUserUseCase(f.users, f.hasher, f.mail, invitePublicURL),
|
||||
useCases.NewAuthenticateUserUseCase(f.users, f.hasher),
|
||||
useCases.NewCreateUserUseCase(f.users, f.hasher, f.mail, invitePublicURL, discardRecorder),
|
||||
useCases.NewAuthenticateUserUseCase(f.users, f.hasher, discardRecorder),
|
||||
true,
|
||||
)
|
||||
|
||||
@@ -500,13 +500,13 @@ func TestAcceptInviteUseCase(t *testing.T) {
|
||||
newUseCase := func() (*useCases.AcceptInviteUseCase, *mockUserRepo, *inviteFakeRepo, *stubHasher) {
|
||||
users, invites, hasher := inviteInviterRepo(""), newInviteFakeRepo(), &stubHasher{}
|
||||
invites.users = users
|
||||
return useCases.NewAcceptInviteUseCase(users, invites, hasher), users, invites, hasher
|
||||
return useCases.NewAcceptInviteUseCase(users, invites, hasher, discardRecorder), users, invites, hasher
|
||||
}
|
||||
command := useCases.AcceptInviteCommand{Code: acceptCode, Username: "lea", Password: acceptPassword}
|
||||
|
||||
t.Run("unknown code is invalid", func(t *testing.T) {
|
||||
uc, _, _, _ := newUseCase()
|
||||
if _, err := uc.AcceptInvite(command); !errors.Is(err, invite.ErrInviteInvalid) {
|
||||
if _, err := uc.AcceptInvite(testCtx, command); !errors.Is(err, invite.ErrInviteInvalid) {
|
||||
t.Errorf("expected ErrInviteInvalid, got %v", err)
|
||||
}
|
||||
})
|
||||
@@ -514,7 +514,7 @@ func TestAcceptInviteUseCase(t *testing.T) {
|
||||
t.Run("empty code is invalid without hashing", func(t *testing.T) {
|
||||
uc, _, invites, hasher := newUseCase()
|
||||
invites.seed(pendingInvite(acceptEmail))
|
||||
if _, err := uc.AcceptInvite(useCases.AcceptInviteCommand{Username: "lea", Password: acceptPassword}); !errors.Is(err, invite.ErrInviteInvalid) || hasher.compareCalls != 0 {
|
||||
if _, err := uc.AcceptInvite(testCtx, useCases.AcceptInviteCommand{Username: "lea", Password: acceptPassword}); !errors.Is(err, invite.ErrInviteInvalid) || hasher.compareCalls != 0 {
|
||||
t.Errorf("expected ErrInviteInvalid, got %v", err)
|
||||
}
|
||||
})
|
||||
@@ -524,7 +524,7 @@ func TestAcceptInviteUseCase(t *testing.T) {
|
||||
stored := expiredInvite(acceptEmail)
|
||||
stored.HashedCode = "hashed:" + acceptCode
|
||||
invites.seed(stored)
|
||||
if _, err := uc.AcceptInvite(command); !errors.Is(err, invite.ErrInviteExpired) {
|
||||
if _, err := uc.AcceptInvite(testCtx, command); !errors.Is(err, invite.ErrInviteExpired) {
|
||||
t.Errorf("expected ErrInviteExpired, got %v", err)
|
||||
}
|
||||
})
|
||||
@@ -534,7 +534,7 @@ func TestAcceptInviteUseCase(t *testing.T) {
|
||||
stored := pendingInvite(acceptEmail)
|
||||
stored.HashedCode = "hashed:" + acceptCode
|
||||
invites.seed(stored)
|
||||
_, err := uc.AcceptInvite(useCases.AcceptInviteCommand{Code: acceptCode, Username: "marta", Password: acceptPassword})
|
||||
_, err := uc.AcceptInvite(testCtx, useCases.AcceptInviteCommand{Code: acceptCode, Username: "marta", Password: acceptPassword})
|
||||
if !errors.Is(err, user.ErrUsernameTaken) || len(users.users) != 1 {
|
||||
t.Errorf("expected ErrUsernameTaken, got %v", err)
|
||||
}
|
||||
@@ -546,7 +546,7 @@ func TestAcceptInviteUseCase(t *testing.T) {
|
||||
stored.HashedCode = "hashed:" + acceptCode
|
||||
invites.seed(stored)
|
||||
users.fail.failNext("GetByUsername")
|
||||
if _, err := uc.AcceptInvite(command); !errors.Is(err, errRepositoryFailure) {
|
||||
if _, err := uc.AcceptInvite(testCtx, command); !errors.Is(err, errRepositoryFailure) {
|
||||
t.Errorf("expected repository failure, got %v", err)
|
||||
}
|
||||
})
|
||||
@@ -557,7 +557,7 @@ func TestAcceptInviteUseCase(t *testing.T) {
|
||||
stored.HashedCode = "hashed:" + acceptCode
|
||||
invites.seed(stored)
|
||||
users.users[8] = user.User{ID: 8, Username: "leam", Email: "LEA.martin@renew.example"}
|
||||
if _, err := uc.AcceptInvite(command); !errors.Is(err, invite.ErrEmailHasAccount) {
|
||||
if _, err := uc.AcceptInvite(testCtx, command); !errors.Is(err, invite.ErrEmailHasAccount) {
|
||||
t.Errorf("expected ErrEmailHasAccount, got %v", err)
|
||||
}
|
||||
})
|
||||
@@ -574,8 +574,8 @@ func TestAcceptInviteUseCase(t *testing.T) {
|
||||
invites.invites[seeded.ID] = seeded
|
||||
users.users[8] = user.User{ID: 8, Username: "lea2", Email: acceptEmail}
|
||||
}}
|
||||
uc := useCases.NewAcceptInviteUseCase(users, racing, hasher)
|
||||
if _, err := uc.AcceptInvite(command); !errors.Is(err, invite.ErrInviteInvalid) {
|
||||
uc := useCases.NewAcceptInviteUseCase(users, racing, hasher, discardRecorder)
|
||||
if _, err := uc.AcceptInvite(testCtx, command); !errors.Is(err, invite.ErrInviteInvalid) {
|
||||
t.Errorf("expected ErrInviteInvalid, got %v", err)
|
||||
}
|
||||
})
|
||||
@@ -586,7 +586,7 @@ func TestAcceptInviteUseCase(t *testing.T) {
|
||||
stored.HashedCode = "hashed:" + acceptCode
|
||||
invites.seed(stored)
|
||||
hasher.hashErr = errors.New("hash boom")
|
||||
if _, err := uc.AcceptInvite(command); err == nil || len(users.users) != 1 {
|
||||
if _, err := uc.AcceptInvite(testCtx, command); err == nil || len(users.users) != 1 {
|
||||
t.Errorf("expected failure without a user, got %v", err)
|
||||
}
|
||||
})
|
||||
@@ -597,7 +597,7 @@ func TestAcceptInviteUseCase(t *testing.T) {
|
||||
stored.HashedCode = "hashed:" + acceptCode
|
||||
seeded := invites.seed(stored)
|
||||
users.fail.failNext("Create")
|
||||
if _, err := uc.AcceptInvite(command); !errors.Is(err, errRepositoryFailure) || invites.invites[seeded.ID].AcceptedAt != nil {
|
||||
if _, err := uc.AcceptInvite(testCtx, command); !errors.Is(err, errRepositoryFailure) || invites.invites[seeded.ID].AcceptedAt != nil {
|
||||
t.Errorf("expected repository failure and a pending invite, got %v", err)
|
||||
}
|
||||
})
|
||||
@@ -609,7 +609,7 @@ func TestAcceptInviteUseCase(t *testing.T) {
|
||||
seeded := invites.seed(stored)
|
||||
invites.fail.failNextWith("MarkAccepted", errors.New("mark down"))
|
||||
users.fail.failNextWith("Delete", errors.New("delete down"))
|
||||
_, err := uc.AcceptInvite(command)
|
||||
_, err := uc.AcceptInvite(testCtx, command)
|
||||
if err == nil || !strings.Contains(err.Error(), "mark down") || strings.Contains(err.Error(), "delete down") {
|
||||
t.Errorf("unexpected error %v", err)
|
||||
}
|
||||
@@ -624,7 +624,7 @@ func TestAcceptInviteUseCase(t *testing.T) {
|
||||
stored.HashedCode = "hashed:" + acceptCode
|
||||
invites.seed(stored)
|
||||
invites.fail.failNextWith("MarkAccepted", invite.ErrInviteNotFound)
|
||||
if _, err := uc.AcceptInvite(command); !errors.Is(err, invite.ErrInviteInvalid) || len(users.users) != 1 {
|
||||
if _, err := uc.AcceptInvite(testCtx, command); !errors.Is(err, invite.ErrInviteInvalid) || len(users.users) != 1 {
|
||||
t.Errorf("expected ErrInviteInvalid, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -20,7 +20,7 @@ import (
|
||||
func newAccountVerificationRouter(userRepo *mockUserRepo, token *jwtauth.JWTAuth) *chi.Mux {
|
||||
hasher := &stubHasher{}
|
||||
verificationHandler := auth.NewVerificationHandler(
|
||||
useCases.NewVerifyUserUseCase(userRepo, hasher),
|
||||
useCases.NewVerifyUserUseCase(userRepo, hasher, discardRecorder),
|
||||
useCases.NewCancelRegistrationUseCase(userRepo),
|
||||
true,
|
||||
)
|
||||
|
||||
@@ -16,9 +16,9 @@ func TestAccountVerificationUseCase(t *testing.T) {
|
||||
VerificationCode: "hashed:right-code",
|
||||
VerificationExpiration: time.Now().Add(time.Hour),
|
||||
}
|
||||
uc := useCases.NewVerifyUserUseCase(repo, &stubHasher{})
|
||||
uc := useCases.NewVerifyUserUseCase(repo, &stubHasher{}, discardRecorder)
|
||||
|
||||
_, err := uc.Verify(3, "wrong-code")
|
||||
_, err := uc.Verify(testCtx, 3, "wrong-code")
|
||||
|
||||
if !errors.Is(err, user.ErrInvalidVerificationCode) {
|
||||
t.Fatalf("expected ErrInvalidVerificationCode, got %v", err)
|
||||
@@ -35,9 +35,9 @@ func TestAccountVerificationUseCase(t *testing.T) {
|
||||
VerificationCode: "hashed:right-code",
|
||||
VerificationExpiration: time.Now().Add(-time.Hour),
|
||||
}
|
||||
uc := useCases.NewVerifyUserUseCase(repo, &stubHasher{})
|
||||
uc := useCases.NewVerifyUserUseCase(repo, &stubHasher{}, discardRecorder)
|
||||
|
||||
_, err := uc.Verify(3, "right-code")
|
||||
_, err := uc.Verify(testCtx, 3, "right-code")
|
||||
|
||||
if !errors.Is(err, user.ErrVerificationCodeExpired) {
|
||||
t.Fatalf("expected ErrVerificationCodeExpired, got %v", err)
|
||||
@@ -54,9 +54,9 @@ func TestAccountVerificationUseCase(t *testing.T) {
|
||||
VerificationCode: "hashed:right-code",
|
||||
VerificationExpiration: time.Now().Add(time.Hour),
|
||||
}
|
||||
uc := useCases.NewVerifyUserUseCase(repo, &stubHasher{})
|
||||
uc := useCases.NewVerifyUserUseCase(repo, &stubHasher{}, discardRecorder)
|
||||
|
||||
result, err := uc.Verify(3, "right-code")
|
||||
result, err := uc.Verify(testCtx, 3, "right-code")
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error, got %v", err)
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"errors"
|
||||
"reflect"
|
||||
"sort"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func activityStrings[T ~string](values []T) []string {
|
||||
result := make([]string, 0, len(values))
|
||||
for _, value := range values {
|
||||
result = append(result, string(value))
|
||||
}
|
||||
sort.Strings(result)
|
||||
return result
|
||||
}
|
||||
|
||||
func TestActivityDomain(t *testing.T) {
|
||||
t.Run("An event carries everything the log needs", func(t *testing.T) {
|
||||
event := audit.NewEvent("article.publish", audit.CategoryArticles)
|
||||
|
||||
if event.Action != "article.publish" || event.Category != audit.CategoryArticles {
|
||||
t.Fatalf("unexpected action or category: %+v", event)
|
||||
}
|
||||
if event.Outcome != audit.OutcomeSuccess {
|
||||
t.Errorf("expected a successful outcome by default, got %q", event.Outcome)
|
||||
}
|
||||
wanted := []string{"ID", "CreatedAt", "Action", "Params", "Category", "Actor", "Target", "Outcome", "FailureReason", "Security", "Source", "IP", "UserAgent", "Changes"}
|
||||
eventType := reflect.TypeOf(event)
|
||||
for _, name := range wanted {
|
||||
if _, ok := eventType.FieldByName(name); !ok {
|
||||
t.Errorf("the event has no %s field", name)
|
||||
}
|
||||
}
|
||||
actorType := reflect.TypeOf(event.Actor)
|
||||
for _, name := range []string{"Type", "ID", "Name"} {
|
||||
if _, ok := actorType.FieldByName(name); !ok {
|
||||
t.Errorf("the actor snapshot has no %s field", name)
|
||||
}
|
||||
}
|
||||
targetType := reflect.TypeOf(event.Target)
|
||||
for _, name := range []string{"Type", "ID", "Name"} {
|
||||
if _, ok := targetType.FieldByName(name); !ok {
|
||||
t.Errorf("the target snapshot has no %s field", name)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
vocabulary := []struct {
|
||||
field string
|
||||
got []string
|
||||
wanted []string
|
||||
}{
|
||||
{"actor.type", activityStrings(audit.ActorTypes()), []string{"anonymous", "api_key", "system", "user"}},
|
||||
{"category", activityStrings(audit.Categories()), []string{"api_keys", "articles", "auth", "media", "system", "users"}},
|
||||
{"outcome", activityStrings(audit.Outcomes()), []string{"failed", "success"}},
|
||||
{"source", activityStrings(audit.Sources()), []string{"api_key", "system", "web"}},
|
||||
{"change.kind", activityStrings(audit.ChangeKinds()), []string{"body", "text"}},
|
||||
}
|
||||
for _, c := range vocabulary {
|
||||
t.Run("The vocabulary is closed: "+c.field, func(t *testing.T) {
|
||||
if !reflect.DeepEqual(c.got, c.wanted) {
|
||||
t.Errorf("expected %v, got %v", c.wanted, c.got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("The repository exposes no way to edit or delete one event", func(t *testing.T) {
|
||||
repoType := reflect.TypeOf((*audit.Repository)(nil)).Elem()
|
||||
var names []string
|
||||
for i := 0; i < repoType.NumMethod(); i++ {
|
||||
names = append(names, repoType.Method(i).Name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
wanted := []string{"Append", "DeleteOlderThan", "List", "Summary"}
|
||||
if !reflect.DeepEqual(names, wanted) {
|
||||
t.Errorf("expected methods %v, got %v", wanted, names)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The sentinel errors are matchable", func(t *testing.T) {
|
||||
if !errors.Is(audit.ErrInvalidFilter, audit.ErrInvalidFilter) || !errors.Is(audit.ErrInvalidRetention, audit.ErrInvalidRetention) {
|
||||
t.Fatal("sentinels must match themselves")
|
||||
}
|
||||
if errors.Is(audit.ErrInvalidFilter, audit.ErrInvalidRetention) {
|
||||
t.Error("the sentinels must be distinct")
|
||||
}
|
||||
if _, err := audit.ParseActor("group:3"); !errors.Is(err, audit.ErrInvalidFilter) {
|
||||
t.Errorf("expected ErrInvalidFilter, got %v", err)
|
||||
}
|
||||
if err := audit.ValidateRetentionDays(7); !errors.Is(err, audit.ErrInvalidRetention) {
|
||||
t.Errorf("expected ErrInvalidRetention, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("An actor reference is parsed from its query form", func(t *testing.T) {
|
||||
cases := []struct {
|
||||
raw string
|
||||
wantType audit.ActorType
|
||||
wantID uint32
|
||||
wantErr bool
|
||||
}{
|
||||
{"user:3", audit.ActorUser, 3, false},
|
||||
{"key:7", audit.ActorAPIKey, 7, false},
|
||||
{"system", audit.ActorSystem, 0, false},
|
||||
{"user:abc", "", 0, true},
|
||||
{"user:-1", "", 0, true},
|
||||
{"user:", "", 0, true},
|
||||
{"group:3", "", 0, true},
|
||||
{"system:1", "", 0, true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
ref, err := audit.ParseActor(c.raw)
|
||||
if c.wantErr {
|
||||
if !errors.Is(err, audit.ErrInvalidFilter) {
|
||||
t.Errorf("%q: expected ErrInvalidFilter, got %v", c.raw, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err != nil || ref.Type != c.wantType {
|
||||
t.Fatalf("%q: unexpected result %+v, %v", c.raw, ref, err)
|
||||
}
|
||||
if c.wantID != 0 && (ref.ID == nil || *ref.ID != c.wantID) {
|
||||
t.Errorf("%q: expected id %d, got %v", c.raw, c.wantID, ref.ID)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A user actor reads the display name and falls back to the username", func(t *testing.T) {
|
||||
named := audit.UserActor(user.User{ID: 3, Username: "marta", DisplayName: "Marta Alves"})
|
||||
if named.Type != audit.ActorUser || named.ID == nil || *named.ID != 3 || named.Name != "Marta Alves" {
|
||||
t.Errorf("unexpected actor %+v", named)
|
||||
}
|
||||
plain := audit.UserActor(user.User{ID: 4, Username: "dev"})
|
||||
if plain.Name != "dev" {
|
||||
t.Errorf("expected the username, got %q", plain.Name)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Only the documented retention periods are valid", func(t *testing.T) {
|
||||
for _, days := range []int{30, 90, 365, 0} {
|
||||
if err := audit.ValidateRetentionDays(days); err != nil {
|
||||
t.Errorf("%d should be valid: %v", days, err)
|
||||
}
|
||||
}
|
||||
for _, days := range []int{7, -1, 366, 1} {
|
||||
if err := audit.ValidateRetentionDays(days); !errors.Is(err, audit.ErrInvalidRetention) {
|
||||
t.Errorf("%d should be invalid, got %v", days, err)
|
||||
}
|
||||
}
|
||||
if audit.DefaultSettings().RetentionDays != 90 {
|
||||
t.Errorf("the default retention must be 90 days")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The cleanup is due once a day at or after 03:00", func(t *testing.T) {
|
||||
at := func(day, hour, minute int) time.Time {
|
||||
return time.Date(2026, time.October, day, hour, minute, 0, 0, time.UTC)
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
last *time.Time
|
||||
now time.Time
|
||||
due bool
|
||||
}{
|
||||
{"never before 03:00", nil, at(6, 2, 59), false},
|
||||
{"never at 03:00", nil, at(6, 3, 0), true},
|
||||
{"never at 14:00", nil, at(6, 14, 0), true},
|
||||
{"yesterday before 03:00", ptrTime(at(5, 3, 0)), at(6, 2, 59), false},
|
||||
{"yesterday at 03:00", ptrTime(at(5, 3, 0)), at(6, 3, 0), true},
|
||||
{"today already", ptrTime(at(6, 3, 0)), at(6, 4, 0), false},
|
||||
{"tomorrow at 03:00", ptrTime(at(6, 3, 0)), at(7, 3, 0), true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
settings := audit.Settings{RetentionDays: 90, LastCleanupAt: c.last}
|
||||
if got := settings.CleanupDue(c.now); got != c.due {
|
||||
t.Errorf("%s: expected %v, got %v", c.name, c.due, got)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The last 24 hours are never removed", func(t *testing.T) {
|
||||
now := time.Date(2026, time.October, 6, 3, 0, 0, 0, time.UTC)
|
||||
tooRecent := now.Add(-time.Hour)
|
||||
if got := audit.ClampCutoff(now, tooRecent); !got.Equal(now.Add(-24 * time.Hour)) {
|
||||
t.Errorf("expected the 24 hour floor, got %v", got)
|
||||
}
|
||||
older := now.Add(-48 * time.Hour)
|
||||
if got := audit.ClampCutoff(now, older); !got.Equal(older) {
|
||||
t.Errorf("expected the older cutoff to stay, got %v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func ptrTime(t time.Time) *time.Time { return &t }
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,173 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestActivityLogBackendQAResetResponseIsIndistinguishable(t *testing.T) {
|
||||
t.Run("unknown email answers the same bytes as an existing account", func(t *testing.T) {
|
||||
e := newActivityHTTPEnv(t, 1000)
|
||||
|
||||
known := e.send(http.MethodPost, "/v1/auth/password-reset", `{"email":"marta@example.com"}`)
|
||||
unknown := e.send(http.MethodPost, "/v1/auth/password-reset", `{"email":"nobody@example.com"}`)
|
||||
|
||||
if known.Code != unknown.Code || known.Body.String() != unknown.Body.String() {
|
||||
t.Errorf("responses differ: %d %q versus %d %q", known.Code, known.Body.String(), unknown.Code, unknown.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestActivityLogBackendQAProducersSurviveRecorderFailure(t *testing.T) {
|
||||
type producer func(e *activityHTTPEnv) *httptest.ResponseRecorder
|
||||
producers := map[string]producer{
|
||||
"login failure": func(e *activityHTTPEnv) *httptest.ResponseRecorder {
|
||||
return e.send(http.MethodPost, "/v1/auth/login", `{"username":"marta","password":"wrongpassword1"}`)
|
||||
},
|
||||
"logout": func(e *activityHTTPEnv) *httptest.ResponseRecorder {
|
||||
return e.send(http.MethodPost, "/v1/auth/logout", "", asUser(e, activityOwnerID))
|
||||
},
|
||||
"password reset request": func(e *activityHTTPEnv) *httptest.ResponseRecorder {
|
||||
return e.send(http.MethodPost, "/v1/auth/password-reset", `{"email":"marta@example.com"}`)
|
||||
},
|
||||
"api key creation": func(e *activityHTTPEnv) *httptest.ResponseRecorder {
|
||||
return e.send(http.MethodPost, "/v1/api-key", `{"name":"Deploy bot"}`, asUser(e, activityOwnerID))
|
||||
},
|
||||
"api key revoke": func(e *activityHTTPEnv) *httptest.ResponseRecorder {
|
||||
_, id := e.issueKey(t, activityOwnerID, "Deploy bot")
|
||||
return e.send(http.MethodDelete, "/v1/api-key/"+strconv.Itoa(int(id)), "", asUser(e, activityOwnerID))
|
||||
},
|
||||
"retention change": func(e *activityHTTPEnv) *httptest.ResponseRecorder {
|
||||
return e.send(http.MethodPatch, "/v1/settings", `{"activity_retention_days": 30}`, asUser(e, activityOwnerID))
|
||||
},
|
||||
}
|
||||
scrub := regexp.MustCompile(`"(id|key|prefix|created_at)":\s*("[^"]*"|[0-9]+)`)
|
||||
for name, run := range producers {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
healthy := run(newActivityHTTPEnv(t, 1000))
|
||||
broken := newActivityHTTPEnv(t, 1000)
|
||||
broken.probe.appendErr = errDiskFull
|
||||
|
||||
got := run(broken)
|
||||
|
||||
if got.Code != healthy.Code || scrub.ReplaceAllString(got.Body.String(), "") != scrub.ReplaceAllString(healthy.Body.String(), "") {
|
||||
t.Errorf("a failing recorder changed the answer: %d %q versus %d %q", got.Code, got.Body.String(), healthy.Code, healthy.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestActivityLogBackendQAGuards(t *testing.T) {
|
||||
read := func(t *testing.T, root string, suffix string) map[string]string {
|
||||
t.Helper()
|
||||
files := map[string]string{}
|
||||
err := filepath.Walk(filepath.Join("..", root), func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil || info.IsDir() || !strings.HasSuffix(path, suffix) {
|
||||
return err
|
||||
}
|
||||
content, readErr := os.ReadFile(path)
|
||||
files[path] = string(content)
|
||||
return readErr
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(files) == 0 {
|
||||
t.Fatalf("no files under %s", root)
|
||||
}
|
||||
return files
|
||||
}
|
||||
|
||||
t.Run("The audit repository source uses no dialect specific SQL", func(t *testing.T) {
|
||||
for path, source := range read(t, "internal/infrastructure/persistence/repositories", ".go") {
|
||||
if !strings.Contains(filepath.Base(path), "audit") {
|
||||
continue
|
||||
}
|
||||
for _, banned := range []string{"ILIKE", "strftime", "date_trunc"} {
|
||||
if strings.Contains(source, banned) {
|
||||
t.Errorf("%s contains %s", path, banned)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The audit domain imports only the stdlib and domain packages", func(t *testing.T) {
|
||||
importLine := regexp.MustCompile(`(?m)^\s*"([^"]+)"$`)
|
||||
for path, source := range read(t, "internal/domain/audit", ".go") {
|
||||
for _, match := range importLine.FindAllStringSubmatch(source, -1) {
|
||||
if strings.Contains(match[1], ".") && !strings.HasPrefix(match[1], "RenewCMS/internal/domain/") {
|
||||
t.Errorf("%s imports %s", path, match[1])
|
||||
}
|
||||
if strings.HasPrefix(match[1], "RenewCMS/") && !strings.HasPrefix(match[1], "RenewCMS/internal/domain/") {
|
||||
t.Errorf("%s imports %s", path, match[1])
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The activity use cases and handlers keep their layering", func(t *testing.T) {
|
||||
banned := []string{"gorm.io", "infrastructure/persistence", "infrastructure/mailer", "net/http", "go-chi", "RenewCMS/api"}
|
||||
for path, source := range read(t, "internal/infrastructure/useCases", ".go") {
|
||||
base := filepath.Base(path)
|
||||
if !strings.Contains(base, "Activity") && !strings.Contains(base, "activity") {
|
||||
continue
|
||||
}
|
||||
for _, word := range banned {
|
||||
if strings.Contains(source, word+`"`) || strings.Contains(source, `"`+word) {
|
||||
t.Errorf("%s imports %s", path, word)
|
||||
}
|
||||
}
|
||||
}
|
||||
for path, source := range read(t, "api/handlers/activity", ".go") {
|
||||
for _, word := range []string{"gorm.io", "persistence", "infrastructure/mailer"} {
|
||||
if strings.Contains(source, word) {
|
||||
t.Errorf("%s references %s", path, word)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The persistence repository asserts the audit contract", func(t *testing.T) {
|
||||
for path, source := range read(t, "internal/infrastructure/persistence/repositories", "auditEventRepository.go") {
|
||||
if !strings.Contains(source, "var _ audit.Repository = &") {
|
||||
t.Errorf("%s lacks the interface assertion", path)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The new Go files hold no comment", func(t *testing.T) {
|
||||
line := regexp.MustCompile(`(?m)^\s*//`)
|
||||
for _, root := range []string{"internal/domain/audit", "internal/infrastructure/auditing", "api/handlers/activity"} {
|
||||
for path, source := range read(t, root, ".go") {
|
||||
if line.MatchString(source) {
|
||||
t.Errorf("%s holds a comment", path)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The docs describe the activity surface", func(t *testing.T) {
|
||||
wants := map[string][]string{
|
||||
"docs/api.md": {"/v1/activity", "/v1/activity/summary", "/v1/activity/export", "activity_retention_days"},
|
||||
"docs/architecture.md": {"audit"},
|
||||
"docs/configuration.md": {"retention"},
|
||||
}
|
||||
for doc, needles := range wants {
|
||||
content, err := os.ReadFile(filepath.Join("..", doc))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, needle := range needles {
|
||||
if !strings.Contains(string(content), needle) {
|
||||
t.Errorf("%s does not mention %s", doc, needle)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,943 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/api"
|
||||
"RenewCMS/internal/domain/article"
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/image"
|
||||
"RenewCMS/internal/domain/invite"
|
||||
"RenewCMS/internal/domain/update"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
var producersTimestamps = regexp.MustCompile(`"(created_at|expires_at)":"[^"]*",?`)
|
||||
|
||||
const (
|
||||
producersUserAgent = "producers-test/1.0"
|
||||
producersClientIP = "192.0.2.1"
|
||||
producersOwnerName = "Marta Alves"
|
||||
producersSpringName = "Spring release"
|
||||
producersBannerPath = "/static/uploadedImages/"
|
||||
)
|
||||
|
||||
type producersEnv struct {
|
||||
*apiKeyEnv
|
||||
audit *activityHarness
|
||||
}
|
||||
|
||||
func newProducersEnv(t *testing.T) *producersEnv {
|
||||
t.Helper()
|
||||
h := newActivityHarness(t)
|
||||
env := newAPIKeyEnvRecording(t, h.recorder)
|
||||
owner := env.users.users[apiKeyOwnerId]
|
||||
owner.DisplayName = producersOwnerName
|
||||
env.users.users[apiKeyOwnerId] = owner
|
||||
env.container.ListActivityUseCase = useCases.NewListActivityUseCase(h.store, env.users, env.articles, env.images, env.keys, h.clock)
|
||||
router := chi.NewRouter()
|
||||
router.Mount("/v1", api.InitBackendRoutes(env.container, env.settings))
|
||||
env.router = router
|
||||
return &producersEnv{apiKeyEnv: env, audit: h}
|
||||
}
|
||||
|
||||
func (p *producersEnv) request(t *testing.T, req *http.Request, userId uint32) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req.Header.Set("User-Agent", producersUserAgent)
|
||||
if userId != 0 {
|
||||
req.AddCookie(p.cookie(t, userId, 0))
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
p.router.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
func (p *producersEnv) as(t *testing.T, userId uint32, method string, path string, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
if body != "" {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
return p.request(t, req, userId)
|
||||
}
|
||||
|
||||
func (p *producersEnv) asKey(t *testing.T, raw string, method string, path string, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
if body != "" {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+raw)
|
||||
return p.request(t, req, 0)
|
||||
}
|
||||
|
||||
func (p *producersEnv) upload(t *testing.T, userId uint32, filename string, contentType string, content []byte) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
return p.request(t, newMultipartFileRequest(t, http.MethodPost, "/v1/media", filename, contentType, content), userId)
|
||||
}
|
||||
|
||||
func (p *producersEnv) events(t *testing.T) []audit.Event {
|
||||
t.Helper()
|
||||
return p.audit.all(t)
|
||||
}
|
||||
|
||||
func (p *producersEnv) single(t *testing.T) audit.Event {
|
||||
t.Helper()
|
||||
events := p.events(t)
|
||||
if len(events) != 1 {
|
||||
t.Fatalf("expected exactly one event, got %d: %+v", len(events), events)
|
||||
}
|
||||
return events[0]
|
||||
}
|
||||
|
||||
func (p *producersEnv) noEvent(t *testing.T) {
|
||||
t.Helper()
|
||||
if events := p.events(t); len(events) != 0 {
|
||||
t.Fatalf("expected no event, got %d: %+v", len(events), events)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *producersEnv) seedSpring(id uint32, body string, online bool) {
|
||||
p.articles.articles[id] = article.Article{ID: id, Title: producersSpringName, Body: body, IsOnline: online}
|
||||
}
|
||||
|
||||
func (p *producersEnv) seedBanner(id uint32, filename string, hash string) {
|
||||
p.images.images[id] = image.Image{ID: id, Filename: filename, ContentType: "image/png", Path: producersBannerPath + strconv.Itoa(int(id)) + ".png", SHA256: hash, UploadedByID: apiKeyOwnerId}
|
||||
}
|
||||
|
||||
func (p *producersEnv) seedPendingInvite(email string) invite.Invite {
|
||||
return p.invites.seed(invite.Invite{Email: email, HashedCode: "hashed:code", ExpiresAt: time.Now().Add(24 * time.Hour), InvitedBy: apiKeyOwnerId, CreatedAt: time.Now()})
|
||||
}
|
||||
|
||||
func paramsJSON(t *testing.T, event audit.Event) string {
|
||||
t.Helper()
|
||||
encoded, err := json.Marshal(event.Params)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(encoded)
|
||||
}
|
||||
|
||||
func changesJSON(t *testing.T, event audit.Event) string {
|
||||
t.Helper()
|
||||
encoded, err := json.Marshal(event.Changes)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(encoded)
|
||||
}
|
||||
|
||||
func assertProducerEvent(t *testing.T, event audit.Event, action string, category audit.Category, outcome audit.Outcome) {
|
||||
t.Helper()
|
||||
if event.Action != action || event.Category != category || event.Outcome != outcome {
|
||||
t.Fatalf("event = %s/%s/%s, expected %s/%s/%s", event.Action, event.Category, event.Outcome, action, category, outcome)
|
||||
}
|
||||
}
|
||||
|
||||
func assertProducerTarget(t *testing.T, event audit.Event, targetType string, id string, name string) {
|
||||
t.Helper()
|
||||
if event.Target != (audit.Target{Type: targetType, ID: id, Name: name}) {
|
||||
t.Errorf("target = %+v, expected {%s %s %s}", event.Target, targetType, id, name)
|
||||
}
|
||||
}
|
||||
|
||||
func assertProducerFailure(t *testing.T, event audit.Event, reason string) {
|
||||
t.Helper()
|
||||
if event.Outcome != audit.OutcomeFailed || event.FailureReason == nil || *event.FailureReason != reason {
|
||||
t.Errorf("outcome = %s, failure_reason = %v, expected failed with %q", event.Outcome, event.FailureReason, reason)
|
||||
}
|
||||
}
|
||||
|
||||
func assertProducerOwnerOrigin(t *testing.T, event audit.Event) {
|
||||
t.Helper()
|
||||
if event.Actor.Type != audit.ActorUser || event.Actor.ID == nil || *event.Actor.ID != apiKeyOwnerId || event.Actor.Name != producersOwnerName {
|
||||
t.Errorf("actor = %+v", event.Actor)
|
||||
}
|
||||
if event.Source != audit.SourceWeb {
|
||||
t.Errorf("source = %s", event.Source)
|
||||
}
|
||||
if event.IP == nil || *event.IP != producersClientIP || event.UserAgent == nil || *event.UserAgent != producersUserAgent {
|
||||
t.Errorf("ip = %v, user agent = %v", event.IP, event.UserAgent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestActivityLogProducersRouteContext(t *testing.T) {
|
||||
t.Run("A producing route carries the origin of the request", func(t *testing.T) {
|
||||
t.Run("POST /v1/article with the owner's jwt cookie", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
rec := p.as(t, apiKeyOwnerId, http.MethodPost, "/v1/article", `{"title":"Spring release","body":"Hello"}`)
|
||||
assertAPIKeyStatus(t, rec, http.StatusCreated)
|
||||
assertProducerOwnerOrigin(t, p.single(t))
|
||||
})
|
||||
|
||||
t.Run("POST /v1/article with an API key Deploy bot", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
raw, keyId := p.issueKey(apiKeyDevId, "Deploy bot")
|
||||
rec := p.asKey(t, raw, http.MethodPost, "/v1/article", `{"title":"Spring release","body":"Hello"}`)
|
||||
assertAPIKeyStatus(t, rec, http.StatusCreated)
|
||||
event := p.single(t)
|
||||
if event.Actor.Type != audit.ActorAPIKey || event.Actor.ID == nil || *event.Actor.ID != keyId || event.Actor.Name != "Deploy bot" || event.Source != audit.SourceAPIKey {
|
||||
t.Errorf("actor = %+v, source = %s", event.Actor, event.Source)
|
||||
}
|
||||
if event.IP == nil || *event.IP != producersClientIP || event.UserAgent == nil || *event.UserAgent != producersUserAgent {
|
||||
t.Errorf("ip = %v, user agent = %v", event.IP, event.UserAgent)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("POST /v1/media with an API key Deploy bot", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
raw, keyId := p.issueKey(apiKeyDevId, "Deploy bot")
|
||||
req := newMultipartFileRequest(t, http.MethodPost, "/v1/media", "spring-banner.png", "image/png", pngBytes(t, 3, 2))
|
||||
req.Header.Set("Authorization", "Bearer "+raw)
|
||||
rec := p.request(t, req, 0)
|
||||
assertAPIKeyStatus(t, rec, http.StatusCreated)
|
||||
event := p.single(t)
|
||||
if event.Actor.Type != audit.ActorAPIKey || event.Actor.ID == nil || *event.Actor.ID != keyId || event.Actor.Name != "Deploy bot" || event.Source != audit.SourceAPIKey {
|
||||
t.Errorf("actor = %+v, source = %s", event.Actor, event.Source)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("POST /v1/system/update/check with the owner's jwt cookie", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
rec := p.as(t, apiKeyOwnerId, http.MethodPost, "/v1/system/update/check", "")
|
||||
assertAPIKeyStatus(t, rec, http.StatusOK)
|
||||
assertProducerOwnerOrigin(t, p.single(t))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func TestActivityLogProducersFailedAuditWrite(t *testing.T) {
|
||||
type row struct {
|
||||
name string
|
||||
panics bool
|
||||
setup func(p *producersEnv)
|
||||
send func(t *testing.T, p *producersEnv) *httptest.ResponseRecorder
|
||||
applied func(t *testing.T, p *producersEnv)
|
||||
}
|
||||
owner := func(method string, path string, body string) func(t *testing.T, p *producersEnv) *httptest.ResponseRecorder {
|
||||
return func(t *testing.T, p *producersEnv) *httptest.ResponseRecorder {
|
||||
return p.as(t, apiKeyOwnerId, method, path, body)
|
||||
}
|
||||
}
|
||||
seedArticle := func(p *producersEnv) { p.seedSpring(8, "Hello", false) }
|
||||
seedCopies := func(p *producersEnv) {
|
||||
p.seedBanner(5, "banner.png", "same")
|
||||
p.seedBanner(6, "banner-copy.png", "same")
|
||||
p.articles.articles[1] = article.Article{ID: 1, Title: "Uses copy", Body: "see 6.png"}
|
||||
}
|
||||
rows := []row{
|
||||
{name: "fails POST /v1/article", setup: func(*producersEnv) {}, send: owner(http.MethodPost, "/v1/article", `{"title":"Spring release","body":"Hello"}`), applied: func(t *testing.T, p *producersEnv) {
|
||||
if len(p.articles.articles) != 1 {
|
||||
t.Errorf("the article was not created")
|
||||
}
|
||||
}},
|
||||
{name: "fails DELETE /v1/article/8", setup: seedArticle, send: owner(http.MethodDelete, "/v1/article/8", ""), applied: func(t *testing.T, p *producersEnv) {
|
||||
if _, found := p.articles.articles[8]; found {
|
||||
t.Errorf("the article was not deleted")
|
||||
}
|
||||
}},
|
||||
{name: "panics PATCH /v1/article/8/publish", panics: true, setup: seedArticle, send: owner(http.MethodPatch, "/v1/article/8/publish", ""), applied: func(t *testing.T, p *producersEnv) {
|
||||
if !p.articles.articles[8].IsOnline {
|
||||
t.Errorf("the article was not published")
|
||||
}
|
||||
}},
|
||||
{name: "fails POST /v1/media", setup: func(*producersEnv) {}, send: func(t *testing.T, p *producersEnv) *httptest.ResponseRecorder {
|
||||
return p.upload(t, apiKeyOwnerId, "spring-banner.png", "image/png", pngBytes(t, 3, 2))
|
||||
}, applied: func(t *testing.T, p *producersEnv) {
|
||||
if len(p.images.images) != 1 {
|
||||
t.Errorf("the image was not stored")
|
||||
}
|
||||
}},
|
||||
{name: "fails POST /v1/media/merge", setup: seedCopies, send: owner(http.MethodPost, "/v1/media/merge", `{"keep_id":5,"merge_ids":[6]}`), applied: func(t *testing.T, p *producersEnv) {
|
||||
if _, found := p.images.images[6]; found {
|
||||
t.Errorf("the copy was not merged")
|
||||
}
|
||||
}},
|
||||
{name: "fails POST /v1/user/invite", setup: func(*producersEnv) {}, send: owner(http.MethodPost, "/v1/user/invite", `{"email":"new@example.com"}`), applied: func(t *testing.T, p *producersEnv) {
|
||||
if len(p.invites.invites) != 1 {
|
||||
t.Errorf("the invite was not created")
|
||||
}
|
||||
}},
|
||||
{name: "fails POST /v1/system/update/restart", setup: func(*producersEnv) {}, send: owner(http.MethodPost, "/v1/system/update/restart", ""), applied: func(*testing.T, *producersEnv) {}},
|
||||
}
|
||||
|
||||
t.Run("A failing or panicking repository leaves the response untouched", func(t *testing.T) {
|
||||
for _, example := range rows {
|
||||
t.Run(example.name, func(t *testing.T) {
|
||||
healthy := newProducersEnv(t)
|
||||
example.setup(healthy)
|
||||
expected := example.send(t, healthy)
|
||||
|
||||
p := newProducersEnv(t)
|
||||
example.setup(p)
|
||||
if example.panics {
|
||||
p.audit.probe.appendPanic = true
|
||||
} else {
|
||||
p.audit.probe.appendErr = errDiskFull
|
||||
}
|
||||
rec := example.send(t, p)
|
||||
|
||||
if rec.Code != expected.Code || producersTimestamps.ReplaceAllString(rec.Body.String(), "") != producersTimestamps.ReplaceAllString(expected.Body.String(), "") {
|
||||
t.Errorf("response = %d %q, healthy response = %d %q", rec.Code, rec.Body.String(), expected.Code, expected.Body.String())
|
||||
}
|
||||
if rec.Code >= http.StatusBadRequest {
|
||||
t.Fatalf("the request was expected to succeed, got %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
example.applied(t, p)
|
||||
if !strings.Contains(p.audit.logs.String(), "audit:") {
|
||||
t.Errorf("the process log does not name the failed audit write: %q", p.audit.logs.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestActivityLogProducersArticles(t *testing.T) {
|
||||
t.Run("Creating an article is recorded", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
rec := p.as(t, apiKeyOwnerId, http.MethodPost, "/v1/article", `{"title":"Spring release","body":"Hello"}`)
|
||||
assertAPIKeyStatus(t, rec, http.StatusCreated)
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "article.create", audit.CategoryArticles, audit.OutcomeSuccess)
|
||||
assertProducerOwnerOrigin(t, event)
|
||||
assertProducerTarget(t, event, "article", "1", producersSpringName)
|
||||
if event.FailureReason != nil || len(event.Changes) != 0 {
|
||||
t.Errorf("failure reason = %v, changes = %+v", event.FailureReason, event.Changes)
|
||||
}
|
||||
if encoded, _ := json.Marshal(event); strings.Contains(string(encoded), "Hello") {
|
||||
t.Errorf("the stored event holds the article body: %s", encoded)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Editing the body records a size delta and never the text", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
p.seedSpring(8, strings.Repeat("a", 100), false)
|
||||
newBody := strings.Repeat("secretbody", 41) + "xx"
|
||||
rec := p.as(t, apiKeyOwnerId, http.MethodPatch, "/v1/article/8", `{"body":"`+newBody+`"}`)
|
||||
assertAPIKeyStatus(t, rec, http.StatusOK)
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "article.edit", audit.CategoryArticles, audit.OutcomeSuccess)
|
||||
assertProducerTarget(t, event, "article", "8", producersSpringName)
|
||||
if got := changesJSON(t, event); got != `[{"field":"body","kind":"body","delta":312}]` {
|
||||
t.Errorf("changes = %s", got)
|
||||
}
|
||||
listing := p.as(t, apiKeyOwnerId, http.MethodGet, "/v1/activity", "")
|
||||
assertAPIKeyStatus(t, listing, http.StatusOK)
|
||||
if strings.Contains(listing.Body.String(), "secretbody") || strings.Contains(listing.Body.String(), "aaaa") {
|
||||
t.Errorf("the activity response holds article text: %s", listing.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Saving an identical body records nothing", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
p.seedSpring(8, "Same text", false)
|
||||
rec := p.as(t, apiKeyOwnerId, http.MethodPatch, "/v1/article/8", `{"body":"Same text"}`)
|
||||
assertAPIKeyStatus(t, rec, http.StatusOK)
|
||||
p.noEvent(t)
|
||||
})
|
||||
|
||||
t.Run("Publishing is recorded with the publish state", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
p.seedSpring(8, "Hello", false)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPatch, "/v1/article/8/publish", ""), http.StatusOK)
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "article.publish", audit.CategoryArticles, audit.OutcomeSuccess)
|
||||
if got := changesJSON(t, event); got != `[{"field":"online","kind":"text","before":"false","after":"true"}]` {
|
||||
t.Errorf("changes = %s", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Unpublishing is recorded with the publish state", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
p.seedSpring(8, "Hello", true)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPatch, "/v1/article/8/unpublish", ""), http.StatusOK)
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "article.unpublish", audit.CategoryArticles, audit.OutcomeSuccess)
|
||||
if got := changesJSON(t, event); got != `[{"field":"online","kind":"text","before":"true","after":"false"}]` {
|
||||
t.Errorf("changes = %s", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A publish state that does not change records nothing", func(t *testing.T) {
|
||||
for _, example := range []struct {
|
||||
state bool
|
||||
path string
|
||||
status int
|
||||
}{{true, "publish", http.StatusOK}, {false, "unpublish", http.StatusOK}} {
|
||||
t.Run(strconv.FormatBool(example.state)+" "+example.path, func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
p.seedSpring(8, "Hello", example.state)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPatch, "/v1/article/8/"+example.path, ""), example.status)
|
||||
p.noEvent(t)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Deleting an article is recorded with its name snapshot", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
p.seedSpring(8, "Hello", false)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodDelete, "/v1/article/8", ""), http.StatusNoContent)
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "article.delete", audit.CategoryArticles, audit.OutcomeSuccess)
|
||||
assertProducerTarget(t, event, "article", "8", producersSpringName)
|
||||
|
||||
listing := p.as(t, apiKeyOwnerId, http.MethodGet, "/v1/activity", "")
|
||||
var page struct {
|
||||
Items []struct {
|
||||
Target struct {
|
||||
Exists bool `json:"exists"`
|
||||
} `json:"target"`
|
||||
} `json:"items"`
|
||||
}
|
||||
if err := json.Unmarshal(listing.Body.Bytes(), &page); err != nil || len(page.Items) != 1 || page.Items[0].Target.Exists {
|
||||
t.Errorf("listing = %s, err = %v", listing.Body.String(), err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A refused article action is recorded as failed with a plain reason", func(t *testing.T) {
|
||||
t.Run("the repository fails with db is locked on create", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
p.articles.fail.failNextWith("Create", errors.New("db is locked"))
|
||||
rec := p.as(t, apiKeyOwnerId, http.MethodPost, "/v1/article", `{"title":"Spring release","body":"Hello"}`)
|
||||
assertAPIKeyStatus(t, rec, http.StatusInternalServerError)
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "article.create", audit.CategoryArticles, audit.OutcomeFailed)
|
||||
assertProducerFailure(t, event, useCases.GenericFailureReason)
|
||||
if strings.Contains(paramsJSON(t, event), "locked") || strings.Contains(*event.FailureReason, "locked") {
|
||||
t.Errorf("the raw error leaked: %+v", event)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the repository fails with db is locked on publish", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
p.seedSpring(8, "Hello", false)
|
||||
p.articles.fail.failNextWith("UpdateIsOnline", errors.New("db is locked"))
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPatch, "/v1/article/8/publish", ""), http.StatusInternalServerError)
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "article.publish", audit.CategoryArticles, audit.OutcomeFailed)
|
||||
assertProducerFailure(t, event, useCases.GenericFailureReason)
|
||||
assertProducerTarget(t, event, "article", "8", producersSpringName)
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("An article that does not exist records nothing", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
for _, call := range []struct{ method, path, body string }{
|
||||
{http.MethodDelete, "/v1/article/99", ""},
|
||||
{http.MethodPatch, "/v1/article/99", `{"body":"x"}`},
|
||||
{http.MethodPatch, "/v1/article/99/publish", ""},
|
||||
{http.MethodPatch, "/v1/article/99/unpublish", ""},
|
||||
} {
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, call.method, call.path, call.body), http.StatusNotFound)
|
||||
}
|
||||
p.noEvent(t)
|
||||
})
|
||||
|
||||
t.Run("A request that fails validation records nothing", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPost, "/v1/article", `{}`), http.StatusBadRequest)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPatch, "/v1/article/abc", `{"body":"x"}`), http.StatusBadRequest)
|
||||
p.noEvent(t)
|
||||
})
|
||||
|
||||
t.Run("Reads are never recorded", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
p.seedSpring(8, "Hello", true)
|
||||
for _, path := range []string{"/v1/article", "/v1/article/8"} {
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodGet, path, ""), http.StatusOK)
|
||||
}
|
||||
assertAPIKeyStatus(t, p.as(t, 0, http.MethodGet, "/v1/article/8", ""), http.StatusOK)
|
||||
p.noEvent(t)
|
||||
})
|
||||
}
|
||||
|
||||
func TestActivityLogProducersMedia(t *testing.T) {
|
||||
t.Run("Uploading an image is recorded", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
assertAPIKeyStatus(t, p.upload(t, apiKeyOwnerId, "spring-banner.png", "image/png", pngBytes(t, 3, 2)), http.StatusCreated)
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "media.upload", audit.CategoryMedia, audit.OutcomeSuccess)
|
||||
assertProducerOwnerOrigin(t, event)
|
||||
assertProducerTarget(t, event, "image", "1", "spring-banner.png")
|
||||
if encoded, _ := json.Marshal(event); strings.Contains(string(encoded), "/static/") {
|
||||
t.Errorf("the stored event holds a storage path: %s", encoded)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A refused upload is recorded as failed", func(t *testing.T) {
|
||||
for _, example := range []struct {
|
||||
name string
|
||||
contentType string
|
||||
content func(t *testing.T) []byte
|
||||
reason string
|
||||
}{
|
||||
{"a GIF", "image/gif", func(t *testing.T) []byte { return []byte("GIF89a") }, "The file must be a PNG, JPEG, WEBP or SVG image."},
|
||||
{"a PNG larger than the limit", "image/png", func(t *testing.T) []byte { return paddedPngBytes(t, int(image.MaxImageSize)+10) }, "The file is too large to upload."},
|
||||
{"a corrupt PNG", "image/png", func(t *testing.T) []byte { return []byte("not a png") }, "The image could not be read."},
|
||||
} {
|
||||
t.Run(example.name, func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
rec := p.upload(t, apiKeyOwnerId, "spring-banner.png", example.contentType, example.content(t))
|
||||
if rec.Code < http.StatusBadRequest {
|
||||
t.Fatalf("expected a refusal, got %d", rec.Code)
|
||||
}
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "media.upload", audit.CategoryMedia, audit.OutcomeFailed)
|
||||
assertProducerFailure(t, event, example.reason)
|
||||
if event.Target.Name != "spring-banner.png" {
|
||||
t.Errorf("target = %+v", event.Target)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Renaming an image records the filename diff", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
p.seedBanner(5, "banner.png", "h")
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPatch, "/v1/media/5", `{"filename":"spring-banner"}`), http.StatusOK)
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "media.rename", audit.CategoryMedia, audit.OutcomeSuccess)
|
||||
assertProducerTarget(t, event, "image", "5", "spring-banner.png")
|
||||
if got := changesJSON(t, event); got != `[{"field":"filename","kind":"text","before":"banner.png","after":"spring-banner.png"}]` {
|
||||
t.Errorf("changes = %s", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Renaming to the same name records nothing", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
p.seedBanner(5, "banner.png", "h")
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPatch, "/v1/media/5", `{"filename":"banner"}`), http.StatusOK)
|
||||
p.noEvent(t)
|
||||
})
|
||||
|
||||
t.Run("A refused rename is recorded as failed", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
p.seedBanner(5, "banner.png", "h")
|
||||
rec := p.as(t, apiKeyOwnerId, http.MethodPatch, "/v1/media/5", `{"filename":"not/valid"}`)
|
||||
assertAPIKeyStatus(t, rec, http.StatusBadRequest)
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "media.rename", audit.CategoryMedia, audit.OutcomeFailed)
|
||||
assertProducerFailure(t, event, "That file name is not valid.")
|
||||
assertProducerTarget(t, event, "image", "5", "banner.png")
|
||||
})
|
||||
|
||||
t.Run("Deleting an image is recorded with its name snapshot", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
p.seedBanner(5, "banner.png", "h")
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodDelete, "/v1/media/5", ""), http.StatusNoContent)
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "media.delete", audit.CategoryMedia, audit.OutcomeSuccess)
|
||||
assertProducerTarget(t, event, "image", "5", "banner.png")
|
||||
})
|
||||
|
||||
t.Run("Merging images is recorded once with its counts", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
p.seedBanner(5, "banner.png", "same")
|
||||
p.seedBanner(6, "banner-copy.png", "same")
|
||||
p.seedBanner(7, "banner-copy-2.png", "same")
|
||||
p.articles.articles[1] = article.Article{ID: 1, Title: "One", Body: "see 6.png"}
|
||||
p.articles.articles[2] = article.Article{ID: 2, Title: "Two", Body: "see 7.png"}
|
||||
rec := p.as(t, apiKeyOwnerId, http.MethodPost, "/v1/media/merge", `{"keep_id":5,"merge_ids":[6,7]}`)
|
||||
assertAPIKeyStatus(t, rec, http.StatusOK)
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "media.merge", audit.CategoryMedia, audit.OutcomeSuccess)
|
||||
assertProducerTarget(t, event, "image", "5", "banner.png")
|
||||
if got := paramsJSON(t, event); got != `{"articles_updated":2,"merged":2}` {
|
||||
t.Errorf("params = %s", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A refused merge is recorded as failed", func(t *testing.T) {
|
||||
for _, example := range []struct {
|
||||
name string
|
||||
setup func(p *producersEnv)
|
||||
body string
|
||||
reason string
|
||||
}{
|
||||
{"ErrInvalidMergeRequest", func(p *producersEnv) { p.seedBanner(5, "banner.png", "same") }, `{"keep_id":5,"merge_ids":[5]}`, "The merge request is not valid."},
|
||||
{"ErrMergeCopyMissing", func(p *producersEnv) { p.seedBanner(5, "banner.png", "same") }, `{"keep_id":5,"merge_ids":[6]}`, "One of the copies no longer exists."},
|
||||
{"ErrMergeHashMismatch", func(p *producersEnv) {
|
||||
p.seedBanner(5, "banner.png", "same")
|
||||
p.seedBanner(6, "other.png", "different")
|
||||
}, `{"keep_id":5,"merge_ids":[6]}`, "The images are not identical copies."},
|
||||
} {
|
||||
t.Run(example.name, func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
example.setup(p)
|
||||
rec := p.as(t, apiKeyOwnerId, http.MethodPost, "/v1/media/merge", example.body)
|
||||
if rec.Code < http.StatusBadRequest {
|
||||
t.Fatalf("expected a refusal, got %d", rec.Code)
|
||||
}
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "media.merge", audit.CategoryMedia, audit.OutcomeFailed)
|
||||
assertProducerFailure(t, event, example.reason)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A manual purge is recorded once and not as separate merges", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
seedTwoGroupPurgePlan(p)
|
||||
rec := p.as(t, apiKeyOwnerId, http.MethodPost, "/v1/media/purge", "")
|
||||
assertAPIKeyStatus(t, rec, http.StatusOK)
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "media.purge", audit.CategoryMedia, audit.OutcomeSuccess)
|
||||
assertProducerOwnerOrigin(t, event)
|
||||
if got := paramsJSON(t, event); got != `{"articles_updated":5,"merged":3}` {
|
||||
t.Errorf("params = %s", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A partly failed manual purge is a success with the failed group count", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
seedThreeGroupPurgePlan(p, 5)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPost, "/v1/media/purge", ""), http.StatusOK)
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "media.purge", audit.CategoryMedia, audit.OutcomeSuccess)
|
||||
if !strings.Contains(paramsJSON(t, event), `"failed_groups":1`) {
|
||||
t.Errorf("params = %s", paramsJSON(t, event))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A refused manual purge is recorded as failed", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
seedTwoGroupPurgePlan(p)
|
||||
rec := p.as(t, apiKeyOwnerId, http.MethodPost, "/v1/media/purge", `{"fingerprint":"stale"}`)
|
||||
assertAPIKeyStatus(t, rec, http.StatusConflict)
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "media.purge", audit.CategoryMedia, audit.OutcomeFailed)
|
||||
assertProducerFailure(t, event, "The library changed since the preview. Review it again.")
|
||||
})
|
||||
|
||||
t.Run("Browsing and the media usage lookup are never recorded", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
p.seedBanner(5, "banner.png", "h")
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodGet, "/v1/media", ""), http.StatusOK)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodGet, "/v1/media/5/usage", ""), http.StatusOK)
|
||||
p.noEvent(t)
|
||||
})
|
||||
}
|
||||
|
||||
func (p *producersEnv) seedArticleUsing(id uint32, body string) {
|
||||
p.articles.articles[id] = article.Article{ID: id, Title: "Article " + strconv.Itoa(int(id)), Body: body}
|
||||
}
|
||||
|
||||
func seedTwoGroupPurgePlan(p *producersEnv) {
|
||||
p.seedBanner(1, "kept-a.png", "hash-a")
|
||||
p.seedBanner(2, "copy-a1.png", "hash-a")
|
||||
p.seedBanner(3, "copy-a2.png", "hash-a")
|
||||
p.seedBanner(4, "kept-b.png", "hash-b")
|
||||
p.seedBanner(5, "copy-b1.png", "hash-b")
|
||||
for id, body := range map[uint32]string{1: "uses 2.png", 2: "uses 3.png", 3: "uses 5.png", 4: "uses 2.png", 5: "uses 3.png", 6: "1.png 4.png", 7: "1.png 4.png", 8: "1.png 4.png"} {
|
||||
p.seedArticleUsing(id, body)
|
||||
}
|
||||
}
|
||||
|
||||
func seedThreeGroupPurgePlan(p *producersEnv, failingCopy uint32) {
|
||||
p.seedBanner(1, "kept-a.png", "hash-a")
|
||||
p.seedBanner(2, "copy-a.png", "hash-a")
|
||||
p.seedBanner(4, "kept-b.png", "hash-b")
|
||||
p.seedBanner(5, "copy-b.png", "hash-b")
|
||||
p.seedBanner(7, "kept-c.png", "hash-c")
|
||||
p.seedBanner(8, "copy-c.png", "hash-c")
|
||||
for id, body := range map[uint32]string{1: "uses 2.png", 2: "uses 5.png", 3: "uses 8.png", 4: "1.png 4.png 7.png", 5: "1.png 4.png 7.png"} {
|
||||
p.seedArticleUsing(id, body)
|
||||
}
|
||||
p.images.failDeleteFor = map[uint32]error{failingCopy: errors.New("storage offline")}
|
||||
}
|
||||
|
||||
func TestActivityLogProducersUsers(t *testing.T) {
|
||||
t.Run("Changing the display name records a before and after", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPatch, "/v1/user/me", `{"display_name":"Marta Alves 2"}`), http.StatusOK)
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "user.update_profile", audit.CategoryUsers, audit.OutcomeSuccess)
|
||||
assertProducerTarget(t, event, "user", "1", "Marta Alves 2")
|
||||
if got := changesJSON(t, event); got != `[{"field":"display_name","kind":"text","before":"Marta Alves","after":"Marta Alves 2"}]` {
|
||||
t.Errorf("changes = %s", got)
|
||||
}
|
||||
if event.Actor.Name != producersOwnerName {
|
||||
t.Errorf("the actor snapshot name = %q, expected the name held when the request began", event.Actor.Name)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Setting a display name that does not change records nothing", func(t *testing.T) {
|
||||
for _, sent := range []string{"Marta Alves", " Marta Alves "} {
|
||||
p := newProducersEnv(t)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPatch, "/v1/user/me", `{"display_name":"`+sent+`"}`), http.StatusOK)
|
||||
p.noEvent(t)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A display name that is too long is recorded as failed", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
rec := p.as(t, apiKeyOwnerId, http.MethodPatch, "/v1/user/me", `{"display_name":"`+strings.Repeat("a", 61)+`"}`)
|
||||
assertAPIKeyStatus(t, rec, http.StatusBadRequest)
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "user.update_profile", audit.CategoryUsers, audit.OutcomeFailed)
|
||||
assertProducerFailure(t, event, "That display name is too long.")
|
||||
if len(event.Changes) != 0 {
|
||||
t.Errorf("changes = %+v", event.Changes)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Creating an invite is recorded", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPost, "/v1/user/invite", `{"email":"new@example.com"}`), http.StatusCreated)
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "invite.create", audit.CategoryUsers, audit.OutcomeSuccess)
|
||||
assertProducerOwnerOrigin(t, event)
|
||||
assertProducerTarget(t, event, "invite", "1", "new@example.com")
|
||||
if encoded, _ := json.Marshal(event); strings.Contains(string(encoded), "hashed:") {
|
||||
t.Errorf("the stored event holds a code hash: %s", encoded)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A refused invite action is recorded as failed", func(t *testing.T) {
|
||||
for _, example := range []struct {
|
||||
name string
|
||||
setup func(p *producersEnv)
|
||||
method string
|
||||
path string
|
||||
body string
|
||||
action string
|
||||
reason string
|
||||
}{
|
||||
{"ErrEmailHasAccount", func(*producersEnv) {}, http.MethodPost, "/v1/user/invite", `{"email":"dev@example.com"}`, "invite.create", "That email already has an account."},
|
||||
{"ErrPendingInvite", func(p *producersEnv) { p.seedPendingInvite("new@example.com") }, http.MethodPost, "/v1/user/invite", `{"email":"new@example.com"}`, "invite.create", "An invitation is already pending for that email."},
|
||||
{"ErrInviteEmailNotSent on create", func(p *producersEnv) { p.mail.fail.failNext("Send") }, http.MethodPost, "/v1/user/invite", `{"email":"new@example.com"}`, "invite.create", "The invitation email could not be sent."},
|
||||
{"ErrInviteEmailNotSent on renew", func(p *producersEnv) { p.seedPendingInvite("new@example.com"); p.mail.fail.failNext("Send") }, http.MethodPost, "/v1/user/invite/1/renew", "", "invite.renew", "The invitation email could not be sent."},
|
||||
{"ErrInviteAlreadyAccepted on renew", func(p *producersEnv) { p.seedAcceptedInvite("new@example.com") }, http.MethodPost, "/v1/user/invite/1/renew", "", "invite.renew", "That invitation was already accepted."},
|
||||
{"ErrInviteAlreadyAccepted on cancel", func(p *producersEnv) { p.seedAcceptedInvite("new@example.com") }, http.MethodDelete, "/v1/user/invite/1", "", "invite.cancel", "That invitation was already accepted."},
|
||||
} {
|
||||
t.Run(example.name, func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
example.setup(p)
|
||||
rec := p.as(t, apiKeyOwnerId, example.method, example.path, example.body)
|
||||
if rec.Code < http.StatusBadRequest {
|
||||
t.Fatalf("expected a refusal, got %d", rec.Code)
|
||||
}
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, example.action, audit.CategoryUsers, audit.OutcomeFailed)
|
||||
assertProducerFailure(t, event, example.reason)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Cancelling an invite is recorded", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
p.seedPendingInvite("new@example.com")
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodDelete, "/v1/user/invite/1", ""), http.StatusNoContent)
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "invite.cancel", audit.CategoryUsers, audit.OutcomeSuccess)
|
||||
assertProducerTarget(t, event, "invite", "1", "new@example.com")
|
||||
})
|
||||
|
||||
t.Run("Renewing an invite is recorded", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
p.seedPendingInvite("new@example.com")
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPost, "/v1/user/invite/1/renew", ""), http.StatusOK)
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "invite.renew", audit.CategoryUsers, audit.OutcomeSuccess)
|
||||
assertProducerTarget(t, event, "invite", "1", "new@example.com")
|
||||
})
|
||||
|
||||
t.Run("An invite or user that does not exist records nothing", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodDelete, "/v1/user/invite/99", ""), http.StatusNotFound)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPost, "/v1/user/invite/99/renew", ""), http.StatusNotFound)
|
||||
p.noEvent(t)
|
||||
})
|
||||
|
||||
t.Run("Reads and checks are never recorded", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
for _, path := range []string{"/v1/user", "/v1/auth/me", "/v1/auth/registration"} {
|
||||
rec := p.as(t, apiKeyOwnerId, http.MethodGet, path, "")
|
||||
assertAPIKeyStatus(t, rec, http.StatusOK)
|
||||
}
|
||||
p.noEvent(t)
|
||||
})
|
||||
}
|
||||
|
||||
func (p *producersEnv) seedAcceptedInvite(email string) {
|
||||
accepted := time.Now().Add(-time.Hour)
|
||||
p.invites.seed(invite.Invite{Email: email, HashedCode: "hashed:code", ExpiresAt: time.Now().Add(24 * time.Hour), InvitedBy: apiKeyOwnerId, AcceptedAt: &accepted, CreatedAt: time.Now().Add(-2 * time.Hour)})
|
||||
}
|
||||
|
||||
func TestActivityLogProducersSystem(t *testing.T) {
|
||||
t.Run("Checking for an update is recorded", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPost, "/v1/system/update/check", ""), http.StatusOK)
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "system.update_checked", audit.CategorySystem, audit.OutcomeSuccess)
|
||||
assertProducerTarget(t, event, "release", "v2.3.0-beta", "v2.3.0-beta")
|
||||
if got := paramsJSON(t, event); got != `{"update_available":true}` {
|
||||
t.Errorf("params = %s", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A failed update check is recorded with a plain reason", func(t *testing.T) {
|
||||
for _, example := range []struct {
|
||||
name string
|
||||
err error
|
||||
reason string
|
||||
}{
|
||||
{"ErrFeedUnavailable", update.ErrFeedUnavailable, "The release feed could not be reached."},
|
||||
{"ErrNoRelease", update.ErrNoRelease, "No release was found."},
|
||||
} {
|
||||
t.Run(example.name, func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
p.feed.err = example.err
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPost, "/v1/system/update/check", ""), http.StatusInternalServerError)
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "system.update_checked", audit.CategorySystem, audit.OutcomeFailed)
|
||||
assertProducerFailure(t, event, example.reason)
|
||||
if event.Target != (audit.Target{}) {
|
||||
t.Errorf("target = %+v", event.Target)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The status poll is never recorded", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodGet, "/v1/system/update", ""), http.StatusOK)
|
||||
p.noEvent(t)
|
||||
})
|
||||
|
||||
t.Run("A restart request is recorded", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPost, "/v1/system/update/restart", ""), http.StatusAccepted)
|
||||
event := p.single(t)
|
||||
assertProducerEvent(t, event, "system.restart_requested", audit.CategorySystem, audit.OutcomeSuccess)
|
||||
assertProducerOwnerOrigin(t, event)
|
||||
if got := paramsJSON(t, event); got != `{"kind":"restart"}` {
|
||||
t.Errorf("params = %s", got)
|
||||
}
|
||||
if event.Target != (audit.Target{}) {
|
||||
t.Errorf("target = %+v", event.Target)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (p *producersEnv) listedActions(t *testing.T, category string) []string {
|
||||
t.Helper()
|
||||
listing := p.as(t, apiKeyOwnerId, http.MethodGet, "/v1/activity?category="+category, "")
|
||||
assertAPIKeyStatus(t, listing, http.StatusOK)
|
||||
var page struct {
|
||||
Items []struct {
|
||||
Action string `json:"action"`
|
||||
Category string `json:"category"`
|
||||
} `json:"items"`
|
||||
}
|
||||
if err := json.Unmarshal(listing.Body.Bytes(), &page); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
actions := []string{}
|
||||
for _, item := range page.Items {
|
||||
if item.Category != category {
|
||||
t.Errorf("item category = %q, expected %q", item.Category, category)
|
||||
}
|
||||
actions = append(actions, item.Action)
|
||||
}
|
||||
return actions
|
||||
}
|
||||
|
||||
func TestActivityLogProducersReadBackOtherCategories(t *testing.T) {
|
||||
t.Run("Media events are listed under their category", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
p.seedBanner(5, "banner.png", "same")
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPatch, "/v1/media/5", `{"filename":"spring"}`), http.StatusOK)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodDelete, "/v1/media/5", ""), http.StatusNoContent)
|
||||
if got := strings.Join(p.listedActions(t, "media"), ","); got != "media.delete,media.rename" {
|
||||
t.Errorf("actions = %s", got)
|
||||
}
|
||||
if got := p.listedActions(t, "articles"); len(got) != 0 {
|
||||
t.Errorf("articles actions = %v", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("User events are listed under their category", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPatch, "/v1/user/me", `{"display_name":"Marta Alves 2"}`), http.StatusOK)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPost, "/v1/user/invite", `{"email":"new@example.com"}`), http.StatusCreated)
|
||||
if got := strings.Join(p.listedActions(t, "users"), ","); got != "invite.create,user.update_profile" {
|
||||
t.Errorf("actions = %s", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("System events are listed under their category", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPost, "/v1/system/update/check", ""), http.StatusOK)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPost, "/v1/system/update/restart", ""), http.StatusAccepted)
|
||||
if got := strings.Join(p.listedActions(t, "system"), ","); got != "system.restart_requested,system.update_checked" {
|
||||
t.Errorf("actions = %s", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestActivityLogProducersReadBack(t *testing.T) {
|
||||
t.Run("Producer events are listed with their documented shape", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPost, "/v1/article", `{"title":"Spring release","body":"Hello"}`), http.StatusCreated)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPatch, "/v1/article/1", `{"body":"Hello world"}`), http.StatusOK)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPatch, "/v1/article/1/publish", ""), http.StatusOK)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodDelete, "/v1/article/1", ""), http.StatusNoContent)
|
||||
|
||||
listing := p.as(t, apiKeyOwnerId, http.MethodGet, "/v1/activity?category=articles", "")
|
||||
assertAPIKeyStatus(t, listing, http.StatusOK)
|
||||
var page struct {
|
||||
Items []struct {
|
||||
Action string `json:"action"`
|
||||
Category string `json:"category"`
|
||||
Target struct {
|
||||
Exists bool `json:"exists"`
|
||||
} `json:"target"`
|
||||
} `json:"items"`
|
||||
}
|
||||
if err := json.Unmarshal(listing.Body.Bytes(), &page); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var actions []string
|
||||
for _, item := range page.Items {
|
||||
actions = append(actions, item.Action)
|
||||
if item.Category != "articles" || item.Target.Exists {
|
||||
t.Errorf("item = %+v", item)
|
||||
}
|
||||
}
|
||||
if strings.Join(actions, ",") != "article.delete,article.publish,article.edit,article.create" {
|
||||
t.Errorf("actions = %v", actions)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A failed producer event is filterable", func(t *testing.T) {
|
||||
p := newProducersEnv(t)
|
||||
p.seedBanner(5, "banner.png", "same")
|
||||
p.as(t, apiKeyOwnerId, http.MethodPost, "/v1/media/merge", `{"keep_id":5,"merge_ids":[6]}`)
|
||||
assertAPIKeyStatus(t, p.as(t, apiKeyOwnerId, http.MethodPatch, "/v1/media/5", `{"filename":"spring"}`), http.StatusOK)
|
||||
|
||||
listing := p.as(t, apiKeyOwnerId, http.MethodGet, "/v1/activity?outcome=failed", "")
|
||||
assertAPIKeyStatus(t, listing, http.StatusOK)
|
||||
var page struct {
|
||||
Items []struct {
|
||||
Action string `json:"action"`
|
||||
FailureReason *string `json:"failure_reason"`
|
||||
} `json:"items"`
|
||||
}
|
||||
if err := json.Unmarshal(listing.Body.Bytes(), &page); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page.Items) != 1 || page.Items[0].Action != "media.merge" || page.Items[0].FailureReason == nil || *page.Items[0].FailureReason != "One of the copies no longer exists." {
|
||||
t.Errorf("items = %+v", page.Items)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,770 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/article"
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/image"
|
||||
"RenewCMS/internal/domain/invite"
|
||||
"RenewCMS/internal/domain/purge"
|
||||
"RenewCMS/internal/domain/update"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const producerSignalTimeout = 5 * time.Second
|
||||
|
||||
type producerSignalRecorder struct {
|
||||
inner audit.Recorder
|
||||
recorded chan struct{}
|
||||
}
|
||||
|
||||
var _ audit.Recorder = &producerSignalRecorder{}
|
||||
|
||||
func newProducerSignalRecorder(inner audit.Recorder) *producerSignalRecorder {
|
||||
return &producerSignalRecorder{inner: inner, recorded: make(chan struct{}, 16)}
|
||||
}
|
||||
|
||||
func (r *producerSignalRecorder) Record(ctx context.Context, event audit.Event) {
|
||||
r.inner.Record(ctx, event)
|
||||
r.recorded <- struct{}{}
|
||||
}
|
||||
|
||||
func (r *producerSignalRecorder) await(t *testing.T) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-r.recorded:
|
||||
case <-time.After(producerSignalTimeout):
|
||||
t.Fatal("no event was recorded")
|
||||
}
|
||||
}
|
||||
|
||||
type producerPurgeRunner struct {
|
||||
result purge.RunResult
|
||||
err error
|
||||
calls int
|
||||
}
|
||||
|
||||
var _ useCases.PurgeRunner = &producerPurgeRunner{}
|
||||
|
||||
func (r *producerPurgeRunner) Execute(*string) (purge.RunResult, error) {
|
||||
r.calls++
|
||||
return r.result, r.err
|
||||
}
|
||||
|
||||
type producerBlockingImageRepo struct {
|
||||
*mockImageRepo
|
||||
entered chan struct{}
|
||||
release chan struct{}
|
||||
}
|
||||
|
||||
func (r *producerBlockingImageRepo) ListDuplicates() ([]image.Image, error) {
|
||||
r.entered <- struct{}{}
|
||||
<-r.release
|
||||
return r.mockImageRepo.ListDuplicates()
|
||||
}
|
||||
|
||||
func producerContext(actor audit.Actor, source audit.Source) context.Context {
|
||||
return audit.WithOrigin(context.Background(), audit.Origin{Actor: actor, Source: source, IP: "192.0.2.1", UserAgent: "producers-test/1.0"})
|
||||
}
|
||||
|
||||
func producerOwnerContext() context.Context {
|
||||
id := uint32(1)
|
||||
return producerContext(audit.Actor{Type: audit.ActorUser, ID: &id, Name: "Marta Alves"}, audit.SourceWeb)
|
||||
}
|
||||
|
||||
func producerAnonymousContext() context.Context {
|
||||
return producerContext(audit.AnonymousActor(""), audit.SourceWeb)
|
||||
}
|
||||
|
||||
func onlyEvent(t *testing.T, h *activityHarness) audit.Event {
|
||||
t.Helper()
|
||||
events := h.all(t)
|
||||
if len(events) != 1 {
|
||||
t.Fatalf("expected exactly one event, got %d: %+v", len(events), events)
|
||||
}
|
||||
return events[0]
|
||||
}
|
||||
|
||||
func assertNoEvents(t *testing.T, h *activityHarness) {
|
||||
t.Helper()
|
||||
if events := h.all(t); len(events) != 0 {
|
||||
t.Fatalf("expected no event, got %+v", events)
|
||||
}
|
||||
}
|
||||
|
||||
func assertEventsHoldNothing(t *testing.T, h *activityHarness, forbidden ...string) {
|
||||
t.Helper()
|
||||
encoded, err := json.Marshal(h.all(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, secret := range forbidden {
|
||||
if strings.Contains(string(encoded), secret) || strings.Contains(h.logs.String(), secret) {
|
||||
t.Errorf("an event or the log holds %q: %s", secret, encoded)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestActivityLogProducersArticleChanges(t *testing.T) {
|
||||
t.Run("The delta is signed and counts characters", func(t *testing.T) {
|
||||
for _, example := range []struct {
|
||||
before int
|
||||
after int
|
||||
delta int
|
||||
}{{100, 412, 312}, {412, 100, -312}, {5, 5, 0}} {
|
||||
t.Run(fmt.Sprintf("%d to %d", example.before, example.after), func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
repo := newMockArticleRepo()
|
||||
repo.articles[8] = article.Article{ID: 8, Title: "Spring release", Body: strings.Repeat("a", example.before)}
|
||||
uc := useCases.NewUpdateArticleUseCase(repo, &fakeBodyRenderer{}, h.recorder)
|
||||
|
||||
if _, err := uc.UpdateBody(producerOwnerContext(), 8, strings.Repeat("b", example.after), article.BodyFormatHTML); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
event := onlyEvent(t, h)
|
||||
if len(event.Changes) != 1 || event.Changes[0].Delta == nil || *event.Changes[0].Delta != example.delta || event.Changes[0].Field != "body" || event.Changes[0].Kind != audit.ChangeBody {
|
||||
t.Errorf("changes = %+v", event.Changes)
|
||||
}
|
||||
assertEventsHoldNothing(t, h, "bbbb")
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A body with multi-byte characters is counted in characters", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
repo := newMockArticleRepo()
|
||||
repo.articles[8] = article.Article{ID: 8, Title: "Spring release", Body: "héllo"}
|
||||
uc := useCases.NewUpdateArticleUseCase(repo, &fakeBodyRenderer{}, h.recorder)
|
||||
|
||||
if _, err := uc.UpdateBody(producerOwnerContext(), 8, "héllo wörld", article.BodyFormatHTML); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
event := onlyEvent(t, h)
|
||||
if event.Changes[0].Delta == nil || *event.Changes[0].Delta != 6 || utf8.RuneCountInString("héllo wörld")-utf8.RuneCountInString("héllo") != 6 {
|
||||
t.Errorf("changes = %+v", event.Changes)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A title change is recorded as a text diff when a title edit exists", func(t *testing.T) {
|
||||
before := article.Article{ID: 8, Title: "Spring release", Body: "x", IsOnline: false}
|
||||
after := article.Article{ID: 8, Title: "Spring release 2", Body: "x", IsOnline: false}
|
||||
|
||||
changes := audit.ArticleChanges(before, after)
|
||||
|
||||
encoded, _ := json.Marshal(changes)
|
||||
if string(encoded) != `[{"field":"title","kind":"text","before":"Spring release","after":"Spring release 2"}]` {
|
||||
t.Errorf("changes = %s", encoded)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Only the fields title, online and body can ever appear in an article event's changes", func(t *testing.T) {
|
||||
before := article.Article{ID: 8, Title: "a", Body: "x", IsOnline: false}
|
||||
after := article.Article{ID: 9, Title: "b", Body: "y", IsOnline: true}
|
||||
|
||||
for _, change := range audit.ArticleChanges(before, after) {
|
||||
if change.Field != "title" && change.Field != "online" && change.Field != "body" {
|
||||
t.Errorf("unexpected field %q", change.Field)
|
||||
}
|
||||
if change.Kind != audit.ChangeText && change.Kind != audit.ChangeBody {
|
||||
t.Errorf("unexpected kind %q", change.Kind)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A refused article title is recorded as failed with a plain reason", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
uc := useCases.NewCreateArticleUseCase(newMockArticleRepo(), &fakeBodyRenderer{}, h.recorder)
|
||||
|
||||
_, err := uc.CreateArticle(producerOwnerContext(), useCases.CreateArticleCommand{Title: "ab", Body: "Hello"})
|
||||
|
||||
if !errors.Is(err, article.ErrInvalidTitle) {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
event := onlyEvent(t, h)
|
||||
assertProducerEvent(t, event, "article.create", audit.CategoryArticles, audit.OutcomeFailed)
|
||||
assertProducerFailure(t, event, "The title must be between 3 and 200 characters.")
|
||||
})
|
||||
}
|
||||
|
||||
func TestActivityLogProducersFailureReasons(t *testing.T) {
|
||||
sentences := []struct {
|
||||
cause error
|
||||
sentence string
|
||||
}{
|
||||
{article.ErrInvalidTitle, "The title must be between 3 and 200 characters."},
|
||||
{image.ErrImageTypeNotAllowed, "The file must be a PNG, JPEG, WEBP or SVG image."},
|
||||
{image.ErrImageTooLarge, "The file is too large to upload."},
|
||||
{image.ErrImageUnreadable, "The image could not be read."},
|
||||
{image.ErrInvalidFilename, "That file name is not valid."},
|
||||
{image.ErrInvalidMergeRequest, "The merge request is not valid."},
|
||||
{image.ErrMergeCopyMissing, "One of the copies no longer exists."},
|
||||
{image.ErrMergeHashMismatch, "The images are not identical copies."},
|
||||
{purge.ErrPurgeConflict, "The library changed since the preview. Review it again."},
|
||||
{user.ErrRegistrationClosed, "Registration is closed on this site."},
|
||||
{user.ErrVerificationEmailNotSent, "The verification email could not be sent."},
|
||||
{user.ErrInvalidVerificationCode, "The verification code is not valid."},
|
||||
{user.ErrVerificationCodeExpired, "The verification code has expired."},
|
||||
{user.ErrInvalidDisplayName, "That display name is too long."},
|
||||
{user.ErrUsernameTaken, "That username is already taken."},
|
||||
{invite.ErrEmailHasAccount, "That email already has an account."},
|
||||
{invite.ErrPendingInvite, "An invitation is already pending for that email."},
|
||||
{invite.ErrInviteEmailNotSent, "The invitation email could not be sent."},
|
||||
{invite.ErrInviteAlreadyAccepted, "That invitation was already accepted."},
|
||||
{invite.ErrInviteInvalid, "That invitation is not valid."},
|
||||
{invite.ErrInviteExpired, "That invitation has expired."},
|
||||
{update.ErrFeedUnavailable, "The release feed could not be reached."},
|
||||
{update.ErrNoRelease, "No release was found."},
|
||||
{update.ErrNotPrepared, "This server cannot apply updates."},
|
||||
{update.ErrJobInProgress, "An update is already being downloaded."},
|
||||
{update.ErrRestartPending, "A restart is already pending."},
|
||||
{update.ErrNothingToUpdate, "There is nothing to update."},
|
||||
{update.ErrPreflightRefused, "The update cannot be downloaded."},
|
||||
{update.ErrRestartKindMismatch, "The requested restart does not match the server state."},
|
||||
}
|
||||
|
||||
dueSettings := func() *mockPurgeSettingsRepo {
|
||||
repo := newMockPurgeSettingsRepo()
|
||||
repo.settings = purge.Settings{AutoPurgeEnabled: true, AutoPurgeIntervalDays: 1, EnabledAt: purgeTime("2026-09-01T00:00:00Z")}
|
||||
return repo
|
||||
}
|
||||
failWith := func(t *testing.T, err error) audit.Event {
|
||||
t.Helper()
|
||||
h := newActivityHarness(t)
|
||||
scheduler := useCases.NewPurgeSchedulerUseCase(dueSettings(), &producerPurgeRunner{err: err}, h.recorder)
|
||||
if _, _, tickErr := scheduler.Tick(*purgeTime("2026-10-05T09:00:00Z")); !errors.Is(tickErr, err) {
|
||||
t.Fatalf("tick err = %v", tickErr)
|
||||
}
|
||||
return onlyEvent(t, h)
|
||||
}
|
||||
|
||||
t.Run("Failure reasons are mapped from domain sentinels", func(t *testing.T) {
|
||||
for _, example := range sentences {
|
||||
t.Run(example.cause.Error(), func(t *testing.T) {
|
||||
event := failWith(t, fmt.Errorf("while working: %w", example.cause))
|
||||
assertProducerFailure(t, event, example.sentence)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Unmapped errors become the generic sentence", func(t *testing.T) {
|
||||
for name, err := range map[string]error{
|
||||
"a plain error": errors.New("db is locked"),
|
||||
"an error carrying an SMTP host": errors.New("dial smtp.internal.example:587 with password hunter2"),
|
||||
"an error carrying a file system path": errors.New(`open C:\data\secret\file.db`),
|
||||
"an error wrapping a sentinel and a raw cause": errors.Join(update.ErrFeedUnavailable, errors.New("token=abc123")),
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
event := failWith(t, err)
|
||||
if name == "an error wrapping a sentinel and a raw cause" {
|
||||
assertProducerFailure(t, event, "The release feed could not be reached.")
|
||||
} else {
|
||||
assertProducerFailure(t, event, useCases.GenericFailureReason)
|
||||
}
|
||||
encoded, _ := json.Marshal(event)
|
||||
for _, leaked := range []string{"locked", "hunter2", "smtp.internal", "secret", "abc123"} {
|
||||
if strings.Contains(string(encoded), leaked) {
|
||||
t.Errorf("the event leaks %q: %s", leaked, encoded)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Every failure reason fits the stored limit", func(t *testing.T) {
|
||||
for _, example := range sentences {
|
||||
if len(example.sentence) > 255 {
|
||||
t.Errorf("%q is %d characters", example.sentence, len(example.sentence))
|
||||
}
|
||||
}
|
||||
if len(useCases.GenericFailureReason) > 255 {
|
||||
t.Errorf("the generic sentence is too long")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A failed event keeps its target when the target is known", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
images := newMockImageRepo()
|
||||
images.images[5] = image.Image{ID: 5, Filename: "banner.png", Path: "/static/uploadedImages/5.png"}
|
||||
uc := useCases.NewRenameMediaUseCase(images, h.recorder)
|
||||
|
||||
if _, err := uc.Rename(producerOwnerContext(), 5, "not valid!"); !errors.Is(err, image.ErrInvalidFilename) {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
|
||||
assertProducerTarget(t, onlyEvent(t, h), "image", "5", "banner.png")
|
||||
})
|
||||
}
|
||||
|
||||
func TestActivityLogProducersScheduledPurge(t *testing.T) {
|
||||
due := func() *mockPurgeSettingsRepo {
|
||||
repo := newMockPurgeSettingsRepo()
|
||||
repo.settings = purge.Settings{AutoPurgeEnabled: true, AutoPurgeIntervalDays: 10, EnabledAt: purgeTime("2026-09-20T09:00:00Z")}
|
||||
return repo
|
||||
}
|
||||
now := *purgeTime("2026-10-05T09:00:00Z")
|
||||
|
||||
t.Run("The scheduled purge is a system event", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
runner := &producerPurgeRunner{result: purge.RunResult{GroupsTotal: 2, GroupsPurged: 2, Merged: 3, ArticlesUpdated: 5}}
|
||||
scheduler := useCases.NewPurgeSchedulerUseCase(due(), runner, h.recorder)
|
||||
|
||||
if _, ran, err := scheduler.Tick(now); err != nil || !ran {
|
||||
t.Fatalf("ran = %v, err = %v", ran, err)
|
||||
}
|
||||
|
||||
event := onlyEvent(t, h)
|
||||
assertProducerEvent(t, event, "system.media_purge", audit.CategorySystem, audit.OutcomeSuccess)
|
||||
if event.Actor.Type != audit.ActorSystem || event.Actor.Name != "System" || event.Source != audit.SourceSystem || event.IP != nil || event.UserAgent != nil {
|
||||
t.Errorf("event = %+v", event)
|
||||
}
|
||||
if got := paramsJSON(t, event); got != `{"articles_updated":5,"merged":3}` {
|
||||
t.Errorf("params = %s", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A scheduled purge with a failed group records the failed group count", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
runner := &producerPurgeRunner{result: purge.RunResult{GroupsTotal: 3, GroupsPurged: 2, FailedGroups: 1, Merged: 2, ArticlesUpdated: 2}}
|
||||
scheduler := useCases.NewPurgeSchedulerUseCase(due(), runner, h.recorder)
|
||||
|
||||
if _, _, err := scheduler.Tick(now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
event := onlyEvent(t, h)
|
||||
assertProducerEvent(t, event, "system.media_purge", audit.CategorySystem, audit.OutcomeSuccess)
|
||||
if !strings.Contains(paramsJSON(t, event), `"failed_groups":1`) {
|
||||
t.Errorf("params = %s", paramsJSON(t, event))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A scheduled purge that is not due or merges nothing records nothing", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
notDue := newMockPurgeSettingsRepo()
|
||||
runner := &producerPurgeRunner{}
|
||||
if _, ran, err := useCases.NewPurgeSchedulerUseCase(notDue, runner, h.recorder).Tick(now); err != nil || ran {
|
||||
t.Fatalf("ran = %v, err = %v", ran, err)
|
||||
}
|
||||
if _, ran, err := useCases.NewPurgeSchedulerUseCase(due(), runner, h.recorder).Tick(now); err != nil || !ran {
|
||||
t.Fatalf("ran = %v, err = %v", ran, err)
|
||||
}
|
||||
assertNoEvents(t, h)
|
||||
})
|
||||
|
||||
t.Run("A scheduled purge that cannot record its run is a failed system event", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
runner := &producerPurgeRunner{err: errRepositoryFailure}
|
||||
|
||||
if _, _, err := useCases.NewPurgeSchedulerUseCase(due(), runner, h.recorder).Tick(now); err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
|
||||
event := onlyEvent(t, h)
|
||||
assertProducerEvent(t, event, "system.media_purge", audit.CategorySystem, audit.OutcomeFailed)
|
||||
assertProducerFailure(t, event, useCases.GenericFailureReason)
|
||||
})
|
||||
|
||||
t.Run("A refused manual purge is recorded as failed when a purge is already running", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
images := &producerBlockingImageRepo{mockImageRepo: newMockImageRepo(), entered: make(chan struct{}, 2), release: make(chan struct{})}
|
||||
articles := newMockArticleRepo()
|
||||
storage := newMockImageStorage()
|
||||
merge := useCases.NewMergeMediaUseCase(images, articles, storage, h.recorder)
|
||||
run := useCases.NewRunPurgeUseCase(images, articles, merge, newMockPurgeSettingsRepo(), func() time.Time { return now }, log.New(io.Discard, "", 0), h.recorder)
|
||||
|
||||
finished := make(chan struct{})
|
||||
go func() {
|
||||
defer close(finished)
|
||||
_, _ = run.Run(producerOwnerContext(), nil)
|
||||
}()
|
||||
<-images.entered
|
||||
|
||||
_, err := run.Run(producerOwnerContext(), nil)
|
||||
close(images.release)
|
||||
<-finished
|
||||
|
||||
if !errors.Is(err, purge.ErrPurgeBusy) {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
events := h.all(t)
|
||||
if len(events) != 2 {
|
||||
t.Fatalf("events = %+v", events)
|
||||
}
|
||||
busy := events[1]
|
||||
if events[0].Outcome == audit.OutcomeFailed {
|
||||
busy = events[0]
|
||||
}
|
||||
assertProducerEvent(t, busy, "media.purge", audit.CategoryMedia, audit.OutcomeFailed)
|
||||
assertProducerFailure(t, busy, "A purge is already running.")
|
||||
})
|
||||
}
|
||||
|
||||
func TestActivityLogProducersAccounts(t *testing.T) {
|
||||
const password = "s3cretpassw0rd"
|
||||
newUsers := func() *mockUserRepo {
|
||||
users := newMockUserRepo()
|
||||
return users
|
||||
}
|
||||
|
||||
t.Run("Registering is recorded with the new account as actor", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
uc := useCases.NewCreateUserUseCase(newUsers(), &stubHasher{}, newMockMailRepo(), "https://cms.example.com", h.recorder)
|
||||
|
||||
created, err := uc.CreateUser(producerAnonymousContext(), useCases.CreateUserCommand{Username: "marta", Password: password, Email: "marta@example.com"})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
event := onlyEvent(t, h)
|
||||
assertProducerEvent(t, event, "user.register", audit.CategoryUsers, audit.OutcomeSuccess)
|
||||
if event.Actor.Type != audit.ActorUser || event.Actor.ID == nil || *event.Actor.ID != created.ID || event.Actor.Name != "marta" || event.Source != audit.SourceWeb {
|
||||
t.Errorf("actor = %+v, source = %s", event.Actor, event.Source)
|
||||
}
|
||||
assertProducerTarget(t, event, "user", "1", "marta")
|
||||
assertEventsHoldNothing(t, h, password, "hashed:", created.VerificationCode)
|
||||
})
|
||||
|
||||
t.Run("A refused registration is recorded as failed", func(t *testing.T) {
|
||||
for _, example := range []struct {
|
||||
cause string
|
||||
setup func(users *mockUserRepo, mail *mockMailRepo)
|
||||
reason string
|
||||
}{
|
||||
{"registration is closed", func(users *mockUserRepo, _ *mockMailRepo) {
|
||||
users.users[9] = user.User{ID: 9, Username: "owner", IsVerified: true}
|
||||
}, "Registration is closed on this site."},
|
||||
{"the verification email cannot be sent", func(_ *mockUserRepo, mail *mockMailRepo) { mail.fail.failNext("Send") }, "The verification email could not be sent."},
|
||||
} {
|
||||
t.Run(example.cause, func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
users := newUsers()
|
||||
mail := newMockMailRepo()
|
||||
example.setup(users, mail)
|
||||
uc := useCases.NewCreateUserUseCase(users, &stubHasher{}, mail, "https://cms.example.com", h.recorder)
|
||||
|
||||
if _, err := uc.CreateUser(producerAnonymousContext(), useCases.CreateUserCommand{Username: "marta", Password: password, Email: "marta@example.com"}); err == nil {
|
||||
t.Fatal("expected a refusal")
|
||||
}
|
||||
|
||||
event := onlyEvent(t, h)
|
||||
assertProducerEvent(t, event, "user.register", audit.CategoryUsers, audit.OutcomeFailed)
|
||||
assertProducerFailure(t, event, example.reason)
|
||||
if event.Actor.Type != audit.ActorAnonymous || event.Actor.Name != "marta" || event.Target != (audit.Target{}) {
|
||||
t.Errorf("actor = %+v, target = %+v", event.Actor, event.Target)
|
||||
}
|
||||
assertEventsHoldNothing(t, h, password)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A failed cleanup after an unsent verification email keeps both causes", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
users := newUsers()
|
||||
mail := newMockMailRepo()
|
||||
mail.fail.failNext("Send")
|
||||
cleanupFailure := errors.New("cleanup failure")
|
||||
users.fail.failNextWith("Delete", cleanupFailure)
|
||||
uc := useCases.NewCreateUserUseCase(users, &stubHasher{}, mail, "https://cms.example.com", h.recorder)
|
||||
|
||||
_, err := uc.CreateUser(producerAnonymousContext(), useCases.CreateUserCommand{Username: "marta", Password: password, Email: "marta@example.com"})
|
||||
|
||||
if !errors.Is(err, user.ErrVerificationEmailNotSent) || !errors.Is(err, cleanupFailure) {
|
||||
t.Errorf("err = %v", err)
|
||||
}
|
||||
assertProducerFailure(t, onlyEvent(t, h), "The verification email could not be sent.")
|
||||
})
|
||||
|
||||
t.Run("Verifying an account is recorded", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
users := newUsers()
|
||||
users.users[4] = user.User{ID: 4, Username: "lea", VerificationCode: "hashed:the-code", VerificationExpiration: time.Now().Add(time.Hour)}
|
||||
uc := useCases.NewVerifyUserUseCase(users, &stubHasher{}, h.recorder)
|
||||
|
||||
if _, err := uc.Verify(producerAnonymousContext(), 4, "the-code"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
event := onlyEvent(t, h)
|
||||
assertProducerEvent(t, event, "user.verify", audit.CategoryUsers, audit.OutcomeSuccess)
|
||||
if event.Actor.Type != audit.ActorUser || event.Actor.ID == nil || *event.Actor.ID != 4 {
|
||||
t.Errorf("actor = %+v", event.Actor)
|
||||
}
|
||||
assertProducerTarget(t, event, "user", "4", "lea")
|
||||
assertEventsHoldNothing(t, h, "the-code", "hashed:")
|
||||
})
|
||||
|
||||
t.Run("A refused verification is recorded as failed", func(t *testing.T) {
|
||||
for _, example := range []struct {
|
||||
name string
|
||||
code string
|
||||
expiration time.Time
|
||||
reason string
|
||||
}{
|
||||
{"ErrInvalidVerificationCode", "wrong", time.Now().Add(time.Hour), "The verification code is not valid."},
|
||||
{"ErrVerificationCodeExpired", "the-code", time.Now().Add(-time.Hour), "The verification code has expired."},
|
||||
} {
|
||||
t.Run(example.name, func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
users := newUsers()
|
||||
users.users[4] = user.User{ID: 4, Username: "lea", VerificationCode: "hashed:the-code", VerificationExpiration: example.expiration}
|
||||
uc := useCases.NewVerifyUserUseCase(users, &stubHasher{}, h.recorder)
|
||||
|
||||
if _, err := uc.Verify(producerAnonymousContext(), 4, example.code); err == nil {
|
||||
t.Fatal("expected a refusal")
|
||||
}
|
||||
|
||||
event := onlyEvent(t, h)
|
||||
assertProducerEvent(t, event, "user.verify", audit.CategoryUsers, audit.OutcomeFailed)
|
||||
assertProducerFailure(t, event, example.reason)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Accepting an invite is recorded with the new account as actor", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
users := newUsers()
|
||||
invites := newInviteFakeRepo()
|
||||
invites.users = users
|
||||
seeded := invites.seed(invite.Invite{Email: "new@example.com", HashedCode: "hashed:the-code", ExpiresAt: time.Now().Add(time.Hour)})
|
||||
uc := useCases.NewAcceptInviteUseCase(users, invites, &stubHasher{}, h.recorder)
|
||||
|
||||
created, err := uc.AcceptInvite(producerAnonymousContext(), useCases.AcceptInviteCommand{Code: "the-code", Username: "sam", Password: password})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
event := onlyEvent(t, h)
|
||||
assertProducerEvent(t, event, "invite.accept", audit.CategoryUsers, audit.OutcomeSuccess)
|
||||
if event.Actor.Type != audit.ActorUser || event.Actor.ID == nil || *event.Actor.ID != created.ID || event.Actor.Name != "sam" || event.Source != audit.SourceWeb {
|
||||
t.Errorf("actor = %+v", event.Actor)
|
||||
}
|
||||
assertProducerTarget(t, event, "invite", fmt.Sprint(seeded.ID), "new@example.com")
|
||||
assertEventsHoldNothing(t, h, "the-code", "hashed:", password)
|
||||
})
|
||||
|
||||
t.Run("A refused acceptance is recorded as failed", func(t *testing.T) {
|
||||
for _, example := range []struct {
|
||||
name string
|
||||
code string
|
||||
expiresIn time.Duration
|
||||
existing []user.User
|
||||
reason string
|
||||
target bool
|
||||
}{
|
||||
{"ErrInviteInvalid", "wrong", time.Hour, nil, "That invitation is not valid.", false},
|
||||
{"ErrInviteExpired", "the-code", -time.Hour, nil, "That invitation has expired.", false},
|
||||
{"ErrUsernameTaken", "the-code", time.Hour, []user.User{{ID: 9, Username: "sam", Email: "sam@example.com"}}, "That username is already taken.", true},
|
||||
{"ErrEmailHasAccount", "the-code", time.Hour, []user.User{{ID: 9, Username: "other", Email: "new@example.com"}}, "That email already has an account.", true},
|
||||
} {
|
||||
t.Run(example.name, func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
users := newUsers()
|
||||
for _, existing := range example.existing {
|
||||
users.users[existing.ID] = existing
|
||||
}
|
||||
invites := newInviteFakeRepo()
|
||||
invites.users = users
|
||||
invites.seed(invite.Invite{Email: "new@example.com", HashedCode: "hashed:the-code", ExpiresAt: time.Now().Add(example.expiresIn)})
|
||||
uc := useCases.NewAcceptInviteUseCase(users, invites, &stubHasher{}, h.recorder)
|
||||
|
||||
if _, err := uc.AcceptInvite(producerAnonymousContext(), useCases.AcceptInviteCommand{Code: example.code, Username: "sam", Password: password}); err == nil {
|
||||
t.Fatal("expected a refusal")
|
||||
}
|
||||
|
||||
event := onlyEvent(t, h)
|
||||
assertProducerEvent(t, event, "invite.accept", audit.CategoryUsers, audit.OutcomeFailed)
|
||||
assertProducerFailure(t, event, example.reason)
|
||||
if event.Actor.Type != audit.ActorAnonymous || event.Actor.Name != "sam" {
|
||||
t.Errorf("actor = %+v", event.Actor)
|
||||
}
|
||||
if (event.Target != audit.Target{}) != example.target {
|
||||
t.Errorf("target = %+v", event.Target)
|
||||
}
|
||||
assertEventsHoldNothing(t, h, "the-code", password)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestActivityLogProducersUpdateDownload(t *testing.T) {
|
||||
cancelledOwnerContext := func() (context.Context, context.CancelFunc) {
|
||||
return context.WithCancel(producerOwnerContext())
|
||||
}
|
||||
newRig := func(t *testing.T) (*downloadRig, *activityHarness, *producerSignalRecorder) {
|
||||
t.Helper()
|
||||
h := newActivityHarness(t)
|
||||
signal := newProducerSignalRecorder(h.recorder)
|
||||
rig := newDownloadRig(t)
|
||||
rig.recorder = signal
|
||||
rig.rebuild()
|
||||
return rig, h, signal
|
||||
}
|
||||
|
||||
t.Run("A download that completes is recorded when the job is ready", func(t *testing.T) {
|
||||
rig, h, signal := newRig(t)
|
||||
ctx, cancel := cancelledOwnerContext()
|
||||
|
||||
if _, err := rig.start.Start(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cancel()
|
||||
signal.await(t)
|
||||
|
||||
event := onlyEvent(t, h)
|
||||
assertProducerEvent(t, event, "system.update_downloaded", audit.CategorySystem, audit.OutcomeSuccess)
|
||||
assertProducerTarget(t, event, "release", downloadTag, downloadTag)
|
||||
if event.Actor.Type != audit.ActorUser || event.Actor.Name != "Marta Alves" || event.Source != audit.SourceWeb || event.IP == nil || *event.IP != "192.0.2.1" {
|
||||
t.Errorf("event = %+v", event)
|
||||
}
|
||||
assertEventsHoldNothing(t, h, "https://", rig.updatesDir)
|
||||
})
|
||||
|
||||
t.Run("A download that fails is recorded with a reason that hides the cause", func(t *testing.T) {
|
||||
for _, example := range []struct {
|
||||
kind string
|
||||
setup func(rig *downloadRig)
|
||||
reason string
|
||||
}{
|
||||
{"download", func(rig *downloadRig) { rig.fetcher.errors[rig.assetName] = errDownloadNetwork }, "The update could not be downloaded."},
|
||||
{"verification", func(rig *downloadRig) {
|
||||
_, otherKey, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rig.signChecksums(rig.checksumsFor(rig.assetName, rig.fetcher.files[rig.assetName]), otherKey)
|
||||
rig.publishAssets()
|
||||
}, "The downloaded update failed its integrity check."},
|
||||
} {
|
||||
t.Run(example.kind, func(t *testing.T) {
|
||||
rig, h, signal := newRig(t)
|
||||
example.setup(rig)
|
||||
|
||||
if _, err := rig.start.Start(producerOwnerContext()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
signal.await(t)
|
||||
|
||||
event := onlyEvent(t, h)
|
||||
assertProducerEvent(t, event, "system.update_downloaded", audit.CategorySystem, audit.OutcomeFailed)
|
||||
assertProducerFailure(t, event, example.reason)
|
||||
assertEventsHoldNothing(t, h, "https://", rig.updatesDir, errDownloadNetwork.Error())
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A download refused at the start is recorded as failed", func(t *testing.T) {
|
||||
for _, example := range []struct {
|
||||
name string
|
||||
setup func(rig *downloadRig)
|
||||
reason string
|
||||
}{
|
||||
{"ErrNotPrepared", func(rig *downloadRig) { rig.helper.installed = false }, "This server cannot apply updates."},
|
||||
{"ErrJobInProgress", func(rig *downloadRig) {
|
||||
rig.jobs.put(update.Job{Tag: downloadTag, State: update.StateDownloading, StartedAt: time.Now()})
|
||||
}, "An update is already being downloaded."},
|
||||
{"ErrRestartPending", func(rig *downloadRig) {
|
||||
_ = rig.requests.Write(update.RestartRequest{Kind: update.RestartKindRestart, RequestedAt: updateTestCheckedAt})
|
||||
}, "A restart is already pending."},
|
||||
{"ErrNothingToUpdate", func(rig *downloadRig) { rig.store.found = false }, "There is nothing to update."},
|
||||
{"ErrPreflightRefused", func(rig *downloadRig) { rig.dropAsset(update.ChecksumsAssetName) }, "The update cannot be downloaded."},
|
||||
} {
|
||||
t.Run(example.name, func(t *testing.T) {
|
||||
rig, h, _ := newRig(t)
|
||||
example.setup(rig)
|
||||
|
||||
if _, err := rig.start.Start(producerOwnerContext()); err == nil {
|
||||
t.Fatal("expected a refusal")
|
||||
}
|
||||
|
||||
event := onlyEvent(t, h)
|
||||
assertProducerEvent(t, event, "system.update_downloaded", audit.CategorySystem, audit.OutcomeFailed)
|
||||
assertProducerFailure(t, event, example.reason)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestActivityLogProducersRestart(t *testing.T) {
|
||||
newRequest := func(t *testing.T) (*restartRig, *activityHarness, *useCases.RequestRestartUseCase) {
|
||||
t.Helper()
|
||||
h := newActivityHarness(t)
|
||||
rig := newRestartRig(updateRunning)
|
||||
request := useCases.NewRequestRestartUseCase(rig.store, rig.jobs, rig.helper, rig.results, rig.requests, updateRunning, rig.clock.Now, h.recorder)
|
||||
return rig, h, request
|
||||
}
|
||||
|
||||
t.Run("A restart request is recorded", func(t *testing.T) {
|
||||
_, h, request := newRequest(t)
|
||||
|
||||
if _, err := request.Request(producerOwnerContext(), updateOwnerId, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
event := onlyEvent(t, h)
|
||||
assertProducerEvent(t, event, "system.restart_requested", audit.CategorySystem, audit.OutcomeSuccess)
|
||||
if got := paramsJSON(t, event); got != `{"kind":"restart"}` {
|
||||
t.Errorf("params = %s", got)
|
||||
}
|
||||
if event.Target != (audit.Target{}) {
|
||||
t.Errorf("target = %+v", event.Target)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A restart that applies a downloaded update records the kind and version", func(t *testing.T) {
|
||||
rig, h, request := newRequest(t)
|
||||
rig.readyJob()
|
||||
|
||||
if _, err := request.Request(producerOwnerContext(), updateOwnerId, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if got := paramsJSON(t, onlyEvent(t, h)); got != `{"kind":"update","tag":"`+downloadTag+`"}` {
|
||||
t.Errorf("params = %s", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A refused restart is recorded as failed", func(t *testing.T) {
|
||||
for _, example := range []struct {
|
||||
name string
|
||||
setup func(rig *restartRig)
|
||||
kind string
|
||||
reason string
|
||||
}{
|
||||
{"ErrNotPrepared", func(rig *restartRig) { rig.helper.installed = false }, "", "This server cannot apply updates."},
|
||||
{"ErrJobInProgress", func(rig *restartRig) {
|
||||
rig.jobs.put(update.Job{Tag: downloadTag, State: update.StateDownloading, StartedAt: restartBaseTime})
|
||||
}, "", "An update is still being downloaded."},
|
||||
{"ErrRestartPending", func(rig *restartRig) {
|
||||
_ = rig.requests.Write(update.RestartRequest{Kind: update.RestartKindRestart, RequestedAt: restartBaseTime})
|
||||
}, "", "A restart is already pending."},
|
||||
{"ErrRestartKindMismatch", func(*restartRig) {}, update.RestartKindUpdate, "The requested restart does not match the server state."},
|
||||
} {
|
||||
t.Run(example.name, func(t *testing.T) {
|
||||
rig, h, request := newRequest(t)
|
||||
example.setup(rig)
|
||||
|
||||
if _, err := request.Request(producerOwnerContext(), updateOwnerId, example.kind); err == nil {
|
||||
t.Fatal("expected a refusal")
|
||||
}
|
||||
|
||||
event := onlyEvent(t, h)
|
||||
assertProducerEvent(t, event, "system.restart_requested", audit.CategorySystem, audit.OutcomeFailed)
|
||||
assertProducerFailure(t, event, example.reason)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/api/pkg/apperr"
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var settingsTestZone = time.FixedZone("server", 2*60*60)
|
||||
|
||||
func settingsTestClock() time.Time {
|
||||
return time.Date(2026, time.October, 6, 10, 0, 0, 0, settingsTestZone)
|
||||
}
|
||||
|
||||
func TestSettingsNextCleanupDomain(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
days int
|
||||
now time.Time
|
||||
next string
|
||||
}{
|
||||
{"before 03:00 today", 90, time.Date(2026, 10, 6, 2, 59, 59, 0, settingsTestZone), "2026-10-06T03:00:00+02:00"},
|
||||
{"mid day", 90, time.Date(2026, 10, 6, 10, 0, 0, 0, settingsTestZone), "2026-10-07T03:00:00+02:00"},
|
||||
{"exactly 03:00 is strictly after", 90, time.Date(2026, 10, 6, 3, 0, 0, 0, settingsTestZone), "2026-10-07T03:00:00+02:00"},
|
||||
{"year end", 30, time.Date(2026, 12, 31, 23, 30, 0, 0, settingsTestZone), "2027-01-01T03:00:00+02:00"},
|
||||
{"365 days", 365, time.Date(2026, 10, 6, 10, 0, 0, 0, settingsTestZone), "2026-10-07T03:00:00+02:00"},
|
||||
{"forever", 0, time.Date(2026, 10, 6, 10, 0, 0, 0, settingsTestZone), ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
got := audit.Settings{RetentionDays: c.days}.WithNextCleanup(c.now).NextCleanupAt
|
||||
if c.next == "" {
|
||||
if got != nil {
|
||||
t.Fatalf("expected nil, got %v", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if got == nil || got.Format(time.RFC3339) != c.next {
|
||||
t.Fatalf("expected %s, got %v", c.next, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingsNextCleanupUseCases(t *testing.T) {
|
||||
t.Run("Get returns the next cleanup from the clock or nil for Forever", func(t *testing.T) {
|
||||
fake := newActivitySettingsFake()
|
||||
get := useCases.NewGetActivityRetentionUseCase(fake, settingsTestClock)
|
||||
|
||||
current, err := get.GetActivityRetention()
|
||||
if err != nil || current.NextCleanupAt == nil || current.NextCleanupAt.Format(time.RFC3339) != "2026-10-07T03:00:00+02:00" {
|
||||
t.Fatalf("unexpected %+v, %v", current, err)
|
||||
}
|
||||
|
||||
fake.settings.RetentionDays = 0
|
||||
current, err = get.GetActivityRetention()
|
||||
if err != nil || current.NextCleanupAt != nil {
|
||||
t.Fatalf("expected nil next cleanup, got %+v, %v", current, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Update returns the next cleanup of the new period", func(t *testing.T) {
|
||||
fake := newActivitySettingsFake()
|
||||
update := useCases.NewUpdateActivityRetentionUseCase(fake, discardRecorder, settingsTestClock)
|
||||
|
||||
forever, err := update.UpdateActivityRetention(testCtx, 0)
|
||||
if err != nil || forever.RetentionDays != 0 || forever.NextCleanupAt != nil {
|
||||
t.Fatalf("unexpected %+v, %v", forever, err)
|
||||
}
|
||||
back, err := update.UpdateActivityRetention(testCtx, 365)
|
||||
if err != nil || back.NextCleanupAt == nil || back.NextCleanupAt.Format(time.RFC3339) != "2026-10-07T03:00:00+02:00" {
|
||||
t.Fatalf("unexpected %+v, %v", back, err)
|
||||
}
|
||||
same, err := update.UpdateActivityRetention(testCtx, 365)
|
||||
if err != nil || same.NextCleanupAt == nil {
|
||||
t.Fatalf("unexpected %+v, %v", same, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Update refuses an invalid period and saves nothing", func(t *testing.T) {
|
||||
fake := newActivitySettingsFake()
|
||||
_, err := useCases.NewUpdateActivityRetentionUseCase(fake, discardRecorder, settingsTestClock).UpdateActivityRetention(testCtx, 7)
|
||||
if !errors.Is(err, audit.ErrInvalidRetention) || fake.retentionOK != 0 {
|
||||
t.Fatalf("expected a refusal, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestSettingsNextCleanupHttp(t *testing.T) {
|
||||
keys := func(t *testing.T, body string) map[string]any {
|
||||
t.Helper()
|
||||
var decoded map[string]any
|
||||
if err := json.Unmarshal([]byte(body), &decoded); err != nil {
|
||||
t.Fatalf("invalid json %q: %v", body, err)
|
||||
}
|
||||
return decoded
|
||||
}
|
||||
|
||||
t.Run("GET keeps the existing fields and adds exactly one", func(t *testing.T) {
|
||||
e := newActivityHTTPEnv(t, 1000)
|
||||
e.settings.settings.LastCleanupAt = activityPtr(time.Date(2026, time.October, 6, 1, 0, 0, 0, time.UTC))
|
||||
e.settings.settings.LastCleanupRemoved = 142
|
||||
|
||||
rec := e.get("/v1/settings", asUser(e, activityEditorID))
|
||||
|
||||
body := keys(t, rec.Body.String())
|
||||
if rec.Code != http.StatusOK || len(body) != 5 || body["activity_next_cleanup_at"] != "2026-10-07T03:00:00Z" || body["activity_last_cleanup_removed"] != float64(142) {
|
||||
t.Errorf("unexpected %d %v", rec.Code, body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("GET is null for Forever and open to an admin", func(t *testing.T) {
|
||||
e := newActivityHTTPEnv(t, 1000)
|
||||
e.settings.settings.RetentionDays = 0
|
||||
|
||||
rec := e.get("/v1/settings", asUser(e, activityAdminID))
|
||||
|
||||
body := keys(t, rec.Body.String())
|
||||
next, present := body["activity_next_cleanup_at"]
|
||||
if rec.Code != http.StatusOK || !present || next != nil {
|
||||
t.Errorf("unexpected %d %v", rec.Code, body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("PATCH returns the next cleanup of the new period", func(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
from, to int
|
||||
null bool
|
||||
}{{90, 30, false}, {90, 0, true}, {0, 365, false}, {90, 90, false}} {
|
||||
e := newActivityHTTPEnv(t, 1000)
|
||||
e.settings.settings.RetentionDays = c.from
|
||||
|
||||
rec := e.send(http.MethodPatch, "/v1/settings", `{"activity_retention_days": `+itoaSettings(c.to)+`}`, asUser(e, activityOwnerID))
|
||||
|
||||
body := keys(t, rec.Body.String())
|
||||
next, present := body["activity_next_cleanup_at"]
|
||||
if rec.Code != http.StatusOK || body["activity_retention_days"] != float64(c.to) || !present || (next == nil) != c.null {
|
||||
t.Errorf("%d to %d: unexpected %d %v", c.from, c.to, rec.Code, body)
|
||||
}
|
||||
if !c.null && next != "2026-10-07T03:00:00Z" {
|
||||
t.Errorf("%d to %d: unexpected next %v", c.from, c.to, next)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestSettingsNextCleanupQAFlow(t *testing.T) {
|
||||
t.Run("GET next cleanup follows the server clock in a +02:00 zone", func(t *testing.T) {
|
||||
cases := []struct {
|
||||
days int
|
||||
now time.Time
|
||||
next any
|
||||
}{
|
||||
{90, time.Date(2026, 10, 6, 10, 0, 0, 0, settingsTestZone), "2026-10-07T03:00:00+02:00"},
|
||||
{90, time.Date(2026, 10, 6, 2, 59, 59, 0, settingsTestZone), "2026-10-06T03:00:00+02:00"},
|
||||
{90, time.Date(2026, 10, 6, 3, 0, 0, 0, settingsTestZone), "2026-10-07T03:00:00+02:00"},
|
||||
{30, time.Date(2026, 12, 31, 23, 30, 0, 0, settingsTestZone), "2027-01-01T03:00:00+02:00"},
|
||||
{365, time.Date(2026, 10, 6, 10, 0, 0, 0, settingsTestZone), "2026-10-07T03:00:00+02:00"},
|
||||
{0, time.Date(2026, 10, 6, 10, 0, 0, 0, settingsTestZone), nil},
|
||||
}
|
||||
for _, c := range cases {
|
||||
e := newActivityHTTPEnv(t, 1000)
|
||||
e.now = c.now
|
||||
e.settings.settings.RetentionDays = c.days
|
||||
|
||||
rec := e.get("/v1/settings", asUser(e, activityOwnerID))
|
||||
|
||||
var body map[string]any
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &body)
|
||||
next, present := body["activity_next_cleanup_at"]
|
||||
if rec.Code != http.StatusOK || !present || next != c.next {
|
||||
t.Errorf("%d at %s: unexpected %d %v", c.days, c.now, rec.Code, body)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("GET is open to owner, admin and editor and refused without a cookie", func(t *testing.T) {
|
||||
e := newActivityHTTPEnv(t, 1000)
|
||||
for _, id := range []uint32{activityOwnerID, activityAdminID, activityEditorID} {
|
||||
if rec := e.get("/v1/settings", asUser(e, id)); rec.Code != http.StatusOK {
|
||||
t.Errorf("user %d: expected 200, got %d", id, rec.Code)
|
||||
}
|
||||
}
|
||||
if rec := e.get("/v1/settings"); rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("expected 401, got %d", rec.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("PATCH by an editor is refused and changes nothing", func(t *testing.T) {
|
||||
e := newActivityHTTPEnv(t, 1000)
|
||||
|
||||
rec := e.send(http.MethodPatch, "/v1/settings", `{"activity_retention_days": 30}`, asUser(e, activityEditorID))
|
||||
|
||||
assertPlain(t, rec, http.StatusForbidden, apperr.OwnerRequiredErrorMessage)
|
||||
if e.settings.retentionOK != 0 || len(e.all(t)) != 0 {
|
||||
t.Error("the editor changed something")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("PATCH with the saved value saves nothing and records nothing", func(t *testing.T) {
|
||||
e := newActivityHTTPEnv(t, 1000)
|
||||
|
||||
rec := e.send(http.MethodPatch, "/v1/settings", `{"activity_retention_days": 90}`, asUser(e, activityOwnerID))
|
||||
|
||||
if rec.Code != http.StatusOK || e.settings.retentionOK != 0 || len(e.all(t)) != 0 {
|
||||
t.Errorf("unexpected %d, saves %d, events %d", rec.Code, e.settings.retentionOK, len(e.all(t)))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A failing settings repository answers 500", func(t *testing.T) {
|
||||
e := newActivityHTTPEnv(t, 1000)
|
||||
e.settings.getErr = errors.New("database is down")
|
||||
|
||||
assertPlain(t, e.get("/v1/settings", asUser(e, activityOwnerID)), http.StatusInternalServerError, "Internal server error")
|
||||
assertPlain(t, e.send(http.MethodPatch, "/v1/settings", `{"activity_retention_days": 30}`, asUser(e, activityOwnerID)), http.StatusInternalServerError, "Internal server error")
|
||||
})
|
||||
|
||||
t.Run("The next cleanup stays at 03:00 local on a DST change day", func(t *testing.T) {
|
||||
paris, err := time.LoadLocation("Europe/Paris")
|
||||
if err != nil {
|
||||
t.Skip("tzdata unavailable")
|
||||
}
|
||||
for _, c := range []struct {
|
||||
now time.Time
|
||||
next string
|
||||
}{
|
||||
{time.Date(2026, 10, 24, 10, 0, 0, 0, paris), "2026-10-25T03:00:00+01:00"},
|
||||
{time.Date(2026, 10, 25, 1, 0, 0, 0, paris), "2026-10-25T03:00:00+01:00"},
|
||||
{time.Date(2026, 10, 25, 10, 0, 0, 0, paris), "2026-10-26T03:00:00+01:00"},
|
||||
{time.Date(2026, 3, 28, 10, 0, 0, 0, paris), "2026-03-29T03:00:00+02:00"},
|
||||
} {
|
||||
got := audit.Settings{RetentionDays: 90}.WithNextCleanup(c.now).NextCleanupAt
|
||||
if got == nil || got.Format(time.RFC3339) != c.next || got.Hour() != audit.CleanupHour {
|
||||
t.Errorf("from %s expected %s, got %v", c.now, c.next, got)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func itoaSettings(n int) string {
|
||||
switch n {
|
||||
case 0:
|
||||
return "0"
|
||||
case 30:
|
||||
return "30"
|
||||
case 90:
|
||||
return "90"
|
||||
}
|
||||
return "365"
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/infrastructure/persistence/database"
|
||||
persistence "RenewCMS/internal/infrastructure/persistence/repositories"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/glebarez/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
var activityDatabaseCounter atomic.Int64
|
||||
|
||||
func openActivityDatabase(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
name := fmt.Sprintf("file:activity%d?mode=memory&cache=shared", activityDatabaseCounter.Add(1))
|
||||
db, err := gorm.Open(sqlite.Open(name), &gorm.Config{Logger: logger.Discard})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to open the in-memory database: %v", err)
|
||||
}
|
||||
if err := database.Migrate(db); err != nil {
|
||||
t.Fatalf("failed to migrate: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if sqlDb, err := db.DB(); err == nil {
|
||||
_ = sqlDb.Close()
|
||||
}
|
||||
})
|
||||
return db
|
||||
}
|
||||
|
||||
func activityPtr[T any](value T) *T { return &value }
|
||||
|
||||
func activityUserEvent(userID uint32, name string, at time.Time) audit.Event {
|
||||
event := audit.NewEvent("article.publish", audit.CategoryArticles)
|
||||
event.CreatedAt = at
|
||||
event.Actor = audit.Actor{Type: audit.ActorUser, ID: activityPtr(userID), Name: name}
|
||||
event.Source = audit.SourceWeb
|
||||
return event
|
||||
}
|
||||
|
||||
func activityMustAppend(t *testing.T, repo audit.Repository, event audit.Event) audit.Event {
|
||||
t.Helper()
|
||||
stored, err := repo.Append(event)
|
||||
if err != nil {
|
||||
t.Fatalf("append failed: %v", err)
|
||||
}
|
||||
return stored
|
||||
}
|
||||
|
||||
func activityIDs(events []audit.Event) []uint64 {
|
||||
ids := make([]uint64, 0, len(events))
|
||||
for _, event := range events {
|
||||
ids = append(ids, event.ID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func activityDay(day int, hour int) time.Time {
|
||||
return time.Date(2026, time.October, day, hour, 0, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
func TestActivityPersistence(t *testing.T) {
|
||||
t.Run("The model is migrated with its indexes", func(t *testing.T) {
|
||||
db := openActivityDatabase(t)
|
||||
|
||||
if !db.Migrator().HasTable("audit_events") {
|
||||
t.Fatal("the audit events table does not exist")
|
||||
}
|
||||
var names []string
|
||||
if err := db.Raw("SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'audit_events'").Scan(&names).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
found := map[string]bool{}
|
||||
for _, name := range names {
|
||||
var columns []struct {
|
||||
Name string
|
||||
}
|
||||
if err := db.Raw("SELECT name FROM pragma_index_info(?) ORDER BY seqno", name).Scan(&columns).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parts := make([]string, 0, len(columns))
|
||||
for _, column := range columns {
|
||||
parts = append(parts, column.Name)
|
||||
}
|
||||
found[strings.Join(parts, ",")] = true
|
||||
}
|
||||
for _, wanted := range []string{"created_at", "actor_type,actor_id,created_at", "category,created_at"} {
|
||||
if !found[wanted] {
|
||||
t.Errorf("missing index on (%s), have %v", wanted, found)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The persistence implementation exposes no other exported method than the contract", func(t *testing.T) {
|
||||
repoType := reflect.TypeOf(persistence.NewAuditEventRepository(nil))
|
||||
var names []string
|
||||
for i := 0; i < repoType.NumMethod(); i++ {
|
||||
names = append(names, repoType.Method(i).Name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
wanted := []string{"Append", "DeleteOlderThan", "List", "Summary"}
|
||||
if !reflect.DeepEqual(names, wanted) {
|
||||
t.Errorf("expected %v, got %v", wanted, names)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("An appended event round-trips", func(t *testing.T) {
|
||||
repo := persistence.NewAuditEventRepository(openActivityDatabase(t))
|
||||
event := audit.NewEvent("media.purge", audit.CategoryMedia)
|
||||
event.CreatedAt = time.Date(2026, time.October, 6, 10, 42, 18, 0, time.UTC)
|
||||
event.Actor = audit.Actor{Type: audit.ActorUser, ID: activityPtr(uint32(3)), Name: "Marta Alves"}
|
||||
event.Target = audit.Target{Type: "article", ID: "8", Name: "Spring release"}
|
||||
event.Source = audit.SourceWeb
|
||||
event.IP = activityPtr("203.0.113.12")
|
||||
event.UserAgent = activityPtr("Chrome 129 on Windows")
|
||||
event.Security = true
|
||||
event.Params = map[string]any{"merged": 3}
|
||||
event.Changes = []audit.Change{
|
||||
{Field: "online", Kind: audit.ChangeText, Before: activityPtr("false"), After: activityPtr("true")},
|
||||
{Field: "body", Kind: audit.ChangeBody, Delta: activityPtr(312)},
|
||||
}
|
||||
|
||||
stored := activityMustAppend(t, repo, event)
|
||||
page, err := repo.List(audit.Filter{Page: 1, Size: 25})
|
||||
|
||||
if err != nil || page.Total != 1 || len(page.Items) != 1 {
|
||||
t.Fatalf("unexpected list: %+v, %v", page, err)
|
||||
}
|
||||
event.ID = stored.ID
|
||||
want, _ := json.Marshal(event)
|
||||
got, _ := json.Marshal(page.Items[0])
|
||||
if string(want) != string(got) {
|
||||
t.Errorf("round trip mismatch\nwant %s\ngot %s", want, got)
|
||||
}
|
||||
if page.Items[0].FailureReason != nil {
|
||||
t.Errorf("failure_reason must stay null, got %v", *page.Items[0].FailureReason)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A system event keeps its null actor id, ip and user agent", func(t *testing.T) {
|
||||
repo := persistence.NewAuditEventRepository(openActivityDatabase(t))
|
||||
event := audit.NewEvent(audit.ActionCleanup, audit.CategorySystem)
|
||||
event.CreatedAt = activityDay(6, 3)
|
||||
event.Actor = audit.SystemActor()
|
||||
event.Source = audit.SourceSystem
|
||||
|
||||
activityMustAppend(t, repo, event)
|
||||
page, _ := repo.List(audit.Filter{Page: 1, Size: 25})
|
||||
|
||||
item := page.Items[0]
|
||||
if item.Actor.ID != nil || item.IP != nil || item.UserAgent != nil || item.Actor.Name != "System" {
|
||||
t.Errorf("unexpected system event %+v", item)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("List sorts by created_at descending then id descending", func(t *testing.T) {
|
||||
repo := persistence.NewAuditEventRepository(openActivityDatabase(t))
|
||||
older := activityMustAppend(t, repo, activityUserEvent(1, "a", activityDay(1, 9)))
|
||||
var same []uint64
|
||||
for i := 0; i < 3; i++ {
|
||||
same = append(same, activityMustAppend(t, repo, activityUserEvent(1, "a", activityDay(2, 9))).ID)
|
||||
}
|
||||
|
||||
page, err := repo.List(audit.Filter{Page: 1, Size: 25})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []uint64{same[2], same[1], same[0], older.ID}
|
||||
if !reflect.DeepEqual(activityIDs(page.Items), want) {
|
||||
t.Errorf("expected %v, got %v", want, activityIDs(page.Items))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Filters narrow the list and the total", func(t *testing.T) {
|
||||
repo := persistence.NewAuditEventRepository(openActivityDatabase(t))
|
||||
add := func(mutate func(*audit.Event)) uint64 {
|
||||
event := activityUserEvent(1, "Someone", activityDay(2, 9))
|
||||
mutate(&event)
|
||||
return activityMustAppend(t, repo, event).ID
|
||||
}
|
||||
user3 := add(func(e *audit.Event) {
|
||||
e.Actor = audit.Actor{Type: audit.ActorUser, ID: activityPtr(uint32(3)), Name: "Marta"}
|
||||
})
|
||||
user3Id7 := add(func(e *audit.Event) {
|
||||
e.Actor = audit.Actor{Type: audit.ActorUser, ID: activityPtr(uint32(7)), Name: "Seven"}
|
||||
})
|
||||
key7 := add(func(e *audit.Event) {
|
||||
e.Actor = audit.Actor{Type: audit.ActorAPIKey, ID: activityPtr(uint32(7)), Name: "Deploy bot"}
|
||||
e.Source = audit.SourceAPIKey
|
||||
})
|
||||
system := add(func(e *audit.Event) {
|
||||
e.Actor = audit.SystemActor()
|
||||
e.Source = audit.SourceSystem
|
||||
e.Category = audit.CategorySystem
|
||||
})
|
||||
authFailed := add(func(e *audit.Event) {
|
||||
e.Actor = audit.AnonymousActor("mallory")
|
||||
e.Category = audit.CategoryAuth
|
||||
e.Outcome = audit.OutcomeFailed
|
||||
e.Security = true
|
||||
})
|
||||
spring := add(func(e *audit.Event) { e.Target = audit.Target{Type: "article", ID: "8", Name: "Spring release"} })
|
||||
percent := add(func(e *audit.Event) { e.Target = audit.Target{Type: "article", ID: "9", Name: "Sale 50%_ off"} })
|
||||
plain := add(func(e *audit.Event) { e.Target = audit.Target{Type: "article", ID: "10", Name: "Sale 505 off"} })
|
||||
oct1 := add(func(e *audit.Event) { e.CreatedAt = time.Date(2026, time.October, 1, 0, 0, 0, 0, time.UTC) })
|
||||
oct3end := add(func(e *audit.Event) { e.CreatedAt = time.Date(2026, time.October, 3, 23, 59, 59, 0, time.UTC) })
|
||||
oct4 := add(func(e *audit.Event) { e.CreatedAt = time.Date(2026, time.October, 4, 0, 0, 0, 0, time.UTC) })
|
||||
sep30 := add(func(e *audit.Event) { e.CreatedAt = time.Date(2026, time.September, 30, 23, 59, 59, 0, time.UTC) })
|
||||
base := add(func(e *audit.Event) {})
|
||||
|
||||
everyone := []uint64{user3, user3Id7, key7, system, authFailed, spring, percent, plain, oct1, oct3end, oct4, sep30, base}
|
||||
sort.Slice(everyone, func(i, j int) bool { return everyone[i] < everyone[j] })
|
||||
from := time.Date(2026, time.October, 1, 0, 0, 0, 0, time.UTC)
|
||||
to := time.Date(2026, time.October, 4, 0, 0, 0, 0, time.UTC)
|
||||
cases := []struct {
|
||||
name string
|
||||
filter audit.Filter
|
||||
want []uint64
|
||||
}{
|
||||
{"actor user:3", audit.Filter{Actor: &audit.ActorRef{Type: audit.ActorUser, ID: activityPtr(uint32(3))}}, []uint64{user3}},
|
||||
{"actor key:7", audit.Filter{Actor: &audit.ActorRef{Type: audit.ActorAPIKey, ID: activityPtr(uint32(7))}}, []uint64{key7}},
|
||||
{"actor system", audit.Filter{Actor: &audit.ActorRef{Type: audit.ActorSystem}}, []uint64{system}},
|
||||
{"category auth", audit.Filter{Category: audit.CategoryAuth}, []uint64{authFailed}},
|
||||
{"outcome failed", audit.Filter{Outcome: audit.OutcomeFailed}, []uint64{authFailed}},
|
||||
{"outcome success", audit.Filter{Outcome: audit.OutcomeSuccess}, withoutIDs(everyone, authFailed)},
|
||||
{"security true", audit.Filter{Security: true}, []uint64{authFailed}},
|
||||
{"q SPRING", audit.Filter{Query: "SPRING"}, []uint64{spring}},
|
||||
{"q actor name", audit.Filter{Query: "marta"}, []uint64{user3}},
|
||||
{"q 50%_", audit.Filter{Query: "50%_"}, []uint64{percent}},
|
||||
{"date range", audit.Filter{From: &from, To: &to}, []uint64{user3, user3Id7, key7, system, authFailed, spring, percent, plain, oct1, oct3end, base}},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
filter := c.filter
|
||||
filter.Page, filter.Size = 1, 100
|
||||
page, err := repo.List(filter)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := activityIDs(page.Items)
|
||||
sort.Slice(got, func(i, j int) bool { return got[i] < got[j] })
|
||||
want := append([]uint64(nil), c.want...)
|
||||
sort.Slice(want, func(i, j int) bool { return want[i] < want[j] })
|
||||
if !reflect.DeepEqual(got, want) || page.Total != len(want) {
|
||||
t.Errorf("expected %v (total %d), got %v (total %d)", want, len(want), got, page.Total)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Paging slices the sorted list and total is the unpaged count", func(t *testing.T) {
|
||||
repo := persistence.NewAuditEventRepository(openActivityDatabase(t))
|
||||
var ids []uint64
|
||||
for i := 0; i < 60; i++ {
|
||||
ids = append(ids, activityMustAppend(t, repo, activityUserEvent(1, "a", activityDay(2, 9).Add(time.Duration(i)*time.Minute))).ID)
|
||||
}
|
||||
|
||||
page, err := repo.List(audit.Filter{Page: 2, Size: 25})
|
||||
|
||||
if err != nil || len(page.Items) != 25 || page.Total != 60 {
|
||||
t.Fatalf("unexpected page: %d items, total %d, %v", len(page.Items), page.Total, err)
|
||||
}
|
||||
if page.Items[0].ID != ids[34] || page.Items[24].ID != ids[10] {
|
||||
t.Errorf("expected the 26th to 50th of the sorted list, got %d..%d", page.Items[0].ID, page.Items[24].ID)
|
||||
}
|
||||
past, _ := repo.List(audit.Filter{Page: 9, Size: 25})
|
||||
if len(past.Items) != 0 || past.Total != 60 {
|
||||
t.Errorf("expected an empty page with total 60, got %d items, total %d", len(past.Items), past.Total)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The summary counts the range and the previous period", func(t *testing.T) {
|
||||
repo := persistence.NewAuditEventRepository(openActivityDatabase(t))
|
||||
now := activityDay(8, 12)
|
||||
at := func(daysAgo int, extra time.Duration) time.Time {
|
||||
return now.Add(-time.Duration(daysAgo)*24*time.Hour + extra)
|
||||
}
|
||||
add := func(when time.Time, mutate func(*audit.Event)) {
|
||||
event := activityUserEvent(1, "one", when)
|
||||
mutate(&event)
|
||||
activityMustAppend(t, repo, event)
|
||||
}
|
||||
none := func(*audit.Event) {}
|
||||
add(at(0, -time.Hour), none)
|
||||
add(at(0, -2*time.Hour), func(e *audit.Event) { e.Outcome = audit.OutcomeFailed })
|
||||
add(at(1, -time.Hour), func(e *audit.Event) {
|
||||
e.Actor = audit.Actor{Type: audit.ActorUser, ID: activityPtr(uint32(2)), Name: "two"}
|
||||
e.Security = true
|
||||
})
|
||||
add(at(3, -time.Hour), func(e *audit.Event) {
|
||||
e.Actor = audit.Actor{Type: audit.ActorAPIKey, ID: activityPtr(uint32(9)), Name: "bot"}
|
||||
})
|
||||
add(at(6, -time.Hour), func(e *audit.Event) {
|
||||
e.Actor = audit.AnonymousActor("x")
|
||||
e.Outcome = audit.OutcomeFailed
|
||||
e.Security = true
|
||||
})
|
||||
add(at(6, -2*time.Hour), func(e *audit.Event) { e.Actor = audit.SystemActor() })
|
||||
for i := 0; i < 4; i++ {
|
||||
add(at(8+i, 0), none)
|
||||
}
|
||||
|
||||
summary, err := repo.Summary(audit.SummaryQuery{From: now.Add(-7 * 24 * time.Hour), To: now})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if summary.Total != 6 || summary.PreviousTotal != 4 || summary.Failed != 2 || summary.Security != 2 {
|
||||
t.Errorf("unexpected counts %+v", summary)
|
||||
}
|
||||
if summary.ActivePeople.Users != 2 || summary.ActivePeople.APIKeys != 1 {
|
||||
t.Errorf("unexpected active people %+v", summary.ActivePeople)
|
||||
}
|
||||
wantTotal := []int{2, 0, 0, 1, 0, 1, 2}
|
||||
if !reflect.DeepEqual(summary.Series.Total, wantTotal) {
|
||||
t.Errorf("expected total series %v, got %v", wantTotal, summary.Series.Total)
|
||||
}
|
||||
if !reflect.DeepEqual(summary.Series.Failed, []int{1, 0, 0, 0, 0, 0, 1}) || !reflect.DeepEqual(summary.Series.Security, []int{1, 0, 0, 0, 0, 1, 0}) {
|
||||
t.Errorf("unexpected failed %v or security %v series", summary.Series.Failed, summary.Series.Security)
|
||||
}
|
||||
if !reflect.DeepEqual(summary.Series.Active, []int{0, 0, 0, 1, 0, 1, 1}) {
|
||||
t.Errorf("unexpected active series %v", summary.Series.Active)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("DeleteOlderThan removes only events before the cutoff", func(t *testing.T) {
|
||||
repo := persistence.NewAuditEventRepository(openActivityDatabase(t))
|
||||
now := activityDay(20, 12)
|
||||
for _, days := range []int{100, 40, 31, 29, 1} {
|
||||
activityMustAppend(t, repo, activityUserEvent(1, "a", now.Add(-time.Duration(days)*24*time.Hour)))
|
||||
}
|
||||
|
||||
removed, err := repo.DeleteOlderThan(now.Add(-30 * 24 * time.Hour))
|
||||
|
||||
if err != nil || removed != 3 {
|
||||
t.Fatalf("expected 3 removed, got %d, %v", removed, err)
|
||||
}
|
||||
page, _ := repo.List(audit.Filter{Page: 1, Size: 25})
|
||||
if page.Total != 2 {
|
||||
t.Errorf("expected 2 events left, got %d", page.Total)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestActivitySettingsPersistence(t *testing.T) {
|
||||
t.Run("No row means the default", func(t *testing.T) {
|
||||
repo := persistence.NewAuditSettingsRepository(openActivityDatabase(t))
|
||||
|
||||
settings, err := repo.Get()
|
||||
|
||||
if err != nil || settings.RetentionDays != 90 || settings.LastCleanupAt != nil || settings.LastCleanupRemoved != 0 {
|
||||
t.Errorf("unexpected default %+v, %v", settings, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The retention and the last cleanup are stored independently", func(t *testing.T) {
|
||||
repo := persistence.NewAuditSettingsRepository(openActivityDatabase(t))
|
||||
at := time.Date(2026, time.October, 6, 3, 0, 0, 0, time.UTC)
|
||||
|
||||
if err := repo.SaveLastCleanup(at, 142); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
settings, _ := repo.Get()
|
||||
if settings.RetentionDays != 90 || settings.LastCleanupAt == nil || !settings.LastCleanupAt.Equal(at) || settings.LastCleanupRemoved != 142 {
|
||||
t.Fatalf("unexpected settings %+v", settings)
|
||||
}
|
||||
if err := repo.SaveRetention(0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
settings, _ = repo.Get()
|
||||
if settings.RetentionDays != 0 || settings.LastCleanupRemoved != 142 {
|
||||
t.Errorf("forever must be stored as 0 and keep the last cleanup, got %+v", settings)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func withoutIDs(ids []uint64, excluded ...uint64) []uint64 {
|
||||
var kept []uint64
|
||||
for _, id := range ids {
|
||||
skip := false
|
||||
for _, other := range excluded {
|
||||
skip = skip || id == other
|
||||
}
|
||||
if !skip {
|
||||
kept = append(kept, id)
|
||||
}
|
||||
}
|
||||
return kept
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestActivityRecentPageSize(t *testing.T) {
|
||||
const homeCardQuery = "/v1/activity?size=5"
|
||||
|
||||
t.Run("The query the Home card sends returns the first five rows", func(t *testing.T) {
|
||||
e := newActivityHTTPEnv(t, 1000)
|
||||
var newest []uint64
|
||||
for minute := 1; minute <= 8; minute++ {
|
||||
event := e.seedBy(t, userActor(activityOwnerID, "Marta Alves"), time.Duration(minute)*time.Minute)
|
||||
if minute <= 5 {
|
||||
newest = append(newest, event.ID)
|
||||
}
|
||||
}
|
||||
|
||||
list := decodeActivityList(t, e.get(homeCardQuery, asUser(e, activityOwnerID)))
|
||||
|
||||
if list.Size != 5 || list.Page != 1 || list.Total != 8 || len(list.Items) != 5 {
|
||||
t.Fatalf("unexpected page %d/%d total %d with %d items", list.Page, list.Size, list.Total, len(list.Items))
|
||||
}
|
||||
if !sameIDs(list.ids(), newest) {
|
||||
t.Errorf("expected %v, got %v", newest, list.ids())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A non-owner at size 5 only gets their own events", func(t *testing.T) {
|
||||
e := newActivityHTTPEnv(t, 1000)
|
||||
var own []uint64
|
||||
for minute := 1; minute <= 7; minute++ {
|
||||
event := e.seedBy(t, userActor(activityEditorID, "ed"), time.Duration(minute)*time.Minute)
|
||||
if minute <= 5 {
|
||||
own = append(own, event.ID)
|
||||
}
|
||||
}
|
||||
for minute := 1; minute <= 3; minute++ {
|
||||
e.seedBy(t, userActor(activityOwnerID, "Marta Alves"), time.Duration(minute)*time.Second)
|
||||
}
|
||||
|
||||
list := decodeActivityList(t, e.get(homeCardQuery, asUser(e, activityEditorID)))
|
||||
|
||||
if list.Size != 5 || list.Total != 7 || !sameIDs(list.ids(), own) {
|
||||
t.Errorf("expected own %v of 7, got %v of %d (size %d)", own, list.ids(), list.Total, list.Size)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Sizes other than 5, 25, 50 and 100 stay refused", func(t *testing.T) {
|
||||
for _, size := range []string{"4", "6", "10", "200"} {
|
||||
e := newActivityHTTPEnv(t, 1000)
|
||||
assertPlain(t, e.get("/v1/activity?size="+size, asUser(e, activityOwnerID)), 400, activityMismatch)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestActivityRecorder(t *testing.T) {
|
||||
t.Run("A failing repository does not fail the caller and the failure is logged", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
h.probe.appendErr = errDiskFull
|
||||
|
||||
h.recorder.Record(testCtx, activityValidEvent())
|
||||
|
||||
logs := h.logs.String()
|
||||
if !strings.Contains(logs, "audit.test") || !strings.Contains(logs, "disk full") {
|
||||
t.Errorf("expected a log line naming the write and the error, got %q", logs)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A panicking repository does not crash the caller", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
h.probe.appendPanic = true
|
||||
|
||||
h.recorder.Record(testCtx, activityValidEvent())
|
||||
|
||||
if !strings.Contains(h.logs.String(), "panicked") {
|
||||
t.Errorf("expected the panic to be logged, got %q", h.logs.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The recorder fills the event from the audit context", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
h.now = time.Date(2026, time.October, 6, 14, 0, 0, 0, time.FixedZone("CEST", 2*3600))
|
||||
ctx := audit.WithOrigin(testCtx, audit.Origin{
|
||||
Actor: audit.Actor{Type: audit.ActorUser, ID: activityPtr(uint32(3)), Name: "marta"},
|
||||
Source: audit.SourceWeb,
|
||||
IP: "203.0.113.12",
|
||||
UserAgent: "Mozilla/5.0 test",
|
||||
})
|
||||
event := audit.NewEvent("audit.test", audit.CategorySystem)
|
||||
|
||||
h.recorder.Record(ctx, event)
|
||||
|
||||
stored := h.all(t)
|
||||
if len(stored) != 1 {
|
||||
t.Fatalf("expected one event, got %d", len(stored))
|
||||
}
|
||||
got := stored[0]
|
||||
if got.Actor.Type != audit.ActorUser || *got.Actor.ID != 3 || got.Actor.Name != "marta" || got.Source != audit.SourceWeb {
|
||||
t.Errorf("unexpected actor or source %+v", got)
|
||||
}
|
||||
if got.IP == nil || *got.IP != "203.0.113.12" || got.UserAgent == nil || *got.UserAgent != "Mozilla/5.0 test" {
|
||||
t.Errorf("unexpected ip or user agent %v %v", got.IP, got.UserAgent)
|
||||
}
|
||||
if !got.CreatedAt.Equal(h.now) || got.CreatedAt.Location() != time.UTC {
|
||||
t.Errorf("expected created_at %v in UTC, got %v", h.now.UTC(), got.CreatedAt)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Values already on the event are kept", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
ctx := audit.WithOrigin(testCtx, audit.Origin{Actor: audit.AnonymousActor("x"), Source: audit.SourceWeb, IP: "203.0.113.12", UserAgent: "ua"})
|
||||
event := audit.NewEvent(audit.ActionCleanup, audit.CategorySystem)
|
||||
event.Actor = audit.SystemActor()
|
||||
event.Source = audit.SourceSystem
|
||||
|
||||
h.recorder.Record(ctx, event)
|
||||
|
||||
got := h.all(t)[0]
|
||||
if got.Actor.Type != audit.ActorSystem || got.Source != audit.SourceSystem {
|
||||
t.Errorf("the explicit actor and source must win, got %+v", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("An event outside the vocabulary is dropped and logged", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
event := activityValidEvent()
|
||||
event.Category = "billing"
|
||||
|
||||
h.recorder.Record(testCtx, event)
|
||||
|
||||
if len(h.all(t)) != 0 || !strings.Contains(h.logs.String(), "dropped") {
|
||||
t.Errorf("expected nothing stored and a log line, got %q", h.logs.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Long names are bounded", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
event := activityValidEvent()
|
||||
event.Target = audit.Target{Type: "article", ID: "1", Name: strings.Repeat("é", 400)}
|
||||
|
||||
h.recorder.Record(testCtx, event)
|
||||
|
||||
if got := h.all(t); len(got) != 1 || len([]rune(got[0].Target.Name)) != 255 {
|
||||
t.Errorf("expected one event with a 255 character target name, got %+v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func activityValidEvent() audit.Event {
|
||||
event := audit.NewEvent("audit.test", audit.CategorySystem)
|
||||
event.Actor = audit.SystemActor()
|
||||
event.Source = audit.SourceSystem
|
||||
return event
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/infrastructure/scheduler"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestActivityRetentionUseCases(t *testing.T) {
|
||||
ownerCtx := activityOwnerCtx
|
||||
|
||||
t.Run("The default is 90 days with no cleanup yet", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
|
||||
settings, err := useCases.NewGetActivityRetentionUseCase(h.settings, h.clock).GetActivityRetention()
|
||||
|
||||
if err != nil || settings.RetentionDays != 90 || settings.LastCleanupAt != nil || settings.LastCleanupRemoved != 0 {
|
||||
t.Errorf("unexpected default %+v, %v", settings, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The owner sets a valid period", func(t *testing.T) {
|
||||
for _, days := range []int{30, 90, 365, 0} {
|
||||
h := newActivityHarness(t)
|
||||
|
||||
settings, err := useCases.NewUpdateActivityRetentionUseCase(h.settings, h.recorder, h.clock).UpdateActivityRetention(ownerCtx(), days)
|
||||
|
||||
if err != nil || settings.RetentionDays != days || h.settings.settings.RetentionDays != days {
|
||||
t.Errorf("%d: unexpected result %+v, %v", days, settings, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Any other value is refused and changes nothing", func(t *testing.T) {
|
||||
for _, days := range []int{7, -1, 366} {
|
||||
h := newActivityHarness(t)
|
||||
|
||||
_, err := useCases.NewUpdateActivityRetentionUseCase(h.settings, h.recorder, h.clock).UpdateActivityRetention(ownerCtx(), days)
|
||||
|
||||
if !errors.Is(err, audit.ErrInvalidRetention) || h.settings.settings.RetentionDays != 90 || len(h.all(t)) != 0 {
|
||||
t.Errorf("%d: expected a refusal, got %v", days, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A change is recorded as a system event by the owner", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
|
||||
_, err := useCases.NewUpdateActivityRetentionUseCase(h.settings, h.recorder, h.clock).UpdateActivityRetention(ownerCtx(), 30)
|
||||
|
||||
events := h.all(t)
|
||||
if err != nil || len(events) != 1 {
|
||||
t.Fatalf("expected one event, got %d, %v", len(events), err)
|
||||
}
|
||||
event := events[0]
|
||||
if event.Action != "system.activity_retention_changed" || event.Category != audit.CategorySystem || event.Actor.Name != "owner" || event.Source != audit.SourceWeb || event.Outcome != audit.OutcomeSuccess || event.Security {
|
||||
t.Errorf("unexpected event %+v", event)
|
||||
}
|
||||
if event.Params["from"] != float64(90) || event.Params["to"] != float64(30) {
|
||||
t.Errorf("unexpected params %v", event.Params)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Setting the same value records nothing", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
|
||||
settings, err := useCases.NewUpdateActivityRetentionUseCase(h.settings, h.recorder, h.clock).UpdateActivityRetention(ownerCtx(), 90)
|
||||
|
||||
if err != nil || settings.RetentionDays != 90 || len(h.all(t)) != 0 || h.settings.retentionOK != 0 {
|
||||
t.Errorf("expected no event and no write, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A failing save is returned and records nothing", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
h.settings.saveErr = errRepositoryFailure
|
||||
|
||||
_, err := useCases.NewUpdateActivityRetentionUseCase(h.settings, h.recorder, h.clock).UpdateActivityRetention(ownerCtx(), 30)
|
||||
|
||||
if !errors.Is(err, errRepositoryFailure) || len(h.all(t)) != 0 {
|
||||
t.Errorf("expected the failure and no event, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func cleanupAt(day int, hour int, minute int) time.Time {
|
||||
return time.Date(2026, time.October, day, hour, minute, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
func activityOwnerCtx() context.Context {
|
||||
return audit.WithOrigin(testCtx, audit.Origin{
|
||||
Actor: audit.Actor{Type: audit.ActorUser, ID: activityPtr(uint32(1)), Name: "owner"},
|
||||
Source: audit.SourceWeb,
|
||||
})
|
||||
}
|
||||
|
||||
func newCleanup(h *activityHarness) *useCases.CleanupActivityUseCase {
|
||||
return useCases.NewCleanupActivityUseCase(h.probe, h.settings, h.recorder)
|
||||
}
|
||||
|
||||
func TestActivityCleanupUseCase(t *testing.T) {
|
||||
t.Run("The cleanup is due once a day at or after 03:00", func(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
last *time.Time
|
||||
now time.Time
|
||||
ran bool
|
||||
}{
|
||||
{"never at 02:59", nil, cleanupAt(6, 2, 59), false},
|
||||
{"never at 03:00", nil, cleanupAt(6, 3, 0), true},
|
||||
{"never at 14:00", nil, cleanupAt(6, 14, 0), true},
|
||||
{"yesterday at 02:59", ptrTime(cleanupAt(5, 3, 0)), cleanupAt(6, 2, 59), false},
|
||||
{"yesterday at 03:00", ptrTime(cleanupAt(5, 3, 0)), cleanupAt(6, 3, 0), true},
|
||||
{"today at 04:00", ptrTime(cleanupAt(6, 3, 0)), cleanupAt(6, 4, 0), false},
|
||||
{"tomorrow at 03:00", ptrTime(cleanupAt(6, 3, 0)), cleanupAt(7, 3, 0), true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
h.settings.settings.LastCleanupAt = c.last
|
||||
h.now = c.now
|
||||
|
||||
_, ran, err := newCleanup(h).Tick(c.now)
|
||||
|
||||
if err != nil || ran != c.ran {
|
||||
t.Errorf("expected ran=%v, got %v, %v", c.ran, ran, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Forever never runs", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
h.settings.settings.RetentionDays = 0
|
||||
|
||||
_, ran, err := newCleanup(h).Tick(cleanupAt(6, 3, 0))
|
||||
|
||||
if err != nil || ran || h.probe.deleteCalls != 0 {
|
||||
t.Errorf("expected nothing to run, got ran=%v, %v, %d deletes", ran, err, h.probe.deleteCalls)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The cutoff is now minus the retention days", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
h.settings.settings.RetentionDays = 30
|
||||
now := cleanupAt(6, 3, 0)
|
||||
h.now = now
|
||||
var kept []uint64
|
||||
for _, days := range []int{40, 31, 29, 1} {
|
||||
id := h.seed(t, activityUserEvent(1, "a", now.Add(-time.Duration(days)*24*time.Hour))).ID
|
||||
if days < 30 {
|
||||
kept = append(kept, id)
|
||||
}
|
||||
}
|
||||
|
||||
result, ran, err := newCleanup(h).Tick(now)
|
||||
|
||||
if err != nil || !ran || result.Removed != 2 {
|
||||
t.Fatalf("expected 2 removed, got %+v ran=%v %v", result, ran, err)
|
||||
}
|
||||
remaining := map[uint64]bool{}
|
||||
for _, event := range h.all(t) {
|
||||
remaining[event.ID] = true
|
||||
}
|
||||
for _, id := range kept {
|
||||
if !remaining[id] {
|
||||
t.Errorf("event %d should remain", id)
|
||||
}
|
||||
}
|
||||
last := h.settings.settings
|
||||
if last.LastCleanupAt == nil || !last.LastCleanupAt.Equal(now) || last.LastCleanupRemoved != 2 {
|
||||
t.Errorf("unexpected last cleanup %+v", last)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A cleanup that removes nothing still records the run and no event", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
now := cleanupAt(6, 3, 0)
|
||||
h.now = now
|
||||
h.seed(t, activityUserEvent(1, "a", now.Add(-24*time.Hour)))
|
||||
|
||||
result, ran, err := newCleanup(h).Tick(now)
|
||||
|
||||
if err != nil || !ran || result.Removed != 0 {
|
||||
t.Fatalf("unexpected result %+v ran=%v %v", result, ran, err)
|
||||
}
|
||||
if h.settings.cleanupOK != 1 || h.settings.settings.LastCleanupAt == nil || !h.settings.settings.LastCleanupAt.Equal(now) || len(h.all(t)) != 1 {
|
||||
t.Errorf("expected the run recorded without event, got %+v with %d events", h.settings.settings, len(h.all(t)))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A cleanup that removes events records a system event after deleting", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
now := cleanupAt(6, 3, 0)
|
||||
h.now = now
|
||||
for i := 0; i < 142; i++ {
|
||||
h.seed(t, activityUserEvent(1, "a", now.Add(-100*24*time.Hour)))
|
||||
}
|
||||
|
||||
result, _, err := newCleanup(h).Tick(now)
|
||||
|
||||
events := h.all(t)
|
||||
if err != nil || result.Removed != 142 || len(events) != 1 {
|
||||
t.Fatalf("expected 142 removed and one event, got %+v, %d events, %v", result, len(events), err)
|
||||
}
|
||||
event := events[0]
|
||||
if event.Action != "system.activity_cleanup" || event.Category != audit.CategorySystem || event.Actor.Type != audit.ActorSystem || event.Source != audit.SourceSystem || event.IP != nil || event.UserAgent != nil || event.Outcome != audit.OutcomeSuccess {
|
||||
t.Errorf("unexpected event %+v", event)
|
||||
}
|
||||
if event.Params["removed"] != float64(142) {
|
||||
t.Errorf("unexpected params %v", event.Params)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A failing delete is retried at the next tick", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
now := cleanupAt(6, 3, 0)
|
||||
h.now = now
|
||||
h.probe.deleteErr = errRepositoryFailure
|
||||
cleanup := newCleanup(h)
|
||||
|
||||
_, ran, err := cleanup.Tick(now)
|
||||
|
||||
if !errors.Is(err, errRepositoryFailure) || ran || h.settings.settings.LastCleanupAt != nil {
|
||||
t.Fatalf("expected the failure without a recorded run, got ran=%v %v", ran, err)
|
||||
}
|
||||
h.probe.deleteErr = nil
|
||||
_, ran, err = cleanup.Tick(now.Add(time.Hour))
|
||||
if err != nil || !ran {
|
||||
t.Errorf("expected the next tick to run, got ran=%v %v", ran, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A failing save of the run is returned", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
h.settings.saveErr = errRepositoryFailure
|
||||
|
||||
_, ran, err := newCleanup(h).Tick(cleanupAt(6, 3, 0))
|
||||
|
||||
if !errors.Is(err, errRepositoryFailure) || ran {
|
||||
t.Errorf("expected the failure, got ran=%v %v", ran, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A shortened period applies at the next cleanup, not at the change", func(t *testing.T) {
|
||||
h := newActivityHarness(t)
|
||||
now := cleanupAt(6, 3, 0)
|
||||
h.now = now
|
||||
h.seed(t, activityUserEvent(1, "a", now.Add(-40*24*time.Hour)))
|
||||
|
||||
_, err := useCases.NewUpdateActivityRetentionUseCase(h.settings, h.recorder, h.clock).UpdateActivityRetention(activityOwnerCtx(), 30)
|
||||
if err != nil || len(h.all(t)) != 2 {
|
||||
t.Fatalf("the change itself must remove nothing, got %d events, %v", len(h.all(t)), err)
|
||||
}
|
||||
|
||||
result, _, _ := newCleanup(h).Tick(now)
|
||||
|
||||
if result.Removed != 1 {
|
||||
t.Errorf("expected the old event removed at the next cleanup, got %+v", result)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type cleanupJobFake struct {
|
||||
calls chan time.Time
|
||||
removed int
|
||||
err error
|
||||
}
|
||||
|
||||
func (c *cleanupJobFake) Tick(now time.Time) (audit.CleanupResult, bool, error) {
|
||||
c.calls <- now
|
||||
return audit.CleanupResult{Removed: c.removed}, c.err == nil, c.err
|
||||
}
|
||||
|
||||
func TestActivityCleanupScheduler(t *testing.T) {
|
||||
start := func(job *cleanupJobFake) (chan time.Time, chan time.Time, *strings.Builder, context.CancelFunc, chan struct{}) {
|
||||
ticks := make(chan time.Time, 4)
|
||||
startup := make(chan time.Time, 1)
|
||||
logs := &strings.Builder{}
|
||||
runner := scheduler.NewCleanupRunner(job, func() time.Time { return cleanupAt(6, 3, 0) }, ticks, startup, log.New(logs, "", 0))
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
runner.Run(ctx)
|
||||
}()
|
||||
return ticks, startup, logs, cancel, done
|
||||
}
|
||||
|
||||
t.Run("The runner ticks the cleanup with the injected clock and logs the count", func(t *testing.T) {
|
||||
job := &cleanupJobFake{calls: make(chan time.Time, 4), removed: 142}
|
||||
ticks, _, logs, cancel, done := start(job)
|
||||
defer func() { cancel(); <-done }()
|
||||
|
||||
ticks <- time.Time{}
|
||||
select {
|
||||
case got := <-job.calls:
|
||||
if !got.Equal(cleanupAt(6, 3, 0)) {
|
||||
t.Errorf("expected the injected clock, got %v", got)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("the job was never ticked")
|
||||
}
|
||||
cancel()
|
||||
<-done
|
||||
if !strings.Contains(logs.String(), "activity cleanup completed: removed=142") {
|
||||
t.Errorf("unexpected log %q", logs.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A failing tick is logged", func(t *testing.T) {
|
||||
job := &cleanupJobFake{calls: make(chan time.Time, 4), err: errRepositoryFailure}
|
||||
_, startup, logs, cancel, done := start(job)
|
||||
|
||||
startup <- time.Time{}
|
||||
<-job.calls
|
||||
cancel()
|
||||
<-done
|
||||
|
||||
if !strings.Contains(logs.String(), "activity cleanup failed") || !strings.Contains(logs.String(), errRepositoryFailure.Error()) {
|
||||
t.Errorf("unexpected log %q", logs.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The scheduler stops with the process", func(t *testing.T) {
|
||||
job := &cleanupJobFake{calls: make(chan time.Time, 4)}
|
||||
_, _, _, cancel, done := start(job)
|
||||
|
||||
cancel()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("the runner did not return after the context was cancelled")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/infrastructure/auditing"
|
||||
persistence "RenewCMS/internal/infrastructure/persistence/repositories"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var testCtx = context.Background()
|
||||
|
||||
var discardRecorder audit.Recorder = audit.Discard
|
||||
|
||||
type activityProbeRepo struct {
|
||||
inner audit.Repository
|
||||
appendErr error
|
||||
appendPanic bool
|
||||
reads int
|
||||
listCalls []audit.Filter
|
||||
deleteErr error
|
||||
deleteCalls int
|
||||
readErr error
|
||||
}
|
||||
|
||||
var _ audit.Repository = &activityProbeRepo{}
|
||||
|
||||
func (p *activityProbeRepo) Append(event audit.Event) (audit.Event, error) {
|
||||
if p.appendPanic {
|
||||
panic("audit repository exploded")
|
||||
}
|
||||
if p.appendErr != nil {
|
||||
return audit.Event{}, p.appendErr
|
||||
}
|
||||
return p.inner.Append(event)
|
||||
}
|
||||
|
||||
func (p *activityProbeRepo) List(filter audit.Filter) (audit.Page, error) {
|
||||
p.reads++
|
||||
p.listCalls = append(p.listCalls, filter)
|
||||
if p.readErr != nil {
|
||||
return audit.Page{}, p.readErr
|
||||
}
|
||||
return p.inner.List(filter)
|
||||
}
|
||||
|
||||
func (p *activityProbeRepo) Summary(query audit.SummaryQuery) (audit.Summary, error) {
|
||||
p.reads++
|
||||
if p.readErr != nil {
|
||||
return audit.Summary{}, p.readErr
|
||||
}
|
||||
return p.inner.Summary(query)
|
||||
}
|
||||
|
||||
func (p *activityProbeRepo) DeleteOlderThan(cutoff time.Time) (int, error) {
|
||||
p.deleteCalls++
|
||||
if p.deleteErr != nil {
|
||||
return 0, p.deleteErr
|
||||
}
|
||||
return p.inner.DeleteOlderThan(cutoff)
|
||||
}
|
||||
|
||||
type activitySettingsFake struct {
|
||||
settings audit.Settings
|
||||
saveErr error
|
||||
getErr error
|
||||
retentionOK int
|
||||
cleanupOK int
|
||||
}
|
||||
|
||||
var _ audit.SettingsRepository = &activitySettingsFake{}
|
||||
|
||||
func newActivitySettingsFake() *activitySettingsFake {
|
||||
return &activitySettingsFake{settings: audit.DefaultSettings()}
|
||||
}
|
||||
|
||||
func (f *activitySettingsFake) Get() (audit.Settings, error) {
|
||||
if f.getErr != nil {
|
||||
return audit.Settings{}, f.getErr
|
||||
}
|
||||
return f.settings, nil
|
||||
}
|
||||
|
||||
func (f *activitySettingsFake) SaveRetention(days int) error {
|
||||
if f.saveErr != nil {
|
||||
return f.saveErr
|
||||
}
|
||||
f.retentionOK++
|
||||
f.settings.RetentionDays = days
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *activitySettingsFake) SaveLastCleanup(at time.Time, removed int) error {
|
||||
if f.saveErr != nil {
|
||||
return f.saveErr
|
||||
}
|
||||
f.cleanupOK++
|
||||
f.settings.LastCleanupAt = &at
|
||||
f.settings.LastCleanupRemoved = removed
|
||||
return nil
|
||||
}
|
||||
|
||||
type activityHarness struct {
|
||||
probe *activityProbeRepo
|
||||
store *persistence.AuditEventRepository
|
||||
settings *activitySettingsFake
|
||||
logs *bytes.Buffer
|
||||
now time.Time
|
||||
recorder *auditing.Recorder
|
||||
}
|
||||
|
||||
func newActivityHarness(t *testing.T) *activityHarness {
|
||||
t.Helper()
|
||||
store := persistence.NewAuditEventRepository(openActivityDatabase(t))
|
||||
h := &activityHarness{
|
||||
probe: &activityProbeRepo{inner: store},
|
||||
store: store,
|
||||
settings: newActivitySettingsFake(),
|
||||
logs: &bytes.Buffer{},
|
||||
now: time.Date(2026, time.October, 6, 12, 0, 0, 0, time.UTC),
|
||||
}
|
||||
h.recorder = auditing.NewRecorder(h.probe, func() time.Time { return h.now }, log.New(h.logs, "", 0))
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *activityHarness) clock() time.Time { return h.now }
|
||||
|
||||
func (h *activityHarness) all(t *testing.T) []audit.Event {
|
||||
t.Helper()
|
||||
page, err := h.store.List(audit.Filter{Page: 1, Size: 1000})
|
||||
if err != nil {
|
||||
t.Fatalf("listing stored events failed: %v", err)
|
||||
}
|
||||
return page.Items
|
||||
}
|
||||
|
||||
func (h *activityHarness) seed(t *testing.T, event audit.Event) audit.Event {
|
||||
t.Helper()
|
||||
return activityMustAppend(t, h.store, event)
|
||||
}
|
||||
|
||||
var errDiskFull = errors.New("disk full")
|
||||
@@ -0,0 +1,491 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/apikey"
|
||||
"RenewCMS/internal/domain/article"
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"bytes"
|
||||
"encoding/csv"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type activityWorld struct {
|
||||
*activityHarness
|
||||
users *mockUserRepo
|
||||
articles *mockArticleRepo
|
||||
images *mockImageRepo
|
||||
keys *mockAPIKeyRepo
|
||||
list *useCases.ListActivityUseCase
|
||||
summary *useCases.GetActivitySummaryUseCase
|
||||
export *useCases.ExportActivityUseCase
|
||||
}
|
||||
|
||||
func newActivityWorld(t *testing.T) *activityWorld {
|
||||
t.Helper()
|
||||
h := newActivityHarness(t)
|
||||
w := &activityWorld{
|
||||
activityHarness: h,
|
||||
users: newMockUserRepo(),
|
||||
articles: newMockArticleRepo(),
|
||||
images: newMockImageRepo(),
|
||||
keys: newMockAPIKeyRepo(),
|
||||
}
|
||||
w.users.users[1] = user.User{ID: 1, Username: "owner", IsVerified: true, Role: user.RoleOwner}
|
||||
w.users.users[2] = user.User{ID: 2, Username: "admin", IsVerified: true, Role: user.RoleAdmin}
|
||||
w.users.users[3] = user.User{ID: 3, Username: "marta", DisplayName: "Marta Alves", IsVerified: true, Role: "editor"}
|
||||
w.list = useCases.NewListActivityUseCase(h.probe, w.users, w.articles, w.images, w.keys, h.clock)
|
||||
w.summary = useCases.NewGetActivitySummaryUseCase(h.probe, h.clock)
|
||||
w.export = useCases.NewExportActivityUseCase(h.probe, h.clock)
|
||||
return w
|
||||
}
|
||||
|
||||
func (w *activityWorld) seedAt(t *testing.T, ago time.Duration, mutate func(*audit.Event)) audit.Event {
|
||||
t.Helper()
|
||||
event := activityUserEvent(3, "Marta Alves", w.now.Add(-ago))
|
||||
if mutate != nil {
|
||||
mutate(&event)
|
||||
}
|
||||
return w.seed(t, event)
|
||||
}
|
||||
|
||||
func TestActivityListUseCase(t *testing.T) {
|
||||
const day = 24 * time.Hour
|
||||
|
||||
t.Run("Omitting the range means seven days", func(t *testing.T) {
|
||||
w := newActivityWorld(t)
|
||||
recent := w.seedAt(t, 2*day, nil)
|
||||
w.seedAt(t, 10*day, nil)
|
||||
|
||||
page, err := w.list.ListActivity(useCases.ListActivityCommand{ViewerID: 1})
|
||||
|
||||
if err != nil || len(page.Items) != 1 || page.Items[0].Event.ID != recent.ID {
|
||||
t.Fatalf("expected only the recent event, got %+v, %v", page, err)
|
||||
}
|
||||
if page.Page != 1 || page.Size != 25 || page.Total != 1 {
|
||||
t.Errorf("unexpected paging %d/%d/%d", page.Page, page.Size, page.Total)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The ranges map to the documented windows", func(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
query useCases.ActivityQuery
|
||||
ago time.Duration
|
||||
found bool
|
||||
}{
|
||||
{"today keeps this morning", useCases.ActivityQuery{Range: "today"}, 11 * time.Hour, true},
|
||||
{"today drops yesterday", useCases.ActivityQuery{Range: "today"}, 13 * time.Hour, false},
|
||||
{"7d keeps six days", useCases.ActivityQuery{Range: "7d"}, 6 * day, true},
|
||||
{"7d drops eight days", useCases.ActivityQuery{Range: "7d"}, 8 * day, false},
|
||||
{"30d keeps twenty nine days", useCases.ActivityQuery{Range: "30d"}, 29 * day, true},
|
||||
{"30d drops thirty one days", useCases.ActivityQuery{Range: "30d"}, 31 * day, false},
|
||||
{"custom keeps the first day", useCases.ActivityQuery{Range: "custom", From: "2026-09-01", To: "2026-09-30"}, 35*day + 12*time.Hour, true},
|
||||
{"custom keeps the end of the last day", useCases.ActivityQuery{Range: "custom", From: "2026-09-01", To: "2026-09-30"}, 5*day + 12*time.Hour + time.Second, true},
|
||||
{"custom drops after the last day", useCases.ActivityQuery{Range: "custom", From: "2026-09-01", To: "2026-09-30"}, 5 * day, false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
w := newActivityWorld(t)
|
||||
w.seedAt(t, c.ago, nil)
|
||||
|
||||
page, err := w.list.ListActivity(useCases.ListActivityCommand{ViewerID: 1, Query: c.query})
|
||||
|
||||
if err != nil || (page.Total == 1) != c.found {
|
||||
t.Errorf("expected found=%v, got total %d, %v", c.found, page.Total, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Invalid values are refused before the repository is read", func(t *testing.T) {
|
||||
queries := []useCases.ActivityQuery{
|
||||
{Actor: "user:abc"}, {Actor: "user:-1"}, {Actor: "group:3"},
|
||||
{Category: "billing"}, {Outcome: "maybe"}, {Security: "false"},
|
||||
{Range: "year"}, {Range: "custom"},
|
||||
{Range: "custom", From: "2026-09-30", To: "2026-09-01"},
|
||||
{Range: "custom", From: "yesterday", To: "today"},
|
||||
{Page: -1}, {Size: 10}, {Size: 200},
|
||||
}
|
||||
for i, query := range queries {
|
||||
w := newActivityWorld(t)
|
||||
|
||||
_, err := w.list.ListActivity(useCases.ListActivityCommand{ViewerID: 1, Query: query})
|
||||
|
||||
if !errors.Is(err, audit.ErrInvalidFilter) || w.probe.reads != 0 {
|
||||
t.Errorf("query %d (%+v): expected ErrInvalidFilter without reading, got %v after %d reads", i, query, err, w.probe.reads)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The outcome all lists both outcomes", func(t *testing.T) {
|
||||
w := newActivityWorld(t)
|
||||
w.seedAt(t, day, nil)
|
||||
w.seedAt(t, day, func(e *audit.Event) { e.Outcome = audit.OutcomeFailed })
|
||||
|
||||
page, _ := w.list.ListActivity(useCases.ListActivityCommand{ViewerID: 1, Query: useCases.ActivityQuery{Outcome: "all"}})
|
||||
|
||||
if page.Total != 2 {
|
||||
t.Errorf("expected both outcomes, got %d", page.Total)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A caller who is not owner or admin is scoped to its own events", func(t *testing.T) {
|
||||
w := newActivityWorld(t)
|
||||
w.seedAt(t, day, nil)
|
||||
w.seedAt(t, day, func(e *audit.Event) {
|
||||
e.Actor = audit.Actor{Type: audit.ActorUser, ID: activityPtr(uint32(2)), Name: "admin"}
|
||||
})
|
||||
w.seedAt(t, day, func(e *audit.Event) { e.Actor = audit.SystemActor() })
|
||||
|
||||
page, err := w.list.ListActivity(useCases.ListActivityCommand{ViewerID: 3})
|
||||
|
||||
if err != nil || page.Total != 1 || *page.Items[0].Event.Actor.ID != 3 {
|
||||
t.Fatalf("expected only user 3's events, got %+v, %v", page, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A scoped caller cannot ask for another actor", func(t *testing.T) {
|
||||
cases := map[string]bool{"user:3": true, "user:2": false, "key:7": false, "system": false}
|
||||
for actor, allowed := range cases {
|
||||
w := newActivityWorld(t)
|
||||
|
||||
_, err := w.list.ListActivity(useCases.ListActivityCommand{ViewerID: 3, Query: useCases.ActivityQuery{Actor: actor}})
|
||||
|
||||
if allowed && err != nil {
|
||||
t.Errorf("%s: expected success, got %v", actor, err)
|
||||
}
|
||||
if !allowed && !errors.Is(err, audit.ErrActorNotAllowed) {
|
||||
t.Errorf("%s: expected ErrActorNotAllowed, got %v", actor, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("An unknown viewer is reported", func(t *testing.T) {
|
||||
w := newActivityWorld(t)
|
||||
|
||||
_, err := w.list.ListActivity(useCases.ListActivityCommand{ViewerID: 99})
|
||||
|
||||
if !errors.Is(err, user.ErrUserNotFound) {
|
||||
t.Errorf("expected ErrUserNotFound, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("target.exists is resolved when the list is read", func(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
target audit.Target
|
||||
seed func(*activityWorld)
|
||||
exists bool
|
||||
}{
|
||||
{"the article still exists", audit.Target{Type: "article", ID: "8", Name: "Spring release"}, func(w *activityWorld) { w.articles.articles[8] = article.Article{ID: 8} }, true},
|
||||
{"the article was deleted", audit.Target{Type: "article", ID: "8", Name: "Spring release"}, func(w *activityWorld) {}, false},
|
||||
{"the user was deleted", audit.Target{Type: "user", ID: "3", Name: "Marta Alves"}, func(w *activityWorld) { delete(w.users.users, 3) }, false},
|
||||
{"the api key still exists", audit.Target{Type: "api_key", ID: "7", Name: "Deploy bot"}, func(w *activityWorld) { w.keys.keys[7] = apikey.APIKey{ID: 7} }, true},
|
||||
{"the api key is unknown", audit.Target{Type: "api_key", ID: "7", Name: "Deploy bot"}, func(w *activityWorld) {}, false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
w := newActivityWorld(t)
|
||||
c.seed(w)
|
||||
w.seedAt(t, day, func(e *audit.Event) { e.Target = c.target })
|
||||
|
||||
page, err := w.list.ListActivity(useCases.ListActivityCommand{ViewerID: 1})
|
||||
|
||||
if err != nil || len(page.Items) != 1 {
|
||||
t.Fatalf("unexpected result %+v, %v", page, err)
|
||||
}
|
||||
if page.Items[0].TargetExists != c.exists || page.Items[0].Event.Target.Name != c.target.Name {
|
||||
t.Errorf("expected exists=%v with the name kept, got %+v", c.exists, page.Items[0])
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A repository failure is returned", func(t *testing.T) {
|
||||
w := newActivityWorld(t)
|
||||
w.users.fail.failNext("Get")
|
||||
|
||||
_, err := w.list.ListActivity(useCases.ListActivityCommand{ViewerID: 1})
|
||||
|
||||
if !errors.Is(err, errRepositoryFailure) {
|
||||
t.Errorf("expected the repository failure, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestActivitySummaryUseCase(t *testing.T) {
|
||||
const day = 24 * time.Hour
|
||||
|
||||
t.Run("The summary of the last seven days compares with the previous period", func(t *testing.T) {
|
||||
w := newActivityWorld(t)
|
||||
for i := 0; i < 12; i++ {
|
||||
i := i
|
||||
w.seedAt(t, time.Duration(i)*12*time.Hour+time.Hour, func(e *audit.Event) {
|
||||
if i < 3 {
|
||||
e.Outcome = audit.OutcomeFailed
|
||||
}
|
||||
e.Security = i < 2
|
||||
if i%2 == 1 {
|
||||
e.Actor = audit.Actor{Type: audit.ActorAPIKey, ID: activityPtr(uint32(7)), Name: "bot"}
|
||||
}
|
||||
})
|
||||
}
|
||||
for i := 0; i < 10; i++ {
|
||||
w.seedAt(t, 7*day+time.Duration(i)*time.Hour+time.Hour, nil)
|
||||
}
|
||||
|
||||
summary, err := w.summary.GetActivitySummary(useCases.ActivityQuery{Range: "7d"})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if summary.Total != 12 || summary.PreviousTotal != 10 || summary.Failed != 3 || summary.Security != 2 {
|
||||
t.Errorf("unexpected counts %+v", summary)
|
||||
}
|
||||
if summary.ActivePeople.Users != 1 || summary.ActivePeople.APIKeys != 1 {
|
||||
t.Errorf("unexpected people %+v", summary.ActivePeople)
|
||||
}
|
||||
sum := 0
|
||||
for _, n := range summary.Series.Total {
|
||||
sum += n
|
||||
}
|
||||
if len(summary.Series.Total) != 7 || len(summary.Series.Active) != 7 || len(summary.Series.Failed) != 7 || len(summary.Series.Security) != 7 || sum != 12 {
|
||||
t.Errorf("unexpected series %+v", summary.Series)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("An empty log answers zeros", func(t *testing.T) {
|
||||
w := newActivityWorld(t)
|
||||
|
||||
summary, err := w.summary.GetActivitySummary(useCases.ActivityQuery{})
|
||||
|
||||
if err != nil || summary.Total != 0 || summary.PreviousTotal != 0 || len(summary.Series.Total) != 7 {
|
||||
t.Errorf("unexpected summary %+v, %v", summary, err)
|
||||
}
|
||||
for _, n := range append(append(summary.Series.Total, summary.Series.Active...), append(summary.Series.Failed, summary.Series.Security...)...) {
|
||||
if n != 0 {
|
||||
t.Errorf("expected only zeros, got %+v", summary.Series)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A custom range compares with the seven days immediately before it", func(t *testing.T) {
|
||||
w := newActivityWorld(t)
|
||||
at := func(day int, month time.Month) {
|
||||
w.seed(t, activityUserEvent(3, "a", time.Date(2026, month, day, 12, 0, 0, 0, time.UTC)))
|
||||
}
|
||||
at(1, time.September)
|
||||
at(7, time.September)
|
||||
at(8, time.September)
|
||||
at(25, time.August)
|
||||
at(31, time.August)
|
||||
at(24, time.August)
|
||||
|
||||
summary, err := w.summary.GetActivitySummary(useCases.ActivityQuery{Range: "custom", From: "2026-09-01", To: "2026-09-07"})
|
||||
|
||||
if err != nil || summary.Total != 2 || summary.PreviousTotal != 2 {
|
||||
t.Errorf("expected 2 and 2, got %+v, %v", summary, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("An invalid range is refused", func(t *testing.T) {
|
||||
w := newActivityWorld(t)
|
||||
|
||||
_, err := w.summary.GetActivitySummary(useCases.ActivityQuery{Range: "year"})
|
||||
|
||||
if !errors.Is(err, audit.ErrInvalidFilter) || w.probe.reads != 0 {
|
||||
t.Errorf("expected ErrInvalidFilter without reading, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func exportToString(t *testing.T, w *activityWorld, query useCases.ActivityQuery) string {
|
||||
t.Helper()
|
||||
prepared, err := w.export.Prepare(query)
|
||||
if err != nil {
|
||||
t.Fatalf("prepare failed: %v", err)
|
||||
}
|
||||
var out bytes.Buffer
|
||||
if err := prepared.WriteCSV(&out); err != nil {
|
||||
t.Fatalf("write failed: %v", err)
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func TestActivityExportUseCase(t *testing.T) {
|
||||
t.Run("The file has the header and one row per event, newest first", func(t *testing.T) {
|
||||
w := newActivityWorld(t)
|
||||
for i := 1; i <= 3; i++ {
|
||||
w.seedAt(t, time.Duration(i)*time.Hour, func(e *audit.Event) { e.Action = fmt.Sprintf("article.edit%d", i) })
|
||||
}
|
||||
|
||||
rows, err := csv.NewReader(strings.NewReader(exportToString(t, w, useCases.ActivityQuery{}))).ReadAll()
|
||||
|
||||
if err != nil || len(rows) != 4 {
|
||||
t.Fatalf("unexpected rows %v, %v", rows, err)
|
||||
}
|
||||
if strings.Join(rows[0], ",") != "when,actor,action,target,outcome,source,ip" {
|
||||
t.Errorf("unexpected header %v", rows[0])
|
||||
}
|
||||
if rows[1][2] != "article.edit1" || rows[3][2] != "article.edit3" {
|
||||
t.Errorf("expected newest first, got %v", rows)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A row holds the documented columns only", func(t *testing.T) {
|
||||
w := newActivityWorld(t)
|
||||
w.seed(t, func() audit.Event {
|
||||
event := activityUserEvent(3, "Marta Alves", time.Date(2026, time.October, 6, 10, 42, 18, 0, time.UTC))
|
||||
event.Target = audit.Target{Type: "article", ID: "8", Name: "Spring release"}
|
||||
event.IP = activityPtr("203.0.113.12")
|
||||
event.UserAgent = activityPtr("Chrome 129 on Windows")
|
||||
event.Changes = []audit.Change{{Field: "online", Kind: audit.ChangeText, Before: activityPtr("false"), After: activityPtr("true")}}
|
||||
return event
|
||||
}())
|
||||
|
||||
file := exportToString(t, w, useCases.ActivityQuery{})
|
||||
|
||||
want := "2026-10-06T10:42:18Z,Marta Alves,article.publish,Spring release,success,web,203.0.113.12\n"
|
||||
if !strings.HasSuffix(file, want) {
|
||||
t.Errorf("expected the row %q, got %q", want, file)
|
||||
}
|
||||
if strings.Contains(file, "Chrome") || strings.Contains(file, "false") {
|
||||
t.Errorf("the file must hold no user agent and no changes: %q", file)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Cells that a spreadsheet would evaluate are neutralised", func(t *testing.T) {
|
||||
cases := []struct {
|
||||
column string
|
||||
value string
|
||||
cell string
|
||||
}{
|
||||
{"actor", "=cmd", "'=cmd"},
|
||||
{"target", "+1+1", "'+1+1"},
|
||||
{"target", "-2", "'-2"},
|
||||
{"actor", "@SUM(A1)", "'@SUM(A1)"},
|
||||
{"target", "Spring release", "Spring release"},
|
||||
{"target", "a=b", "a=b"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
w := newActivityWorld(t)
|
||||
w.seedAt(t, time.Hour, func(e *audit.Event) {
|
||||
if c.column == "actor" {
|
||||
e.Actor.Name = c.value
|
||||
} else {
|
||||
e.Target = audit.Target{Type: "article", ID: "1", Name: c.value}
|
||||
}
|
||||
})
|
||||
|
||||
rows, _ := csv.NewReader(strings.NewReader(exportToString(t, w, useCases.ActivityQuery{}))).ReadAll()
|
||||
|
||||
index := 1
|
||||
if c.column == "target" {
|
||||
index = 3
|
||||
}
|
||||
if rows[1][index] != c.cell {
|
||||
t.Errorf("%s %q: expected %q, got %q", c.column, c.value, c.cell, rows[1][index])
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Commas, quotes and newlines are quoted and keep one row", func(t *testing.T) {
|
||||
w := newActivityWorld(t)
|
||||
name := "Hello, \"world\"\nsecond line"
|
||||
w.seedAt(t, time.Hour, func(e *audit.Event) { e.Target = audit.Target{Type: "article", ID: "1", Name: name} })
|
||||
|
||||
file := exportToString(t, w, useCases.ActivityQuery{})
|
||||
|
||||
if !strings.Contains(file, "\"Hello, \"\"world\"\"\nsecond line\"") {
|
||||
t.Errorf("the cell is not quoted with doubled quotes: %q", file)
|
||||
}
|
||||
rows, err := csv.NewReader(strings.NewReader(file)).ReadAll()
|
||||
if err != nil || len(rows) != 2 || rows[1][3] != name {
|
||||
t.Errorf("expected one data row holding the name, got %v, %v", rows, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The filters apply and paging is ignored", func(t *testing.T) {
|
||||
w := newActivityWorld(t)
|
||||
for i := 0; i < 60; i++ {
|
||||
failed := i < 8
|
||||
w.seedAt(t, time.Duration(i+1)*time.Minute, func(e *audit.Event) {
|
||||
if failed {
|
||||
e.Outcome = audit.OutcomeFailed
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
rows, _ := csv.NewReader(strings.NewReader(exportToString(t, w, useCases.ActivityQuery{Outcome: "failed", Page: 2, Size: 25}))).ReadAll()
|
||||
|
||||
if len(rows) != 9 {
|
||||
t.Errorf("expected the header and 8 failed rows, got %d lines", len(rows))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A system event has an empty ip cell", func(t *testing.T) {
|
||||
w := newActivityWorld(t)
|
||||
w.seedAt(t, time.Hour, func(e *audit.Event) { e.Actor = audit.SystemActor(); e.Source = audit.SourceSystem })
|
||||
|
||||
rows, _ := csv.NewReader(strings.NewReader(exportToString(t, w, useCases.ActivityQuery{}))).ReadAll()
|
||||
|
||||
if rows[1][6] != "" || rows[1][1] != "System" {
|
||||
t.Errorf("unexpected row %v", rows[1])
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("An invalid filter is refused before anything is prepared", func(t *testing.T) {
|
||||
w := newActivityWorld(t)
|
||||
|
||||
_, err := w.export.Prepare(useCases.ActivityQuery{Outcome: "maybe"})
|
||||
|
||||
if !errors.Is(err, audit.ErrInvalidFilter) || w.probe.reads != 0 {
|
||||
t.Errorf("expected ErrInvalidFilter without reading, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A large export is read in batches", func(t *testing.T) {
|
||||
w := newActivityWorld(t)
|
||||
for i := 0; i < 1200; i++ {
|
||||
w.seedAt(t, time.Duration(i+1)*time.Second, nil)
|
||||
}
|
||||
|
||||
rows, err := csv.NewReader(strings.NewReader(exportToString(t, w, useCases.ActivityQuery{}))).ReadAll()
|
||||
|
||||
if err != nil || len(rows) != 1201 {
|
||||
t.Fatalf("expected 1200 rows plus the header, got %d, %v", len(rows), err)
|
||||
}
|
||||
if len(w.probe.listCalls) < 2 {
|
||||
t.Errorf("expected several paged reads, got %d", len(w.probe.listCalls))
|
||||
}
|
||||
for _, call := range w.probe.listCalls {
|
||||
if call.Size == 0 || call.Size >= 1200 {
|
||||
t.Errorf("every read must be a bounded page, got size %d", call.Size)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("An export that fills whole batches stops without an extra read", func(t *testing.T) {
|
||||
for _, c := range []struct{ events, reads int }{{500, 1}, {1000, 2}} {
|
||||
w := newActivityWorld(t)
|
||||
for i := 0; i < c.events; i++ {
|
||||
w.seedAt(t, time.Duration(i+1)*time.Second, nil)
|
||||
}
|
||||
|
||||
rows, err := csv.NewReader(strings.NewReader(exportToString(t, w, useCases.ActivityQuery{}))).ReadAll()
|
||||
|
||||
if err != nil || len(rows) != c.events+1 {
|
||||
t.Fatalf("%d events: expected %d rows, got %d, %v", c.events, c.events+1, len(rows), err)
|
||||
}
|
||||
if len(w.probe.listCalls) != c.reads {
|
||||
t.Errorf("%d events: expected %d reads, got %d", c.events, c.reads, len(w.probe.listCalls))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func validActivityEvent() audit.Event {
|
||||
event := audit.NewEvent("article.publish", audit.CategoryArticles)
|
||||
event.Source = audit.SourceWeb
|
||||
event.Actor = audit.Actor{Type: audit.ActorUser, Name: "marta"}
|
||||
return event
|
||||
}
|
||||
|
||||
func TestActivityEventValidation(t *testing.T) {
|
||||
long := func(n int) *string { value := strings.Repeat("x", n); return &value }
|
||||
cases := []struct {
|
||||
name string
|
||||
mutate func(*audit.Event)
|
||||
valid bool
|
||||
}{
|
||||
{"complete event", func(e *audit.Event) {}, true},
|
||||
{"empty action", func(e *audit.Event) { e.Action = "" }, false},
|
||||
{"action at the limit", func(e *audit.Event) { e.Action = strings.Repeat("a", 64) }, true},
|
||||
{"action over the limit", func(e *audit.Event) { e.Action = strings.Repeat("a", 65) }, false},
|
||||
{"unknown category", func(e *audit.Event) { e.Category = "nope" }, false},
|
||||
{"unknown outcome", func(e *audit.Event) { e.Outcome = "nope" }, false},
|
||||
{"unknown source", func(e *audit.Event) { e.Source = "nope" }, false},
|
||||
{"unknown actor type", func(e *audit.Event) { e.Actor.Type = "nope" }, false},
|
||||
{"failure reason at the limit", func(e *audit.Event) { e.FailureReason = long(255) }, true},
|
||||
{"failure reason over the limit", func(e *audit.Event) { e.FailureReason = long(256) }, false},
|
||||
{"unknown change kind", func(e *audit.Event) { e.Changes = []audit.Change{{Field: "a", Kind: "nope"}} }, false},
|
||||
{"body change", func(e *audit.Event) { e.Changes = []audit.Change{{Field: "a", Kind: audit.ChangeBody}} }, true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
event := validActivityEvent()
|
||||
c.mutate(&event)
|
||||
|
||||
err := event.Validate()
|
||||
|
||||
if c.valid && err != nil {
|
||||
t.Errorf("%s: expected valid, got %v", c.name, err)
|
||||
}
|
||||
if !c.valid && !errors.Is(err, audit.ErrInvalidEvent) {
|
||||
t.Errorf("%s: expected ErrInvalidEvent, got %v", c.name, err)
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("Names are cut to 255 characters", func(t *testing.T) {
|
||||
event := validActivityEvent()
|
||||
event.Actor.Name = strings.Repeat("é", 256)
|
||||
event.Target.Name = strings.Repeat("é", 255)
|
||||
|
||||
cut := event.Truncated()
|
||||
|
||||
if len([]rune(cut.Actor.Name)) != 255 || len([]rune(cut.Target.Name)) != 255 {
|
||||
t.Errorf("unexpected lengths %d and %d", len([]rune(cut.Actor.Name)), len([]rune(cut.Target.Name)))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The discard recorder accepts events silently", func(t *testing.T) {
|
||||
audit.Discard.Record(testCtx, validActivityEvent())
|
||||
})
|
||||
}
|
||||
|
||||
func TestActivityHandlerErrorMapping(t *testing.T) {
|
||||
t.Run("A signed-in user who no longer exists is unauthorised", func(t *testing.T) {
|
||||
e := newActivityHTTPEnv(t, 1000)
|
||||
|
||||
rec := e.get("/v1/activity", asUser(e, 99))
|
||||
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("expected 401, got %d", rec.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A storage failure is a plain 500", func(t *testing.T) {
|
||||
for _, path := range []string{"/v1/activity", "/v1/activity/summary", "/v1/activity/export"} {
|
||||
e := newActivityHTTPEnv(t, 1000)
|
||||
e.probe.readErr = errors.New("storage down")
|
||||
|
||||
rec := e.get(path, asUser(e, activityOwnerID))
|
||||
|
||||
if path != "/v1/activity/export" && rec.Code != http.StatusInternalServerError {
|
||||
t.Errorf("%s: expected 500, got %d", path, rec.Code)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
+36
-20
@@ -6,6 +6,7 @@ import (
|
||||
validator "RenewCMS/api/pkg/validator"
|
||||
"RenewCMS/internal/domain/apikey"
|
||||
"RenewCMS/internal/domain/article"
|
||||
"RenewCMS/internal/domain/audit"
|
||||
"RenewCMS/internal/domain/image"
|
||||
"RenewCMS/internal/domain/update"
|
||||
"RenewCMS/internal/domain/user"
|
||||
@@ -15,6 +16,8 @@ import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"regexp"
|
||||
@@ -45,6 +48,7 @@ type apiKeyEnv struct {
|
||||
articles *mockArticleRepo
|
||||
images *mockImageRepo
|
||||
invites *inviteFakeRepo
|
||||
mail *mockMailRepo
|
||||
feed *fakeReleaseFeed
|
||||
updates *fakeUpdateStore
|
||||
token *jwtauth.JWTAuth
|
||||
@@ -57,6 +61,11 @@ type apiKeyEnv struct {
|
||||
}
|
||||
|
||||
func newAPIKeyEnv(t *testing.T) *apiKeyEnv {
|
||||
t.Helper()
|
||||
return newAPIKeyEnvRecording(t, discardRecorder)
|
||||
}
|
||||
|
||||
func newAPIKeyEnvRecording(t *testing.T, recorder audit.Recorder) *apiKeyEnv {
|
||||
t.Helper()
|
||||
validator.InitValidator()
|
||||
|
||||
@@ -89,40 +98,47 @@ func newAPIKeyEnv(t *testing.T) *apiKeyEnv {
|
||||
clock := func() time.Time { return env.now }
|
||||
hasher := &stubHasher{}
|
||||
mail := newMockMailRepo()
|
||||
env.mail = mail
|
||||
renderer := &fakeBodyRenderer{}
|
||||
mergeMedia := useCases.NewMergeMediaUseCase(env.images, env.articles, newMockImageStorage(), recorder)
|
||||
purgeSettings := newMockPurgeSettingsRepo()
|
||||
restartJobs := &fakeJobStore{}
|
||||
env.container = &api.UseCases{
|
||||
Token: env.token,
|
||||
CreateArticleUseCase: useCases.NewCreateArticleUseCase(env.articles, renderer),
|
||||
CreateArticleUseCase: useCases.NewCreateArticleUseCase(env.articles, renderer, recorder),
|
||||
GetArticleUseCase: useCases.NewGetArticleUseCase(env.articles, renderer),
|
||||
ListArticlesUseCase: useCases.NewListArticlesUseCase(env.articles, renderer),
|
||||
UpdateArticleUseCase: useCases.NewUpdateArticleUseCase(env.articles, renderer),
|
||||
DeleteArticleUseCase: useCases.NewDeleteArticleUseCase(env.articles),
|
||||
UpdateArticleUseCase: useCases.NewUpdateArticleUseCase(env.articles, renderer, recorder),
|
||||
DeleteArticleUseCase: useCases.NewDeleteArticleUseCase(env.articles, recorder),
|
||||
GetUserUseCase: useCases.NewGetUserUseCase(env.users),
|
||||
CreateUserUseCase: useCases.NewCreateUserUseCase(env.users, hasher, mail, "https://cms.example.com"),
|
||||
AuthenticateUserUseCase: useCases.NewAuthenticateUserUseCase(env.users, hasher),
|
||||
VerifyUserUseCase: useCases.NewVerifyUserUseCase(env.users, hasher),
|
||||
CreateUserUseCase: useCases.NewCreateUserUseCase(env.users, hasher, mail, "https://cms.example.com", recorder),
|
||||
AuthenticateUserUseCase: useCases.NewAuthenticateUserUseCase(env.users, hasher, recorder),
|
||||
VerifyUserUseCase: useCases.NewVerifyUserUseCase(env.users, hasher, recorder),
|
||||
CancelRegistrationUseCase: useCases.NewCancelRegistrationUseCase(env.users),
|
||||
RequestPasswordResetUseCase: useCases.NewRequestPasswordResetUseCase(env.users, hasher, mail, "https://cms.example.com"),
|
||||
ResetPasswordUseCase: useCases.NewResetPasswordUseCase(env.users, hasher, env.keys, clock),
|
||||
UpdateUserProfileUseCase: useCases.NewUpdateUserProfileUseCase(env.users),
|
||||
CreateInviteUseCase: useCases.NewCreateInviteUseCase(env.users, env.invites, hasher, mail, "https://cms.example.com"),
|
||||
CancelInviteUseCase: useCases.NewCancelInviteUseCase(env.invites),
|
||||
RenewInviteUseCase: useCases.NewRenewInviteUseCase(env.users, env.invites, hasher, mail, "https://cms.example.com"),
|
||||
RequestPasswordResetUseCase: useCases.NewRequestPasswordResetUseCase(env.users, hasher, mail, "https://cms.example.com", recorder),
|
||||
ResetPasswordUseCase: useCases.NewResetPasswordUseCase(env.users, hasher, env.keys, clock, recorder),
|
||||
UpdateUserProfileUseCase: useCases.NewUpdateUserProfileUseCase(env.users, recorder),
|
||||
CreateInviteUseCase: useCases.NewCreateInviteUseCase(env.users, env.invites, hasher, mail, "https://cms.example.com", recorder),
|
||||
CancelInviteUseCase: useCases.NewCancelInviteUseCase(env.invites, recorder),
|
||||
RenewInviteUseCase: useCases.NewRenewInviteUseCase(env.users, env.invites, hasher, mail, "https://cms.example.com", recorder),
|
||||
ListUsersAndInvitesUseCase: useCases.NewListUsersAndInvitesUseCase(env.users, env.invites),
|
||||
GetInviteUseCase: useCases.NewGetInviteUseCase(env.invites, hasher),
|
||||
AcceptInviteUseCase: useCases.NewAcceptInviteUseCase(env.users, env.invites, hasher),
|
||||
CreateImageUseCase: useCases.NewCreateImageUseCase(env.images, newMockImageStorage()),
|
||||
AcceptInviteUseCase: useCases.NewAcceptInviteUseCase(env.users, env.invites, hasher, recorder),
|
||||
CreateImageUseCase: useCases.NewCreateImageUseCase(env.images, newMockImageStorage(), recorder),
|
||||
ListMediaUseCase: useCases.NewListMediaUseCase(env.images, env.articles, env.users),
|
||||
RenameMediaUseCase: useCases.NewRenameMediaUseCase(env.images),
|
||||
DeleteMediaUseCase: useCases.NewDeleteMediaUseCase(env.images, newMockImageStorage()),
|
||||
MergeMediaUseCase: useCases.NewMergeMediaUseCase(env.images, env.articles, newMockImageStorage()),
|
||||
RenameMediaUseCase: useCases.NewRenameMediaUseCase(env.images, recorder),
|
||||
DeleteMediaUseCase: useCases.NewDeleteMediaUseCase(env.images, newMockImageStorage(), recorder),
|
||||
MergeMediaUseCase: mergeMedia,
|
||||
RunPurgeUseCase: useCases.NewRunPurgeUseCase(env.images, env.articles, mergeMedia, purgeSettings, clock, log.New(io.Discard, "", 0), recorder),
|
||||
RequestRestartUseCase: useCases.NewRequestRestartUseCase(env.updates, restartJobs, &fakeHelperDetector{installed: true}, &fakeResultStore{}, &fakeRestartRequestStore{}, apiKeyRunningVersion, clock, recorder),
|
||||
GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(env.images, env.articles),
|
||||
GetSettingsUseCase: useCases.NewGetSettingsUseCase(apiKeyRunningVersion),
|
||||
GetActivityRetentionUseCase: useCases.NewGetActivityRetentionUseCase(newActivitySettingsFake(), time.Now),
|
||||
GetUpdateStatusUseCase: newUpdateStatusUseCase(env.updates, &fakeJobStore{}, &fakeHelperDetector{}, apiKeyRunningVersion),
|
||||
CheckForUpdateUseCase: useCases.NewCheckForUpdateUseCase(env.feed, env.updates, apiKeyRunningVersion, clock),
|
||||
CreateAPIKeyUseCase: useCases.NewCreateAPIKeyUseCase(env.keys, env.generator, clock),
|
||||
CheckForUpdateUseCase: useCases.NewCheckForUpdateUseCase(env.feed, env.updates, apiKeyRunningVersion, clock, recorder),
|
||||
CreateAPIKeyUseCase: useCases.NewCreateAPIKeyUseCase(env.keys, env.generator, clock, recorder),
|
||||
ListAPIKeysUseCase: useCases.NewListAPIKeysUseCase(env.keys, env.users, clock),
|
||||
RevokeAPIKeyUseCase: useCases.NewRevokeAPIKeyUseCase(env.keys, env.users, clock),
|
||||
RevokeAPIKeyUseCase: useCases.NewRevokeAPIKeyUseCase(env.keys, env.users, clock, recorder),
|
||||
AuthenticateAPIKeyUseCase: useCases.NewAuthenticateAPIKeyUseCase(env.keys, env.generator, env.users, clock),
|
||||
}
|
||||
router := chi.NewRouter()
|
||||
|
||||
+28
-28
@@ -221,9 +221,9 @@ func TestSHA256KeyGenerator(t *testing.T) {
|
||||
func TestCreateAPIKeyUseCase(t *testing.T) {
|
||||
t.Run("Use case: creating a key hashes it and stores no plaintext", func(t *testing.T) {
|
||||
repo := newMockAPIKeyRepo()
|
||||
uc := useCases.NewCreateAPIKeyUseCase(repo, &stubKeyGenerator{raw: "rcms_fake", prefix: "rcms_fake"}, apiKeyUnitClock)
|
||||
uc := useCases.NewCreateAPIKeyUseCase(repo, &stubKeyGenerator{raw: "rcms_fake", prefix: "rcms_fake"}, apiKeyUnitClock, discardRecorder)
|
||||
|
||||
created, err := uc.CreateAPIKey(useCases.CreateAPIKeyCommand{UserID: 2, Name: "ci"})
|
||||
created, err := uc.CreateAPIKey(testCtx, useCases.CreateAPIKeyCommand{UserID: 2, Name: "ci"})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
@@ -248,9 +248,9 @@ func TestCreateAPIKeyUseCase(t *testing.T) {
|
||||
t.Run("An expiry that is not in the future is refused and nothing is stored", func(t *testing.T) {
|
||||
for name, expiry := range map[string]time.Time{"in the past": apiKeyUnitNow.Add(-time.Hour), "exactly now": apiKeyUnitNow} {
|
||||
repo := newMockAPIKeyRepo()
|
||||
uc := useCases.NewCreateAPIKeyUseCase(repo, &stubKeyGenerator{raw: "rcms_fake", prefix: "rcms_fake"}, apiKeyUnitClock)
|
||||
uc := useCases.NewCreateAPIKeyUseCase(repo, &stubKeyGenerator{raw: "rcms_fake", prefix: "rcms_fake"}, apiKeyUnitClock, discardRecorder)
|
||||
|
||||
_, err := uc.CreateAPIKey(useCases.CreateAPIKeyCommand{UserID: 2, Name: "ci", ExpiresAt: &expiry})
|
||||
_, err := uc.CreateAPIKey(testCtx, useCases.CreateAPIKeyCommand{UserID: 2, Name: "ci", ExpiresAt: &expiry})
|
||||
if !errors.Is(err, apikey.ErrExpiryNotInFuture) {
|
||||
t.Errorf("%s: expected ErrExpiryNotInFuture, got %v", name, err)
|
||||
}
|
||||
@@ -263,9 +263,9 @@ func TestCreateAPIKeyUseCase(t *testing.T) {
|
||||
t.Run("A repository failure is returned", func(t *testing.T) {
|
||||
repo := newMockAPIKeyRepo()
|
||||
repo.fail.failNext("Create")
|
||||
uc := useCases.NewCreateAPIKeyUseCase(repo, &stubKeyGenerator{raw: "rcms_fake", prefix: "rcms_fake"}, apiKeyUnitClock)
|
||||
uc := useCases.NewCreateAPIKeyUseCase(repo, &stubKeyGenerator{raw: "rcms_fake", prefix: "rcms_fake"}, apiKeyUnitClock, discardRecorder)
|
||||
|
||||
if _, err := uc.CreateAPIKey(useCases.CreateAPIKeyCommand{UserID: 2, Name: "ci"}); !errors.Is(err, errRepositoryFailure) {
|
||||
if _, err := uc.CreateAPIKey(testCtx, useCases.CreateAPIKeyCommand{UserID: 2, Name: "ci"}); !errors.Is(err, errRepositoryFailure) {
|
||||
t.Errorf("expected the repository failure, got %v", err)
|
||||
}
|
||||
})
|
||||
@@ -486,9 +486,9 @@ func TestRevokeAPIKeyUseCase(t *testing.T) {
|
||||
t.Run("A creator revokes their own key at the clock's now", func(t *testing.T) {
|
||||
repo := newMockAPIKeyRepo()
|
||||
stored := seedStubKey(repo, "rcms_a", nil)
|
||||
uc := useCases.NewRevokeAPIKeyUseCase(repo, apiKeyUnitUsers(), apiKeyUnitClock)
|
||||
uc := useCases.NewRevokeAPIKeyUseCase(repo, apiKeyUnitUsers(), apiKeyUnitClock, discardRecorder)
|
||||
|
||||
if err := uc.RevokeAPIKey(2, stored.ID); err != nil {
|
||||
if err := uc.RevokeAPIKey(testCtx, 2, stored.ID); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got := repo.keys[stored.ID].RevokedAt; got == nil || !got.Equal(apiKeyUnitNow) {
|
||||
@@ -499,9 +499,9 @@ func TestRevokeAPIKeyUseCase(t *testing.T) {
|
||||
t.Run("Another admin gets not found and the key stays active", func(t *testing.T) {
|
||||
repo := newMockAPIKeyRepo()
|
||||
stored := seedStubKey(repo, "rcms_a", nil)
|
||||
uc := useCases.NewRevokeAPIKeyUseCase(repo, apiKeyUnitUsers(), apiKeyUnitClock)
|
||||
uc := useCases.NewRevokeAPIKeyUseCase(repo, apiKeyUnitUsers(), apiKeyUnitClock, discardRecorder)
|
||||
|
||||
if err := uc.RevokeAPIKey(3, stored.ID); !errors.Is(err, apikey.ErrAPIKeyNotFound) {
|
||||
if err := uc.RevokeAPIKey(testCtx, 3, stored.ID); !errors.Is(err, apikey.ErrAPIKeyNotFound) {
|
||||
t.Errorf("expected ErrAPIKeyNotFound, got %v", err)
|
||||
}
|
||||
if repo.keys[stored.ID].RevokedAt != nil || repo.revokeCalls != 0 {
|
||||
@@ -512,9 +512,9 @@ func TestRevokeAPIKeyUseCase(t *testing.T) {
|
||||
t.Run("The owner revokes any key", func(t *testing.T) {
|
||||
repo := newMockAPIKeyRepo()
|
||||
stored := seedStubKey(repo, "rcms_a", func(k *apikey.APIKey) { k.UserID = 3 })
|
||||
uc := useCases.NewRevokeAPIKeyUseCase(repo, apiKeyUnitUsers(), apiKeyUnitClock)
|
||||
uc := useCases.NewRevokeAPIKeyUseCase(repo, apiKeyUnitUsers(), apiKeyUnitClock, discardRecorder)
|
||||
|
||||
if err := uc.RevokeAPIKey(1, stored.ID); err != nil {
|
||||
if err := uc.RevokeAPIKey(testCtx, 1, stored.ID); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if repo.keys[stored.ID].RevokedAt == nil {
|
||||
@@ -526,9 +526,9 @@ func TestRevokeAPIKeyUseCase(t *testing.T) {
|
||||
repo := newMockAPIKeyRepo()
|
||||
original := apiKeyUnitNow.Add(-time.Hour)
|
||||
stored := seedStubKey(repo, "rcms_a", func(k *apikey.APIKey) { k.RevokedAt = &original })
|
||||
uc := useCases.NewRevokeAPIKeyUseCase(repo, apiKeyUnitUsers(), apiKeyUnitClock)
|
||||
uc := useCases.NewRevokeAPIKeyUseCase(repo, apiKeyUnitUsers(), apiKeyUnitClock, discardRecorder)
|
||||
|
||||
if err := uc.RevokeAPIKey(2, stored.ID); err != nil {
|
||||
if err := uc.RevokeAPIKey(testCtx, 2, stored.ID); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got := repo.keys[stored.ID].RevokedAt; got == nil || !got.Equal(original) {
|
||||
@@ -539,16 +539,16 @@ func TestRevokeAPIKeyUseCase(t *testing.T) {
|
||||
t.Run("An unknown key, an unknown requester and repository failures are returned", func(t *testing.T) {
|
||||
repo := newMockAPIKeyRepo()
|
||||
stored := seedStubKey(repo, "rcms_a", nil)
|
||||
uc := useCases.NewRevokeAPIKeyUseCase(repo, apiKeyUnitUsers(), apiKeyUnitClock)
|
||||
uc := useCases.NewRevokeAPIKeyUseCase(repo, apiKeyUnitUsers(), apiKeyUnitClock, discardRecorder)
|
||||
|
||||
if err := uc.RevokeAPIKey(2, 999); !errors.Is(err, apikey.ErrAPIKeyNotFound) {
|
||||
if err := uc.RevokeAPIKey(testCtx, 2, 999); !errors.Is(err, apikey.ErrAPIKeyNotFound) {
|
||||
t.Errorf("expected ErrAPIKeyNotFound, got %v", err)
|
||||
}
|
||||
if err := uc.RevokeAPIKey(99, stored.ID); !errors.Is(err, user.ErrUserNotFound) {
|
||||
if err := uc.RevokeAPIKey(testCtx, 99, stored.ID); !errors.Is(err, user.ErrUserNotFound) {
|
||||
t.Errorf("expected ErrUserNotFound, got %v", err)
|
||||
}
|
||||
repo.fail.failNext("Revoke")
|
||||
if err := uc.RevokeAPIKey(2, stored.ID); !errors.Is(err, errRepositoryFailure) {
|
||||
if err := uc.RevokeAPIKey(testCtx, 2, stored.ID); !errors.Is(err, errRepositoryFailure) {
|
||||
t.Errorf("expected the repository failure, got %v", err)
|
||||
}
|
||||
})
|
||||
@@ -566,9 +566,9 @@ func TestResetPasswordRevokesAPIKeys(t *testing.T) {
|
||||
keys := newMockAPIKeyRepo()
|
||||
seedStubKey(keys, "rcms_a", func(k *apikey.APIKey) { k.UserID = 2 })
|
||||
other := seedStubKey(keys, "rcms_c", func(k *apikey.APIKey) { k.UserID = 3 })
|
||||
uc := useCases.NewResetPasswordUseCase(resetUser(apiKeyUnitNow.Add(time.Hour)), &stubHasher{}, keys, apiKeyUnitClock)
|
||||
uc := useCases.NewResetPasswordUseCase(resetUser(apiKeyUnitNow.Add(time.Hour)), &stubHasher{}, keys, apiKeyUnitClock, discardRecorder)
|
||||
|
||||
if err := uc.ResetPassword("dev@example.com", "reset-code-1", "newpassword1"); err != nil {
|
||||
if err := uc.ResetPassword(testCtx, "dev@example.com", "reset-code-1", "newpassword1"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(keys.revokeAllCalls) != 1 || keys.revokeAllCalls[0].userId != 2 || !keys.revokeAllCalls[0].at.Equal(apiKeyUnitNow) {
|
||||
@@ -594,9 +594,9 @@ func TestResetPasswordRevokesAPIKeys(t *testing.T) {
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
keys := newMockAPIKeyRepo()
|
||||
uc := useCases.NewResetPasswordUseCase(resetUser(tc.expiration), &stubHasher{}, keys, apiKeyUnitClock)
|
||||
uc := useCases.NewResetPasswordUseCase(resetUser(tc.expiration), &stubHasher{}, keys, apiKeyUnitClock, discardRecorder)
|
||||
|
||||
if err := uc.ResetPassword(tc.email, tc.code, "newpassword1"); !errors.Is(err, tc.want) {
|
||||
if err := uc.ResetPassword(testCtx, tc.email, tc.code, "newpassword1"); !errors.Is(err, tc.want) {
|
||||
t.Errorf("expected %v, got %v", tc.want, err)
|
||||
}
|
||||
if len(keys.revokeAllCalls) != 0 {
|
||||
@@ -610,14 +610,14 @@ func TestResetPasswordRevokesAPIKeys(t *testing.T) {
|
||||
keys := newMockAPIKeyRepo()
|
||||
users := resetUser(apiKeyUnitNow.Add(time.Hour))
|
||||
users.fail.failNext("ResetPassword")
|
||||
uc := useCases.NewResetPasswordUseCase(users, &stubHasher{}, keys, apiKeyUnitClock)
|
||||
if err := uc.ResetPassword("dev@example.com", "reset-code-1", "newpassword1"); !errors.Is(err, errRepositoryFailure) {
|
||||
uc := useCases.NewResetPasswordUseCase(users, &stubHasher{}, keys, apiKeyUnitClock, discardRecorder)
|
||||
if err := uc.ResetPassword(testCtx, "dev@example.com", "reset-code-1", "newpassword1"); !errors.Is(err, errRepositoryFailure) {
|
||||
t.Errorf("expected the repository failure, got %v", err)
|
||||
}
|
||||
|
||||
hashErr := errors.New("hash failed")
|
||||
uc = useCases.NewResetPasswordUseCase(resetUser(apiKeyUnitNow.Add(time.Hour)), &stubHasher{hashErr: hashErr}, keys, apiKeyUnitClock)
|
||||
if err := uc.ResetPassword("dev@example.com", "reset-code-1", "newpassword1"); !errors.Is(err, hashErr) {
|
||||
uc = useCases.NewResetPasswordUseCase(resetUser(apiKeyUnitNow.Add(time.Hour)), &stubHasher{hashErr: hashErr}, keys, apiKeyUnitClock, discardRecorder)
|
||||
if err := uc.ResetPassword(testCtx, "dev@example.com", "reset-code-1", "newpassword1"); !errors.Is(err, hashErr) {
|
||||
t.Errorf("expected the hash error, got %v", err)
|
||||
}
|
||||
if len(keys.revokeAllCalls) != 0 {
|
||||
@@ -629,9 +629,9 @@ func TestResetPasswordRevokesAPIKeys(t *testing.T) {
|
||||
keys := newMockAPIKeyRepo()
|
||||
keys.fail.failNext("RevokeAllByUser")
|
||||
users := resetUser(apiKeyUnitNow.Add(time.Hour))
|
||||
uc := useCases.NewResetPasswordUseCase(users, &stubHasher{}, keys, apiKeyUnitClock)
|
||||
uc := useCases.NewResetPasswordUseCase(users, &stubHasher{}, keys, apiKeyUnitClock, discardRecorder)
|
||||
|
||||
err := uc.ResetPassword("dev@example.com", "reset-code-1", "newpassword1")
|
||||
err := uc.ResetPassword(testCtx, "dev@example.com", "reset-code-1", "newpassword1")
|
||||
if !errors.Is(err, errRepositoryFailure) {
|
||||
t.Errorf("expected the revoke failure, got %v", err)
|
||||
}
|
||||
|
||||
@@ -43,11 +43,11 @@ const (
|
||||
func newBodyFormatRouter(articleRepo *mockArticleRepo, userRepo *mockUserRepo, renderer domainArticle.BodyRenderer, token *jwtauth.JWTAuth) *chi.Mux {
|
||||
getUserUseCase := useCases.NewGetUserUseCase(userRepo)
|
||||
articleHandler := article.NewHandler(
|
||||
useCases.NewCreateArticleUseCase(articleRepo, renderer),
|
||||
useCases.NewCreateArticleUseCase(articleRepo, renderer, discardRecorder),
|
||||
useCases.NewGetArticleUseCase(articleRepo, renderer),
|
||||
useCases.NewListArticlesUseCase(articleRepo, renderer),
|
||||
useCases.NewDeleteArticleUseCase(articleRepo),
|
||||
useCases.NewUpdateArticleUseCase(articleRepo, renderer),
|
||||
useCases.NewDeleteArticleUseCase(articleRepo, discardRecorder),
|
||||
useCases.NewUpdateArticleUseCase(articleRepo, renderer, discardRecorder),
|
||||
getUserUseCase,
|
||||
)
|
||||
|
||||
|
||||
Loaded 100 of 207 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user