History retention: preview and password before keeping less
Shortening the retention deleted history at once and for good, with no
second look. Besides mistakes, it was a way to remove traces: anyone with an
open admin session could wipe the history of what they did.
Now (owner's decision 2026-11-30):
- PUT /api/v1/settings/app?dry_run=1 saves nothing and returns what the new
retention would remove (entries, backups, oldest entry left) and whether
it is shorter.
- A shorter retention (fewer days or entries) needs a recently confirmed
password (403 confirm_password, like deleting data, F-AUT-5). A longer one
removes nothing new and needs none.
- System page: Save on a shorter setting shows the preview first ("Removed
now: 237 entries and 17 backups; the oldest entry left is from …",
can't be undone); "Remove now" applies it, and the UI asks for the
password when needed. While the preview is open the fields are locked, so
what was previewed is what gets applied. When nothing would be removed now
the button says "Save shorter history".
- The daily trim stays automatic; it only removes what the confirmed
setting already lets expire.
Trim got a dry-run mode (journal and backups are only counted);
Retention.Shorter compares two retentions.
Tests: dry run changes nothing (configstore), Shorter (changes), API:
preview saves and removes nothing, shorter without a recent password is
refused and changes nothing, longer needs no password, after confirming it
applies (internal/server); e2e on CT 151 desktop + phone. Checked in a real
browser on CT 151 after the 5-minute window: the password dialog appears
("Shortening the change history needs your password again"), and after
confirming the setting is saved.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
335a4a9c0c
commit
e143730c53
15 files changed
+197
-38
No files matched your search
@@ -241,7 +241,7 @@ func run(listen, dataDir, adminGroup string, log *slog.Logger) error {
|
||||
if err != nil {
|
||||
log.Warn("reading settings for the history retention", "error", err)
|
||||
}
|
||||
if t, err := store.Trim(ctx, st.Retention()); err != nil {
|
||||
if t, err := store.Trim(ctx, st.Retention(), false); err != nil {
|
||||
log.Warn("trimming the change history", "error", err)
|
||||
} else if t.Removed > 0 || t.Backups > 0 {
|
||||
log.Info("change history trimmed", "entries", t.Removed, "backups", t.Backups)
|
||||
|
||||
@@ -118,7 +118,7 @@ Items marked ❓ depend on an open question in [README](README.md#open-questions
|
||||
| F-HIS-9 | **Audit-only** (never revertible): logins and failed logins, password changes, API key use/creation/revocation, data deletion, connections. Passwords and keys are never stored in the journal | M | MVP ✅ |
|
||||
| F-HIS-10 | Users/groups created or changed **on the command line** are detected and shown as "outside the UI" (audit only) | S | v1 |
|
||||
| F-HIS-11 | Filters (config / users / services / security / by hand), date range, search, paging on the server; the same through the API | S | MVP ✅ |
|
||||
| F-HIS-12 | **Retention:** the change history keeps entries for 365 days, at most 1,000 (defaults; set on the System page, through the API or in `settings.json`); older entries and the config backups older than them are removed at start and once a day (the newest 10 backups per file always stay); the trim itself is recorded. The history holds personal data (who changed what), so it is never kept forever (N-17) | S | MVP ✅ |
|
||||
| F-HIS-12 | **Retention:** the change history keeps entries for 365 days, at most 1,000 (defaults; set on the System page, through the API or in `settings.json`); older entries and the config backups older than them are removed at start and once a day (the newest 10 backups per file always stay); the trim itself is recorded. A **shorter** setting shows first what it would remove and needs the password again (F-AUT-5): it deletes history for good and could hide what someone did. The history holds personal data (who changed what), so it is never kept forever (N-17) | S | MVP ✅ |
|
||||
| F-HIS-13 | Tamper-evident audit log (hash chain), so a manipulated entry is detected | S | v1 |
|
||||
|
||||
### Quotas & usage
|
||||
|
||||
+4
-2
@@ -25,10 +25,12 @@ The web UI sets one cookie: the session (technically necessary, no consent neede
|
||||
## Change how long the history is kept
|
||||
|
||||
*System → Change history*: days (7–3,650) and the maximum number of entries (50–100,000). A shorter
|
||||
time applies at once.
|
||||
setting first shows what would be removed and needs your password again; it then applies at once.
|
||||
Removed entries can't be brought back.
|
||||
|
||||
For automation: `PUT /api/v1/settings/app` with `history_days` and `history_entries` (see the *API*
|
||||
page in the UI), or the same two values in `/var/lib/sharestead/settings.json`; a value edited in
|
||||
page in the UI; `?dry_run=1` shows what would be removed, a shorter setting needs a recently
|
||||
confirmed password), or the same two values in `/var/lib/sharestead/settings.json`; a value edited in
|
||||
the file applies at the next daily run or start.
|
||||
|
||||
✅ Check: *Changes* shows "Kept: the last … days, at most … entries".
|
||||
|
||||
@@ -356,14 +356,15 @@ const backupTime = "20060102T150405.000000000"
|
||||
// Trim applies a retention to the history (F-HIS-12): old journal entries
|
||||
// go, and backups older than the oldest entry left (at least the newest
|
||||
// keepBackups per file stay). What was removed is recorded as an audit entry.
|
||||
func (s *Store) Trim(_ context.Context, r changes.Retention) (changes.Trimmed, error) {
|
||||
// dryRun only counts what would be removed.
|
||||
func (s *Store) Trim(_ context.Context, r changes.Retention, dryRun bool) (changes.Trimmed, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
now := s.now()
|
||||
var t changes.Trimmed
|
||||
cutoff := now.Add(-r.MaxAge)
|
||||
if s.Journal != nil {
|
||||
removed, oldest, err := s.Journal.Trim(func(all []Entry) int { return r.Keep(all, now) })
|
||||
removed, oldest, err := s.Journal.Trim(func(all []Entry) int { return r.Keep(all, now) }, dryRun)
|
||||
if err != nil {
|
||||
return t, fmt.Errorf("trimming the change history: %w", err)
|
||||
}
|
||||
@@ -376,12 +377,12 @@ func (s *Store) Trim(_ context.Context, r changes.Retention) (changes.Trimmed, e
|
||||
}
|
||||
}
|
||||
}
|
||||
n, err := pruneBackups(s.BackupDir, cutoff, keepBackups)
|
||||
n, err := pruneBackups(s.BackupDir, cutoff, keepBackups, dryRun)
|
||||
t.Backups = n
|
||||
if err != nil {
|
||||
return t, fmt.Errorf("removing old backups: %w", err)
|
||||
}
|
||||
if (t.Removed > 0 || t.Backups > 0) && s.Journal != nil {
|
||||
if (t.Removed > 0 || t.Backups > 0) && s.Journal != nil && !dryRun {
|
||||
days := int(r.MaxAge / (24 * time.Hour))
|
||||
summary := fmt.Sprintf("Change history trimmed: %d entries and %d backups removed (kept: the last %d days, at most %d entries)", t.Removed, t.Backups, days, r.MaxEntries)
|
||||
if err := s.Journal.Append(Entry{ID: now.Format("20060102T150405.000000"), Time: now, Actor: Retention, Summary: summary, Kind: changes.KindAudit}); err != nil {
|
||||
@@ -392,8 +393,8 @@ func (s *Store) Trim(_ context.Context, r changes.Retention) (changes.Trimmed, e
|
||||
}
|
||||
|
||||
// pruneBackups removes backups made before cutoff, keeping the newest keep
|
||||
// of every file. Files whose name doesn't end in a backup timestamp stay.
|
||||
func pruneBackups(dir string, cutoff time.Time, keep int) (int, error) {
|
||||
// of every file (dryRun: only counts them). Files whose name doesn't end in a backup timestamp stay.
|
||||
func pruneBackups(dir string, cutoff time.Time, keep int, dryRun bool) (int, error) {
|
||||
if dir == "" {
|
||||
return 0, nil
|
||||
}
|
||||
@@ -428,8 +429,10 @@ func pruneBackups(dir string, cutoff time.Time, keep int) (int, error) {
|
||||
if i < keep || !b.at.Before(cutoff) {
|
||||
continue
|
||||
}
|
||||
if err := os.Remove(filepath.Join(dir, b.name)); err != nil {
|
||||
return removed, err
|
||||
if !dryRun {
|
||||
if err := os.Remove(filepath.Join(dir, b.name)); err != nil {
|
||||
return removed, err
|
||||
}
|
||||
}
|
||||
removed++
|
||||
}
|
||||
|
||||
@@ -85,8 +85,9 @@ func (j *Journal) Get(id string) (Entry, bool, error) {
|
||||
// Trim removes the oldest entries: keepFrom gets all entries, oldest first,
|
||||
// and returns the index of the first one that stays. The file is rewritten
|
||||
// atomically, so a crash leaves either the old or the new journal. It
|
||||
// returns the number removed and the oldest entry left (nil: none).
|
||||
func (j *Journal) Trim(keepFrom func(all []Entry) int) (int, *Entry, error) {
|
||||
// returns the number removed and the oldest entry left (nil: none); with
|
||||
// dryRun nothing is written.
|
||||
func (j *Journal) Trim(keepFrom func(all []Entry) int, dryRun bool) (int, *Entry, error) {
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
f, err := os.Open(j.Path)
|
||||
@@ -114,8 +115,8 @@ func (j *Journal) Trim(keepFrom func(all []Entry) int) (int, *Entry, error) {
|
||||
if from < len(all) {
|
||||
oldest = &all[from]
|
||||
}
|
||||
if from == 0 {
|
||||
return 0, oldest, nil
|
||||
if from == 0 || dryRun {
|
||||
return from, oldest, nil
|
||||
}
|
||||
var buf []byte
|
||||
for _, e := range all[from:] {
|
||||
|
||||
@@ -49,7 +49,7 @@ func backups(t *testing.T, e *env) int {
|
||||
func TestTrimByAgeKeepsTheRestUndoable(t *testing.T) {
|
||||
e, _ := history(t, 400, 380, 10, 1)
|
||||
year, _ := changes.NewRetention(365, 1000)
|
||||
tr, err := e.store.Trim(context.Background(), year)
|
||||
tr, err := e.store.Trim(context.Background(), year, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -75,7 +75,7 @@ func TestTrimByAgeKeepsTheRestUndoable(t *testing.T) {
|
||||
func TestTrimByCountAndNothingToDo(t *testing.T) {
|
||||
e, _ := history(t, 5, 4, 3, 2, 1)
|
||||
r := changes.Retention{MaxAge: 365 * 24 * time.Hour, MaxEntries: 2}
|
||||
tr, err := e.store.Trim(context.Background(), r)
|
||||
tr, err := e.store.Trim(context.Background(), r, false)
|
||||
if err != nil || tr.Removed != 3 {
|
||||
t.Fatalf("trimmed = %+v, %v", tr, err)
|
||||
}
|
||||
@@ -84,7 +84,7 @@ func TestTrimByCountAndNothingToDo(t *testing.T) {
|
||||
t.Errorf("entries = %d, want 2 kept + 1 audit entry", n)
|
||||
}
|
||||
e2, _ := history(t, 3, 2)
|
||||
tr, err = e2.store.Trim(context.Background(), r)
|
||||
tr, err = e2.store.Trim(context.Background(), r, false)
|
||||
if err != nil || tr.Removed != 0 || tr.Backups != 0 {
|
||||
t.Errorf("nothing to trim: %+v %v", tr, err)
|
||||
}
|
||||
@@ -105,7 +105,7 @@ func TestTrimRemovesOldBackupsButKeepsTheNewest(t *testing.T) {
|
||||
t.Fatalf("backups before = %d", backups(t, e))
|
||||
}
|
||||
week, _ := changes.NewRetention(7, 1000)
|
||||
tr, err := e.store.Trim(context.Background(), week)
|
||||
tr, err := e.store.Trim(context.Background(), week, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -119,7 +119,7 @@ func TestTrimRemovesOldBackupsButKeepsTheNewest(t *testing.T) {
|
||||
if err := os.WriteFile(other, []byte("x"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := e.store.Trim(context.Background(), changes.Retention{MaxAge: time.Hour, MaxEntries: 50}); err != nil {
|
||||
if _, err := e.store.Trim(context.Background(), changes.Retention{MaxAge: time.Hour, MaxEntries: 50}, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(other); err != nil {
|
||||
@@ -129,11 +129,11 @@ func TestTrimRemovesOldBackupsButKeepsTheNewest(t *testing.T) {
|
||||
|
||||
func TestTrimWithoutJournalOrBackups(t *testing.T) {
|
||||
s := &Store{}
|
||||
if tr, err := s.Trim(context.Background(), changes.Retention{MaxAge: time.Hour, MaxEntries: 50}); err != nil || tr.Removed != 0 {
|
||||
if tr, err := s.Trim(context.Background(), changes.Retention{MaxAge: time.Hour, MaxEntries: 50}, false); err != nil || tr.Removed != 0 {
|
||||
t.Errorf("empty store: %+v %v", tr, err)
|
||||
}
|
||||
j := &Journal{Path: filepath.Join(t.TempDir(), "none.jsonl")}
|
||||
if n, oldest, err := j.Trim(func([]Entry) int { return 0 }); n != 0 || oldest != nil || err != nil {
|
||||
if n, oldest, err := j.Trim(func([]Entry) int { return 0 }, false); n != 0 || oldest != nil || err != nil {
|
||||
t.Errorf("missing journal: %d %v %v", n, oldest, err)
|
||||
}
|
||||
}
|
||||
@@ -145,7 +145,7 @@ func TestTrimDropsUnreadableLines(t *testing.T) {
|
||||
f, _ := os.OpenFile(e.path("journal.jsonl"), os.O_APPEND|os.O_WRONLY, 0)
|
||||
_, _ = f.WriteString("{broken\n")
|
||||
f.Close()
|
||||
n, oldest, err := e.store.Journal.Trim(func(all []Entry) int { return 1 })
|
||||
n, oldest, err := e.store.Journal.Trim(func(all []Entry) int { return 1 }, false)
|
||||
if err != nil || n != 1 || oldest == nil || oldest.Summary != "change b" {
|
||||
t.Fatalf("trim = %d %+v %v", n, oldest, err)
|
||||
}
|
||||
@@ -156,3 +156,22 @@ func TestTrimDropsUnreadableLines(t *testing.T) {
|
||||
t.Errorf("journal mode = %v, want 0600 (it holds config contents)", st.Mode().Perm())
|
||||
}
|
||||
}
|
||||
|
||||
// A dry run counts what a trim would remove and changes nothing.
|
||||
func TestTrimDryRunChangesNothing(t *testing.T) {
|
||||
ages := []int{}
|
||||
for d := 30; d >= 1; d-- {
|
||||
ages = append(ages, d)
|
||||
}
|
||||
e, _ := history(t, ages...)
|
||||
before, _ := os.ReadFile(e.path("journal.jsonl"))
|
||||
week, _ := changes.NewRetention(7, 1000)
|
||||
tr, err := e.store.Trim(context.Background(), week, true)
|
||||
if err != nil || tr.Removed != 23 || tr.Backups != 20 {
|
||||
t.Fatalf("dry run = %+v %v, want 23 entries and 20 backups counted", tr, err)
|
||||
}
|
||||
after, _ := os.ReadFile(e.path("journal.jsonl"))
|
||||
if string(before) != string(after) || backups(t, e) != 30 {
|
||||
t.Error("the dry run changed the journal or removed backups")
|
||||
}
|
||||
}
|
||||
@@ -59,7 +59,14 @@ type Trimmed struct {
|
||||
Oldest *time.Time `json:"oldest,omitempty"` // the oldest entry left
|
||||
}
|
||||
|
||||
// Trimmer applies a retention to the history (the config store).
|
||||
// Trimmer applies a retention to the history (the config store). With
|
||||
// dryRun it only counts what would be removed.
|
||||
type Trimmer interface {
|
||||
Trim(ctx context.Context, r Retention) (Trimmed, error)
|
||||
Trim(ctx context.Context, r Retention, dryRun bool) (Trimmed, error)
|
||||
}
|
||||
|
||||
// Shorter reports whether r keeps less than old (fewer days or entries):
|
||||
// applying it removes history that old would still keep.
|
||||
func (r Retention) Shorter(old Retention) bool {
|
||||
return r.MaxAge < old.MaxAge || r.MaxEntries < old.MaxEntries
|
||||
}
|
||||
@@ -49,3 +49,17 @@ func TestNewRetentionBounds(t *testing.T) {
|
||||
t.Errorf("bounds themselves are allowed: %+v %v", r, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A retention is shorter when it keeps fewer days or fewer entries.
|
||||
func TestShorter(t *testing.T) {
|
||||
year, _ := NewRetention(365, 1000)
|
||||
for _, c := range []struct {
|
||||
days, entries int
|
||||
want bool
|
||||
}{{365, 1000, false}, {400, 1000, false}, {300, 1000, true}, {365, 999, true}, {400, 500, true}} {
|
||||
r, _ := NewRetention(c.days, c.entries)
|
||||
if got := r.Shorter(year); got != c.want {
|
||||
t.Errorf("%d days, %d entries: shorter = %v", c.days, c.entries, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,12 +10,13 @@ import (
|
||||
|
||||
"sharestead/internal/app/changes"
|
||||
"sharestead/internal/app/settings"
|
||||
"sharestead/internal/auth"
|
||||
)
|
||||
|
||||
// historyWorld has a journal with entries 400, 200 and 10 days old.
|
||||
func historyWorld(t *testing.T) *world {
|
||||
func historyWorld(t *testing.T, more ...func(*Deps)) *world {
|
||||
t.Helper()
|
||||
w := newWorld(t, func(d *Deps) { d.Settings = &settings.Store{Files: memSettings{}, Path: "/s.json"} })
|
||||
w := newWorld(t, append([]func(*Deps){func(d *Deps) { d.Settings = &settings.Store{Files: memSettings{}, Path: "/s.json"} }}, more...)...)
|
||||
var lines []byte
|
||||
for _, days := range []int{400, 200, 10} {
|
||||
at := time.Now().Add(-time.Duration(days) * 24 * time.Hour)
|
||||
@@ -100,3 +101,52 @@ func TestHistoryRetentionBounds(t *testing.T) {
|
||||
t.Error("a refused value trimmed the history")
|
||||
}
|
||||
}
|
||||
|
||||
// Shortening the history deletes it for good: preview first (nothing is
|
||||
// saved or removed), then only with the password again (F-AUT-5). A longer
|
||||
// retention removes nothing and needs no password.
|
||||
func TestShorterHistoryNeedsPreviewAndPassword(t *testing.T) {
|
||||
now := time.Now()
|
||||
w := historyWorld(t, func(d *Deps) {
|
||||
d.Auth = auth.NewService(fakeAuthn{}, auth.Config{Now: func() time.Time { return now }})
|
||||
})
|
||||
now = now.Add(6 * time.Minute) // the password from the login is no longer recent
|
||||
oldest := func() float64 {
|
||||
var k keptAnswer
|
||||
w.call("GET", "/api/v1/changes", nil).json(t, &k)
|
||||
o, _ := time.Parse(time.RFC3339, *k.Kept.Oldest)
|
||||
return time.Since(o).Hours() / 24
|
||||
}
|
||||
var got struct {
|
||||
appSettings
|
||||
Trimmed *changes.Trimmed
|
||||
Shorter bool
|
||||
}
|
||||
r := w.call("PUT", "/api/v1/settings/app?dry_run=1", map[string]any{"history_days": 300})
|
||||
r.json(t, &got)
|
||||
if r.Code != 200 || !got.Shorter || got.Trimmed == nil || got.Trimmed.Removed != 1 || got.HistoryDays != 300 {
|
||||
t.Fatalf("preview: %d %s", r.Code, r.Body)
|
||||
}
|
||||
var s appSettings
|
||||
w.call("GET", "/api/v1/settings/app", nil).json(t, &s)
|
||||
if s.HistoryDays != 365 || oldest() < 399 {
|
||||
t.Fatalf("the preview saved or removed something: %+v, oldest %.0f days", s, oldest())
|
||||
}
|
||||
if r := w.call("PUT", "/api/v1/settings/app", map[string]any{"history_days": 300}); r.Code != 403 || r.problemCode() != "confirm_password" {
|
||||
t.Fatalf("shorter without a recent password: %d %s", r.Code, r.Body)
|
||||
}
|
||||
if w.call("GET", "/api/v1/settings/app", nil).json(t, &s); s.HistoryDays != 365 || oldest() < 399 {
|
||||
t.Fatalf("refused change was applied: %+v", s)
|
||||
}
|
||||
if r := w.call("PUT", "/api/v1/settings/app", map[string]any{"history_days": 500}); r.Code != 200 || strings.Contains(r.Body, `"shorter":true`) {
|
||||
t.Fatalf("longer retention: %d %s", r.Code, r.Body)
|
||||
}
|
||||
if r := w.call("POST", "/api/v1/auth/confirm", map[string]any{"password": "pw"}); r.Code != 204 {
|
||||
t.Fatalf("confirm: %d %s", r.Code, r.Body)
|
||||
}
|
||||
r = w.call("PUT", "/api/v1/settings/app", map[string]any{"history_days": 300})
|
||||
r.json(t, &got)
|
||||
if r.Code != 200 || got.Trimmed == nil || got.Trimmed.Removed != 1 || oldest() > 201 {
|
||||
t.Fatalf("after confirming: %d %s, oldest %.0f days", r.Code, r.Body, oldest())
|
||||
}
|
||||
}
|
||||
@@ -63,7 +63,7 @@ var apiDocs = map[string]opDoc{
|
||||
"GET /api/v1/settings/samba": {Tag: "Settings", Summary: "Server-wide Samba settings", Response: share.GlobalValues{}},
|
||||
"PUT /api/v1/settings/samba": {Tag: "Settings", Summary: "Change server-wide Samba settings", Request: setSambaSettingsRequest{}, Response: editResponse{}, Edit: true},
|
||||
"GET /api/v1/settings/app": {Tag: "Settings", Summary: "Sharestead's own settings", Response: appSettings{}},
|
||||
"PUT /api/v1/settings/app": {Tag: "Settings", Summary: "Change Sharestead's own settings", Description: "Switching self-service off ends all user sessions. A new change history retention (history_days, history_entries) applies right away: older entries and their backups are removed (trimmed).", Request: setAppSettingsRequest{}, Response: appSettingsChanged{}},
|
||||
"PUT /api/v1/settings/app": {Tag: "Settings", Summary: "Change Sharestead's own settings", Description: "Switching self-service off ends all user sessions. A new change history retention (history_days, history_entries) applies right away: older entries and their backups are removed (trimmed). ?dry_run=1 saves nothing and returns what would be removed. A shorter retention (fewer days or entries) needs the password again (403 confirm_password).", Request: setAppSettingsRequest{}, Response: appSettingsChanged{}, Confirm: true, Query: []queryParam{dryRunParam}},
|
||||
"GET /api/v1/changes": {Tag: "Changes", Summary: "Change history", Description: "Every change made here or by hand in a managed file, newest first, with the lines changed. Filtered and paged on the server. kept says how long the history is kept and how far back it goes.", Response: changesList{}, Query: []queryParam{
|
||||
{Name: "q", Description: "text in the summary, the actor or a file path (case-insensitive)"},
|
||||
{Name: "kind", Description: "config: can be undone; hand: made outside Sharestead; audit: recorded only", Schema: map[string]any{"type": "string", "enum": []string{"all", "config", "hand", "audit"}, "default": "all"}},
|
||||
|
||||
@@ -160,6 +160,6 @@ func (emptyStore) Restore(context.Context, string, string, string, bool, map[str
|
||||
}
|
||||
func (emptyStore) Record(string, string) error { return nil }
|
||||
func (emptyStore) Sync(context.Context) error { return nil }
|
||||
func (emptyStore) Trim(context.Context, changes.Retention) (changes.Trimmed, error) {
|
||||
func (emptyStore) Trim(context.Context, changes.Retention, bool) (changes.Trimmed, error) {
|
||||
return changes.Trimmed{}, nil
|
||||
}
|
||||
@@ -61,8 +61,12 @@ type setAppSettingsRequest struct {
|
||||
type appSettingsChanged struct {
|
||||
appSettings
|
||||
SessionsEnded int `json:"sessions_ended"` // user sessions ended because self-service was switched off
|
||||
// Trimmed: what the new history retention removed right away.
|
||||
// Trimmed: what the new history retention removed right away (with
|
||||
// dry_run: what it would remove; nothing is saved then).
|
||||
Trimmed *changes.Trimmed `json:"trimmed,omitempty"`
|
||||
// Shorter: the new retention keeps less history than before; applying
|
||||
// it needs the password again (it deletes history for good).
|
||||
Shorter bool `json:"shorter,omitempty"`
|
||||
}
|
||||
|
||||
func (a *api) setAppSettings(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -87,6 +91,29 @@ func (a *api) setAppSettings(w http.ResponseWriter, r *http.Request) {
|
||||
problem(w, http.StatusBadRequest, "invalid_input", "Please check the history settings", fmt.Sprintf("Keep the history %d to %d days, with %d to %d entries — nothing was changed.", changes.MinHistoryDays, changes.MaxHistoryDays, changes.MinHistoryEntries, changes.MaxHistoryEntries), nil)
|
||||
return
|
||||
}
|
||||
// Shortening the history deletes entries for good (and could hide what
|
||||
// someone did): preview first, then only with the password again.
|
||||
shorter := retention.Shorter(before.Retention())
|
||||
if dryRun(r) {
|
||||
preview := before
|
||||
if in.SelfService != nil {
|
||||
preview.SelfService = in.SelfService
|
||||
}
|
||||
if in.HomeByDefault != nil {
|
||||
preview.HomeByDefault = in.HomeByDefault
|
||||
}
|
||||
preview.HistoryDays, preview.HistoryEntries = &days, &entries
|
||||
t, err := a.store.Trim(r.Context(), retention, true)
|
||||
if err != nil {
|
||||
problem(w, http.StatusInternalServerError, "journal_unreadable", "The change history couldn’t be read", err.Error()+" — nothing was changed.", nil)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, appSettingsChanged{appSettings: toAppSettings(preview), Trimmed: &t, Shorter: shorter})
|
||||
return
|
||||
}
|
||||
if shorter && a.needsConfirm(w, r, "Shortening the change history") {
|
||||
return
|
||||
}
|
||||
st, err := a.settings.Update(func(s *settings.Settings) {
|
||||
if in.SelfService != nil {
|
||||
s.SelfService = in.SelfService
|
||||
@@ -127,14 +154,14 @@ func (a *api) setAppSettings(w http.ResponseWriter, r *http.Request) {
|
||||
if bd, be := before.History(); bd != days || be != entries {
|
||||
a.audit(r, fmt.Sprintf("change history: %d days, %d entries", days, entries), "", nil)
|
||||
a.record(r, fmt.Sprintf("Change history kept for %d days, at most %d entries", days, entries), nil)
|
||||
t, err := a.store.Trim(r.Context(), retention)
|
||||
t, err := a.store.Trim(r.Context(), retention, false)
|
||||
if err != nil {
|
||||
a.log.Warn("trimming the change history", "error", err)
|
||||
} else {
|
||||
trimmed = &t
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, appSettingsChanged{toAppSettings(st), ended, trimmed})
|
||||
writeJSON(w, http.StatusOK, appSettingsChanged{appSettings: toAppSettings(st), SessionsEnded: ended, Trimmed: trimmed, Shorter: shorter})
|
||||
}
|
||||
|
||||
// selfServiceOff refuses self-service routes for normal users while
|
||||
|
||||
@@ -851,9 +851,17 @@ test('change history retention: set on the System page, shown on Changes (F-HIS-
|
||||
await openNav(page, 'Changes', isMobile);
|
||||
await expect(page.getByText(/Kept: the last 3,000 days, at most [\d,]+ entries/)).toBeVisible();
|
||||
await expect(page.getByText(/Change history kept for 3000 days/).first()).toBeVisible();
|
||||
await openNav(page, 'System', isMobile); // back as it was
|
||||
await openNav(page, 'System', isMobile); // back as it was: shorter, so preview and confirm first
|
||||
await days.fill(before);
|
||||
await card.getByRole('button', { name: 'Save' }).click();
|
||||
await expect(card.getByRole('alert')).toContainText('This keeps less history.');
|
||||
await expect(days).toBeDisabled(); // what was previewed is what is applied
|
||||
await card.getByRole('button', { name: /^(Remove now|Save shorter history)$/ }).click();
|
||||
const pw = page.getByRole('dialog');
|
||||
if (await pw.isVisible().catch(() => false)) { // the password was entered more than a few minutes ago
|
||||
await pw.getByLabel('Password').fill(pass);
|
||||
await pw.getByRole('button', { name: /Confirm/ }).click();
|
||||
}
|
||||
await expect(card.getByRole('status')).toContainText('Saved.');
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
+2
-1
@@ -152,7 +152,8 @@ export const api = {
|
||||
me: () => request<Me>('GET', '/api/v1/me'),
|
||||
setMyPassword: (current: string, next: string) => request<void>('PUT', '/api/v1/me/password', { current, new: next }),
|
||||
appSettings: () => request<AppSettings>('GET', '/api/v1/settings/app'),
|
||||
setAppSettings: (s: Partial<AppSettings>) => request<AppSettings & { sessions_ended: number; trimmed?: { removed: number; backups_removed: number } }>('PUT', '/api/v1/settings/app', s),
|
||||
setAppSettings: (s: Partial<AppSettings>, dry = false) =>
|
||||
request<AppSettings & { sessions_ended: number; shorter?: boolean; trimmed?: { removed: number; backups_removed: number; oldest?: string } }>('PUT', '/api/v1/settings/app' + (dry ? '?dry_run=1' : ''), s),
|
||||
storage: () => request<StorageReport>('GET', '/api/v1/storage'),
|
||||
storageBackground: () => background<StorageReport>('/api/v1/storage'),
|
||||
measureStorage: () => request<void>('POST', '/api/v1/storage/scan'),
|
||||
|
||||
@@ -43,11 +43,20 @@
|
||||
let histOk = $state('');
|
||||
let histProblem = $state<Problem | null>(null);
|
||||
const histValid = $derived(Number.isInteger(histDays) && histDays >= 7 && histDays <= 3650 && Number.isInteger(histEntries) && histEntries >= 50 && histEntries <= 100000);
|
||||
// A shorter retention deletes history for good: preview what goes, then
|
||||
// "Remove now" (the server asks for the password again).
|
||||
let histPreview = $state<{ removed: number; backups_removed: number; oldest?: string } | null>(null);
|
||||
async function saveHistory(e: SubmitEvent) {
|
||||
e.preventDefault();
|
||||
histBusy = true; histProblem = null; histOk = '';
|
||||
try {
|
||||
if (!histPreview && (histDays < histSaved.days || histEntries < histSaved.entries)) {
|
||||
const p = await api.setAppSettings({ history_days: histDays, history_entries: histEntries }, true);
|
||||
histPreview = p.trimmed ?? { removed: 0, backups_removed: 0 };
|
||||
return;
|
||||
}
|
||||
const r = await api.setAppSettings({ history_days: histDays, history_entries: histEntries });
|
||||
histPreview = null;
|
||||
histSaved = { days: r.history_days, entries: r.history_entries };
|
||||
const t = r.trimmed;
|
||||
histOk = 'Saved.' + (t && (t.removed || t.backups_removed) ? ` Removed right away: ${t.removed} older entries and ${t.backups_removed} backups.` : '');
|
||||
@@ -178,11 +187,27 @@
|
||||
<p class="muted small desc">How long Sharestead keeps the change history and the backups of config files. Older entries are removed once a day.</p>
|
||||
<div class="row wrap hist">
|
||||
<div><FieldLabel for="hist-days" term="retention">Keep for (days)</FieldLabel>
|
||||
<input class="t num" id="hist-days" type="number" min="7" max="3650" step="1" bind:value={histDays} disabled={histSaved.days === 0} /></div>
|
||||
<input class="t num" id="hist-days" type="number" min="7" max="3650" step="1" bind:value={histDays} disabled={histSaved.days === 0 || !!histPreview} /></div>
|
||||
<div><FieldLabel for="hist-entries">At most (entries)</FieldLabel>
|
||||
<input class="t num" id="hist-entries" type="number" min="50" max="100000" step="1" bind:value={histEntries} disabled={histSaved.days === 0} /></div>
|
||||
<button class="btn primary" type="submit" disabled={histBusy || !histValid || (histDays === histSaved.days && histEntries === histSaved.entries)}>{histBusy ? 'Saving…' : 'Save'}</button>
|
||||
<input class="t num" id="hist-entries" type="number" min="50" max="100000" step="1" bind:value={histEntries} disabled={histSaved.days === 0 || !!histPreview} /></div>
|
||||
{#if !histPreview}<button class="btn primary" type="submit" disabled={histBusy || !histValid || (histDays === histSaved.days && histEntries === histSaved.entries)}>{histBusy ? 'Saving…' : 'Save'}</button>{/if}
|
||||
</div>
|
||||
{#if histPreview}
|
||||
<div class="confirm-box" role="alert">
|
||||
<p><b>This keeps less history.</b>
|
||||
{#if histPreview.removed || histPreview.backups_removed}
|
||||
Removed now: {histPreview.removed.toLocaleString()} {histPreview.removed === 1 ? 'entry' : 'entries'} and {histPreview.backups_removed.toLocaleString()} {histPreview.backups_removed === 1 ? 'backup' : 'backups'}{#if histPreview.oldest}; the oldest entry left is from {new Date(histPreview.oldest).toLocaleDateString()}{/if}.
|
||||
This can’t be undone, and those changes can’t be undone any more either.
|
||||
{:else}
|
||||
Nothing is removed now. From now on, entries are removed for good once they pass the new limit.
|
||||
{/if}</p>
|
||||
<div class="row end">
|
||||
<button class="btn" type="button" onclick={() => (histPreview = null)} disabled={histBusy}>Cancel</button>
|
||||
<button class="btn danger solid" type="submit" disabled={histBusy}>{histBusy ? 'Saving…' : histPreview.removed || histPreview.backups_removed ? 'Remove now' : 'Save shorter history'}</button>
|
||||
</div>
|
||||
<p class="facts">You’ll be asked for your password.</p>
|
||||
</div>
|
||||
{/if}
|
||||
{#if !histValid && histSaved.days}<p class="small warnline" role="status">7–3,650 days and 50–100,000 entries.</p>{/if}
|
||||
<p class="facts">The history holds user names and who changed what — personal data. Keep it only as long as you need it (GDPR: storage limitation). Default: 365 days, 1,000 entries.</p>
|
||||
<Notice ok={histOk} problem={histProblem} />
|
||||
@@ -212,4 +237,6 @@
|
||||
.hist { align-items: flex-end; gap: 12px; }
|
||||
.num { width: 140px; }
|
||||
.warnline { color: var(--warn); }
|
||||
.confirm-box { margin-top: 12px; padding: 12px 14px; border: 1px solid var(--bad); border-radius: 8px; background: var(--bad-soft); }
|
||||
.confirm-box p { margin: 0 0 8px; }
|
||||
</style>
|
||||
Reference in new issue
Block a user