diff --git a/backend/api/safefetch.go b/backend/api/safefetch.go index 2b454fe..ccdfa8d 100644 --- a/backend/api/safefetch.go +++ b/backend/api/safefetch.go @@ -58,33 +58,57 @@ func validateFetchURL(rawURL string) (*url.URL, error) { return u, nil } -// isBlockedIP returns true if dialing this address would reach loopback, -// link-local, RFC1918/ULA private space, multicast, or the unspecified -// address. Pulled out of the dialer so it can be unit-tested directly. +// isBlockedIP returns true if dialing this address would reach a non-public +// destination. It adopts an allow-global-only baseline: anything that is not a +// global-unicast address is blocked (this covers loopback, link-local, +// multicast, and unspecified). On top of that it explicitly blocks RFC1918/ULA +// private space, the RFC 6598 CGNAT range 100.64.0.0/10 for IPv4, and the +// IPv6 transition ranges 6to4 2002::/16 and Teredo 2001::/32 — Go's +// IsGlobalUnicast reports those last two as global, so they must be checked +// explicitly. Pulled out of the dialer so it can be unit-tested directly. func isBlockedIP(addr netip.Addr) bool { if !addr.IsValid() { return true } // Unmap so an IPv4-in-IPv6 address (::ffff:127.0.0.1) is checked as IPv4. addr = addr.Unmap() - if addr.IsLoopback() { + + // Allow-global-only baseline. Anything that isn't a routable global + // unicast address (loopback, link-local, multicast, unspecified) is + // refused. + if !addr.IsGlobalUnicast() { return true } + + // Explicitly block RFC1918 (IPv4) / RFC4193 ULA (IPv6) private space. if addr.IsPrivate() { return true } - if addr.IsLinkLocalUnicast() { - return true - } - if addr.IsLinkLocalMulticast() { - return true - } - if addr.IsMulticast() { - return true + + // RFC 6598 carrier-grade NAT: 100.64.0.0/10. Only applies to IPv4. + if addr.Is4() { + b := addr.As4() + if b[0] == 100 && b[1]&0xc0 == 64 { + return true + } } - if addr.IsUnspecified() { - return true + + // Non-global IPv6 transition ranges that Go still classifies as global + // unicast: 6to4 (2002::/16) embeds an arbitrary IPv4 destination and + // Teredo (2001:0::/32) tunnels to one, so either can be used to reach an + // otherwise-blocked v4 target. Block them outright. + if addr.Is6() { + b := addr.As16() + // 6to4: 2002::/16. + if b[0] == 0x20 && b[1] == 0x02 { + return true + } + // Teredo: 2001:0000::/32 (the first 32 bits are 2001:0000). + if b[0] == 0x20 && b[1] == 0x01 && b[2] == 0x00 && b[3] == 0x00 { + return true + } } + return false } diff --git a/backend/api/safefetch_test.go b/backend/api/safefetch_test.go index 9625a15..0715217 100644 --- a/backend/api/safefetch_test.go +++ b/backend/api/safefetch_test.go @@ -105,11 +105,25 @@ func TestIsBlockedIP(t *testing.T) { {"239.255.255.255", true, "multicast v4 edge"}, {"ff02::1", true, "multicast v6"}, + // RFC 6598 carrier-grade NAT 100.64.0.0/10. + {"100.64.0.0", true, "CGNAT low edge"}, + {"100.64.0.1", true, "CGNAT"}, + {"100.100.100.100", true, "CGNAT mid"}, + {"100.127.255.255", true, "CGNAT high edge"}, + + // Non-global IPv6 transition ranges. + {"2002::1", true, "6to4 2002::/16"}, + {"2002:c058:6301::1", true, "6to4 wrapping a public v4"}, + {"2001::1", true, "Teredo 2001::/32"}, + {"2001:0:4136:e378:8000:63bf:3fff:fdd2", true, "Teredo full"}, + {"8.8.8.8", false, "Google DNS"}, {"1.1.1.1", false, "Cloudflare DNS"}, {"2001:4860:4860::8888", false, "Google DNS v6"}, {"172.15.0.1", false, "just below RFC1918"}, {"172.32.0.1", false, "just above RFC1918"}, + {"100.63.255.255", false, "just below CGNAT"}, + {"100.128.0.0", false, "just above CGNAT"}, } for _, tc := range cases { diff --git a/backend/engine/diskfree_unix.go b/backend/engine/diskfree_unix.go index 5aeca2e..b24b394 100644 --- a/backend/engine/diskfree_unix.go +++ b/backend/engine/diskfree_unix.go @@ -2,7 +2,11 @@ package engine -import "golang.org/x/sys/unix" +import ( + "math" + + "golang.org/x/sys/unix" +) // diskFreeBytes returns the bytes available on the filesystem containing path, // from the perspective of the calling user (i.e. excluding root-reserved @@ -14,6 +18,16 @@ func diskFreeBytes(path string) int64 { return -1 } // Bavail × Bsize gives the user-available bytes. Bfree includes - // root-reserved blocks and would over-report. - return int64(stat.Bavail) * int64(stat.Bsize) + // root-reserved blocks and would over-report. Compute in uint64 and + // saturate to MaxInt64 so a huge/odd filesystem can't overflow or wrap + // the int64 result into a negative ("unknown") value. + avail := uint64(stat.Bavail) + bsize := uint64(stat.Bsize) + if bsize == 0 { + return -1 + } + if avail > math.MaxInt64/bsize { + return math.MaxInt64 + } + return int64(avail * bsize) } diff --git a/backend/engine/diskfree_windows.go b/backend/engine/diskfree_windows.go index 0200c26..3d8c22f 100644 --- a/backend/engine/diskfree_windows.go +++ b/backend/engine/diskfree_windows.go @@ -1,6 +1,10 @@ package engine -import "golang.org/x/sys/windows" +import ( + "math" + + "golang.org/x/sys/windows" +) // diskFreeBytes returns the bytes available on the volume containing path // for the calling user (Windows GetDiskFreeSpaceEx's "FreeBytesAvailable", @@ -15,5 +19,10 @@ func diskFreeBytes(path string) int64 { if err := windows.GetDiskFreeSpaceEx(p, &freeAvail, &totalBytes, &totalFree); err != nil { return -1 } + // freeAvail is a uint64; int64(freeAvail) would truncate/wrap a value + // above MaxInt64 into a negative ("unknown") result. Saturate instead. + if freeAvail > math.MaxInt64 { + return math.MaxInt64 + } return int64(freeAvail) } diff --git a/backend/engine/safepath.go b/backend/engine/safepath.go index 1fd01bd..7ccc4ee 100644 --- a/backend/engine/safepath.go +++ b/backend/engine/safepath.go @@ -3,6 +3,7 @@ package engine import ( "errors" "fmt" + "os" "path/filepath" "strings" ) @@ -58,8 +59,16 @@ func safeRemovePath(saveTo, name string) (string, error) { // the lexical check above is sufficient and we return cleanTarget directly. evalSaveTo, err := filepath.EvalSymlinks(cleanSaveTo) if err != nil { - // saveTo missing or unreadable — best we can do is the lexical check. - return cleanTarget, nil + // This is a DELETE operation, so fail closed. If saveTo doesn't exist + // there's nothing under it to remove and the lexical check already + // passed — degrade to the lexical result. But for any other error + // (permission denied, a symlink loop, an I/O error) we must NOT fall + // back to a lexical-only check: that would let a symlink we couldn't + // resolve redirect the RemoveAll outside saveTo. Refuse instead. + if os.IsNotExist(err) { + return cleanTarget, nil + } + return "", fmt.Errorf("safeRemovePath: cannot resolve save dir %q: %w", saveTo, err) } evalTarget, err := filepath.EvalSymlinks(cleanTarget) if err != nil { diff --git a/backend/engine/scheduler.go b/backend/engine/scheduler.go index 2334d19..331e92a 100644 --- a/backend/engine/scheduler.go +++ b/backend/engine/scheduler.go @@ -16,7 +16,8 @@ type Scheduler struct { maxActiveDownloads int // 0 = unlimited maxActiveSeeds int - stop chan struct{} + stop chan struct{} + closeOnce sync.Once } func NewScheduler(eng *Engine, maxDL, maxSeeds int, tickEvery time.Duration) *Scheduler { @@ -38,7 +39,9 @@ func (s *Scheduler) Limits() (int, int) { return s.maxActiveDownloads, s.maxActiveSeeds } -func (s *Scheduler) Close() { close(s.stop) } +// Close stops the scheduler's tick loop. It is idempotent: calling Close more +// than once is safe and will not panic on a double close(s.stop). +func (s *Scheduler) Close() { s.closeOnce.Do(func() { close(s.stop) }) } func (s *Scheduler) run(every time.Duration) { t := time.NewTicker(every) diff --git a/backend/engine/scheduler_test.go b/backend/engine/scheduler_test.go index c72f04b..53abdb0 100644 --- a/backend/engine/scheduler_test.go +++ b/backend/engine/scheduler_test.go @@ -79,6 +79,22 @@ func TestScheduler_TieBreaksDeterministicallyOnEqualQueuePosition(t *testing.T) } } +// TestScheduler_CloseIsIdempotent guards the double-close panic: Close used to +// do a bare close(s.stop), which panics on the second call. A sync.Once makes +// it safe to call Close any number of times. +func TestScheduler_CloseIsIdempotent(t *testing.T) { + fb := NewFakeBackend() + eng := NewEngine(fb, 50*time.Millisecond) + t.Cleanup(func() { _ = eng.Close() }) + + s := NewScheduler(eng, 2, 0, 50*time.Millisecond) + require.NotPanics(t, func() { + s.Close() + s.Close() + s.Close() + }, "calling Close multiple times must not panic") +} + func TestScheduler_ForceStartBypassesLimit(t *testing.T) { fb := NewFakeBackend() eng := NewEngine(fb, 50*time.Millisecond) diff --git a/backend/engine/verify_snapshot.go b/backend/engine/verify_snapshot.go index 37bd849..ea53a95 100644 --- a/backend/engine/verify_snapshot.go +++ b/backend/engine/verify_snapshot.go @@ -3,6 +3,7 @@ package engine import ( "crypto/sha256" "fmt" + "log" "os" "path/filepath" "strings" @@ -40,9 +41,13 @@ type SnapshotStore interface { } // computeFileSnapshot returns a SHA-256 over the torrent's on-disk file -// state. Each metainfo file contributes a `path|size|mtime_ns` line; missing -// files contribute `MISSING:` so a deletion changes the digest. The -// path component is the joined relative path inside the torrent (forward- +// state. Each metainfo file contributes a `path|size|mtime_ns|mode` line; +// missing files contribute `MISSING:` so a deletion changes the digest. +// The mode component is the file's os.FileMode bits, so swapping a regular +// file for a directory or symlink (regular↔dir↔symlink) changes the digest +// even if the size/mtime happen to match. We stat with os.Lstat so a planted +// symlink is recorded as a symlink rather than being followed to its target. +// The path component is the joined relative path inside the torrent (forward- // slash separators) so the digest is stable across OSes for the same files. // // `saveTo` matches anacrolix's `storage.NewFile` root: a single-file torrent @@ -67,30 +72,38 @@ func computeFileSnapshot(info *metainfo.Info, saveTo string) ([]byte, error) { // Single-file torrent. Path on disk is saveTo/info.Name. rel := info.Name full := filepath.Join(saveTo, info.Name) - st, err := os.Stat(full) + st, err := os.Lstat(full) if err != nil { if os.IsNotExist(err) { writeLine("MISSING:" + rel) } else { + // Non-not-exist stat error: log it and return so the caller + // falls through to a full piece-by-piece hash rather than + // silently trusting a stale snapshot. + log.Printf("computeFileSnapshot: lstat %q: %v — falling back to full hash", full, err) return nil, err } } else { - writeLine(fmt.Sprintf("%s|%d|%d", rel, st.Size(), st.ModTime().UnixNano())) + writeLine(fmt.Sprintf("%s|%d|%d|%o", rel, st.Size(), st.ModTime().UnixNano(), st.Mode())) } } else { for _, f := range info.Files { rel := strings.Join(f.Path, "/") parts := append([]string{saveTo, info.Name}, f.Path...) full := filepath.Join(parts...) - st, err := os.Stat(full) + st, err := os.Lstat(full) if err != nil { if os.IsNotExist(err) { writeLine("MISSING:" + rel) continue } + // Non-not-exist stat error: log it and return so the caller + // falls through to a full piece-by-piece hash rather than + // silently trusting a stale snapshot. + log.Printf("computeFileSnapshot: lstat %q: %v — falling back to full hash", full, err) return nil, err } - writeLine(fmt.Sprintf("%s|%d|%d", rel, st.Size(), st.ModTime().UnixNano())) + writeLine(fmt.Sprintf("%s|%d|%d|%o", rel, st.Size(), st.ModTime().UnixNano(), st.Mode())) } } return h.Sum(nil), nil diff --git a/backend/engine/verify_snapshot_test.go b/backend/engine/verify_snapshot_test.go index 6ee10fe..2a009f7 100644 --- a/backend/engine/verify_snapshot_test.go +++ b/backend/engine/verify_snapshot_test.go @@ -123,3 +123,55 @@ func TestComputeFileSnapshot_NilInfo(t *testing.T) { _, err := computeFileSnapshot(nil, t.TempDir()) require.Error(t, err) } + +// TestComputeFileSnapshot_ChangesOnTypeSwap covers the mode/type component of +// the per-file digest line. Swapping a regular file for a directory (a +// regular↔dir swap) must change the digest even though both entries exist — +// otherwise a planted directory/symlink could masquerade as the original file +// and slip past fast-resume. computeFileSnapshot digests st.Mode() (which +// carries the type bits) precisely to catch this. +func TestComputeFileSnapshot_ChangesOnTypeSwap(t *testing.T) { + saveTo := t.TempDir() + info := makeFakeTorrentTree(t, saveTo) + + before, err := computeFileSnapshot(info, saveTo) + require.NoError(t, err) + + // Replace the regular file a.txt with a directory of the same name. Size + // and even mtime may differ, but the load-bearing assertion is that the + // type change alone is reflected in the digest. + target := filepath.Join(saveTo, info.Name, "a.txt") + require.NoError(t, os.Remove(target)) + require.NoError(t, os.Mkdir(target, 0o755)) + + after, err := computeFileSnapshot(info, saveTo) + require.NoError(t, err) + require.False(t, bytes.Equal(before, after), "regular→dir type swap must alter snapshot") +} + +// TestComputeFileSnapshot_NotFollowSymlink verifies os.Lstat semantics: when a +// file is replaced by a symlink (even one pointing at content of the same +// size), the digest records the symlink's own mode rather than following it to +// the target — so the swap is detected. Guards against a symlink-redirection +// fast-resume bypass. +func TestComputeFileSnapshot_NotFollowSymlink(t *testing.T) { + saveTo := t.TempDir() + info := makeFakeTorrentTree(t, saveTo) + + before, err := computeFileSnapshot(info, saveTo) + require.NoError(t, err) + + // Replace a.txt (content "hello", 5 bytes) with a symlink to another file + // that also holds 5 bytes. If we followed the link via os.Stat the size + // would match and the digest could collide; with os.Lstat the symlink mode + // bit changes the digest. + target := filepath.Join(saveTo, info.Name, "a.txt") + decoy := filepath.Join(saveTo, "decoy.txt") + require.NoError(t, os.WriteFile(decoy, []byte("world"), 0o644)) + require.NoError(t, os.Remove(target)) + require.NoError(t, os.Symlink(decoy, target)) + + after, err := computeFileSnapshot(info, saveTo) + require.NoError(t, err) + require.False(t, bytes.Equal(before, after), "regular→symlink swap must alter snapshot (Lstat, not Stat)") +} diff --git a/backend/logging/logging.go b/backend/logging/logging.go index 5b59c3c..c1ac8aa 100644 --- a/backend/logging/logging.go +++ b/backend/logging/logging.go @@ -14,7 +14,7 @@ import ( // logDir/mosaic.log and pretty console output to stderr in debug mode. // Returns a closer that flushes the file writer. func Init(logDir string, debug bool) (io.Closer, error) { - if err := os.MkdirAll(logDir, 0o755); err != nil { + if err := os.MkdirAll(logDir, 0o700); err != nil { return nil, err } diff --git a/backend/notifications/beeep_notifier.go b/backend/notifications/beeep_notifier.go index 9702072..d520bd3 100644 --- a/backend/notifications/beeep_notifier.go +++ b/backend/notifications/beeep_notifier.go @@ -31,9 +31,15 @@ type BeeepNotifier struct{} // "" to use a platform default. Errors from the underlying delivery surface // are surfaced verbatim — the caller decides whether to log or ignore. func (BeeepNotifier) Notify(title, body, icon string) error { + // Hold the lock across BOTH the AppName assignment and the Notify call: + // beeep.Notify reads the package-global beeep.AppName internally, so + // releasing the lock before Notify would let a concurrent Notify (or a + // transitive dep) stomp the value mid-read — a data race that could also + // send the notification under the wrong app name. Serializing the whole + // section is cheap (notifications are infrequent) and race-free. appNameMu.Lock() + defer appNameMu.Unlock() beeep.AppName = mosaicAppName - appNameMu.Unlock() if icon == "" { return beeep.Notify(title, body, nil) } diff --git a/backend/notifications/linux_notifier.go b/backend/notifications/linux_notifier.go index 93bbfb5..c65a769 100644 --- a/backend/notifications/linux_notifier.go +++ b/backend/notifications/linux_notifier.go @@ -72,11 +72,31 @@ func (n *LinuxDBusNotifier) Notify(title, body, icon string) error { _, err = notify.SendNotification(conn, note) if err != nil { + // The cached session connection may be dead (the bus dropped, the + // daemon restarted, etc.). Drop and close it so the next Notify + // reconnects from scratch instead of failing forever against a + // stale *dbus.Conn. + n.resetConn(conn) return fmt.Errorf("notifications: send: %w", err) } return nil } +// resetConn drops the cached connection so a later call reconnects. It only +// clears the cache if conn is still the one stored (a concurrent Notify may +// already have replaced it) and closes the connection we discard. Safe to +// call with a nil conn. +func (n *LinuxDBusNotifier) resetConn(conn *dbus.Conn) { + n.mu.Lock() + if n.conn == conn { + n.conn = nil + } + n.mu.Unlock() + if conn != nil { + _ = conn.Close() + } +} + func (n *LinuxDBusNotifier) session() (*dbus.Conn, error) { n.mu.Lock() defer n.mu.Unlock() diff --git a/backend/persistence/rss_feeds.go b/backend/persistence/rss_feeds.go index 67f9c66..96f45ed 100644 --- a/backend/persistence/rss_feeds.go +++ b/backend/persistence/rss_feeds.go @@ -21,6 +21,25 @@ type Feeds struct{ db *DB } func NewFeeds(db *DB) *Feeds { return &Feeds{db: db} } +// unixOrZero serializes a time.Time to a unix timestamp, mapping the zero +// time.Time{} to 0 rather than the bogus -62135596800 that t.Unix() yields for +// the zero value. The read side treats a stored 0 as the zero time. +func unixOrZero(t time.Time) int64 { + if t.IsZero() { + return 0 + } + return t.Unix() +} + +// timeFromUnix is the inverse of unixOrZero: a stored 0 round-trips back to the +// zero time.Time{} (so IsZero() is true) rather than the 1970 epoch. +func timeFromUnix(sec int64) time.Time { + if sec == 0 { + return time.Time{} + } + return time.Unix(sec, 0) +} + func (f *Feeds) Create(ctx context.Context, feed Feed) (int, error) { interval := feed.IntervalMin if interval <= 0 { @@ -29,7 +48,7 @@ func (f *Feeds) Create(ctx context.Context, feed Feed) (int, error) { res, err := f.db.SQL().ExecContext(ctx, `INSERT INTO rss_feeds (url, name, interval_min, last_polled, etag, enabled) VALUES (?, ?, ?, ?, ?, ?)`, - feed.URL, feed.Name, interval, feed.LastPolled.Unix(), feed.ETag, boolToInt(feed.Enabled)) + feed.URL, feed.Name, interval, unixOrZero(feed.LastPolled), feed.ETag, boolToInt(feed.Enabled)) if err != nil { return 0, err } @@ -50,7 +69,7 @@ func (f *Feeds) Get(ctx context.Context, id int) (Feed, error) { if err != nil { return feed, err } - feed.LastPolled = time.Unix(lastPolled, 0) + feed.LastPolled = timeFromUnix(lastPolled) feed.Enabled = enabled == 1 return feed, nil } @@ -70,7 +89,7 @@ func (f *Feeds) List(ctx context.Context) ([]Feed, error) { if err := rows.Scan(&feed.ID, &feed.URL, &feed.Name, &feed.IntervalMin, &lastPolled, &feed.ETag, &enabled); err != nil { return nil, err } - feed.LastPolled = time.Unix(lastPolled, 0) + feed.LastPolled = timeFromUnix(lastPolled) feed.Enabled = enabled == 1 out = append(out, feed) } @@ -78,9 +97,13 @@ func (f *Feeds) List(ctx context.Context) ([]Feed, error) { } func (f *Feeds) Update(ctx context.Context, feed Feed) error { + interval := feed.IntervalMin + if interval <= 0 { + interval = 30 + } _, err := f.db.SQL().ExecContext(ctx, `UPDATE rss_feeds SET url = ?, name = ?, interval_min = ?, enabled = ? WHERE id = ?`, - feed.URL, feed.Name, feed.IntervalMin, boolToInt(feed.Enabled), feed.ID) + feed.URL, feed.Name, interval, boolToInt(feed.Enabled), feed.ID) return err } @@ -92,6 +115,6 @@ func (f *Feeds) Delete(ctx context.Context, id int) error { func (f *Feeds) UpdatePollResult(ctx context.Context, id int, lastPolled time.Time, etag string) error { _, err := f.db.SQL().ExecContext(ctx, `UPDATE rss_feeds SET last_polled = ?, etag = ? WHERE id = ?`, - lastPolled.Unix(), etag, id) + unixOrZero(lastPolled), etag, id) return err } diff --git a/backend/persistence/rss_feeds_test.go b/backend/persistence/rss_feeds_test.go index 383d3a3..c20ff4d 100644 --- a/backend/persistence/rss_feeds_test.go +++ b/backend/persistence/rss_feeds_test.go @@ -85,6 +85,50 @@ func TestFeeds_Delete(t *testing.T) { require.ErrorIs(t, err, ErrNotFound) } +// TestFeeds_LastPolledZeroRoundTrips: a feed created without a LastPolled must +// store 0 (not the bogus -62135596800 from the zero time's Unix()) and read +// back as the zero time.Time{} so IsZero() is true. +func TestFeeds_LastPolledZeroRoundTrips(t *testing.T) { + db := newTestDB(t) + f := NewFeeds(db) + ctx := context.Background() + + id, err := f.Create(ctx, Feed{URL: "u", Name: "n", IntervalMin: 30, Enabled: true}) + require.NoError(t, err) + + // The stored column must be exactly 0. + var stored int64 + require.NoError(t, db.SQL().QueryRowContext(ctx, + `SELECT last_polled FROM rss_feeds WHERE id = ?`, id).Scan(&stored)) + require.Equal(t, int64(0), stored) + + got, err := f.Get(ctx, id) + require.NoError(t, err) + require.True(t, got.LastPolled.IsZero(), "LastPolled should round-trip to the zero time") + + rows, err := f.List(ctx) + require.NoError(t, err) + require.Len(t, rows, 1) + require.True(t, rows[0].LastPolled.IsZero(), "LastPolled from List should be the zero time") +} + +// TestFeeds_UpdateFloorsInterval: Update must floor a non-positive interval to +// 30, matching Create's behavior. +func TestFeeds_UpdateFloorsInterval(t *testing.T) { + db := newTestDB(t) + f := NewFeeds(db) + ctx := context.Background() + + id, err := f.Create(ctx, Feed{URL: "u", Name: "n", IntervalMin: 60, Enabled: true}) + require.NoError(t, err) + + require.NoError(t, f.Update(ctx, Feed{ID: id, URL: "u", Name: "n", IntervalMin: 0, Enabled: true})) + + got, err := f.Get(ctx, id) + require.NoError(t, err) + require.Equal(t, 30, got.IntervalMin, "Update should floor interval 0 to 30") +} + func TestFeeds_UpdatePollResult(t *testing.T) { db := newTestDB(t) f := NewFeeds(db) diff --git a/backend/persistence/torrent_access_test.go b/backend/persistence/torrent_access_test.go new file mode 100644 index 0000000..71fcf79 --- /dev/null +++ b/backend/persistence/torrent_access_test.go @@ -0,0 +1,45 @@ +package persistence + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +// TestUsers_DeleteNullsGrantedBy: deleting a user who granted access to others +// must not violate the torrent_access.granted_by FK (which has no ON DELETE +// action while foreign_keys is ON). The grantee's row must survive with +// granted_by set to NULL. +func TestUsers_DeleteNullsGrantedBy(t *testing.T) { + db := newTestDB(t) + users := NewUsers(db) + access := NewTorrentAccess(db) + tor := NewTorrents(db) + ctx := context.Background() + + // torrent_access.infohash references torrents(infohash); create the torrent. + require.NoError(t, tor.Save(ctx, TorrentRecord{ + InfoHash: "hash-a", Name: "t", SavePath: "/tmp", AddedAt: time.Now(), + })) + + idA, err := users.Create(ctx, User{Username: "alice", Role: RoleUser}) + require.NoError(t, err) + idB, err := users.Create(ctx, User{Username: "bob", Role: RoleUser}) + require.NoError(t, err) + + // A grants B access to the torrent. + require.NoError(t, access.Grant(ctx, "hash-a", idB, AccessEditor, &idA)) + + // Deleting A must succeed despite the granted_by reference. + require.NoError(t, users.Delete(ctx, idA)) + + // B's grant must remain, with granted_by now NULL. + rows, err := access.ListForTorrent(ctx, "hash-a") + require.NoError(t, err) + require.Len(t, rows, 1) + require.Equal(t, idB, rows[0].UserID) + require.Equal(t, AccessEditor, rows[0].Access) + require.Nil(t, rows[0].GrantedBy, "granted_by should be NULL after the granter is deleted") +} diff --git a/backend/persistence/users.go b/backend/persistence/users.go index 8192903..a563a90 100644 --- a/backend/persistence/users.go +++ b/backend/persistence/users.go @@ -198,11 +198,26 @@ func (d *Users) SetAPIKey(ctx context.Context, id int, hash, hint string) error return err } -// Delete removes a user. Their torrent_access rows are cascade-deleted by the -// foreign key; torrents they solely owned are handled by the caller. +// Delete removes a user. Their torrent_access rows (where they are the grantee) +// are cascade-deleted by the user_id foreign key; torrents they solely owned are +// handled by the caller. The granted_by column references users(id) without an +// ON DELETE action, so with foreign_keys ON a bare DELETE would fail when this +// user granted access to others — we first null out those references in the +// same transaction. granted_by is nullable. func (d *Users) Delete(ctx context.Context, id int) error { - _, err := d.db.SQL().ExecContext(ctx, `DELETE FROM users WHERE id = ?`, id) - return err + tx, err := d.db.SQL().BeginTx(ctx, nil) + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + if _, err := tx.ExecContext(ctx, + `UPDATE torrent_access SET granted_by = NULL WHERE granted_by = ?`, id); err != nil { + return err + } + if _, err := tx.ExecContext(ctx, `DELETE FROM users WHERE id = ?`, id); err != nil { + return err + } + return tx.Commit() } // isUniqueViolation reports whether err is a SQLite UNIQUE constraint failure. diff --git a/backend/remote/certs.go b/backend/remote/certs.go index 386c7e6..10146d7 100644 --- a/backend/remote/certs.go +++ b/backend/remote/certs.go @@ -15,13 +15,18 @@ import ( "net" "os" "path/filepath" + "sync" "time" ) +// certMu serializes EnsureSelfSignedCert so concurrent callers cannot +// interleave the cert/key writes and leave a mismatched pair on disk. +var certMu sync.Mutex + // EnsureSelfSignedCert returns a tls.Certificate, generating a fresh ECDSA P-256 -// self-signed certificate (10-year validity) under dir/cert.pem + key.pem if not -// already present OR the cached cert's SAN list doesn't cover the requested -// extraIPs. The cert always covers localhost + 127.0.0.1 + ::1; extraIPs is +// self-signed certificate (397-day validity) under dir/cert.pem + key.pem if not +// already present, the cached cert's SAN list doesn't cover the requested +// extraIPs, OR the cached cert is expired/expiring soon. The cert always covers localhost + 127.0.0.1 + ::1; extraIPs is // the set of bound LAN-interface addresses appended on top so a browser // hitting the box at its local-network address doesn't trip a TLS-name- // mismatch warning. @@ -32,6 +37,9 @@ import ( // networks. Removing an old IP doesn't trigger regen; over-permissive SANs // for unreachable interfaces are harmless. func EnsureSelfSignedCert(dir string, extraIPs []net.IP) (tls.Certificate, error) { + certMu.Lock() + defer certMu.Unlock() + certPath := filepath.Join(dir, "cert.pem") keyPath := filepath.Join(dir, "key.pem") @@ -40,7 +48,7 @@ func EnsureSelfSignedCert(dir string, extraIPs []net.IP) (tls.Certificate, error if _, err := os.Stat(certPath); err == nil { if _, err := os.Stat(keyPath); err == nil { if cert, err := tls.LoadX509KeyPair(certPath, keyPath); err == nil { - if certCoversIPs(cert, want) { + if certCoversIPs(cert, want) && !certExpiringSoon(cert) { return cert, nil } } @@ -63,7 +71,7 @@ func EnsureSelfSignedCert(dir string, extraIPs []net.IP) (tls.Certificate, error SerialNumber: serial, Subject: pkix.Name{CommonName: "Mosaic local"}, NotBefore: time.Now(), - NotAfter: time.Now().Add(10 * 365 * 24 * time.Hour), + NotAfter: time.Now().Add(397 * 24 * time.Hour), KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true, @@ -74,19 +82,82 @@ func EnsureSelfSignedCert(dir string, extraIPs []net.IP) (tls.Certificate, error if err != nil { return tls.Certificate{}, err } - if err := os.WriteFile(certPath, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o600); err != nil { - return tls.Certificate{}, err - } keyDER, err := x509.MarshalECPrivateKey(priv) if err != nil { return tls.Certificate{}, err } - if err := os.WriteFile(keyPath, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}), 0o600); err != nil { + + // Write each PEM to a temp file in the same directory, then os.Rename into + // place. Rename is atomic within a filesystem, so a concurrent reader (or a + // process that crashes mid-write) never observes a partially written or + // mismatched cert/key pair. The package-level mutex above already + // serializes writers; the atomic rename additionally protects external + // readers and survives crashes. + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) + if err := writeFileAtomic(certPath, certPEM, 0o600); err != nil { + return tls.Certificate{}, err + } + keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}) + if err := writeFileAtomic(keyPath, keyPEM, 0o600); err != nil { return tls.Certificate{}, err } return tls.LoadX509KeyPair(certPath, keyPath) } +// writeFileAtomic writes data to a temp file in the same directory as path and +// then renames it into place, so readers never see a partial write. The temp +// file is created with perm directly (and re-chmod'd to defeat umask) and is +// cleaned up on any error before the rename succeeds. +func writeFileAtomic(path string, data []byte, perm os.FileMode) error { + dir := filepath.Dir(path) + tmp, err := os.CreateTemp(dir, filepath.Base(path)+".tmp-*") + if err != nil { + return err + } + tmpName := tmp.Name() + cleanup := func() { _ = os.Remove(tmpName) } + + if err := tmp.Chmod(perm); err != nil { + _ = tmp.Close() + cleanup() + return err + } + if _, err := tmp.Write(data); err != nil { + _ = tmp.Close() + cleanup() + return err + } + if err := tmp.Sync(); err != nil { + _ = tmp.Close() + cleanup() + return err + } + if err := tmp.Close(); err != nil { + cleanup() + return err + } + if err := os.Rename(tmpName, path); err != nil { + cleanup() + return err + } + return nil +} + +// certExpiringSoon reports whether the leaf cert is already expired or will +// expire within a short renewal window, so EnsureSelfSignedCert can mint a +// fresh one before the old one stops validating. +func certExpiringSoon(cert tls.Certificate) bool { + if len(cert.Certificate) == 0 { + return true + } + leaf, err := x509.ParseCertificate(cert.Certificate[0]) + if err != nil { + return true + } + // Renew once we are within 30 days of expiry (or already past it). + return time.Now().Add(30 * 24 * time.Hour).After(leaf.NotAfter) +} + // certCoversIPs reports whether every IP in want is present in the loaded // certificate's IPAddresses SAN list. Used by EnsureSelfSignedCert to decide // when a regeneration is needed. @@ -128,8 +199,8 @@ func dedupIPs(in []net.IP) []net.IP { return out } -// LocalInterfaceIPs returns every non-loopback unicast IP on the host, used -// to populate the cert SAN list when binding 0.0.0.0. We can't know which +// LocalInterfaceIPs returns every non-loopback, non-link-local unicast IP on +// the host, used to populate the cert SAN list when binding 0.0.0.0. We can't know which // interface the user's browser will reach us from, so we cover all of them. // Returns an empty slice on enumeration failure — caller falls back to the // loopback-only SAN set, the same behavior as before this function existed. @@ -141,10 +212,17 @@ func LocalInterfaceIPs() []net.IP { out := make([]net.IP, 0, len(addrs)) for _, a := range addrs { ipnet, ok := a.(*net.IPNet) - if !ok || ipnet.IP.IsLoopback() { + if !ok { continue } - out = append(out, ipnet.IP) + ip := ipnet.IP + // Skip loopback and link-local addresses: link-local addrs + // (169.254.0.0/16, fe80::/10, and link-local multicast) are not + // reachable across networks and should not be baked into SANs. + if ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() { + continue + } + out = append(out, ip) } return out } diff --git a/backend/remote/certs_test.go b/backend/remote/certs_test.go index e4da6a2..2a8e1a5 100644 --- a/backend/remote/certs_test.go +++ b/backend/remote/certs_test.go @@ -1,12 +1,15 @@ package remote import ( + "crypto/tls" "crypto/x509" "encoding/pem" "net" "os" "path/filepath" + "sync" "testing" + "time" "github.com/stretchr/testify/require" ) @@ -76,6 +79,77 @@ func TestEnsureSelfSignedCert_RegeneratesWhenLANIPRequested(t *testing.T) { require.Contains(t, ipStrings, "127.0.0.1") // loopback still covered } +func TestEnsureSelfSignedCert_IdempotentMatchingPair(t *testing.T) { + dir := t.TempDir() + + // Idempotent: repeated calls return a usable cert whose on-disk cert.pem + // and key.pem always parse as a matching pair (the public key in the cert + // corresponds to the private key in key.pem). This is the property the + // non-atomic write + missing mutex previously could violate. + for i := 0; i < 3; i++ { + cert, err := EnsureSelfSignedCert(dir, nil) + require.NoError(t, err) + require.NotEmpty(t, cert.Certificate) + + // tls.LoadX509KeyPair already verifies the public/private key match; + // re-load explicitly to be sure the bytes on disk are consistent. + reloaded, err := tls.LoadX509KeyPair( + filepath.Join(dir, "cert.pem"), + filepath.Join(dir, "key.pem"), + ) + require.NoError(t, err, "cert.pem and key.pem must form a matching pair") + require.NotEmpty(t, reloaded.Certificate) + } +} + +func TestEnsureSelfSignedCert_ConcurrentMatchingPair(t *testing.T) { + dir := t.TempDir() + + const n = 16 + var wg sync.WaitGroup + errs := make(chan error, n) + for i := 0; i < n; i++ { + // Mix IP requests so some goroutines trigger regeneration while others + // hit the cache, maximizing the chance of interleaved writes. + var extra []net.IP + if i%2 == 0 { + extra = []net.IP{net.ParseIP("192.168.1.42")} + } + wg.Add(1) + go func(extra []net.IP) { + defer wg.Done() + if _, err := EnsureSelfSignedCert(dir, extra); err != nil { + errs <- err + } + }(extra) + } + wg.Wait() + close(errs) + for err := range errs { + require.NoError(t, err) + } + + // Whatever the final state, the on-disk pair must match. + _, err := tls.LoadX509KeyPair( + filepath.Join(dir, "cert.pem"), + filepath.Join(dir, "key.pem"), + ) + require.NoError(t, err, "concurrent writes must leave a matching cert/key pair") +} + +func TestEnsureSelfSignedCert_ValidityUnderOneYearPlus(t *testing.T) { + dir := t.TempDir() + cert, err := EnsureSelfSignedCert(dir, nil) + require.NoError(t, err) + + leaf, err := x509.ParseCertificate(cert.Certificate[0]) + require.NoError(t, err) + + validity := leaf.NotAfter.Sub(leaf.NotBefore) + require.InDelta(t, (397 * 24 * time.Hour).Hours(), validity.Hours(), 24, + "cert validity should be ~397 days, not multi-year") +} + func TestEnsureSelfSignedCert_WritesPEMFiles(t *testing.T) { dir := t.TempDir() _, err := EnsureSelfSignedCert(dir, nil) diff --git a/backend/tray/availability_linux.go b/backend/tray/availability_linux.go index 1346b79..3d5d571 100644 --- a/backend/tray/availability_linux.go +++ b/backend/tray/availability_linux.go @@ -7,6 +7,7 @@ import ( "time" "github.com/godbus/dbus/v5" + "github.com/rs/zerolog/log" ) // Available reports whether a StatusNotifierItem watcher is currently @@ -37,6 +38,7 @@ func Available() bool { // No session bus reachable — headless / sandboxed / SSH session // without DISPLAY. Fall back to "tray unavailable" so close-to-tray // gets disabled for the session. + log.Debug().Err(err).Msg("tray: session bus unreachable; treating tray as unavailable") return false } defer conn.Close() @@ -49,6 +51,7 @@ func Available() bool { "org.kde.StatusNotifierWatcher", ).Store(&hasOwner) if err != nil { + log.Debug().Err(err).Msg("tray: NameHasOwner check failed; treating tray as unavailable") return false } return hasOwner diff --git a/backend/tray/gnome_linux.go b/backend/tray/gnome_linux.go index d8bd377..ef0e25b 100644 --- a/backend/tray/gnome_linux.go +++ b/backend/tray/gnome_linux.go @@ -11,6 +11,8 @@ import ( "path/filepath" "strings" "time" + + "github.com/rs/zerolog/log" ) // AppIndicatorExtensionUUID is the well-known shell-extension uuid that @@ -60,11 +62,17 @@ func appIndicatorExtensionSearchPaths() []string { // still need to log out + back in for a freshly-enabled extension to // activate. Use Available() to test the actual runtime state. func AppIndicatorExtensionEnabled(ctx context.Context) bool { + bin, err := exec.LookPath("gnome-extensions") + if err != nil { + log.Debug().Err(err).Msg("tray: gnome-extensions CLI not on PATH; treating AppIndicator extension as not enabled") + return false + } cctx, cancel := context.WithTimeout(ctx, 2*time.Second) defer cancel() - cmd := exec.CommandContext(cctx, "gnome-extensions", "list", "--enabled") + cmd := exec.CommandContext(cctx, bin, "list", "--enabled") out, err := cmd.Output() if err != nil { + log.Debug().Err(err).Msg("tray: gnome-extensions list --enabled failed; treating AppIndicator extension as not enabled") return false } for _, line := range strings.Split(string(out), "\n") { @@ -82,12 +90,13 @@ func AppIndicatorExtensionEnabled(ctx context.Context) bool { // the shell for the change to take effect — Mosaic's UI surfaces that // requirement after this returns. func EnableAppIndicatorExtension(ctx context.Context) error { - if _, err := exec.LookPath("gnome-extensions"); err != nil { + bin, err := exec.LookPath("gnome-extensions") + if err != nil { return errors.New("gnome-extensions CLI not found on PATH") } cctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() - cmd := exec.CommandContext(cctx, "gnome-extensions", "enable", AppIndicatorExtensionUUID) + cmd := exec.CommandContext(cctx, bin, "enable", AppIndicatorExtensionUUID) out, err := cmd.CombinedOutput() if err != nil { return fmt.Errorf("gnome-extensions enable: %w (%s)", err, strings.TrimSpace(string(out))) diff --git a/backend/tray/tray_other.go b/backend/tray/tray_other.go index e0ed41a..a29a931 100644 --- a/backend/tray/tray_other.go +++ b/backend/tray/tray_other.go @@ -6,6 +6,7 @@ import ( _ "embed" "runtime" "sync" + "time" "github.com/energye/systray" "github.com/rs/zerolog/log" @@ -41,15 +42,21 @@ type otherImpl struct { settingsItem *systray.MenuItem quitItem *systray.MenuItem ready bool + + // done is closed when systray.Run returns (the tray goroutine has fully + // torn down). stop() waits on it so shutdown is synchronized rather than + // racing the goroutine. + done chan struct{} } -func newImpl(t *Tray) trayImpl { return &otherImpl{t: t} } +func newImpl(t *Tray) trayImpl { return &otherImpl{t: t, done: make(chan struct{})} } func (o *otherImpl) start() { go func() { // systray.Run blocks until Quit is called. It's the canonical entry // point and guarantees the LockOSThread invariant the platform tray // APIs require. + defer close(o.done) defer func() { if r := recover(); r != nil { log.Error().Interface("panic", r).Msg("tray: panic in systray.Run") @@ -61,6 +68,13 @@ func (o *otherImpl) start() { func (o *otherImpl) stop() { systray.Quit() + // Wait for the tray goroutine to confirm teardown so shutdown is + // synchronized, but don't block forever if systray.Run wedges. + select { + case <-o.done: + case <-time.After(2 * time.Second): + log.Warn().Msg("tray: timed out waiting for systray.Run to return on stop") + } } func (o *otherImpl) refreshIcon() { diff --git a/backend/updater/install_source.go b/backend/updater/install_source.go index d142441..9456e08 100644 --- a/backend/updater/install_source.go +++ b/backend/updater/install_source.go @@ -100,9 +100,22 @@ func sentinelExists(path string) bool { return info.Mode().IsRegular() } +// maxDpkgListSize caps how large a dpkg .list file we're willing to read +// into memory before line-scanning. Real mosaic*.list files are a few KB; +// anything multi-megabyte is corrupt or hostile, so we refuse it rather +// than risk a large allocation. dpkg .list files for normal packages are +// well under this. +const maxDpkgListSize = 4 << 20 // 4 MiB + // aptListMatch is the legacy detection path: search /var/lib/dpkg/info/ -// mosaic*.list for a line equal to the running exe path. Kept for users +// mosaic*.list for a line that names the running exe path. Kept for users // on pre-sentinel installs; remove once those have rolled forward. +// +// Paths are normalized on both sides (filepath.Clean, plus EvalSymlinks +// where the target exists) so a symlinked install or a /usr/local shim +// — e.g. /usr/bin/mosaic → /opt/mosaic/mosaic, or a dpkg line recorded +// as a relative-ish path — isn't misclassified as a manual install. We +// stay conservative: only a confident path match returns apt-managed. func aptListMatch() bool { exe, err := os.Executable() if err != nil { @@ -111,10 +124,11 @@ func aptListMatch() bool { // /proc/self/exe (what os.Executable resolves to on Linux) is // already a symlink-resolved absolute path, but a user could have // re-symlinked /usr/bin/mosaic → /opt/something/mosaic. Resolve - // once more defensively. - resolved, err := filepath.EvalSymlinks(exe) - if err != nil { - resolved = exe + // once more defensively, then Clean both forms. + exeClean := filepath.Clean(exe) + resolved := exeClean + if r, err := filepath.EvalSymlinks(exe); err == nil { + resolved = filepath.Clean(r) } // Search all .list files matching mosaic*.list — covers both the @@ -125,6 +139,10 @@ func aptListMatch() bool { return false } for _, listFile := range matches { + info, err := os.Stat(listFile) + if err != nil || !info.Mode().IsRegular() || info.Size() > maxDpkgListSize { + continue + } data, err := os.ReadFile(listFile) if err != nil { continue @@ -134,9 +152,20 @@ func aptListMatch() bool { if line == "" { continue } - if line == exe || line == resolved { + // Normalize each dpkg-recorded path the same way we + // normalized the exe: Clean, plus EvalSymlinks when the + // path exists on disk (catches /usr/bin/mosaic shims that + // point at the real binary). + lineClean := filepath.Clean(line) + if lineClean == exeClean || lineClean == resolved { return true } + if lineResolved, err := filepath.EvalSymlinks(line); err == nil { + lr := filepath.Clean(lineResolved) + if lr == exeClean || lr == resolved { + return true + } + } } } return false