From 772e78c9f681fef14b7c8d17350891605049984a Mon Sep 17 00:00:00 2001 From: ssenerg Date: Sun, 25 Oct 2026 18:48:53 +0330 Subject: [PATCH 1/2] Let folder shares end on their own Sharing a folder with someone can now be for a day, a week, a month or three months instead of until it is stopped, from the People popover or with expires= for scripts. Sharing it again changes the end date. The popover and the Shared page say until when; expired shares stop at once and are purged with expired links. Co-Authored-By: Claude Opus 5.5 --- README.md | 18 ++-- internal/auth/authtest/store.go | 20 ++-- internal/auth/people.go | 20 ++-- internal/auth/people_test.go | 100 +++++++++++++++--- internal/auth/postgres.go | 54 +++++++--- internal/auth/service.go | 6 +- internal/auth/store.go | 15 +-- internal/db/db_test.go | 2 +- .../db/migrations/011_folder_share_expiry.sql | 2 + internal/server/people.go | 44 ++++++-- internal/server/people_test.go | 31 ++++++ internal/server/templates/listing.html | 7 +- internal/server/templates/shares.html | 6 +- 13 files changed, 254 insertions(+), 71 deletions(-) create mode 100644 internal/db/migrations/011_folder_share_expiry.sql diff --git a/README.md b/README.md index 7d4ab0f..c9358f2 100644 --- a/README.md +++ b/README.md @@ -193,29 +193,31 @@ new user of the same name gets in. Users can let other users into a folder of their home, or the whole home: **People** in the folder adds someone by username, who can then view what is in it, or edit it too (upload, create folders, rename, overwrite and -delete in it, but not delete or rename the shared folder itself). Sharing -it with them again changes how; nested folders shared both ways give the -more of the two. It is listed under **Shared** on both sides, where its +delete in it, but not delete or rename the shared folder itself), until +the owner stops it or for a day, a week, a month or 3 months. Sharing it +with them again changes how and for how long; nested folders shared both +ways give the more of the two. It is listed under **Shared** on both sides, where its owner can stop sharing it and its user can leave it, and a superadmin can end any share without seeing where it is. Users find what is shared with them under **Shared**, and over WebDAV on the way to it through `/home/`, with nothing else of the owner's home. A share follows its folder when it is renamed or moved within the home, -and ends when the folder is deleted (a restored folder is no longer -shared), moved out of the home or replaced by another, or when either +and ends at its end date, when the folder is deleted (a restored folder is +no longer shared), moved out of the home or replaced by another, or when either user is deleted. It lets its user do only what the owner may do and share there, and rules for the same paths come first, as for homes. What they add counts against the owner's quota; what they delete goes to the trash, where both see it. Scripts: ```sh -curl -H "Authorization: Bearer $TOKEN" -d action=grant -d path=/home/bob/photos -d user=alice -d access=edit https://host/.shares/ -# {"id":1,"path":"/home/bob/photos","user":"alice","access":"edit"} +curl -H "Authorization: Bearer $TOKEN" -d action=grant -d path=/home/bob/photos -d user=alice -d access=edit -d expires=7d https://host/.shares/ +# {"id":1,"path":"/home/bob/photos","user":"alice","access":"edit","expires_at":"..."} curl -H "Authorization: Bearer $TOKEN" -d action=ungrant -d id=1 https://host/.shares/ ``` -`access` is `read` (the default) or `edit`. Sharing needs the `share` +`access` is `read` (the default) or `edit`; `expires` is `1d`, `7d`, `30d` +or `90d`, or left out for no end date (`expires_at` is then `null`). Sharing needs the `share` action on the folder, and `write` for edit, which everyone has in their home unless a rule takes it away. diff --git a/internal/auth/authtest/store.go b/internal/auth/authtest/store.go index 3fba604..5eedf58 100644 --- a/internal/auth/authtest/store.go +++ b/internal/auth/authtest/store.go @@ -265,11 +265,11 @@ func (s *Store) ShareFolder(_ context.Context, fs *auth.FolderShare) error { n := 0 for _, other := range s.folders { if other.Path == fs.Path && other.UserID == fs.UserID { - other.Write = fs.Write + other.Write, other.ExpiresAt = fs.Write, fs.ExpiresAt fs.ID, fs.CreatedAt = other.ID, other.CreatedAt return nil } - if other.OwnerID == fs.OwnerID { + if other.OwnerID == fs.OwnerID && live(other) { n++ } } @@ -286,12 +286,15 @@ func (s *Store) ShareFolder(_ context.Context, fs *auth.FolderShare) error { return nil } -// folderShares lists the folder shares keep picks, with the current names -// of their users. +// live reports whether fs has not expired. +func live(fs *auth.FolderShare) bool { return fs.ExpiresAt.IsZero() || time.Now().Before(fs.ExpiresAt) } + +// folderShares lists the unexpired folder shares keep picks, with the +// current names of their users. func (s *Store) folderShares(keep func(*auth.FolderShare) bool) []auth.FolderShare { var out []auth.FolderShare for _, fs := range s.folders { - if keep(fs) { + if live(fs) && keep(fs) { c := *fs c.Owner, c.User = s.users[fs.OwnerID].Username, s.users[fs.UserID].Username out = append(out, c) @@ -320,7 +323,7 @@ func (s *Store) DeleteFolderShare(_ context.Context, id, userID int64) (*auth.Fo s.mu.Lock() defer s.mu.Unlock() fs, ok := s.folders[id] - if !ok || userID != 0 && fs.OwnerID != userID && fs.UserID != userID { + if !ok || !live(fs) || userID != 0 && fs.OwnerID != userID && fs.UserID != userID { return nil, auth.ErrNotFound } delete(s.folders, id) @@ -613,6 +616,11 @@ func (s *Store) DeleteExpiredShares(context.Context) error { delete(s.shares, k) } } + for id, fs := range s.folders { + if !live(fs) { + delete(s.folders, id) + } + } return nil } diff --git a/internal/auth/people.go b/internal/auth/people.go index 8eb664f..9a02a01 100644 --- a/internal/auth/people.go +++ b/internal/auth/people.go @@ -13,8 +13,9 @@ import ( // what is in it, or with Write to change it too, but for deleting or // renaming the folder itself. It lets them do only what its owner may do // there and share, and the rules of administrators for the same paths come -// first. It ends when the folder is deleted or leaves the home, and follows -// it when it moves within the home (see MoveFolderShares). +// first. It ends at ExpiresAt, if set, or when the folder is deleted or +// leaves the home, and follows it when it moves within the home (see +// MoveFolderShares). type FolderShare struct { ID int64 OwnerID int64 @@ -24,6 +25,7 @@ type FolderShare struct { User string // their username Write bool CreatedAt time.Time + ExpiresAt time.Time // zero for never } // MaxFolderShares bounds the folder shares of one owner. @@ -31,9 +33,10 @@ const MaxFolderShares = 200 // ShareFolder shares the folder at path, which really is owner's home or in // it, with the user username (ErrNotFound if there is none), to read or with -// write to change; sharing it with them again changes how. It does not -// check that the folder exists. -func (s *Service) ShareFolder(ctx context.Context, owner *User, path, username string, write bool) (*FolderShare, error) { +// write to change, for ttl or with 0 until it is stopped; sharing it with +// them again changes how and for how long. It does not check that the +// folder exists. +func (s *Service) ShareFolder(ctx context.Context, owner *User, path, username string, write bool, ttl time.Duration) (*FolderShare, error) { home := s.HomeOf(owner.Username) if home == "" || !s.within(path, home) { return nil, fmt.Errorf("%w: only folders in your home can be shared with people", ErrInvalid) @@ -58,14 +61,17 @@ func (s *Service) ShareFolder(ctx context.Context, owner *User, path, username s } } fs := &FolderShare{OwnerID: owner.ID, Owner: owner.Username, Path: path, UserID: user.ID, User: user.Username, Write: write} + if ttl > 0 { + fs.ExpiresAt = time.Now().Add(ttl) + } if err := s.store.ShareFolder(ctx, fs); err != nil { return nil, err } return fs, nil } -// FolderShares lists the folders owner shares with people, newest first; -// those of everyone with all. +// FolderShares lists the folders owner shares with people that have not +// expired, newest first; those of everyone with all. func (s *Service) FolderShares(ctx context.Context, owner *User, all bool) ([]FolderShare, error) { if all { return s.store.FolderShares(ctx, 0) diff --git a/internal/auth/people_test.go b/internal/auth/people_test.go index 41ef98e..ea184f9 100644 --- a/internal/auth/people_test.go +++ b/internal/auth/people_test.go @@ -6,6 +6,9 @@ import ( "fmt" "strings" "testing" + "time" + + "go.uber.org/zap" "goftp/internal/auth" ) @@ -32,11 +35,11 @@ func TestFolderShares(t *testing.T) { {"/home/dora/docs", "dora", auth.ErrInvalid}, // dora's already {"/home/dora/docs", "nobody", auth.ErrNotFound}, } { - if _, err := svc.ShareFolder(ctx, dora, tc.path, tc.user, false); !errors.Is(err, tc.want) { + if _, err := svc.ShareFolder(ctx, dora, tc.path, tc.user, false, 0); !errors.Is(err, tc.want) { t.Errorf("ShareFolder(%q, %q): %v", tc.path, tc.user, err) } } - fs, err := svc.ShareFolder(ctx, dora, "/home/dora/docs", "Erin", false) + fs, err := svc.ShareFolder(ctx, dora, "/home/dora/docs", "Erin", false, 0) if err != nil { t.Fatal(err) } @@ -76,7 +79,7 @@ func TestFolderShares(t *testing.T) { }) // Sharing it again changes how. - again, err := svc.ShareFolder(ctx, dora, "/home/dora/docs", "erin", true) + again, err := svc.ShareFolder(ctx, dora, "/home/dora/docs", "erin", true, 0) if err != nil || again.ID != fs.ID || !again.Write { t.Fatalf("shared again: %+v, %v", again, err) } @@ -136,10 +139,10 @@ func TestFolderShares(t *testing.T) { t.Errorf("SharedWith(%s) = %v, want %v", u.Username, got, want) } } - if _, err := svc.ShareFolder(ctx, dora, "/home/dora/docs/team", "finn", false); err != nil { + if _, err := svc.ShareFolder(ctx, dora, "/home/dora/docs/team", "finn", false, 0); err != nil { t.Fatal(err) } - if _, err := svc.ShareFolder(ctx, erin, "/home/erin", "dora", false); err != nil { + if _, err := svc.ShareFolder(ctx, erin, "/home/erin", "dora", false, 0); err != nil { t.Fatal(err) } lists(dora, false, "dora:/home/dora/docs/team>finn", "dora:/home/dora/docs>erin") @@ -176,7 +179,7 @@ func TestFolderShares(t *testing.T) { // Unrelated moves leave them be; shares left where a folder moves to // are of a folder that is gone. for _, p := range []string{"/home/dora/p", "/home/dora/q", "/home/dora/qq"} { - if _, err := svc.ShareFolder(ctx, dora, p, "erin", false); err != nil { + if _, err := svc.ShareFolder(ctx, dora, p, "erin", false, 0); err != nil { t.Fatal(err) } } @@ -205,7 +208,7 @@ func TestFolderShares(t *testing.T) { if _, err := svc.UnshareFolder(ctx, dora, q, false); !errors.Is(err, auth.ErrNotFound) { t.Errorf("ended twice: %v", err) } - fs, err = svc.ShareFolder(ctx, dora, "/home/dora", "finn", false) + fs, err = svc.ShareFolder(ctx, dora, "/home/dora", "finn", false, 0) if err != nil { t.Fatal(err) } @@ -214,7 +217,7 @@ func TestFolderShares(t *testing.T) { } // Users' shares go with them. - if _, err := svc.ShareFolder(ctx, dora, "/home/dora/x", "erin", false); err != nil { + if _, err := svc.ShareFolder(ctx, dora, "/home/dora/x", "erin", false, 0); err != nil { t.Fatal(err) } if err := svc.DeleteUser(ctx, "erin"); err != nil { @@ -223,7 +226,7 @@ func TestFolderShares(t *testing.T) { lists(dora, true) // Homes that moved leave their shares behind. - if _, err := svc.ShareFolder(ctx, dora, "/home/dora/x", "finn", true); err != nil { + if _, err := svc.ShareFolder(ctx, dora, "/home/dora/x", "finn", true, 0); err != nil { t.Fatal(err) } svc.SetHomes("/users") @@ -245,15 +248,15 @@ func TestFolderShareLimit(t *testing.T) { } dora := userNamed(t, svc, "dora") for i := range auth.MaxFolderShares { - if _, err := svc.ShareFolder(ctx, dora, fmt.Sprintf("/home/dora/%d", i), "erin", false); err != nil { + if _, err := svc.ShareFolder(ctx, dora, fmt.Sprintf("/home/dora/%d", i), "erin", false, 0); err != nil { t.Fatal(err) } } - if _, err := svc.ShareFolder(ctx, dora, "/home/dora/more", "erin", false); !errors.Is(err, auth.ErrTooMany) { + if _, err := svc.ShareFolder(ctx, dora, "/home/dora/more", "erin", false, 0); !errors.Is(err, auth.ErrTooMany) { t.Errorf("one too many: %v", err) } // Changing how one is shared is not one more. - if _, err := svc.ShareFolder(ctx, dora, "/home/dora/0", "erin", true); err != nil { + if _, err := svc.ShareFolder(ctx, dora, "/home/dora/0", "erin", true, 0); err != nil { t.Errorf("shared again: %v", err) } }) @@ -272,11 +275,11 @@ func TestFolderSharesFolded(t *testing.T) { } } dora, erin := userNamed(t, svc, "dora"), userNamed(t, svc, "erin") - first, err := svc.ShareFolder(ctx, dora, "/home/dora/Docs", "erin", false) + first, err := svc.ShareFolder(ctx, dora, "/home/dora/Docs", "erin", false, 0) if err != nil { t.Fatal(err) } - again, err := svc.ShareFolder(ctx, dora, "/home/dora/DOCS", "erin", true) + again, err := svc.ShareFolder(ctx, dora, "/home/dora/DOCS", "erin", true, 0) if err != nil || again.ID != first.ID || again.Path != "/home/dora/Docs" { t.Errorf("shared again: %+v, %v", again, err) } @@ -296,3 +299,72 @@ func TestFolderSharesFolded(t *testing.T) { } }) } + +func TestFolderShareExpiry(t *testing.T) { + services(t, func(t *testing.T, svc *auth.Service) { + ctx := context.Background() + svc.SetHomes("/home") + for _, name := range []string{"dora", "erin"} { + if _, err := svc.CreateUser(ctx, name, "user"); err != nil { + t.Fatal(err) + } + } + dora, erin := userNamed(t, svc, "dora"), userNamed(t, svc, "erin") + reads := func(p string) bool { + t.Helper() + rules, err := svc.RulesFor(ctx, erin) + if err != nil { + t.Fatal(err) + } + return rules.Allow(p, auth.ActRead) + } + + fs, err := svc.ShareFolder(ctx, dora, "/home/dora/docs", "erin", false, time.Hour) + if err != nil { + t.Fatal(err) + } + if until := time.Until(fs.ExpiresAt); until < 59*time.Minute || until > time.Hour { + t.Errorf("expires in %v", until) + } + shares, err := svc.SharedWith(ctx, erin) + if err != nil || len(shares) != 1 || time.Until(shares[0].ExpiresAt) < 59*time.Minute { + t.Errorf("listed: %+v, %v", shares, err) + } + // Sharing it again changes until when, here to never. + if again, err := svc.ShareFolder(ctx, dora, "/home/dora/docs", "erin", false, 0); err != nil || again.ID != fs.ID || !again.ExpiresAt.IsZero() { + t.Errorf("shared again: %+v, %v", again, err) + } + if shares, err := svc.FolderShares(ctx, dora, false); err != nil || len(shares) != 1 || !shares[0].ExpiresAt.IsZero() { + t.Errorf("no end: %+v, %v", shares, err) + } + + // Once it ends, it is gone, though kept until purged. + old, err := svc.ShareFolder(ctx, dora, "/home/dora/old", "erin", true, 50*time.Millisecond) + if err != nil { + t.Fatal(err) + } + if !reads("/home/dora/old/a.txt") { + t.Error("not shared before it ends") + } + time.Sleep(100 * time.Millisecond) + if reads("/home/dora/old/a.txt") { + t.Error("shared after it ended") + } + if shares, err := svc.FolderShares(ctx, dora, true); err != nil || len(shares) != 1 || shares[0].Path != "/home/dora/docs" { + t.Errorf("listed after it ended: %+v, %v", shares, err) + } + if _, err := svc.UnshareFolder(ctx, dora, old.ID, false); !errors.Is(err, auth.ErrNotFound) { + t.Errorf("stopped after it ended: %v", err) + } + purge, cancel := context.WithTimeout(ctx, 300*time.Millisecond) + svc.PurgeExpired(purge, time.Hour, zap.NewNop()) + cancel() + renewed, err := svc.ShareFolder(ctx, dora, "/home/dora/old", "erin", false, 0) + if err != nil || renewed.ID == old.ID { + t.Errorf("shared anew after the purge: %+v, %v", renewed, err) + } + if !reads("/home/dora/old/a.txt") || !reads("/home/dora/docs/a.txt") { + t.Error("shared anew") + } + }) +} diff --git a/internal/auth/postgres.go b/internal/auth/postgres.go index 742bd06..e01baa7 100644 --- a/internal/auth/postgres.go +++ b/internal/auth/postgres.go @@ -167,47 +167,70 @@ func (s *PgStore) ShareFolder(ctx context.Context, fs *FolderShare) error { return err } var n int - err := tx.QueryRow(ctx, "SELECT count(*) FROM folder_shares WHERE owner_id = $1 AND NOT (path = $2 AND user_id = $3)", - fs.OwnerID, fs.Path, fs.UserID).Scan(&n) + err := tx.QueryRow(ctx, `SELECT count(*) FROM folder_shares WHERE owner_id = $1 AND NOT (path = $2 AND user_id = $3) + AND `+unexpired, fs.OwnerID, fs.Path, fs.UserID).Scan(&n) if err != nil { return err } if n >= MaxFolderShares { return ErrTooMany } - return tx.QueryRow(ctx, `INSERT INTO folder_shares (owner_id, path, user_id, can_write) VALUES ($1, $2, $3, $4) - ON CONFLICT (path, user_id) DO UPDATE SET can_write = EXCLUDED.can_write RETURNING id, created_at`, - fs.OwnerID, fs.Path, fs.UserID, fs.Write).Scan(&fs.ID, &fs.CreatedAt) + return tx.QueryRow(ctx, `INSERT INTO folder_shares (owner_id, path, user_id, can_write, expires_at) VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (path, user_id) DO UPDATE SET can_write = EXCLUDED.can_write, expires_at = EXCLUDED.expires_at + RETURNING id, created_at`, + fs.OwnerID, fs.Path, fs.UserID, fs.Write, nullTime(fs.ExpiresAt)).Scan(&fs.ID, &fs.CreatedAt) }) } -const folderShareQuery = `SELECT f.id, f.owner_id, o.username, f.path, f.user_id, u.username, f.can_write, f.created_at - FROM folder_shares f JOIN users o ON o.id = f.owner_id JOIN users u ON u.id = f.user_id ` +// unexpired picks the folder shares that have not expired. +const unexpired = "(expires_at IS NULL OR expires_at > now())" + +const folderShareQuery = `SELECT f.id, f.owner_id, o.username, f.path, f.user_id, u.username, f.can_write, f.created_at, f.expires_at + FROM folder_shares f JOIN users o ON o.id = f.owner_id JOIN users u ON u.id = f.user_id + WHERE (f.expires_at IS NULL OR f.expires_at > now()) ` + +// nullTime is t for the database, NULL if zero. +func nullTime(t time.Time) *time.Time { + if t.IsZero() { + return nil + } + return &t +} func collectFolderShares(rows pgx.Rows, err error) ([]FolderShare, error) { if err != nil { return nil, err } return pgx.CollectRows(rows, func(row pgx.CollectableRow) (FolderShare, error) { - var fs FolderShare - err := row.Scan(&fs.ID, &fs.OwnerID, &fs.Owner, &fs.Path, &fs.UserID, &fs.User, &fs.Write, &fs.CreatedAt) + var ( + fs FolderShare + expires *time.Time + ) + err := row.Scan(&fs.ID, &fs.OwnerID, &fs.Owner, &fs.Path, &fs.UserID, &fs.User, &fs.Write, &fs.CreatedAt, &expires) + if expires != nil { + fs.ExpiresAt = *expires + } return fs, err }) } func (s *PgStore) FolderShares(ctx context.Context, ownerID int64) ([]FolderShare, error) { - return collectFolderShares(s.db.Query(ctx, folderShareQuery+"WHERE $1 = 0 OR f.owner_id = $1 ORDER BY f.created_at DESC, f.id DESC", ownerID)) + return collectFolderShares(s.db.Query(ctx, folderShareQuery+"AND ($1 = 0 OR f.owner_id = $1) ORDER BY f.created_at DESC, f.id DESC", ownerID)) } func (s *PgStore) SharedWith(ctx context.Context, userID int64) ([]FolderShare, error) { - return collectFolderShares(s.db.Query(ctx, folderShareQuery+"WHERE f.user_id = $1 ORDER BY f.path", userID)) + return collectFolderShares(s.db.Query(ctx, folderShareQuery+"AND f.user_id = $1 ORDER BY f.path", userID)) } func (s *PgStore) DeleteFolderShare(ctx context.Context, id, userID int64) (*FolderShare, error) { fs := FolderShare{ID: id} + var expires *time.Time err := s.db.QueryRow(ctx, `DELETE FROM folder_shares WHERE id = $1 AND ($2 = 0 OR owner_id = $2 OR user_id = $2) - RETURNING owner_id, path, user_id, can_write, created_at`, id, userID). - Scan(&fs.OwnerID, &fs.Path, &fs.UserID, &fs.Write, &fs.CreatedAt) + AND `+unexpired+` RETURNING owner_id, path, user_id, can_write, created_at, expires_at`, id, userID). + Scan(&fs.OwnerID, &fs.Path, &fs.UserID, &fs.Write, &fs.CreatedAt, &expires) + if expires != nil { + fs.ExpiresAt = *expires + } if errors.Is(err, pgx.ErrNoRows) { return nil, ErrNotFound } @@ -479,7 +502,10 @@ func (s *PgStore) DeleteShare(ctx context.Context, id, userID int64) error { } func (s *PgStore) DeleteExpiredShares(ctx context.Context) error { - _, err := s.db.Exec(ctx, "DELETE FROM shares WHERE expires_at <= now()") + if _, err := s.db.Exec(ctx, "DELETE FROM shares WHERE expires_at <= now()"); err != nil { + return err + } + _, err := s.db.Exec(ctx, "DELETE FROM folder_shares WHERE expires_at <= now()") return err } diff --git a/internal/auth/service.go b/internal/auth/service.go index 96fe582..dd1c842 100644 --- a/internal/auth/service.go +++ b/internal/auth/service.go @@ -235,8 +235,8 @@ func (s *Service) Role(username string) string { return strings.Join(roles, ",") } -// PurgeExpired deletes expired sessions and share links periodically until -// ctx ends. +// PurgeExpired deletes expired sessions, share links and folder shares +// periodically until ctx ends. func (s *Service) PurgeExpired(ctx context.Context, every time.Duration, log *zap.Logger) { t := time.NewTicker(every) defer t.Stop() @@ -245,7 +245,7 @@ func (s *Service) PurgeExpired(ctx context.Context, every time.Duration, log *za log.Warn("purge sessions", zap.Error(err)) } if err := s.store.DeleteExpiredShares(ctx); err != nil && ctx.Err() == nil { - log.Warn("purge share links", zap.Error(err)) + log.Warn("purge share links and folder shares", zap.Error(err)) } select { case <-ctx.Done(): diff --git a/internal/auth/store.go b/internal/auth/store.go index 2efc1c5..f292e5c 100644 --- a/internal/auth/store.go +++ b/internal/auth/store.go @@ -109,14 +109,15 @@ type Store interface { // once a minute. AppPasswordUser(ctx context.Context, username string, tokenHash []byte) (*User, error) - // ShareFolder stores fs, or changes how the folder of fs is shared with - // its user if it is already, and sets ID and CreatedAt; ErrTooMany if - // the owner has MaxFolderShares. + // ShareFolder stores fs, or changes how and until when the folder of fs + // is shared with its user if it is already, and sets ID and CreatedAt; + // ErrTooMany if the owner has MaxFolderShares that have not expired. ShareFolder(ctx context.Context, fs *FolderShare) error - // FolderShares lists the folder shares of ownerID, of everyone for 0, - // newest first. + // FolderShares lists the unexpired folder shares of ownerID, of + // everyone for 0, newest first. FolderShares(ctx context.Context, ownerID int64) ([]FolderShare, error) - // SharedWith lists the folders shared with userID. + // SharedWith lists the folders shared with userID that have not + // expired. SharedWith(ctx context.Context, userID int64) ([]FolderShare, error) // DeleteFolderShare deletes the folder share id, if userID (unless 0) // is its owner or its user, and returns it, without the usernames @@ -185,6 +186,8 @@ type Store interface { // DeleteShare deletes the link id if userID created it, or whoever did // if userID is 0. DeleteShare(ctx context.Context, id, userID int64) error + // DeleteExpiredShares deletes the links and folder shares that + // expired. DeleteExpiredShares(ctx context.Context) error // CreateUpload stores up, which expires after keep, and sets its ID, diff --git a/internal/db/db_test.go b/internal/db/db_test.go index e6ca1be..89f9759 100644 --- a/internal/db/db_test.go +++ b/internal/db/db_test.go @@ -56,7 +56,7 @@ func TestConcurrentMigrations(t *testing.T) { if err := pools[0].QueryRow(ctx, "SELECT count(*) FROM casbin_rule").Scan(&rules); err != nil { t.Fatal(err) } - if versions != 10 || rules != 9 { + if versions != 11 || rules != 9 { t.Errorf("%d migrations recorded, %d rules seeded", versions, rules) } } diff --git a/internal/db/migrations/011_folder_share_expiry.sql b/internal/db/migrations/011_folder_share_expiry.sql new file mode 100644 index 0000000..0abacd4 --- /dev/null +++ b/internal/db/migrations/011_folder_share_expiry.sql @@ -0,0 +1,2 @@ +-- Folder shares may end on their own: NULL for never. +ALTER TABLE folder_shares ADD COLUMN expires_at TIMESTAMPTZ; diff --git a/internal/server/people.go b/internal/server/people.go index ed2d06f..140d941 100644 --- a/internal/server/people.go +++ b/internal/server/people.go @@ -8,6 +8,7 @@ import ( "slices" "strconv" "strings" + "time" "github.com/gofiber/fiber/v3" "go.uber.org/zap" @@ -27,6 +28,17 @@ type folderShareView struct { Owner, User string Write bool Since, SinceISO string + Until, UntilISO string // when it ends; "" for never +} + +// folderShareTTLs are how long a folder may be shared, as the People +// popover offers it; "" is until it is stopped. +var folderShareTTLs = []shareTTL{ + {"", "Until I stop it", 0, true}, + {"1d", "1 day", 24 * time.Hour, false}, + {"7d", "1 week", 7 * 24 * time.Hour, false}, + {"30d", "1 month", 30 * 24 * time.Hour, false}, + {"90d", "3 months", 90 * 24 * time.Hour, false}, } // viewFolderShare describes fs to the visitor of c, who may see where it @@ -34,6 +46,9 @@ type folderShareView struct { func (s *Server) viewFolderShare(c fiber.Ctx, fs auth.FolderShare, private bool) folderShareView { v := folderShareView{ID: fs.ID, Name: shareName(fs.Path), Path: fs.Path, Href: escapePath(object(fs.Path, true)), Owner: fs.Owner, User: fs.User, Write: fs.Write, Since: shownTime(fs.CreatedAt), SinceISO: isoTime(fs.CreatedAt)} + if !fs.ExpiresAt.IsZero() { + v.Until, v.UntilISO = shownTime(fs.ExpiresAt), isoTime(fs.ExpiresAt) + } switch { case private: v.Name, v.Path, v.Href = "Private folder", "", "" @@ -155,9 +170,10 @@ func accessOf(write bool) string { // grantFolder shares the folder at form["path"], the visitor's home or a // folder in it, with the user form["user"]: with form["access"] read to let -// them see what is in it, or edit to change it too. Sharing it with them -// again changes how. It needs the rights to share the folder, and to -// change it for edit. +// them see what is in it, or edit to change it too, and with +// form["expires"] (1d, 7d, 30d or 90d) for that long. Sharing it with them +// again changes how and for how long. It needs the rights to share the +// folder, and to change it for edit. func (s *Server) grantFolder(c fiber.Ctx, u *auth.User, form map[string]string) error { write := false switch form["access"] { @@ -167,6 +183,15 @@ func (s *Server) grantFolder(c fiber.Ctx, u *auth.User, form map[string]string) default: return explain(fiber.ErrBadRequest, "People may read a folder (access=read) or edit it (access=edit).") } + ttl, known := time.Duration(0), false + for _, t := range folderShareTTLs { + if t.Value == form["expires"] { + ttl, known = t.TTL, true + } + } + if !known { + return explain(fiber.ErrBadRequest, "Share a folder for 1d, 7d, 30d or 90d, or without expires until you stop it.") + } urlPath, ok := formPath(form["path"]) if !ok { return fiber.ErrBadRequest @@ -205,7 +230,7 @@ func (s *Server) grantFolder(c fiber.Ctx, u *auth.User, form map[string]string) ctx, cancel := dbContext(c) defer cancel() - fs, err := s.auth.ShareFolder(ctx, u, realPath, username, write) + fs, err := s.auth.ShareFolder(ctx, u, realPath, username, write, ttl) switch { case errors.Is(err, auth.ErrInvalid): // It leads out of the home. @@ -218,9 +243,13 @@ func (s *Server) grantFolder(c fiber.Ctx, u *auth.User, form map[string]string) return err } s.log.Info("folder shared", zap.String("ip", c.IP()), zap.String("user", u.Username), zap.String("path", fs.Path), - zap.String("with", fs.User), zap.Bool("write", fs.Write), zap.Int64("folder_share", fs.ID)) + zap.String("with", fs.User), zap.Bool("write", fs.Write), zap.Int64("folder_share", fs.ID), zap.Duration("for", ttl)) if !strings.Contains(c.Get(fiber.HeaderAccept), fiber.MIMETextHTML) { - return c.Status(fiber.StatusCreated).JSON(fiber.Map{"id": fs.ID, "path": fs.Path, "user": fs.User, "access": accessOf(fs.Write)}) + out := fiber.Map{"id": fs.ID, "path": fs.Path, "user": fs.User, "access": accessOf(fs.Write), "expires_at": nil} + if !fs.ExpiresAt.IsZero() { + out["expires_at"] = fs.ExpiresAt.UTC().Format(time.RFC3339) + } + return c.Status(fiber.StatusCreated).JSON(out) } return s.redirect(c, escapePath(object(urlPath, true))+"?granted="+url.QueryEscape(fs.User)) } @@ -263,6 +292,7 @@ func (s *Server) ungrantFolder(c fiber.Ctx, u *auth.User, form map[string]string type peopleHere struct { Path string // URL path of the folder Shares []folderShareView + TTLs []shareTTL // how long it may be shared } // peopleAt returns who the folder at urlPath, really at realPath, in the @@ -278,7 +308,7 @@ func (s *Server) peopleAt(c fiber.Ctx, urlPath, realPath string) (*peopleHere, e if err != nil { return nil, err } - p := &peopleHere{Path: urlPath} + p := &peopleHere{Path: urlPath, TTLs: folderShareTTLs} for _, fs := range shares { if s.folded(fs.Path) == s.folded(realPath) { p.Shares = append(p.Shares, s.viewFolderShare(c, fs, false)) diff --git a/internal/server/people_test.go b/internal/server/people_test.go index 6b77ab7..2f8c374 100644 --- a/internal/server/people_test.go +++ b/internal/server/people_test.go @@ -8,6 +8,7 @@ import ( "strconv" "strings" "testing" + "time" "goftp/internal/auth" "goftp/internal/config" @@ -235,6 +236,36 @@ func TestFolderSharing(t *testing.T) { t.Errorf("twice: %d %s", resp.StatusCode, body) } + // For a while only. + resp, body = post(t, dora, sharesPath, "action=grant&path=/home/dora/other&user=erin&expires=forever") + if resp.StatusCode != http.StatusBadRequest || !strings.Contains(body, "1d, 7d, 30d or 90d") { + t.Errorf("bad expires: %d %s", resp.StatusCode, body) + } + resp, body = post(t, dora, sharesPath, "action=grant&path=/home/dora/other&user=erin&expires=7d") + expectStatus(t, resp, http.StatusCreated) + var until struct { + ExpiresAt time.Time `json:"expires_at"` + } + if err := json.Unmarshal([]byte(body), &until); err != nil || time.Until(until.ExpiresAt) < 7*24*time.Hour-time.Minute { + t.Errorf("expires_at: %s", body) + } + _, body = dora.do(t, "GET", "/home/dora/other/", html...) + if !strings.Contains(body, `Can view · until