Change history retention (F-HIS-12) and a privacy page (GDPR)
ci / test-guard (pull_request) Successful in 3s
ci / go (pull_request) Successful in 3m26s
ci / package (pull_request) Successful in 2m18s
ci / install-test (debian:12) (pull_request) Successful in 1m12s
ci / install-test (debian:13) (pull_request) Successful in 1m28s
ci / smb (pull_request) Successful in 1m35s
ci / e2e (pull_request) Successful in 3m3s
ci / test-guard (pull_request) Successful in 3s
ci / go (pull_request) Successful in 3m26s
ci / package (pull_request) Successful in 2m18s
ci / install-test (debian:12) (pull_request) Successful in 1m12s
ci / install-test (debian:13) (pull_request) Successful in 1m28s
ci / smb (pull_request) Successful in 1m35s
ci / e2e (pull_request) Successful in 3m3s
The change journal and the config backups grew forever: every entry holds the full content of the changed files, and every change left a backup copy. The history also holds personal data (who changed what, user names), which the GDPR's storage limitation says not to keep longer than needed. Retention, owner's decision 2026-11-30: - Entries older than 365 days go, and of the rest at most the newest 1,000 stay (whichever is reached first). Both values are app settings: System page, PUT /api/v1/settings/app (history_days 7–3650, history_entries 50–100000) or settings.json; out-of-range values in the file fall back to the defaults, never to "keep forever". - Applied at start, once a day, and right away when the setting changes. The journal is rewritten atomically (temp file + rename), so a crash leaves the old or the new file; unreadable lines, already ignored, are dropped. - Backups older than the oldest kept entry go; the newest 10 per file always stay. Backup names now carry a UTC timestamp, so writing and reading them agree in every time zone. - What a trim removed is itself an audit entry; the setting change too. - The Changes page says how long the history is kept and how far back it goes (GET /api/v1/changes → kept). Privacy: docs/privacy.md lists what personal data Sharestead keeps, where, for how long and how to delete it (incl. when someone leaves), and that it sends nothing anywhere. N-17 in the requirements; README links to it. 03-solution-design: retention row added; the user/group undo row now says audit only (F-HIS-8 was dropped). Tests: retention rules (changes, 98%), journal and backup trimming on real files incl. undo after a trim and unrelated files kept (configstore), settings defaults and fallback, API (defaults, trim on change, bounds, history entries); e2e on CT 151 (desktop + phone), axe unchanged. Checked on CT 151: history_entries 50 trimmed 286 → 51 entries and 43 → 26 backups, journal still 0600. Coverage minimums raised (total 77, server 85, auth 95). Test changed because: web/e2e/fixtures/base.json is a recorded API answer that fixtures_test.go checks against the API description; GET /api/v1/settings/app and GET /api/v1/changes now have the required fields history_days/history_entries and kept. Only those fields were added (two existing lines got a trailing comma); no expectation changed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
dd3272b771
commit
335a4a9c0c
27 files changed
+829
-23
No files matched your search
+3
-3
@@ -1,9 +1,9 @@
|
||||
# Minimum test coverage in %, checked by scripts/coverage-check.sh in CI.
|
||||
# Raise a number when coverage went up (CI prints the new value); never lower it
|
||||
# without a reason in the commit message.
|
||||
total 76.0
|
||||
internal/server 83.0
|
||||
internal/auth 93.0
|
||||
total 77.0
|
||||
internal/server 85.0
|
||||
internal/auth 95.0
|
||||
internal/domain/share 89.0
|
||||
internal/rootfs 83.0
|
||||
internal/adapters/osfs 81.0
|
||||
|
||||
@@ -23,6 +23,8 @@ truth: changes made by hand keep working and show up in the UI.
|
||||
| **Problems** | Checks of the configuration and the system, each with cause and fix. Missing system features (e.g. no ACLs in a container) are explained once and can be acknowledged. Diagnostic bundle for bug reports, with passwords removed |
|
||||
| **API** | Everything the UI does, as a REST API described in OpenAPI 3.1 (*API* page in the UI) |
|
||||
|
||||
What personal data Sharestead keeps, for how long, and how to delete it: [privacy](docs/privacy.md).
|
||||
|
||||
Sharestead deliberately doesn't manage disks, RAID or ZFS pools, run apps or VMs, or act as an
|
||||
Active Directory domain controller — see [what we won't do](docs/planning/06-outlook.md).
|
||||
|
||||
|
||||
@@ -233,6 +233,32 @@ func run(listen, dataDir, adminGroup string, log *slog.Logger) error {
|
||||
}
|
||||
}
|
||||
}()
|
||||
// The change history is kept only as long as set (F-HIS-12): at start
|
||||
// and once a day.
|
||||
go func() {
|
||||
trim := func() {
|
||||
st, err := appSettings.Get()
|
||||
if err != nil {
|
||||
log.Warn("reading settings for the history retention", "error", err)
|
||||
}
|
||||
if t, err := store.Trim(ctx, st.Retention()); 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)
|
||||
}
|
||||
}
|
||||
trim()
|
||||
t := time.NewTicker(24 * time.Hour)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
trim()
|
||||
}
|
||||
}
|
||||
}()
|
||||
return server.New(listen, cert, deps, log).Run(ctx)
|
||||
}
|
||||
|
||||
|
||||
@@ -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 configurable (default: config versions 1 year or 1 000 entries, audit 1 year) | S | v1 |
|
||||
| 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-13 | Tamper-evident audit log (hash chain), so a manipulated entry is detected | S | v1 |
|
||||
|
||||
### Quotas & usage
|
||||
@@ -293,6 +293,7 @@ Details: [07-security-and-testing](07-security-and-testing.md).
|
||||
| N-14 Update-safe | Samba/NFS security updates install automatically without breaking the app | runtime parameter discovery, validation gate, self-check after package updates, CI on Debian testing ([03 §6b](03-solution-design.md#6b-compatibility-with-sambanfs-updates)) |
|
||||
| N-15 Clean architecture | maintainable by one person for years, easy to extend | ports & adapters, inward-only dependencies enforced by lint, pure domain, ADRs ([03 §1b](03-solution-design.md#1b-architecture-rules-clean-architecture)) |
|
||||
| N-16 Resilience | file access never depends on the app; no half-applied changes after a crash | write-ahead journal, atomic writes, rollback, watchdog, module isolation ([03 §6c](03-solution-design.md#6c-resilience--reliability)) |
|
||||
| N-17 Privacy (GDPR) | Sharestead keeps only the personal data it needs, each with a retention, and sends nothing anywhere | what is stored where and for how long, and how to delete it, in [privacy](../privacy.md); history retention F-HIS-12; no telemetry (F-UPD-2) |
|
||||
| N-13 Automated testing | every change is tested automatically | quality gates in [07 §3.2](07-security-and-testing.md#32-quality-gates); bug fix = regression test |
|
||||
|
||||
## 4. Owner's MVP checklist (acceptance)
|
||||
|
||||
@@ -124,6 +124,7 @@ File watch (inotify) on all involved files → UI refresh + "changed outside the
|
||||
| Hand-edit detection | each managed file has a last-known hash; on inotify (and at start) a different hash → snapshot + `outside` entry with diff |
|
||||
| Undo one change | apply the inverse diff with a three-way merge against the current file. Clean → normal apply pipeline. Overlap with later edits → conflict view, nothing written |
|
||||
| Restore point in time | write the snapshot of that entry (one file or all), through the apply pipeline |
|
||||
| Retention (F-HIS-12) | `journal.jsonl` keeps entries for N days (default 365), at most M (default 1,000); at start and daily the file is rewritten atomically without older entries, and backups older than the oldest kept entry go (the newest 10 per file stay). The trim is an audit entry. Set in the app settings (System page, API, `settings.json`) |
|
||||
| Change sets | all steps of one action recorded together; undo runs the inverse steps in reverse order; if one step fails, the already-reverted steps are rolled forward again |
|
||||
|
||||
What can be reverted, and how:
|
||||
@@ -133,7 +134,7 @@ What can be reverted, and how:
|
||||
| Config files (Samba, NFS, DLNA, discovery, app config) | ✅ file snapshot / inverse diff | incl. hand edits |
|
||||
| Create share / folder | ✅ remove share; folder removed only if still empty | never deletes data that appeared later |
|
||||
| Remove share (data kept) | ✅ share section restored | |
|
||||
| User/group create, rename, members, UID, disable | ✅ inverse operation | |
|
||||
| User/group create, rename, members, UID, disable | ❌ audit only | undo via inverse operations dropped (F-HIS-8, 2026-11-30) |
|
||||
| User delete | ⚠️ account + memberships restored, **new password needed** | the journal never stores password hashes |
|
||||
| Service on/off | ✅ | |
|
||||
| Folder permissions (owner/mode/ACL) | ✅ for the folder itself; recursive fixes: ✅ if ≤ 10 000 entries (old values stored), otherwise audit only | |
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
# Personal data in Sharestead (GDPR)
|
||||
|
||||
Sharestead is a tool: whoever runs it decides what is stored on the NAS and is the controller under
|
||||
the GDPR. This page lists what personal data Sharestead itself keeps, where, and for how long, so
|
||||
you can document it and answer requests. Sharestead sends no data anywhere (no telemetry, no
|
||||
connection to the internet; system updates come from the system's own package sources).
|
||||
|
||||
## What is stored where
|
||||
|
||||
| Data | Where | Kept | Deleted |
|
||||
|---|---|---|---|
|
||||
| Accounts: user names, full names, groups, password hashes | the system's account files (`/etc/passwd`, `/etc/group`, `/etc/shadow`) and Samba's password database | while the account exists | when the user is deleted |
|
||||
| User and group names, IP addresses or networks of NFS clients | `smb.conf`, `/etc/exports` | while used in a share | when removed from the share |
|
||||
| **Change history**: who changed what and when, with the full content of the changed config files | `/var/lib/sharestead/journal.jsonl` | **365 days, at most 1,000 entries** (default) | automatically, once a day |
|
||||
| Backups of config files before each change | `/var/lib/sharestead/backups/` | as long as the history (the newest 10 per file always stay) | automatically, with the history |
|
||||
| Limits per personal folder (user names) | `/var/lib/sharestead/limits.json` | while the user exists | when the user is deleted |
|
||||
| Usage per personal folder | in memory and `/run/sharestead/` | until the next measurement or restart | automatically |
|
||||
| Sessions: user name, client IP (for slowing down wrong passwords) | in memory only | until logout, expiry or restart | automatically |
|
||||
| Action log lines (who did what) | the system journal (`journalctl -u sharestead`) | as the system journal is set up | by the system journal's own limits |
|
||||
| Diagnostic bundle: config, user/share/host names, IP addresses, recent log lines; passwords and keys removed | only created when an admin downloads it | not stored by Sharestead | — |
|
||||
| Files in the shares | your storage | your decision | your decision |
|
||||
|
||||
The web UI sets one cookie: the session (technically necessary, no consent needed).
|
||||
|
||||
## 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.
|
||||
|
||||
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
|
||||
the file applies at the next daily run or start.
|
||||
|
||||
✅ Check: *Changes* shows "Kept: the last … days, at most … entries".
|
||||
|
||||
## When someone leaves
|
||||
|
||||
| Step | Where |
|
||||
|---|---|
|
||||
| Delete the user | *Users* → user → *Delete* (their files are kept) |
|
||||
| Delete or hand over their files | *Folders* (their personal folder and files in shares) |
|
||||
| Their name in the change history and backups | removed automatically when the retention period ends; to remove it earlier, shorten the retention |
|
||||
| Their name in the system journal | removed by the system journal's own limits (`journalctl --vacuum-time=…`) |
|
||||
|
||||
Subfolder permissions keep the deleted user's ID on disk; the share page lists it as an ID that no
|
||||
longer exists, and saving the rule again without them removes it.
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
@@ -128,7 +129,7 @@ func (s *Store) apply(ctx context.Context, actor, summary string, writes []Write
|
||||
}
|
||||
for i, w := range writes {
|
||||
if existed[i] {
|
||||
name := filepath.Join(s.BackupDir, strings.ReplaceAll(strings.TrimPrefix(w.Path, "/"), "/", "_")+"."+now.Format("20060102T150405.000000000"))
|
||||
name := filepath.Join(s.BackupDir, strings.ReplaceAll(strings.TrimPrefix(w.Path, "/"), "/", "_")+"."+now.UTC().Format(backupTime))
|
||||
if err := os.WriteFile(name, befores[i], 0o600); err != nil {
|
||||
return Entry{}, fmt.Errorf("backup of %s: %w — nothing was changed", w.Path, err)
|
||||
}
|
||||
@@ -343,6 +344,99 @@ func (s *Store) Record(actor, summary string) error {
|
||||
return s.Journal.Append(Entry{ID: now.Format("20060102T150405.000000"), Time: now, Actor: actor, Summary: summary, Kind: changes.KindAudit})
|
||||
}
|
||||
|
||||
// Retention is the actor of the entry that records a history trim.
|
||||
const Retention = "Sharestead (retention)"
|
||||
|
||||
// keepBackups is how many backups of each file stay, however old.
|
||||
const keepBackups = 10
|
||||
|
||||
// backupTime is the timestamp format (UTC) at the end of a backup's name.
|
||||
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) {
|
||||
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) })
|
||||
if err != nil {
|
||||
return t, fmt.Errorf("trimming the change history: %w", err)
|
||||
}
|
||||
t.Removed = removed
|
||||
if oldest != nil {
|
||||
ot := oldest.Time
|
||||
t.Oldest = &ot
|
||||
if removed > 0 && ot.After(cutoff) {
|
||||
cutoff = ot // removed by count: their backups go too
|
||||
}
|
||||
}
|
||||
}
|
||||
n, err := pruneBackups(s.BackupDir, cutoff, keepBackups)
|
||||
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 {
|
||||
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 {
|
||||
return t, err
|
||||
}
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// 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) {
|
||||
if dir == "" {
|
||||
return 0, nil
|
||||
}
|
||||
ents, err := os.ReadDir(dir)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return 0, nil
|
||||
}
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
type backup struct {
|
||||
name string
|
||||
at time.Time
|
||||
}
|
||||
byFile := map[string][]backup{}
|
||||
for _, e := range ents {
|
||||
n := e.Name()
|
||||
if e.IsDir() || len(n) < len(backupTime)+2 || n[len(n)-len(backupTime)-1] != '.' {
|
||||
continue
|
||||
}
|
||||
at, err := time.Parse(backupTime, n[len(n)-len(backupTime):])
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
file := n[:len(n)-len(backupTime)-1]
|
||||
byFile[file] = append(byFile[file], backup{n, at})
|
||||
}
|
||||
removed := 0
|
||||
for _, list := range byFile {
|
||||
sort.Slice(list, func(i, j int) bool { return list[i].at.After(list[j].at) }) // newest first
|
||||
for i, b := range list {
|
||||
if i < keep || !b.at.Before(cutoff) {
|
||||
continue
|
||||
}
|
||||
if err := os.Remove(filepath.Join(dir, b.name)); err != nil {
|
||||
return removed, err
|
||||
}
|
||||
removed++
|
||||
}
|
||||
}
|
||||
return removed, nil
|
||||
}
|
||||
|
||||
// Sync records hand edits of watched files (see sync).
|
||||
func (s *Store) Sync(_ context.Context) error {
|
||||
s.mu.Lock()
|
||||
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
|
||||
"sharestead/internal/adapters/osfs"
|
||||
)
|
||||
|
||||
// Journal stores change sets as JSON lines (one entry per line, append-only,
|
||||
@@ -79,3 +81,52 @@ func (j *Journal) Get(id string) (Entry, bool, error) {
|
||||
}
|
||||
return Entry{}, false, nil
|
||||
}
|
||||
|
||||
// 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) {
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
f, err := os.Open(j.Path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return 0, nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
var all []Entry
|
||||
sc := bufio.NewScanner(f)
|
||||
sc.Buffer(make([]byte, 1<<20), 16<<20)
|
||||
for sc.Scan() {
|
||||
var e Entry
|
||||
if json.Unmarshal(sc.Bytes(), &e) == nil {
|
||||
all = append(all, e)
|
||||
}
|
||||
}
|
||||
f.Close()
|
||||
if err := sc.Err(); err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
from := keepFrom(all)
|
||||
var oldest *Entry
|
||||
if from < len(all) {
|
||||
oldest = &all[from]
|
||||
}
|
||||
if from == 0 {
|
||||
return 0, oldest, nil
|
||||
}
|
||||
var buf []byte
|
||||
for _, e := range all[from:] {
|
||||
b, err := json.Marshal(e)
|
||||
if err != nil {
|
||||
return 0, oldest, err
|
||||
}
|
||||
buf = append(append(buf, b...), '\n')
|
||||
}
|
||||
if err := osfs.WriteAtomic(j.Path, buf); err != nil {
|
||||
return 0, oldest, err
|
||||
}
|
||||
return from, oldest, nil
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package configstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"sharestead/internal/app/changes"
|
||||
)
|
||||
|
||||
// clock is a settable time for the store.
|
||||
type clock struct{ t time.Time }
|
||||
|
||||
func (c *clock) now() time.Time { c.t = c.t.Add(time.Second); return c.t }
|
||||
|
||||
// history writes one change per age (days ago, oldest first), each with a
|
||||
// backup, and returns the env with the clock set to "now".
|
||||
func history(t *testing.T, days ...int) (*env, *clock) {
|
||||
t.Helper()
|
||||
e := newEnv(t)
|
||||
now := time.Date(2026, 11, 30, 12, 0, 0, 0, time.UTC)
|
||||
c := &clock{}
|
||||
e.store.Now = c.now
|
||||
for i, d := range days {
|
||||
c.t = now.Add(-time.Duration(d) * 24 * time.Hour)
|
||||
_, ver, _ := e.store.Read(e.path("smb.conf"))
|
||||
content := []byte("[global]\n\tworkgroup = X\n# change " + string(rune('a'+i)) + "\n")
|
||||
if _, err := e.store.Apply(context.Background(), "admin", "change "+string(rune('a'+i)), []Write{{Path: e.path("smb.conf"), Content: content, Version: ver}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
c.t = now
|
||||
return e, c
|
||||
}
|
||||
|
||||
func backups(t *testing.T, e *env) int {
|
||||
t.Helper()
|
||||
b, err := os.ReadDir(e.path("backups"))
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return len(b)
|
||||
}
|
||||
|
||||
// F-HIS-12: entries older than the retention go, the rest stays usable.
|
||||
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)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tr.Removed != 2 || tr.Oldest == nil {
|
||||
t.Fatalf("trimmed = %+v, want 2 removed", tr)
|
||||
}
|
||||
list := e.mustList(t) // newest first
|
||||
if len(list) != 3 || list[0].Actor != Retention || !strings.Contains(list[0].Summary, "2 entries") {
|
||||
t.Fatalf("journal after trim: %+v", list)
|
||||
}
|
||||
if list[1].Summary != "change d" || list[2].Summary != "change c" {
|
||||
t.Errorf("kept entries: %q, %q", list[1].Summary, list[2].Summary)
|
||||
}
|
||||
if !tr.Oldest.Equal(list[2].Time) {
|
||||
t.Errorf("oldest = %v, want %v", tr.Oldest, list[2].Time)
|
||||
}
|
||||
// The kept entries still work: undo the newest change.
|
||||
if _, err := e.store.Undo(context.Background(), "admin", list[1].ID); err != nil {
|
||||
t.Errorf("undo after trim: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
if err != nil || tr.Removed != 3 {
|
||||
t.Fatalf("trimmed = %+v, %v", tr, err)
|
||||
}
|
||||
// The two newest changes stay, plus the audit entry of the trim itself.
|
||||
if n := len(e.mustList(t)); n != 3 {
|
||||
t.Errorf("entries = %d, want 2 kept + 1 audit entry", n)
|
||||
}
|
||||
e2, _ := history(t, 3, 2)
|
||||
tr, err = e2.store.Trim(context.Background(), r)
|
||||
if err != nil || tr.Removed != 0 || tr.Backups != 0 {
|
||||
t.Errorf("nothing to trim: %+v %v", tr, err)
|
||||
}
|
||||
if n := len(e2.mustList(t)); n != 2 {
|
||||
t.Errorf("no audit entry when nothing was removed: %d entries", n)
|
||||
}
|
||||
}
|
||||
|
||||
// Backups older than the oldest kept entry go, but the newest 10 of each
|
||||
// file always stay.
|
||||
func TestTrimRemovesOldBackupsButKeepsTheNewest(t *testing.T) {
|
||||
ages := []int{}
|
||||
for d := 30; d >= 1; d-- {
|
||||
ages = append(ages, d)
|
||||
}
|
||||
e, _ := history(t, ages...) // 30 changes, 30 backups of smb.conf
|
||||
if backups(t, e) != 30 {
|
||||
t.Fatalf("backups before = %d", backups(t, e))
|
||||
}
|
||||
week, _ := changes.NewRetention(7, 1000)
|
||||
tr, err := e.store.Trim(context.Background(), week)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Changes of the last 7 days stay (7); their backups are fewer than 10,
|
||||
// so the newest 10 backups stay.
|
||||
if tr.Removed != 23 || tr.Backups != 20 || backups(t, e) != 10 {
|
||||
t.Errorf("trimmed = %+v, backups left %d; want 23 entries and 20 backups removed, 10 left", tr, backups(t, e))
|
||||
}
|
||||
// A file that doesn't look like a backup is never touched.
|
||||
other := filepath.Join(e.path("backups"), "notes.txt")
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(other); err != nil {
|
||||
t.Errorf("unrelated file removed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
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 {
|
||||
t.Errorf("missing journal: %d %v %v", n, oldest, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A journal line that can't be read was already ignored; a trim drops it
|
||||
// and keeps every readable entry.
|
||||
func TestTrimDropsUnreadableLines(t *testing.T) {
|
||||
e, _ := history(t, 3, 2)
|
||||
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 })
|
||||
if err != nil || n != 1 || oldest == nil || oldest.Summary != "change b" {
|
||||
t.Fatalf("trim = %d %+v %v", n, oldest, err)
|
||||
}
|
||||
if b, _ := os.ReadFile(e.path("journal.jsonl")); strings.Contains(string(b), "{broken") {
|
||||
t.Error("unreadable line kept")
|
||||
}
|
||||
if st, _ := os.Stat(e.path("journal.jsonl")); st.Mode().Perm() != 0o600 {
|
||||
t.Errorf("journal mode = %v, want 0600 (it holds config contents)", st.Mode().Perm())
|
||||
}
|
||||
}
|
||||
@@ -82,4 +82,5 @@ type Store interface {
|
||||
Record(actor, summary string) error
|
||||
// Sync records hand edits of managed files since Sharestead last saw them.
|
||||
Sync(ctx context.Context) error
|
||||
Trimmer
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package changes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Retention is how long the change history is kept (F-HIS-12): entries
|
||||
// older than MaxAge go, and of the rest at most the newest MaxEntries stay.
|
||||
// The history holds who changed what (personal data), so it isn't kept
|
||||
// forever (GDPR: storage limitation).
|
||||
type Retention struct {
|
||||
MaxAge time.Duration
|
||||
MaxEntries int
|
||||
}
|
||||
|
||||
// Defaults and bounds of the retention settings.
|
||||
const (
|
||||
DefaultHistoryDays = 365
|
||||
DefaultHistoryEntries = 1000
|
||||
MinHistoryDays = 7
|
||||
MaxHistoryDays = 3650
|
||||
MinHistoryEntries = 50
|
||||
MaxHistoryEntries = 100000
|
||||
)
|
||||
|
||||
// ErrInvalidRetention is returned for values outside the bounds.
|
||||
var ErrInvalidRetention = fmt.Errorf("retention out of range: %d–%d days, %d–%d entries", MinHistoryDays, MaxHistoryDays, MinHistoryEntries, MaxHistoryEntries)
|
||||
|
||||
// NewRetention checks the settings and returns the retention.
|
||||
func NewRetention(days, entries int) (Retention, error) {
|
||||
if days < MinHistoryDays || days > MaxHistoryDays || entries < MinHistoryEntries || entries > MaxHistoryEntries {
|
||||
return Retention{}, ErrInvalidRetention
|
||||
}
|
||||
return Retention{MaxAge: time.Duration(days) * 24 * time.Hour, MaxEntries: entries}, nil
|
||||
}
|
||||
|
||||
// Keep returns the index of the first entry that stays: entries are oldest
|
||||
// first, everything before the index is removed.
|
||||
func (r Retention) Keep(entries []Entry, now time.Time) int {
|
||||
from := 0
|
||||
if r.MaxEntries > 0 && len(entries) > r.MaxEntries {
|
||||
from = len(entries) - r.MaxEntries
|
||||
}
|
||||
if r.MaxAge > 0 {
|
||||
cutoff := now.Add(-r.MaxAge)
|
||||
for from < len(entries) && entries[from].Time.Before(cutoff) {
|
||||
from++
|
||||
}
|
||||
}
|
||||
return from
|
||||
}
|
||||
|
||||
// Trimmed says what applying a retention removed.
|
||||
type Trimmed struct {
|
||||
Removed int `json:"removed"` // journal entries
|
||||
Backups int `json:"backups_removed"` // backup copies of config files
|
||||
Oldest *time.Time `json:"oldest,omitempty"` // the oldest entry left
|
||||
}
|
||||
|
||||
// Trimmer applies a retention to the history (the config store).
|
||||
type Trimmer interface {
|
||||
Trim(ctx context.Context, r Retention) (Trimmed, error)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package changes
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var now = time.Date(2026, 11, 30, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
func entriesAged(days ...int) []Entry {
|
||||
var out []Entry
|
||||
for _, d := range days {
|
||||
out = append(out, Entry{ID: time.Duration(d).String(), Time: now.Add(-time.Duration(d) * 24 * time.Hour)})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// F-HIS-12: default 1 year or 1,000 entries, whichever is reached first.
|
||||
func TestKeepByAgeAndCount(t *testing.T) {
|
||||
year, _ := NewRetention(365, 1000)
|
||||
for name, c := range map[string]struct {
|
||||
r Retention
|
||||
ages []int // oldest first
|
||||
keepIdx int
|
||||
}{
|
||||
"all young, few": {year, []int{300, 10, 0}, 0},
|
||||
"older than a year": {year, []int{400, 366, 364, 1}, 2},
|
||||
"exactly a year stays": {year, []int{365, 1}, 0},
|
||||
"count is reached": {Retention{MaxAge: year.MaxAge, MaxEntries: 2}, []int{30, 20, 10, 0}, 2},
|
||||
"both: age cuts more": {Retention{MaxAge: 7 * 24 * time.Hour, MaxEntries: 3}, []int{30, 20, 10, 0}, 3},
|
||||
"empty": {year, nil, 0},
|
||||
"everything too old": {year, []int{900, 800}, 2},
|
||||
} {
|
||||
if got := c.r.Keep(entriesAged(c.ages...), now); got != c.keepIdx {
|
||||
t.Errorf("%s: keep from %d, want %d", name, got, c.keepIdx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewRetentionBounds(t *testing.T) {
|
||||
for _, c := range []struct{ days, entries int }{{6, 1000}, {3651, 1000}, {365, 49}, {365, 100001}, {0, 0}} {
|
||||
if _, err := NewRetention(c.days, c.entries); !errors.Is(err, ErrInvalidRetention) {
|
||||
t.Errorf("%d days, %d entries: %v", c.days, c.entries, err)
|
||||
}
|
||||
}
|
||||
r, err := NewRetention(MinHistoryDays, MaxHistoryEntries)
|
||||
if err != nil || r.MaxAge != 7*24*time.Hour || r.MaxEntries != MaxHistoryEntries {
|
||||
t.Errorf("bounds themselves are allowed: %+v %v", r, err)
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"sync"
|
||||
|
||||
"sharestead/internal/app/changes"
|
||||
)
|
||||
|
||||
// Settings of the app. Pointers keep "not set" apart from false, so
|
||||
@@ -24,6 +26,32 @@ type Settings struct {
|
||||
// (share name → paths relative to the share folder). Their access
|
||||
// itself lives on disk as ACLs.
|
||||
Subfolders map[string][]string `json:"subfolders,omitempty"`
|
||||
// HistoryDays and HistoryEntries limit the change history (F-HIS-12);
|
||||
// nil: the defaults (1 year, 1,000 entries).
|
||||
HistoryDays *int `json:"history_days,omitempty"`
|
||||
HistoryEntries *int `json:"history_entries,omitempty"`
|
||||
}
|
||||
|
||||
// History returns how many days and entries of change history are kept.
|
||||
func (s Settings) History() (days, entries int) {
|
||||
days, entries = changes.DefaultHistoryDays, changes.DefaultHistoryEntries
|
||||
if s.HistoryDays != nil {
|
||||
days = *s.HistoryDays
|
||||
}
|
||||
if s.HistoryEntries != nil {
|
||||
entries = *s.HistoryEntries
|
||||
}
|
||||
return days, entries
|
||||
}
|
||||
|
||||
// Retention returns the history retention; values outside the bounds (a
|
||||
// settings file edited by hand) fall back to the defaults.
|
||||
func (s Settings) Retention() changes.Retention {
|
||||
r, err := changes.NewRetention(s.History())
|
||||
if err != nil {
|
||||
r, _ = changes.NewRetention(changes.DefaultHistoryDays, changes.DefaultHistoryEntries)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// HomeByDefaultOn reports whether new users get a personal folder by
|
||||
|
||||
@@ -29,3 +29,29 @@ func TestSelfServiceDefaultsOnAndCanBeSwitchedOff(t *testing.T) {
|
||||
t.Fatal("still on")
|
||||
}
|
||||
}
|
||||
|
||||
// F-HIS-12: 1 year / 1,000 entries unless set; a value out of range (a
|
||||
// settings file edited by hand) doesn't switch the limit off.
|
||||
func TestHistoryRetention(t *testing.T) {
|
||||
st := &Store{Files: mem{}, Path: "/s.json"}
|
||||
s, _ := st.Get()
|
||||
if d, n := s.History(); d != 365 || n != 1000 {
|
||||
t.Errorf("defaults = %d days, %d entries", d, n)
|
||||
}
|
||||
if r := s.Retention(); r.MaxEntries != 1000 || r.MaxAge.Hours() != 365*24 {
|
||||
t.Errorf("default retention = %+v", r)
|
||||
}
|
||||
days, entries := 90, 500
|
||||
if _, err := st.Update(func(s *Settings) { s.HistoryDays, s.HistoryEntries = &days, &entries }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, _ = st.Get()
|
||||
if r := s.Retention(); r.MaxEntries != 500 || r.MaxAge.Hours() != 90*24 {
|
||||
t.Errorf("set retention = %+v", r)
|
||||
}
|
||||
bad := 0
|
||||
s.HistoryDays = &bad
|
||||
if r := s.Retention(); r.MaxEntries != 1000 || r.MaxAge.Hours() != 365*24 {
|
||||
t.Errorf("0 days must fall back to the defaults, not keep nothing or everything: %+v", r)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"sharestead/internal/app/changes"
|
||||
"sharestead/internal/app/settings"
|
||||
)
|
||||
|
||||
// historyWorld has a journal with entries 400, 200 and 10 days old.
|
||||
func historyWorld(t *testing.T) *world {
|
||||
t.Helper()
|
||||
w := newWorld(t, func(d *Deps) { d.Settings = &settings.Store{Files: memSettings{}, Path: "/s.json"} })
|
||||
var lines []byte
|
||||
for _, days := range []int{400, 200, 10} {
|
||||
at := time.Now().Add(-time.Duration(days) * 24 * time.Hour)
|
||||
e := changes.Entry{ID: at.Format("20060102T150405.000000"), Time: at, Actor: "admin", Summary: "old change", Kind: changes.KindAudit}
|
||||
b, _ := json.Marshal(e)
|
||||
lines = append(append(lines, b...), '\n')
|
||||
}
|
||||
j := filepath.Join(w.dir, "data", "journal.jsonl")
|
||||
old, _ := os.ReadFile(j)
|
||||
if err := os.WriteFile(j, append(lines, old...), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
type keptAnswer struct {
|
||||
Kept struct {
|
||||
Days, Entries int
|
||||
Oldest *string
|
||||
}
|
||||
}
|
||||
|
||||
// F-HIS-12: the history says how long it is kept and how far back it goes;
|
||||
// a shorter retention applies at once, and the change is in the history.
|
||||
func TestHistoryRetentionThroughTheAPI(t *testing.T) {
|
||||
w := historyWorld(t)
|
||||
var s appSettings
|
||||
w.call("GET", "/api/v1/settings/app", nil).json(t, &s)
|
||||
if s.HistoryDays != 365 || s.HistoryEntries != 1000 {
|
||||
t.Fatalf("defaults = %+v, want 365 days, 1000 entries", s)
|
||||
}
|
||||
var k keptAnswer
|
||||
w.call("GET", "/api/v1/changes", nil).json(t, &k)
|
||||
if k.Kept.Days != 365 || k.Kept.Entries != 1000 || k.Kept.Oldest == nil {
|
||||
t.Fatalf("kept = %+v", k.Kept)
|
||||
}
|
||||
oldest, _ := time.Parse(time.RFC3339, *k.Kept.Oldest)
|
||||
if d := time.Since(oldest).Hours() / 24; d < 399 || d > 401 {
|
||||
t.Errorf("oldest entry is %.0f days old, want 400 (not trimmed until the daily run)", d)
|
||||
}
|
||||
|
||||
r := w.call("PUT", "/api/v1/settings/app", map[string]any{"history_days": 300})
|
||||
var changed struct {
|
||||
appSettings
|
||||
Trimmed *changes.Trimmed
|
||||
}
|
||||
r.json(t, &changed)
|
||||
if r.Code != 200 || changed.HistoryDays != 300 || changed.Trimmed == nil || changed.Trimmed.Removed != 1 {
|
||||
t.Fatalf("set 300 days: %d %s", r.Code, r.Body)
|
||||
}
|
||||
w.call("GET", "/api/v1/changes?limit=200", nil).json(t, &k)
|
||||
oldest, _ = time.Parse(time.RFC3339, *k.Kept.Oldest)
|
||||
if d := time.Since(oldest).Hours() / 24; d < 199 || d > 201 || k.Kept.Days != 300 {
|
||||
t.Errorf("after trim: oldest %.0f days, kept %+v; want 200 days, 300", d, k.Kept)
|
||||
}
|
||||
hist := w.call("GET", "/api/v1/changes?limit=200", nil).Body
|
||||
if !strings.Contains(hist, "Change history kept for 300 days, at most 1000 entries") || !strings.Contains(hist, "Change history trimmed: 1 entries") {
|
||||
t.Errorf("history misses the setting change or the trim:\n%s", hist)
|
||||
}
|
||||
// Unchanged retention: nothing trimmed, nothing recorded.
|
||||
r = w.call("PUT", "/api/v1/settings/app", map[string]any{"history_days": 300, "self_service": true})
|
||||
if r.Code != 200 || strings.Contains(r.Body, "trimmed") {
|
||||
t.Errorf("same retention again: %d %s", r.Code, r.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHistoryRetentionBounds(t *testing.T) {
|
||||
w := historyWorld(t)
|
||||
for _, body := range []map[string]any{{"history_days": 6}, {"history_days": 3651}, {"history_entries": 49}, {"history_entries": 100001}} {
|
||||
if r := w.call("PUT", "/api/v1/settings/app", body); r.Code != 400 || r.problemCode() != "invalid_input" {
|
||||
t.Errorf("%v: %d %s", body, r.Code, r.Body)
|
||||
}
|
||||
}
|
||||
var s appSettings
|
||||
w.call("GET", "/api/v1/settings/app", nil).json(t, &s)
|
||||
if s.HistoryDays != 365 || s.HistoryEntries != 1000 {
|
||||
t.Errorf("a refused value changed the settings: %+v", s)
|
||||
}
|
||||
var k keptAnswer
|
||||
w.call("GET", "/api/v1/changes", nil).json(t, &k)
|
||||
if oldest, _ := time.Parse(time.RFC3339, *k.Kept.Oldest); time.Since(oldest).Hours()/24 < 399 {
|
||||
t.Error("a refused value trimmed the history")
|
||||
}
|
||||
}
|
||||
@@ -63,8 +63,8 @@ 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.", Request: setAppSettingsRequest{}, Response: appSettingsChanged{}},
|
||||
"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.", Response: changesList{}, Query: []queryParam{
|
||||
"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{}},
|
||||
"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"}},
|
||||
{Name: "from", Description: "entries at or after this time", Schema: map[string]any{"type": "string", "format": "date-time"}},
|
||||
|
||||
@@ -49,6 +49,15 @@ type changesList struct {
|
||||
Total int `json:"total"` // entries matching the filter
|
||||
Offset int `json:"offset"` // index of the first entry on this page
|
||||
Limit int `json:"limit"` // page size
|
||||
// Kept says how much history is kept (F-HIS-12) and how far back it goes.
|
||||
Kept historyKept `json:"kept"`
|
||||
}
|
||||
|
||||
// historyKept is the retention of the change history and its oldest entry.
|
||||
type historyKept struct {
|
||||
Days int `json:"days"` // entries older than this many days are removed
|
||||
Entries int `json:"entries"` // at most this many entries are kept
|
||||
Oldest *string `json:"oldest,omitempty"` // time of the oldest entry (RFC 3339); none: empty history
|
||||
}
|
||||
|
||||
// folderRoots lists the storage folders Sharestead may use.
|
||||
|
||||
@@ -160,3 +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) {
|
||||
return changes.Trimmed{}, nil
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"sharestead/internal/app/changes"
|
||||
"sharestead/internal/app/settings"
|
||||
)
|
||||
|
||||
@@ -17,25 +19,50 @@ func (a *api) getAppSettings(w http.ResponseWriter, _ *http.Request) {
|
||||
problem(w, http.StatusInternalServerError, "settings_unreadable", "Settings couldn’t be read", err.Error(), nil)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, appSettings{SelfService: s.SelfServiceOn(), HomeByDefault: s.HomeByDefaultOn()})
|
||||
writeJSON(w, http.StatusOK, toAppSettings(s))
|
||||
}
|
||||
|
||||
func toAppSettings(s settings.Settings) appSettings {
|
||||
days, entries := s.History()
|
||||
return appSettings{SelfService: s.SelfServiceOn(), HomeByDefault: s.HomeByDefaultOn(), HistoryDays: days, HistoryEntries: entries}
|
||||
}
|
||||
|
||||
// history returns the change history retention (days, entries).
|
||||
func (a *api) history() (int, int) {
|
||||
if a.settings == nil {
|
||||
return settings.Settings{}.History()
|
||||
}
|
||||
s, err := a.settings.Get()
|
||||
if err != nil {
|
||||
return settings.Settings{}.History()
|
||||
}
|
||||
return s.History()
|
||||
}
|
||||
|
||||
// appSettings are Sharestead's own settings as the API shows them.
|
||||
type appSettings struct {
|
||||
SelfService bool `json:"self_service"` // users may log in to "My account"
|
||||
HomeByDefault bool `json:"home_by_default"` // new users get a personal folder unless unticked
|
||||
// The change history keeps entries this many days, and at most this many
|
||||
// entries; older ones and their backups are removed daily (F-HIS-12).
|
||||
HistoryDays int `json:"history_days"`
|
||||
HistoryEntries int `json:"history_entries"`
|
||||
}
|
||||
|
||||
// setAppSettingsRequest changes the given settings; omitted ones stay.
|
||||
type setAppSettingsRequest struct {
|
||||
SelfService *bool `json:"self_service,omitempty"`
|
||||
HomeByDefault *bool `json:"home_by_default,omitempty"`
|
||||
SelfService *bool `json:"self_service,omitempty"`
|
||||
HomeByDefault *bool `json:"home_by_default,omitempty"`
|
||||
HistoryDays *int `json:"history_days,omitempty"` // 7–3650
|
||||
HistoryEntries *int `json:"history_entries,omitempty"` // 50–100000
|
||||
}
|
||||
|
||||
// appSettingsChanged is the answer to setAppSettings.
|
||||
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 *changes.Trimmed `json:"trimmed,omitempty"`
|
||||
}
|
||||
|
||||
func (a *api) setAppSettings(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -43,11 +70,23 @@ func (a *api) setAppSettings(w http.ResponseWriter, r *http.Request) {
|
||||
if !decode(w, r, &in) {
|
||||
return
|
||||
}
|
||||
if in.SelfService == nil && in.HomeByDefault == nil {
|
||||
problem(w, http.StatusBadRequest, "invalid_input", "Nothing to change", "Send self_service and/or home_by_default.", nil)
|
||||
if in.SelfService == nil && in.HomeByDefault == nil && in.HistoryDays == nil && in.HistoryEntries == nil {
|
||||
problem(w, http.StatusBadRequest, "invalid_input", "Nothing to change", "Send self_service, home_by_default, history_days and/or history_entries.", nil)
|
||||
return
|
||||
}
|
||||
before, _ := a.settings.Get()
|
||||
days, entries := before.History()
|
||||
if in.HistoryDays != nil {
|
||||
days = *in.HistoryDays
|
||||
}
|
||||
if in.HistoryEntries != nil {
|
||||
entries = *in.HistoryEntries
|
||||
}
|
||||
retention, rerr := changes.NewRetention(days, entries)
|
||||
if rerr != nil {
|
||||
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
|
||||
}
|
||||
st, err := a.settings.Update(func(s *settings.Settings) {
|
||||
if in.SelfService != nil {
|
||||
s.SelfService = in.SelfService
|
||||
@@ -55,6 +94,12 @@ func (a *api) setAppSettings(w http.ResponseWriter, r *http.Request) {
|
||||
if in.HomeByDefault != nil {
|
||||
s.HomeByDefault = in.HomeByDefault
|
||||
}
|
||||
if in.HistoryDays != nil {
|
||||
s.HistoryDays = in.HistoryDays
|
||||
}
|
||||
if in.HistoryEntries != nil {
|
||||
s.HistoryEntries = in.HistoryEntries
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
a.audit(r, "change app settings", "", err)
|
||||
@@ -78,7 +123,18 @@ func (a *api) setAppSettings(w http.ResponseWriter, r *http.Request) {
|
||||
a.audit(r, "personal folder for new users: "+what, "", nil)
|
||||
a.record(r, "Personal folder for new users: "+what, nil)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, appSettingsChanged{appSettings{st.SelfServiceOn(), st.HomeByDefaultOn()}, ended})
|
||||
var trimmed *changes.Trimmed
|
||||
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)
|
||||
if err != nil {
|
||||
a.log.Warn("trimming the change history", "error", err)
|
||||
} else {
|
||||
trimmed = &t
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, appSettingsChanged{toAppSettings(st), ended, trimmed})
|
||||
}
|
||||
|
||||
// selfServiceOff refuses self-service routes for normal users while
|
||||
|
||||
@@ -230,7 +230,13 @@ func (a *api) listChanges(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
out = append(out, c)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, changesList{Changes: out, Total: page.Total, Offset: offset, Limit: limit})
|
||||
kept := historyKept{}
|
||||
kept.Days, kept.Entries = a.history()
|
||||
if len(entries) > 0 {
|
||||
o := entries[len(entries)-1].Time.Format(time.RFC3339)
|
||||
kept.Oldest = &o
|
||||
}
|
||||
writeJSON(w, http.StatusOK, changesList{Changes: out, Total: page.Total, Offset: offset, Limit: limit, Kept: kept})
|
||||
}
|
||||
|
||||
func (a *api) undoChange(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -835,7 +835,9 @@
|
||||
},
|
||||
"GET /api/v1/settings/app": {
|
||||
"self_service": true,
|
||||
"home_by_default": true
|
||||
"home_by_default": true,
|
||||
"history_days": 365,
|
||||
"history_entries": 1000
|
||||
},
|
||||
"GET /api/v1/settings/samba": {
|
||||
"workgroup": "WORKGROUP",
|
||||
@@ -873,7 +875,12 @@
|
||||
],
|
||||
"total": 3,
|
||||
"offset": 0,
|
||||
"limit": 50
|
||||
"limit": 50,
|
||||
"kept": {
|
||||
"days": 365,
|
||||
"entries": 1000,
|
||||
"oldest": "2026-11-29T20:59:08Z"
|
||||
}
|
||||
},
|
||||
"GET /api/v1/folders": {
|
||||
"roots": [
|
||||
|
||||
@@ -833,6 +833,31 @@ test('subfolder permissions: folder tree, dialog from the share’s people, revi
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
test('change history retention: set on the System page, shown on Changes (F-HIS-12)', async ({ page, isMobile }) => {
|
||||
const errors = watchConsole(page, true);
|
||||
await login(page);
|
||||
await openNav(page, 'System', isMobile);
|
||||
const card = page.locator('form.card', { has: page.getByRole('heading', { name: 'Change history' }) });
|
||||
const days = card.getByLabel('Keep for (days)');
|
||||
await expect(days).not.toHaveValue('0');
|
||||
const before = await days.inputValue();
|
||||
await expect(card).toContainText('GDPR');
|
||||
await days.fill('6');
|
||||
await expect(card.getByRole('button', { name: 'Save' })).toBeDisabled();
|
||||
await expect(card.getByRole('status')).toContainText('7–3,650 days');
|
||||
await days.fill('3000');
|
||||
await card.getByRole('button', { name: 'Save' }).click();
|
||||
await expect(card.getByRole('status')).toContainText('Saved.');
|
||||
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 days.fill(before);
|
||||
await card.getByRole('button', { name: 'Save' }).click();
|
||||
await expect(card.getByRole('status')).toContainText('Saved.');
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
test('system: storage folders show whether subfolder permissions (ACLs) are possible', async ({ page, isMobile }) => {
|
||||
const errors = watchConsole(page, true);
|
||||
await login(page);
|
||||
|
||||
+3
-3
@@ -1,4 +1,4 @@
|
||||
import type { DLNAStatus, MediaDir, Me, HomesStatus, UpdateStatus, FolderCapabilities, StorageReport, HealthProblem, Client, ServiceStatus, FolderEntry, FolderListing, FolderStats, AccessSpec, Accounts, ChangeFilter, ChangesPage, EditResponse, RestoreResponse, NFSClient, Problem, SambaSettings, SessionInfo, Share, ShareOptions, SubfolderEntry, SubfolderInfo, SubfolderResponse } from './types';
|
||||
import type { AppSettings, DLNAStatus, MediaDir, Me, HomesStatus, UpdateStatus, FolderCapabilities, StorageReport, HealthProblem, Client, ServiceStatus, FolderEntry, FolderListing, FolderStats, AccessSpec, Accounts, ChangeFilter, ChangesPage, EditResponse, RestoreResponse, NFSClient, Problem, SambaSettings, SessionInfo, Share, ShareOptions, SubfolderEntry, SubfolderInfo, SubfolderResponse } from './types';
|
||||
|
||||
/** An API call that failed. Carries the server's problem details. */
|
||||
export class ApiError extends Error {
|
||||
@@ -151,8 +151,8 @@ export const api = {
|
||||
allowDLNA: (path: string) => request<{ group: string }>('POST', '/api/v1/dlna/allow', { path }),
|
||||
me: () => request<Me>('GET', '/api/v1/me'),
|
||||
setMyPassword: (current: string, next: string) => request<void>('PUT', '/api/v1/me/password', { current, new: next }),
|
||||
appSettings: () => request<{ self_service: boolean; home_by_default: boolean }>('GET', '/api/v1/settings/app'),
|
||||
setAppSettings: (s: { self_service?: boolean; home_by_default?: boolean }) => request<{ self_service: boolean; home_by_default: boolean; sessions_ended: number }>('PUT', '/api/v1/settings/app', s),
|
||||
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),
|
||||
storage: () => request<StorageReport>('GET', '/api/v1/storage'),
|
||||
storageBackground: () => background<StorageReport>('/api/v1/storage'),
|
||||
measureStorage: () => request<void>('POST', '/api/v1/storage/scan'),
|
||||
|
||||
@@ -27,6 +27,7 @@ export const glossary: Record<string, Entry> = {
|
||||
acl: { title: 'Subfolder permissions', body: 'Lets a folder inside a share have its own access, e.g. Family/Finances only for alex. It needs POSIX ACLs on the storage folder; without them, access is set per share, which is enough for most homes.', tech: 'POSIX ACLs (access + default) on the subfolder and everything inside; the subfolder belongs to root · Samba create masks keep group rw' },
|
||||
posixAcl: { title: 'ACL (POSIX ACL)', body: 'An access list on a file or folder: besides owner, one group and everyone else, it can give more users and groups their own rights. The filesystem must support it and have it switched on (ext4, XFS and btrfs usually do; ZFS when enabled); Windows shows ACLs on the Security tab. Off: each folder has just owner, group and others.', tech: 'getfacl / setfacl · acl, posixacl' },
|
||||
shareGroup: { title: 'Share group', body: 'A folder created together with a share gets its own group, so files stay usable for everyone with access, whoever created them.', tech: 'force group = sst-<name> · mode 0770' },
|
||||
retention: { title: 'History retention', body: 'How long the change history and the backups of config files are kept. Older entries are removed once a day, so the history doesn’t grow forever and personal data (who changed what) isn’t kept longer than needed. Changes older than that can’t be undone any more.', tech: 'journal.jsonl + backups/ in /var/lib/sharestead · settings history_days, history_entries' },
|
||||
changes: { title: 'Changes and undo', body: 'Every change Sharestead makes, and every hand edit of a managed config file, is recorded with the exact lines. Undo writes the old lines back, unless later changes touched them.', tech: 'journal in /var/lib/sharestead' },
|
||||
confirm: { title: 'Password confirmation', body: 'Deleting data or users, changing admin rights and switching services ask for your password again, at most every 5 minutes. Someone at an unlocked browser can’t do these alone.', tech: 're-authentication' },
|
||||
rootSquash: { title: 'Root access from clients', body: 'With root squash (recommended), the admin (root) of a Linux PC is treated like a nobody on this share, so a PC admin can’t take over files.', tech: 'root_squash / no_root_squash' },
|
||||
|
||||
@@ -38,7 +38,8 @@ export interface RestoreResponse extends EditResponse { skipped?: string[] }
|
||||
export interface AccessSpec { guests: Level; everyone: Level; named: Access[] }
|
||||
export interface Change { id: string; time: string; actor: string; summary: string; kind?: string; undo_of?: string; undone_by?: string; files: FilePreview[] }
|
||||
export interface ChangeFilter { q?: string; kind?: string; from?: string; to?: string; limit?: number; offset?: number }
|
||||
export interface ChangesPage { changes: Change[]; total: number; offset: number; limit: number }
|
||||
export interface ChangesPage { changes: Change[]; total: number; offset: number; limit: number; kept: { days: number; entries: number; oldest?: string } }
|
||||
export interface AppSettings { self_service: boolean; home_by_default: boolean; history_days: number; history_entries: number }
|
||||
|
||||
export interface ShareOptions { comment?: string; browsable?: boolean; available?: boolean; hide_dot_files?: boolean }
|
||||
export interface SambaSettings { workgroup: string; server_string: string; min_protocol: string; guest_access: boolean; macos: boolean; shares_own_vfs?: string[] }
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
import Notice from '../components/Notice.svelte';
|
||||
import Pager from '../components/Pager.svelte';
|
||||
import { PAGE } from '../lib/list';
|
||||
import { router, setQuery } from '../lib/router.svelte';
|
||||
import { href, router, setQuery } from '../lib/router.svelte';
|
||||
import { dayStart } from '../lib/format';
|
||||
|
||||
let { reload }: { reload: () => Promise<void> } = $props();
|
||||
@@ -123,6 +123,9 @@
|
||||
</label>
|
||||
{#if filtered}<button type="button" class="linkish clear" onclick={clear}>Clear filters</button>{/if}
|
||||
</form>
|
||||
{#if data?.kept}
|
||||
<p class="facts kept">Kept: the last {data.kept.days.toLocaleString()} days, at most {data.kept.entries.toLocaleString()} entries{#if data.kept.oldest} · oldest entry {new Date(data.kept.oldest).toLocaleDateString()}{/if} · <a href={href('system')}>change on the System page</a></p>
|
||||
{/if}
|
||||
|
||||
<Notice {ok} {problem} />
|
||||
|
||||
@@ -170,6 +173,7 @@
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.kept { margin: -4px 0 12px; }
|
||||
.list { padding: 4px 16px; }
|
||||
.item { border-bottom: 1px solid var(--line); padding: 10px 0; }
|
||||
.item:last-child { border-bottom: none; }
|
||||
|
||||
@@ -35,7 +35,31 @@
|
||||
}
|
||||
let selfService = $state<boolean | null>(null);
|
||||
let selfBusy = $state(false);
|
||||
onMount(() => { load(); loadUpdates(); api.appSettings().then((s) => (selfService = s.self_service)).catch((err) => (problem = toProblem(err))); });
|
||||
// Change history retention (F-HIS-12)
|
||||
let histDays = $state(0);
|
||||
let histEntries = $state(0);
|
||||
let histSaved = $state({ days: 0, entries: 0 });
|
||||
let histBusy = $state(false);
|
||||
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);
|
||||
async function saveHistory(e: SubmitEvent) {
|
||||
e.preventDefault();
|
||||
histBusy = true; histProblem = null; histOk = '';
|
||||
try {
|
||||
const r = await api.setAppSettings({ history_days: histDays, history_entries: histEntries });
|
||||
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.` : '');
|
||||
} catch (err) { histProblem = toProblem(err); } finally { histBusy = false; }
|
||||
}
|
||||
onMount(() => {
|
||||
load(); loadUpdates();
|
||||
api.appSettings().then((s) => {
|
||||
selfService = s.self_service;
|
||||
histDays = s.history_days; histEntries = s.history_entries; histSaved = { days: s.history_days, entries: s.history_entries };
|
||||
}).catch((err) => (problem = toProblem(err)));
|
||||
});
|
||||
async function setSelfService(on: boolean) {
|
||||
selfBusy = true; problem = null; ok = '';
|
||||
try {
|
||||
@@ -149,6 +173,21 @@
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<form class="card" aria-labelledby="hist-title" onsubmit={saveHistory}>
|
||||
<h2 id="hist-title">Change history</h2>
|
||||
<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>
|
||||
<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>
|
||||
</div>
|
||||
{#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} />
|
||||
</form>
|
||||
|
||||
<div class="card info">
|
||||
<h2>About</h2>
|
||||
<table>
|
||||
@@ -170,4 +209,7 @@
|
||||
.pkgs td { padding: 4px 6px; }
|
||||
.kv { margin-top: 10px; }
|
||||
.kv td { padding: 4px 6px; }
|
||||
.hist { align-items: flex-end; gap: 12px; }
|
||||
.num { width: 140px; }
|
||||
.warnline { color: var(--warn); }
|
||||
</style>
|
||||
Reference in new issue
Block a user