From ae09247d4cb7332d24b519d5dc5145f8454137a5 Mon Sep 17 00:00:00 2001 From: ssenerg Date: Sun, 25 Oct 2026 17:40:07 +0330 Subject: [PATCH] Let users share folders of their homes with other users A user can now let another user into a folder of their home, or the whole home, to view what is in it or to edit it too, from a People popover in the folder. The Shared page lists the folders you share and those shared with you, where owners stop sharing and users leave. Shares are built-in rules for their user that allow only what the owner may do and share there; administrators' rules for the same paths come first. They follow the folder when it moves within the home, and end when it is deleted, leaves the home or is replaced, or when either user is deleted. WebDAV shows the way to them through /home/. Co-Authored-By: Claude Opus 5.5 --- README.md | 40 ++- internal/auth/authtest/store.go | 94 +++++- internal/auth/people.go | 197 ++++++++++++ internal/auth/people_test.go | 298 +++++++++++++++++++ internal/auth/postgres.go | 73 +++++ internal/auth/rules.go | 59 +++- internal/auth/rules_test.go | 3 +- internal/auth/service.go | 2 +- internal/auth/store.go | 18 ++ internal/db/db_test.go | 2 +- internal/db/migrations/009_folder_shares.sql | 16 + internal/server/dav.go | 47 +-- internal/server/listing.go | 37 ++- internal/server/manage.go | 14 +- internal/server/middleware.go | 1 + internal/server/move.go | 3 + internal/server/move_test.go | 7 +- internal/server/people.go | 289 ++++++++++++++++++ internal/server/people_test.go | 297 ++++++++++++++++++ internal/server/resumable.go | 4 +- internal/server/share.go | 51 +++- internal/server/share_test.go | 8 +- internal/server/templates/app.js | 52 +++- internal/server/templates/base.html | 31 +- internal/server/templates/listing.html | 35 ++- internal/server/templates/shares.html | 163 +++++++--- internal/server/upload.go | 2 +- 27 files changed, 1730 insertions(+), 113 deletions(-) create mode 100644 internal/auth/people.go create mode 100644 internal/auth/people_test.go create mode 100644 internal/db/migrations/009_folder_shares.sql create mode 100644 internal/server/people.go create mode 100644 internal/server/people_test.go diff --git a/README.md b/README.md index 638c237..27f02d4 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,37 @@ deleted for good. A hidden `.goftp-owner` file in each home notes whose it is, so a home that a deleted user left behind goes to the trash before a new user of the same name gets in. +### Sharing folders with people + +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 +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 +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=ungrant -d id=1 https://host/.shares/ +``` + +`access` is `read` (the default) or `edit`. Sharing needs the `share` +action on the folder, and `write` for edit, which everyone has in their +home unless a rule takes it away. + ## Running without Docker ```sh @@ -496,8 +527,13 @@ Wrong app passwords count against the client's sign-in budget a minute. The cookie that remembers a password lasts at most `auth.session_ttl`. - Homes are private by built-in rules, which also hold against admins and - superadmins until a rule opens them up. A superadmin can still change - the rules, and whoever runs the server can read its files. + superadmins until a rule opens them up, or their user shares a folder + with someone. A superadmin can still change the rules, and whoever runs + the server can read its files. +- Sharing a folder with people tells whether a username exists, to any + user with a home. A folder deleted by other means than goftp (on the + server's disk, say) keeps its shares, for a folder made in its place, + until its owner stops them. - Upload links let whoever has them fill a folder, with files of up to `upload.max_size` each, until the disk is down to `upload.min_free`: give them a short life, a password, a limit of files or of size. Into a diff --git a/internal/auth/authtest/store.go b/internal/auth/authtest/store.go index 4b611c0..ae02294 100644 --- a/internal/auth/authtest/store.go +++ b/internal/auth/authtest/store.go @@ -20,6 +20,7 @@ type Store struct { shares map[string]*auth.Share // by token hash uploads map[string]*upload // by token hash apps map[string]*auth.AppPassword // by token hash + folders map[int64]*auth.FolderShare // by ID } type upload struct { @@ -37,7 +38,7 @@ var _ auth.Store = (*Store)(nil) func NewStore() *Store { return &Store{users: make(map[int64]*auth.User), sessions: make(map[string]session), shares: make(map[string]*auth.Share), - uploads: make(map[string]*upload), apps: make(map[string]*auth.AppPassword)} + uploads: make(map[string]*upload), apps: make(map[string]*auth.AppPassword), folders: make(map[int64]*auth.FolderShare)} } // NewService returns a service with an empty store and the default policy. @@ -135,6 +136,97 @@ func (s *Store) DeleteUser(_ context.Context, userID int64) error { s.deleteSessions(userID) s.deleteShares(userID) s.deleteApps(userID) + for id, fs := range s.folders { + if fs.OwnerID == userID || fs.UserID == userID { + delete(s.folders, id) + } + } + return nil +} + +func (s *Store) ShareFolder(_ context.Context, fs *auth.FolderShare) error { + s.mu.Lock() + defer s.mu.Unlock() + n := 0 + for _, other := range s.folders { + if other.Path == fs.Path && other.UserID == fs.UserID { + other.Write = fs.Write + fs.ID, fs.CreatedAt = other.ID, other.CreatedAt + return nil + } + if other.OwnerID == fs.OwnerID { + n++ + } + } + if n >= auth.MaxFolderShares { + return auth.ErrTooMany + } + if s.users[fs.OwnerID] == nil || s.users[fs.UserID] == nil { + return auth.ErrNotFound + } + s.nextID++ + fs.ID, fs.CreatedAt = s.nextID, time.Now() + c := *fs + s.folders[fs.ID] = &c + return nil +} + +// folderShares lists the 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) { + c := *fs + c.Owner, c.User = s.users[fs.OwnerID].Username, s.users[fs.UserID].Username + out = append(out, c) + } + } + return out +} + +func (s *Store) FolderShares(_ context.Context, ownerID int64) ([]auth.FolderShare, error) { + s.mu.Lock() + defer s.mu.Unlock() + out := s.folderShares(func(fs *auth.FolderShare) bool { return ownerID == 0 || fs.OwnerID == ownerID }) + slices.SortFunc(out, func(a, b auth.FolderShare) int { return cmp.Compare(b.ID, a.ID) }) + return out, nil +} + +func (s *Store) SharedWith(_ context.Context, userID int64) ([]auth.FolderShare, error) { + s.mu.Lock() + defer s.mu.Unlock() + out := s.folderShares(func(fs *auth.FolderShare) bool { return fs.UserID == userID }) + slices.SortFunc(out, func(a, b auth.FolderShare) int { return strings.Compare(a.Path, b.Path) }) + return out, nil +} + +func (s *Store) DeleteFolderShare(_ context.Context, id, userID int64) (*auth.FolderShare, error) { + s.mu.Lock() + defer s.mu.Unlock() + fs, ok := s.folders[id] + if !ok || userID != 0 && fs.OwnerID != userID && fs.UserID != userID { + return nil, auth.ErrNotFound + } + delete(s.folders, id) + c := *fs + c.Owner, c.User = "", "" + return &c, nil +} + +func (s *Store) MoveFolderShare(_ context.Context, id int64, p string) error { + s.mu.Lock() + defer s.mu.Unlock() + fs, ok := s.folders[id] + if !ok { + return auth.ErrNotFound + } + for other, o := range s.folders { + if other != id && o.Path == p && o.UserID == fs.UserID { + delete(s.folders, other) + } + } + fs.Path = p return nil } diff --git a/internal/auth/people.go b/internal/auth/people.go new file mode 100644 index 0000000..8eb664f --- /dev/null +++ b/internal/auth/people.go @@ -0,0 +1,197 @@ +package auth + +import ( + "context" + "errors" + "fmt" + "path" + "strings" + "time" +) + +// FolderShare lets a user into a folder of another user's home: to read +// 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). +type FolderShare struct { + ID int64 + OwnerID int64 + Owner string // the owner's username + Path string // URL path where the folder really is + UserID int64 // who it is shared with + User string // their username + Write bool + CreatedAt time.Time +} + +// MaxFolderShares bounds the folder shares of one owner. +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) { + 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) + } + user, err := s.store.UserByName(ctx, NormalizeUsername(username)) + if err != nil { + return nil, err + } + if user.ID == owner.ID { + return nil, fmt.Errorf("%w: it is yours already", ErrInvalid) + } + if s.folder() != nil { + // The folder spelled otherwise is the same folder. + shares, err := s.store.FolderShares(ctx, owner.ID) + if err != nil { + return nil, err + } + for _, fs := range shares { + if fs.UserID == user.ID && s.within(fs.Path, path) && s.within(path, fs.Path) { + path = fs.Path + } + } + } + fs := &FolderShare{OwnerID: owner.ID, Owner: owner.Username, Path: path, UserID: user.ID, User: user.Username, Write: write} + 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. +func (s *Service) FolderShares(ctx context.Context, owner *User, all bool) ([]FolderShare, error) { + if all { + return s.store.FolderShares(ctx, 0) + } + return s.store.FolderShares(ctx, owner.ID) +} + +// SharedWith lists the folders shared with u that are still in the homes +// of their owners, by path. +func (s *Service) SharedWith(ctx context.Context, u *User) ([]FolderShare, error) { + if s.Homes() == "" { + return nil, nil + } + shares, err := s.store.SharedWith(ctx, u.ID) + if err != nil { + return nil, err + } + // Homes may have moved since, to where the paths mean something else. + out := shares[:0] + for _, fs := range shares { + if s.within(fs.Path, s.HomeOf(fs.Owner)) { + out = append(out, fs) + } + } + return out, nil +} + +// UnshareFolder ends the folder share id, of which u is the owner or the +// user it is shared with, unless all is set, and returns it (ErrNotFound +// if there is no such share). +func (s *Service) UnshareFolder(ctx context.Context, u *User, id int64, all bool) (*FolderShare, error) { + by := u.ID + if all { + by = 0 + } + return s.store.DeleteFolderShare(ctx, id, by) +} + +// MoveFolderShares has the shares of the folder at the URL path from, and of +// those in it, follow it to to, where it moved; they end with to "", as it +// was deleted, or when it left its home. Shares left at to by a folder +// that is gone end as well: they must not reach what takes its place. +func (s *Service) MoveFolderShares(ctx context.Context, from, to string) error { + if s.Homes() == "" { + return nil + } + var shares []FolderShare + homes := map[int64]string{} + for _, p := range []string{from, to} { + owner, err := s.homeOwner(ctx, p) + if err != nil { + return err + } + if owner == nil || homes[owner.ID] != "" { + continue + } + homes[owner.ID] = s.HomeOf(owner.Username) + more, err := s.store.FolderShares(ctx, owner.ID) + if err != nil { + return err + } + shares = append(shares, more...) + } + for _, fs := range shares { + var err error + switch { + case s.within(fs.Path, from) && to != "" && s.within(to, homes[fs.OwnerID]): + err = s.store.MoveFolderShare(ctx, fs.ID, to+below(fs.Path, from)) + case s.within(fs.Path, from), to != "" && s.within(fs.Path, to): + _, err = s.store.DeleteFolderShare(ctx, fs.ID, 0) + } + if err != nil && !errors.Is(err, ErrNotFound) { + return err + } + } + return nil +} + +// homeOwner returns the user whose home the URL path p is in, or is; nil if +// it is in none. +func (s *Service) homeOwner(ctx context.Context, p string) (*User, error) { + rest, ok := strings.CutPrefix(p, s.Homes()+"/") + name, _, _ := strings.Cut(rest, "/") + if !ok || name == "" { + return nil, nil + } + u, err := s.store.UserByName(ctx, NormalizeUsername(name)) + if errors.Is(err, ErrNotFound) { + return nil, nil + } + return u, err +} + +// within reports whether the URL path p is the folder dir or inside it, +// as rules compare paths. +func (s *Service) within(p, dir string) bool { + if path.Clean(p) != p { + return false + } + if fold := s.folder(); fold != nil { + p, dir = fold(p), fold(dir) + } + return p == dir || strings.HasPrefix(p, dir+"/") +} + +// below returns what follows the folder dir in the URL path p, which is in +// it: "" for dir itself, or e.g. "/a/b". +func below(p, dir string) string { + if rest := strings.Split(p, "/")[strings.Count(dir, "/")+1:]; len(rest) > 0 { + return "/" + strings.Join(rest, "/") + } + return "" +} + +// shareRules are the rules of the folder shared with someone by fs, whose +// owner has the rules owner: built in, so that administrators' rules for +// the same paths come first. +func shareRules(fs FolderShare, owner *Rules) []rule { + base := fs.Path + "/" + rules := []rule{{base: base, wildcard: true, act: ActRead, distance: builtIn, owner: owner}} + if fs.Write { + for _, act := range []string{ActWrite, ActOverwrite, ActDelete} { + rules = append(rules, rule{base: base, wildcard: true, act: act, distance: builtIn, owner: owner}) + } + // The folder itself stays, whatever happens in it. + rules = append(rules, rule{base: base, deny: true, act: ActDelete, distance: builtIn}) + } + return rules +} diff --git a/internal/auth/people_test.go b/internal/auth/people_test.go new file mode 100644 index 0000000..41ef98e --- /dev/null +++ b/internal/auth/people_test.go @@ -0,0 +1,298 @@ +package auth_test + +import ( + "context" + "errors" + "fmt" + "strings" + "testing" + + "goftp/internal/auth" +) + +func TestFolderShares(t *testing.T) { + services(t, func(t *testing.T, svc *auth.Service) { + ctx := context.Background() + svc.SetHomes("/home") + for _, name := range []string{"dora", "erin", "finn"} { + if _, err := svc.CreateUser(ctx, name, "user"); err != nil { + t.Fatal(err) + } + } + dora, erin, finn := userNamed(t, svc, "dora"), userNamed(t, svc, "erin"), userNamed(t, svc, "finn") + + for _, tc := range []struct { + path, user string + want error + }{ + {"/home/erin/docs", "erin", auth.ErrInvalid}, // not dora's + {"/home/doras", "erin", auth.ErrInvalid}, + {"/public", "erin", auth.ErrInvalid}, + {"/home/dora/../erin", "erin", auth.ErrInvalid}, + {"/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) { + t.Errorf("ShareFolder(%q, %q): %v", tc.path, tc.user, err) + } + } + fs, err := svc.ShareFolder(ctx, dora, "/home/dora/docs", "Erin", false) + if err != nil { + t.Fatal(err) + } + if fs.ID == 0 || fs.UserID != erin.ID || fs.User != "erin" || fs.Write || fs.CreatedAt.IsZero() { + t.Errorf("share %+v", fs) + } + + allowed := func(u *auth.User, obj, act string) bool { + t.Helper() + rules, err := svc.RulesFor(ctx, u) + if err != nil { + t.Fatal(err) + } + return rules.Allow(obj, act) + } + type check struct { + who *auth.User + obj, act string + want bool + } + checks := func(cs []check) { + t.Helper() + for _, c := range cs { + if got := allowed(c.who, c.obj, c.act); got != c.want { + t.Errorf("%s may %s %s: %v", c.who.Username, c.act, c.obj, got) + } + } + } + checks([]check{ + {erin, "/home/dora/docs/", auth.ActRead, true}, + {erin, "/home/dora/docs/a.txt", auth.ActRead, true}, + {erin, "/home/dora/docs/a.txt", auth.ActWrite, false}, + {erin, "/home/dora/", auth.ActRead, false}, + {erin, "/home/dora/other/", auth.ActRead, false}, + {erin, "/home/dora/docs/", auth.ActShare, false}, + {finn, "/home/dora/docs/a.txt", auth.ActRead, false}, + }) + + // Sharing it again changes how. + again, err := svc.ShareFolder(ctx, dora, "/home/dora/docs", "erin", true) + if err != nil || again.ID != fs.ID || !again.Write { + t.Fatalf("shared again: %+v, %v", again, err) + } + checks([]check{ + {erin, "/home/dora/docs/a.txt", auth.ActWrite, true}, + {erin, "/home/dora/docs/a.txt", auth.ActOverwrite, true}, + {erin, "/home/dora/docs/sub/", auth.ActDelete, true}, + {erin, "/home/dora/docs/", auth.ActDelete, false}, + {erin, "/home/dora/docs/", auth.ActShare, false}, + {erin, "/home/dora/", auth.ActWrite, false}, + }) + + // Only as far as its owner may go and share, and administrators' + // rules for the same paths come first. + for _, rule := range [][3]string{ + {"user:dora", "!/home/dora/docs/secret/*", "*"}, + {"user:dora", "!/home/dora/docs/mine/*", auth.ActShare}, + {"user:erin", "!/home/dora/docs/*", auth.ActDelete}, + } { + if ok, err := svc.AddPolicy(rule[0], rule[1], rule[2]); !ok || err != nil { + t.Fatalf("AddPolicy(%q) = %v, %v", rule, ok, err) + } + } + checks([]check{ + {erin, "/home/dora/docs/secret/a.txt", auth.ActRead, false}, + {erin, "/home/dora/docs/mine/a.txt", auth.ActRead, false}, + {dora, "/home/dora/docs/mine/a.txt", auth.ActRead, true}, + {erin, "/home/dora/docs/sub/", auth.ActDelete, false}, + {erin, "/home/dora/docs/a.txt", auth.ActRead, true}, + }) + + lists := func(u *auth.User, all bool, want ...string) { + t.Helper() + shares, err := svc.FolderShares(ctx, u, all) + if err != nil { + t.Fatal(err) + } + var got []string + for _, fs := range shares { + got = append(got, fs.Owner+":"+fs.Path+">"+fs.User) + } + if fmt.Sprint(got) != fmt.Sprint(want) { + t.Errorf("FolderShares(%s, %v) = %v, want %v", u.Username, all, got, want) + } + } + sharedWith := func(u *auth.User, want ...string) { + t.Helper() + shares, err := svc.SharedWith(ctx, u) + if err != nil { + t.Fatal(err) + } + var got []string + for _, fs := range shares { + got = append(got, fs.Path) + } + if fmt.Sprint(got) != fmt.Sprint(want) { + 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 { + t.Fatal(err) + } + if _, err := svc.ShareFolder(ctx, erin, "/home/erin", "dora", false); err != nil { + t.Fatal(err) + } + lists(dora, false, "dora:/home/dora/docs/team>finn", "dora:/home/dora/docs>erin") + lists(dora, true, "erin:/home/erin>dora", "dora:/home/dora/docs/team>finn", "dora:/home/dora/docs>erin") + sharedWith(erin, "/home/dora/docs") + sharedWith(dora, "/home/erin") + checks([]check{{dora, "/home/erin/x/a.txt", auth.ActRead, true}}) + + // Shares follow their folders within the home, and end once they + // leave it. + moves := []struct{ from, to string }{ + {"/home/dora/docs", "/home/dora/a/papers"}, + {"/home/dora/a/papers/team", "/home/dora/team"}, + } + for _, m := range moves { + if err := svc.MoveFolderShares(ctx, m.from, m.to); err != nil { + t.Fatal(err) + } + } + sharedWith(erin, "/home/dora/a/papers") + sharedWith(finn, "/home/dora/team") + checks([]check{ + {erin, "/home/dora/a/papers/x.txt", auth.ActRead, true}, + {erin, "/home/dora/docs/x.txt", auth.ActRead, false}, + }) + if err := svc.MoveFolderShares(ctx, "/home/dora/team", "/home/erin/team"); err != nil { + t.Fatal(err) + } + sharedWith(finn) + if err := svc.MoveFolderShares(ctx, "/home/dora/a", ""); err != nil { + t.Fatal(err) + } + sharedWith(erin) + // 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 { + t.Fatal(err) + } + } + if err := svc.MoveFolderShares(ctx, "/home/dora/p", "/home/dora/q"); err != nil { + t.Fatal(err) + } + sharedWith(erin, "/home/dora/q", "/home/dora/qq") + if err := svc.MoveFolderShares(ctx, "/home/dora/z", "/home/dora/qq"); err != nil { + t.Fatal(err) + } + sharedWith(erin, "/home/dora/q") + + // Their owner stops them, or their user leaves; nobody else may. + shares, err := svc.SharedWith(ctx, erin) + if err != nil { + t.Fatal(err) + } + q := shares[0].ID + if _, err := svc.UnshareFolder(ctx, finn, q, false); !errors.Is(err, auth.ErrNotFound) { + t.Errorf("finn ended a share: %v", err) + } + gone, err := svc.UnshareFolder(ctx, erin, q, false) + if err != nil || gone.Path != "/home/dora/q" || gone.OwnerID != dora.ID || gone.UserID != erin.ID { + t.Errorf("erin left: %+v, %v", gone, err) + } + 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) + if err != nil { + t.Fatal(err) + } + if _, err := svc.UnshareFolder(ctx, erin, fs.ID, true); err != nil { + t.Errorf("ended by a superadmin: %v", err) + } + + // Users' shares go with them. + if _, err := svc.ShareFolder(ctx, dora, "/home/dora/x", "erin", false); err != nil { + t.Fatal(err) + } + if err := svc.DeleteUser(ctx, "erin"); err != nil { + t.Fatal(err) + } + lists(dora, true) + + // Homes that moved leave their shares behind. + if _, err := svc.ShareFolder(ctx, dora, "/home/dora/x", "finn", true); err != nil { + t.Fatal(err) + } + svc.SetHomes("/users") + sharedWith(finn) + checks([]check{{finn, "/home/dora/x/a.txt", auth.ActWrite, false}}) + svc.SetHomes("") + sharedWith(finn) + }) +} + +func TestFolderShareLimit(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 := 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 { + t.Fatal(err) + } + } + if _, err := svc.ShareFolder(ctx, dora, "/home/dora/more", "erin", false); !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 { + t.Errorf("shared again: %v", err) + } + }) +} + +// Where names are found whatever their case, the folder spelled otherwise +// is the same folder. +func TestFolderSharesFolded(t *testing.T) { + services(t, func(t *testing.T, svc *auth.Service) { + ctx := context.Background() + svc.SetHomes("/home") + svc.SetFold(strings.ToLower) + 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") + first, err := svc.ShareFolder(ctx, dora, "/home/dora/Docs", "erin", false) + if err != nil { + t.Fatal(err) + } + again, err := svc.ShareFolder(ctx, dora, "/home/dora/DOCS", "erin", true) + if err != nil || again.ID != first.ID || again.Path != "/home/dora/Docs" { + t.Errorf("shared again: %+v, %v", again, err) + } + if err := svc.MoveFolderShares(ctx, "/home/dora/docs", "/home/dora/Papers"); err != nil { + t.Fatal(err) + } + shares, err := svc.SharedWith(ctx, erin) + if err != nil || len(shares) != 1 || shares[0].Path != "/home/dora/Papers" { + t.Errorf("moved: %+v, %v", shares, err) + } + rules, err := svc.RulesFor(ctx, erin) + if err != nil { + t.Fatal(err) + } + if !rules.Allow("/home/dora/PAPERS/a.txt", auth.ActWrite) { + t.Error("the folder spelled otherwise is not shared") + } + }) +} diff --git a/internal/auth/postgres.go b/internal/auth/postgres.go index bbe1d5f..58dc9a6 100644 --- a/internal/auth/postgres.go +++ b/internal/auth/postgres.go @@ -158,6 +158,79 @@ func (s *PgStore) AppPasswordUser(ctx context.Context, username string, tokenHas return &u, nil } +func (s *PgStore) ShareFolder(ctx context.Context, fs *FolderShare) error { + return pgx.BeginFunc(ctx, s.db, func(tx pgx.Tx) error { + // The row lock serializes an owner's shares, so they cannot exceed + // the limit together. + if _, err := tx.Exec(ctx, "SELECT 1 FROM users WHERE id = $1 FOR UPDATE", fs.OwnerID); err != nil { + 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) + 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) + }) +} + +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 ` + +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) + 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)) +} + +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)) +} + +func (s *PgStore) DeleteFolderShare(ctx context.Context, id, userID int64) (*FolderShare, error) { + fs := FolderShare{ID: id} + 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) + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + return &fs, nil +} + +func (s *PgStore) MoveFolderShare(ctx context.Context, id int64, p string) error { + return pgx.BeginFunc(ctx, s.db, func(tx pgx.Tx) error { + _, err := tx.Exec(ctx, `DELETE FROM folder_shares WHERE path = $2 AND id <> $1 + AND user_id = (SELECT user_id FROM folder_shares WHERE id = $1)`, id, p) + if err != nil { + return err + } + tag, err := tx.Exec(ctx, "UPDATE folder_shares SET path = $2 WHERE id = $1", id, p) + if err == nil && tag.RowsAffected() == 0 { + err = ErrNotFound + } + return err + }) +} + func (s *PgStore) SetHomeQuota(ctx context.Context, userID int64, quota *int64) error { tag, err := s.db.Exec(ctx, "UPDATE users SET home_quota = $2 WHERE id = $1", userID, quota) if err == nil && tag.RowsAffected() == 0 { diff --git a/internal/auth/rules.go b/internal/auth/rules.go index 37357c1..533b6f8 100644 --- a/internal/auth/rules.go +++ b/internal/auth/rules.go @@ -1,6 +1,7 @@ package auth import ( + "context" "math" "path" "strings" @@ -19,6 +20,7 @@ const DenyPrefix = "!" // roles' rules, and a role's rules before those of the roles it inherits. // Between rules that are still equal, a denial comes before an allowance. // Signed-in users may also do whatever the rules for everyone allow. +// Folders shared with a user (see FolderShare) add rules of their own. type Rules struct { own, anonymous []rule fold func(string) string // see SetFold; nil compares paths as they are @@ -30,6 +32,10 @@ type rule struct { deny bool act string distance int // 0 for the user's own rules, 1 for their roles', and so on + // owner has the rules of the owner of a folder shared with the visitor, + // for the rules that share it: they allow only what its owner may do + // and share. + owner *Rules } // builtIn is the distance of the rules goftp makes up itself: after every @@ -70,13 +76,39 @@ func (s *Service) HomeOf(username string) string { return "" } -// RulesFor gathers the rules that apply to u, nil for anonymous visitors. -func (s *Service) RulesFor(u *User) (*Rules, error) { +// RulesFor gathers the rules that apply to u, nil for anonymous visitors, +// with those of the folders shared with them. +func (s *Service) RulesFor(ctx context.Context, u *User) (*Rules, error) { + r, err := s.rulesOf(u) + if err != nil || u == nil { + return r, err + } + shared, err := s.SharedWith(ctx, u) + if err != nil { + return nil, err + } + owners := map[int64]*Rules{} + for _, fs := range shared { + owner := owners[fs.OwnerID] + if owner == nil { + if owner, err = s.rulesOf(&User{ID: fs.OwnerID, Username: fs.Owner}); err != nil { + return nil, err + } + owners[fs.OwnerID] = owner + } + r.own = append(r.own, r.folded(shareRules(fs, owner))...) + } + return r, nil +} + +// rulesOf gathers the rules that apply to u, nil for anonymous visitors, +// but for those of the folders shared with them. +func (s *Service) rulesOf(u *User) (*Rules, error) { policies, err := s.enforcer.GetPolicy() if err != nil { return nil, err } - r := &Rules{anonymous: compile(policies, map[string]int{Anonymous: 0})} + r := &Rules{anonymous: compile(policies, map[string]int{Anonymous: 0}), fold: s.folder()} homes := s.Homes() closed := rule{base: homes + "/", wildcard: true, deny: true, act: "*", distance: builtIn} if homes != "" { @@ -95,14 +127,18 @@ func (s *Service) RulesFor(u *User) (*Rules, error) { rule{base: home, deny: true, act: ActDelete, distance: builtIn}) } } - if r.fold = s.folder(); r.fold != nil { - for _, rules := range [][]rule{r.own, r.anonymous} { - for i := range rules { - rules[i].base = r.fold(rules[i].base) - } + r.own, r.anonymous = r.folded(r.own), r.folded(r.anonymous) + return r, nil +} + +// folded has rules compare paths as r does, and returns them. +func (r *Rules) folded(rules []rule) []rule { + if r.fold != nil { + for i := range rules { + rules[i].base = r.fold(rules[i].base) } } - return r, nil + return rules } // distances maps sub and the roles it holds, directly or through other @@ -160,7 +196,10 @@ func decide(rules []rule, obj, act string) bool { winner = r } } - return winner != nil && !winner.deny + if winner == nil || winner.deny { + return false + } + return winner.owner == nil || winner.owner.Allow(obj, act) && winner.owner.Allow(obj, ActShare) } func (r *rule) matches(obj string) bool { diff --git a/internal/auth/rules_test.go b/internal/auth/rules_test.go index 7396401..b4c49b7 100644 --- a/internal/auth/rules_test.go +++ b/internal/auth/rules_test.go @@ -1,6 +1,7 @@ package auth_test import ( + "context" "strings" "testing" @@ -90,7 +91,7 @@ func TestDenyRules(t *testing.T) { } // Rules are checked as the request found them. - rules, err := svc.RulesFor(&auth.User{Username: "alice"}) + rules, err := svc.RulesFor(context.Background(), &auth.User{Username: "alice"}) if err != nil { t.Fatal(err) } diff --git a/internal/auth/service.go b/internal/auth/service.go index fb0c047..6656730 100644 --- a/internal/auth/service.go +++ b/internal/auth/service.go @@ -209,7 +209,7 @@ func (s *Service) ChangePassword(ctx context.Context, u *User, current, next str // Allowed reports whether u (nil for anonymous) may perform act on obj. // For many checks, RulesFor gathers the rules once. func (s *Service) Allowed(u *User, obj, act string) (bool, error) { - r, err := s.RulesFor(u) + r, err := s.RulesFor(context.Background(), u) if err != nil { return false, err } diff --git a/internal/auth/store.go b/internal/auth/store.go index edf9fd3..6351385 100644 --- a/internal/auth/store.go +++ b/internal/auth/store.go @@ -98,6 +98,24 @@ 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(ctx context.Context, fs *FolderShare) error + // FolderShares lists the 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(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 + // (ErrNotFound if there is no such share). + DeleteFolderShare(ctx context.Context, id, userID int64) (*FolderShare, error) + // MoveFolderShare gives the folder share id the path p, where its + // folder moved, and deletes a share of p with the same user, which a + // folder that is gone left (ErrNotFound if there is no share id). + MoveFolderShare(ctx context.Context, id int64, p string) error + // CreateSession starts a session for u, unless u was deleted or changed // password since it was read (ErrNotFound). It may drop the user's // oldest sessions to bound their number. diff --git a/internal/db/db_test.go b/internal/db/db_test.go index bf8d195..ccb00fe 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 != 8 || rules != 9 { + if versions != 9 || rules != 9 { t.Errorf("%d migrations recorded, %d rules seeded", versions, rules) } } diff --git a/internal/db/migrations/009_folder_shares.sql b/internal/db/migrations/009_folder_shares.sql new file mode 100644 index 0000000..84ed0a1 --- /dev/null +++ b/internal/db/migrations/009_folder_shares.sql @@ -0,0 +1,16 @@ +-- Folders that users share from their homes with other users, to read or, +-- with can_write, to change too (see auth.FolderShare). path is the URL +-- path where the folder really is; it follows the folder when it moves +-- within its home, and the share ends when it is deleted or leaves. +CREATE TABLE folder_shares ( + id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + owner_id BIGINT NOT NULL REFERENCES users (id) ON DELETE CASCADE, + path TEXT NOT NULL CHECK (path LIKE '/%'), + user_id BIGINT NOT NULL REFERENCES users (id) ON DELETE CASCADE, + can_write BOOLEAN NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + UNIQUE (path, user_id), + CHECK (user_id <> owner_id) +); +CREATE INDEX folder_shares_user_id_idx ON folder_shares (user_id); +CREATE INDEX folder_shares_owner_id_idx ON folder_shares (owner_id); diff --git a/internal/server/dav.go b/internal/server/dav.go index ce0d831..98b0e93 100644 --- a/internal/server/dav.go +++ b/internal/server/dav.go @@ -279,15 +279,19 @@ func (s *Server) davPropfind(c fiber.Ctx, urlPath string) error { } } _ = f.Close() - case statusOf(err) == fiber.StatusNotFound && s.towardHome(c, urlPath) != "": + case statusOf(err) == fiber.StatusNotFound && len(s.davWays(c, urlPath)) > 0: res = append(res, s.wayHome(urlPath)) default: return err } - // Folders that rules close can still be the way to one's home. - if next := s.towardHome(c, urlPath); depth == "1" && res[0].dir && next != "" && - !slices.ContainsFunc(res[1:], func(r davResource) bool { return r.path == next }) { - res = append(res, s.wayHome(next)) + // Folders that rules close can still be the way to one's home, or to + // folders shared with one. + if depth == "1" && res[0].dir { + for _, next := range s.davWays(c, urlPath) { + if !slices.ContainsFunc(res[1:], func(r davResource) bool { return r.path == next }) { + res = append(res, s.wayHome(next)) + } + } } s.lockDiscoveries(res) @@ -331,20 +335,8 @@ func (s *Server) davPropfind(c fiber.Ctx, urlPath string) error { return c.Status(fiber.StatusMultiStatus).Send(b.Bytes()) } -// towardHome returns, for the folder at urlPath on the way to the home of -// the visitor of c, the next folder on that way; "" for other paths. -func (s *Server) towardHome(c fiber.Ctx, urlPath string) string { - home := s.homeOf(userOf(c)) - rest, ok := strings.CutPrefix(home, strings.TrimSuffix(urlPath, "/")+"/") - if home == "" || !ok || rest == "" { - return "" - } - next, _, _ := strings.Cut(rest, "/") - return path.Join(urlPath, next) -} - -// wayHome describes the folder at urlPath on the way to a home, which says -// nothing of what else it holds. +// wayHome describes the folder at urlPath on the way to a home, or to a +// shared folder, which says nothing of what else it holds. func (s *Server) wayHome(urlPath string) davResource { r := davResource{path: urlPath, dir: true, mod: time.Now()} if info, err := s.root.Stat(rootName(urlPath)); err == nil { @@ -707,12 +699,22 @@ func (s *Server) replacing(c fiber.Ctx, dst string, isDir bool, do func() error) if err != nil { return err } + // The shares of a folder stay with it, wherever it ends up. + asidePath := path.Join(realDir, aside) + if isDir { + s.foldersMoved(realPath, asidePath) + defer s.foldersMoved(asidePath, "") + } if err := do(); err != nil { - if perr := renameNoReplace(dir, aside, name, info); perr != nil { + perr := renameNoReplace(dir, aside, name, info) + switch { + case perr == nil && isDir: + s.foldersMoved(asidePath, realPath) + case perr != nil: // Something took the name meanwhile. if _, terr := s.toTrash(c, dir, aside, realPath, info); terr != nil { s.log.Error("put back what a move or copy that failed was to replace", zap.String("path", dst), - zap.String("kept as", path.Join(realDir, aside)), zap.Error(perr)) + zap.String("kept as", asidePath), zap.Error(perr)) } } return err @@ -726,8 +728,7 @@ func (s *Server) replacing(c fiber.Ctx, dst string, isDir bool, do func() error) err = dir.Remove(aside) } if err != nil { - s.log.Error("remove what a move or copy replaced", zap.String("path", dst), zap.String("kept as", path.Join(realDir, aside)), - zap.Error(err)) + s.log.Error("remove what a move or copy replaced", zap.String("path", dst), zap.String("kept as", asidePath), zap.Error(err)) } syncDir(dir) s.homeChanged(realPath) diff --git a/internal/server/listing.go b/internal/server/listing.go index ab21a2c..be39144 100644 --- a/internal/server/listing.go +++ b/internal/server/listing.go @@ -66,7 +66,7 @@ type page struct { Shares bool // may share links, or administers them Trash bool // may delete, so the trash is of use MyFiles string // the visitor's home, if they have one - Section string // the top bar's tab for the page: "files", "shared" or "" + Section string // the top bar's tab for the page: "files", "home", "shared", "shared-folder", "trash" or "" Here string MinLength int // Shared is set on pages reached through a share link, which show @@ -175,6 +175,15 @@ type listing struct { Usage *usage // what the visitor's home holds, in it // ShareHere is set when the visitor may share this folder. ShareHere bool + // People is set in the visitor's home, where they may share the folder + // with people. + People *peopleHere + // Granted is who the folder was just shared with; Ungranted is set + // when someone was just let go. + Granted *folderShareView + Ungranted bool + // SharedBy is set in a folder shared with the visitor, or in one in it. + SharedBy *auth.FolderShare } // undo restores the one entry a deletion moved to the trash. @@ -322,14 +331,25 @@ func (s *Server) serveDir(c fiber.Ctx, dir *os.File, urlPath, realPath string, w } data := listing{page: s.page(c, "All files"), Path: urlPath, Action: escapePath(object(urlPath, true)), Home: "/", Crumbs: crumbs("", urlPath), Items: items, Summary: summaryOf(items)} - // In their home, the path starts there. + // In their home, the path starts there; in a folder shared with them, + // at that folder. home := s.homeOf(userOf(c)) rel := inHome(home, urlPath) + shareRoot := false if rel != "" { data.Home, data.Crumbs = escapePath(home+"/"), crumbs(home, rel) if data.Usage, err = s.usageOf(userOf(c).Username); err != nil { return err } + if data.People, err = s.peopleAt(c, urlPath, realPath); err != nil { + return err + } + } else if sh := s.shareAt(c, urlPath); sh != nil { + data.SharedBy, data.Section = sh, "shared-folder" + parts := strings.Split(urlPath, "/") + n := strings.Count(sh.Path, "/") + base := strings.Join(parts[:n], "/") + data.Crumbs, shareRoot = crumbs(base, strings.TrimPrefix(urlPath, base)), len(parts) == n+1 } create, replace, err := s.uploadRightsAt(c, object(urlPath, true), object(realPath, true)) if err != nil { @@ -360,6 +380,10 @@ func (s *Server) serveDir(c fiber.Ctx, dir *os.File, urlPath, realPath string, w switch { case rel == "/": data.Title = "My files" + case shareRoot && path.Clean(data.SharedBy.Path) == s.auth.HomeOf(data.SharedBy.Owner): + data.Title = "Home of " + data.SharedBy.Owner + case shareRoot: + data.Title = path.Base(urlPath) case urlPath != "/": data.Title = path.Base(urlPath) data.Parent = escapePath(object(path.Dir(urlPath), true)) @@ -393,6 +417,15 @@ func (s *Server) serveDir(c fiber.Ctx, dir *os.File, urlPath, realPath string, w return err } data.Moved = s.movedBanner(c) + if data.People != nil { + // Only who it is shared with is confirmed. + for i, fs := range data.People.Shares { + if fs.User == c.Query("granted") { + data.Granted = &data.People.Shares[i] + } + } + data.Ungranted = c.Query("ungranted") == "1" + } if create || replace { data.Upload = &uploadForm{Action: data.Action, Replace: replace} } diff --git a/internal/server/manage.go b/internal/server/manage.go index 0384bdd..ed7d3ee 100644 --- a/internal/server/manage.go +++ b/internal/server/manage.go @@ -227,6 +227,9 @@ func (s *Server) remove(c fiber.Ctx, dirPath, name string, permanent bool) (stri syncDir(dir) // What its home holds moved to the trash, or left. s.homeChanged(path.Join(realDir, name)) + if info.IsDir() { + s.foldersMoved(path.Join(realDir, name), "") + } s.log.Info("delete", zap.String("ip", c.IP()), zap.String("user", visitor(c)), zap.String("path", target), zap.Bool("folder", info.IsDir()), zap.Int("contents", contents), zap.Bool("trash", id != "")) return id, nil @@ -370,6 +373,9 @@ func (s *Server) rename(c fiber.Ctx, dirPath, from, to string) error { return s.openError(err) } syncDir(dir) + if info.IsDir() { + s.foldersMoved(path.Join(realDir, from), path.Join(realDir, to)) + } s.log.Info("rename", zap.String("ip", c.IP()), zap.String("user", visitor(c)), zap.String("path", src), zap.String("to", dst)) } return s.done(c, dirPath, fiber.StatusCreated, escapePath(object(dst, info.IsDir())), "renamed="+url.QueryEscape(to)) @@ -496,7 +502,7 @@ func (s *Server) visitorRules(c fiber.Ctx) allowFunc { if r, ok := c.Locals(rulesKey).(cached); ok && r.user == u { return r.allow } - allow := s.rulesOf(u) + allow := s.rulesOf(c, u) // A home someone else left behind must not reach u: u stays out of it // until it can be moved away. if err := s.claimHome(u); err != nil { @@ -515,8 +521,10 @@ func (s *Server) visitorRules(c fiber.Ctx) allowFunc { // rulesOf applies the rules for u, nil for anonymous visitors, as they are // now: gathered once for the many checks to come. -func (s *Server) rulesOf(u *auth.User) allowFunc { - rules, err := s.auth.RulesFor(u) +func (s *Server) rulesOf(c fiber.Ctx, u *auth.User) allowFunc { + ctx, cancel := dbContext(c) + defer cancel() + rules, err := s.auth.RulesFor(ctx, u) return func(obj, act string) (bool, error) { if err != nil { return false, err diff --git a/internal/server/middleware.go b/internal/server/middleware.go index 613f855..0d837e1 100644 --- a/internal/server/middleware.go +++ b/internal/server/middleware.go @@ -21,6 +21,7 @@ const ( sessionKey shareKey rulesKey + sharedKey ) type logState struct { diff --git a/internal/server/move.go b/internal/server/move.go index 6cccedc..b040821 100644 --- a/internal/server/move.go +++ b/internal/server/move.go @@ -168,6 +168,9 @@ func (s *Server) moveEntry(c fiber.Ctx, dirPath, name, dest, newName string, rep } syncDir(dir) syncDir(to) + if info.IsDir() { + s.foldersMoved(realSrc, path.Join(realTo, newName)) + } if toHome != fromHome { s.recount(fromHome) s.recount(toHome) diff --git a/internal/server/move_test.go b/internal/server/move_test.go index f984641..d6bfade 100644 --- a/internal/server/move_test.go +++ b/internal/server/move_test.go @@ -1,6 +1,7 @@ package server import ( + "context" "errors" "net/http" "os" @@ -331,7 +332,11 @@ func TestCopyChecksWhereItReads(t *testing.T) { if err := os.Symlink("b", filepath.Join(f.dir, "a")); err != nil { t.Fatal(err) } - allow := f.srv.rulesOf(nil) + rules, err := f.srv.auth.RulesFor(context.Background(), nil) + if err != nil { + t.Fatal(err) + } + allow := func(obj, act string) (bool, error) { return rules.Allow(obj, act), nil } if _, err := f.srv.readable("/a", "/a", allow); !errors.Is(err, errChanged) { t.Errorf("a folder elsewhere: %v", err) } diff --git a/internal/server/people.go b/internal/server/people.go new file mode 100644 index 0000000..ed2d06f --- /dev/null +++ b/internal/server/people.go @@ -0,0 +1,289 @@ +package server + +import ( + "context" + "errors" + "net/url" + "path" + "slices" + "strconv" + "strings" + + "github.com/gofiber/fiber/v3" + "go.uber.org/zap" + + "goftp/internal/auth" +) + +// Users share folders of their homes with other users (see +// auth.FolderShare): the People popover of the folder adds them, and the +// Shared page lists what is shared, both ways. + +// folderShareView describes a folder shared with someone. +type folderShareView struct { + ID int64 + Name, Path string // the folder; Path "" if it is not the visitor's to see + Href string // "" if it is not the visitor's to see + Owner, User string + Write bool + Since, SinceISO string +} + +// viewFolderShare describes fs to the visitor of c, who may see where it +// is unless private is set. +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)} + switch { + case private: + v.Name, v.Path, v.Href = "Private folder", "", "" + case fs.Path != s.auth.HomeOf(fs.Owner): + case fs.OwnerID == userOf(c).ID: + v.Name = "My files" + default: + v.Name = "Home of " + fs.Owner + } + return v +} + +// folderShares lists the folders the visitor u shares with people, those +// of everyone with all, and those shared with u. +func (s *Server) folderShares(c fiber.Ctx, u *auth.User, all bool) (shares, withYou []folderShareView, err error) { + ctx, cancel := dbContext(c) + defer cancel() + mine, err := s.auth.FolderShares(ctx, u, all) + if err != nil { + return nil, nil, err + } + for _, fs := range mine { + private := false + if fs.OwnerID != u.ID { + // Superadmins may stop any share, but learn nothing of where + // they may not look, such as others' homes. + ok, err := s.allowed(c, object(fs.Path, true), auth.ActRead) + if err != nil { + return nil, nil, err + } + private = !ok + } + shares = append(shares, s.viewFolderShare(c, fs, private)) + } + for _, fs := range s.sharedWith(c) { + withYou = append(withYou, s.viewFolderShare(c, fs, false)) + } + return shares, withYou, nil +} + +// sharedWith lists the folders shared with the visitor of c, looked up +// once per request. +func (s *Server) sharedWith(c fiber.Ctx) []auth.FolderShare { + type cached struct { + user *auth.User + shares []auth.FolderShare + } + u := userOf(c) + if u == nil { + return nil + } + if v, ok := c.Locals(sharedKey).(cached); ok && v.user == u { + return v.shares + } + ctx, cancel := dbContext(c) + defer cancel() + shares, err := s.auth.SharedWith(ctx, u) + if err != nil { + // Only how the way to them is shown depends on it. + s.log.Error("folders shared with a user", zap.String("user", u.Username), zap.Error(err)) + } + c.Locals(sharedKey, cached{u, shares}) + return shares +} + +// shareAt returns the innermost folder shared with the visitor of c that +// the URL path urlPath is, or is in; nil if none. +func (s *Server) shareAt(c fiber.Ctx, urlPath string) *auth.FolderShare { + var found *auth.FolderShare + for _, fs := range s.sharedWith(c) { + if inHome(s.folded(fs.Path), s.folded(urlPath)) != "" && (found == nil || len(fs.Path) > len(found.Path)) { + found = &fs + } + } + return found +} + +// davWays returns the folders in the folder at urlPath on the way to the +// home of the visitor of c, or to folders shared with them, which rules +// may keep closed otherwise. +func (s *Server) davWays(c fiber.Ctx, urlPath string) []string { + places := []string{s.homeOf(userOf(c))} + for _, fs := range s.sharedWith(c) { + places = append(places, fs.Path) + } + var ways []string + for _, p := range places { + rest, ok := strings.CutPrefix(p, strings.TrimSuffix(urlPath, "/")+"/") + if p == "" || !ok || rest == "" { + continue + } + next, _, _ := strings.Cut(rest, "/") + if way := path.Join(urlPath, next); !slices.Contains(ways, way) { + ways = append(ways, way) + } + } + return ways +} + +// foldersMoved has the folder shares of the folder at the real URL path +// from, and of those in it, follow it to to, where it moved; they end with +// to "", as it was deleted, or once it left its home. A folder deleted by +// other means than goftp keeps its shares, until its owner stops them. +func (s *Server) foldersMoved(from, to string) { + ctx, cancel := context.WithTimeout(context.Background(), dbTimeout) + defer cancel() + if err := s.auth.MoveFolderShares(ctx, from, to); err != nil { + s.log.Error("move folder shares", zap.String("path", from), zap.String("to", to), zap.Error(err)) + } +} + +// accessOf names what a folder share lets its user do. +func accessOf(write bool) string { + if write { + return "edit" + } + return "read" +} + +// 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. +func (s *Server) grantFolder(c fiber.Ctx, u *auth.User, form map[string]string) error { + write := false + switch form["access"] { + case "", "read": + case "edit": + write = true + default: + return explain(fiber.ErrBadRequest, "People may read a folder (access=read) or edit it (access=edit).") + } + urlPath, ok := formPath(form["path"]) + if !ok { + return fiber.ErrBadRequest + } + home := s.homeOf(u) + if hidden(urlPath) || home == "" || inHome(s.folded(home), s.folded(urlPath)) == "" { + return explain(fiber.ErrForbidden, "Only folders in your own home can be shared with people.") + } + username := strings.TrimSpace(form["user"]) + switch { + case username == "": + return explain(fiber.ErrBadRequest, "Say whom to share it with: their username.") + case auth.NormalizeUsername(username) == u.Username: + return explain(fiber.ErrBadRequest, "It is yours already: share it with someone else.") + } + f, info, realPath, err := s.lookup(urlPath, s.visitorRules(c)) + if err != nil { + return err + } + _ = f.Close() + if !info.IsDir() { + return explain(fiber.ErrBadRequest, "Only folders can be shared with people: share files with a link.") + } + if ok, err := s.mayAt(c, auth.ActShare, urlPath, realPath, true); err != nil { + return err + } else if !ok { + return explain(fiber.ErrForbidden, "You may not share this folder.") + } + if write { + if ok, err := s.mayAt(c, auth.ActWrite, urlPath, realPath, true); err != nil { + return err + } else if !ok { + return explain(fiber.ErrForbidden, "You may not change this folder, so you cannot let others do it.") + } + } + + ctx, cancel := dbContext(c) + defer cancel() + fs, err := s.auth.ShareFolder(ctx, u, realPath, username, write) + switch { + case errors.Is(err, auth.ErrInvalid): + // It leads out of the home. + return explain(fiber.ErrForbidden, "Only folders in your own home can be shared with people.") + case errors.Is(err, auth.ErrNotFound): + return explain(fiber.ErrNotFound, "There is no user "+username+".") + case errors.Is(err, auth.ErrTooMany): + return explain(fiber.ErrConflict, "You share too many folders. Stop sharing some under Shared first.") + case err != nil: + 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)) + 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)}) + } + return s.redirect(c, escapePath(object(urlPath, true))+"?granted="+url.QueryEscape(fs.User)) +} + +// ungrantFolder ends the folder share form["id"]: its owner stops sharing +// the folder, or its user leaves it; superadmins may end any. Browsers go +// back to the folder with form["back"] set, if it is the visitor's. +func (s *Server) ungrantFolder(c fiber.Ctx, u *auth.User, form map[string]string) error { + id, err := strconv.ParseInt(form["id"], 10, 64) + if err != nil { + return fiber.ErrBadRequest + } + ctx, cancel := dbContext(c) + defer cancel() + html := strings.Contains(c.Get(fiber.HeaderAccept), fiber.MIMETextHTML) + fs, err := s.auth.UnshareFolder(ctx, u, id, s.auth.IsSuperadmin(u.Username)) + switch { + case errors.Is(err, auth.ErrNotFound) && html: + return s.renderShares(c, fiber.StatusNotFound, "", "It is not shared anymore: someone stopped sharing it already.", nil) + case errors.Is(err, auth.ErrNotFound): + return fiber.ErrNotFound + case err != nil: + return err + } + s.log.Info("folder unshared", zap.String("ip", c.IP()), zap.String("user", u.Username), zap.String("path", fs.Path), + zap.Int64("folder_share", id)) + switch { + case !html: + return c.SendStatus(fiber.StatusNoContent) + case form["back"] != "" && fs.OwnerID == u.ID: + return s.redirect(c, escapePath(object(fs.Path, true))+"?ungranted=1") + case fs.UserID == u.ID: + return s.redirect(c, sharesPath+"?done=left") + } + return s.redirect(c, sharesPath+"?done=ungranted") +} + +// peopleHere is what the People popover of a folder in the visitor's home +// shows: who it is shared with. +type peopleHere struct { + Path string // URL path of the folder + Shares []folderShareView +} + +// peopleAt returns who the folder at urlPath, really at realPath, in the +// visitor's home, is shared with, if the visitor may share it. +func (s *Server) peopleAt(c fiber.Ctx, urlPath, realPath string) (*peopleHere, error) { + if ok, err := s.mayAt(c, auth.ActShare, urlPath, realPath, true); err != nil || !ok { + return nil, err + } + u := userOf(c) + ctx, cancel := dbContext(c) + defer cancel() + shares, err := s.auth.FolderShares(ctx, u, false) + if err != nil { + return nil, err + } + p := &peopleHere{Path: urlPath} + for _, fs := range shares { + if s.folded(fs.Path) == s.folded(realPath) { + p.Shares = append(p.Shares, s.viewFolderShare(c, fs, false)) + } + } + slices.SortFunc(p.Shares, func(a, b folderShareView) int { return strings.Compare(a.User, b.User) }) + return p, nil +} diff --git a/internal/server/people_test.go b/internal/server/people_test.go new file mode 100644 index 0000000..6b77ab7 --- /dev/null +++ b/internal/server/people_test.go @@ -0,0 +1,297 @@ +package server + +import ( + "encoding/json" + "maps" + "net/http" + "slices" + "strconv" + "strings" + "testing" + + "goftp/internal/auth" + "goftp/internal/config" +) + +// signedIn returns a copy of f that sends requests with the session token. +func (f *fixture) signedIn(token string) *fixture { + c := *f + c.token = token + return &c +} + +// grant shares the folder at p as owner with user, read or edit, and +// returns the share's ID. +func grant(t *testing.T, owner *fixture, p, user, access string) int64 { + t.Helper() + resp, body := post(t, owner, sharesPath, "action=grant&path="+p+"&user="+user+"&access="+access) + expectStatus(t, resp, http.StatusCreated) + var out struct { + ID int64 + Path, User string + Access string + } + if err := json.Unmarshal([]byte(body), &out); err != nil { + t.Fatal(err) + } + if out.ID == 0 || out.User != user || out.Access != access { + t.Errorf("granted %s", body) + } + return out.ID +} + +func TestFolderSharing(t *testing.T) { + ta := newTestAuth(t) + f := newFixtureWith(t, ta, withHomes, func(cfg *config.Config) { cfg.Homes.Quota = 1000 }) + dora := f.signedIn(ta.addUser(t, "dora", "user")) + erin := f.signedIn(ta.addUser(t, "erin", "user")) + finn := f.signedIn(ta.addUser(t, "finn", "user")) + html := []string{"Accept", "text/html"} + f.write(t, "home/dora/docs/a.txt", "alpha") + f.write(t, "home/dora/other/o.txt", "other") + + _, body := dora.do(t, "GET", "/home/dora/docs/", html...) + if !strings.Contains(body, `
`) || !strings.Contains(body, "Only you can open this folder.") { + t.Errorf("dora's folder: %s", body) + } + if resp, _ := erin.do(t, "GET", "/home/dora/docs/a.txt"); resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusNotFound { + t.Errorf("erin before: %d", resp.StatusCode) + } + + for _, tc := range []struct { + who *fixture + form string + status int + detail string + }{ + {dora, "action=grant&path=/home/dora/docs&user=nobody", 404, "There is no user nobody."}, + {dora, "action=grant&path=/home/dora/docs&user=Dora", 400, "It is yours already"}, + {dora, "action=grant&path=/home/dora/docs&user=", 400, "Say whom"}, + {dora, "action=grant&path=/home/dora/docs&user=erin&access=all", 400, "access=edit"}, + {dora, "action=grant&path=/home/dora/docs/a.txt&user=erin", 400, "Only folders"}, + {dora, "action=grant&path=/home/dora/missing&user=erin", 404, ""}, + {dora, "action=grant&path=/home/erin&user=erin", 403, "your own home"}, + {dora, "action=grant&path=/docs&user=erin", 403, "your own home"}, + {dora, "action=grant&path=/home/dora/.goftp-trash&user=erin", 403, "your own home"}, + {erin, "action=grant&path=/home/dora/docs&user=finn", 403, "your own home"}, + {f.as(""), "action=grant&path=/home/dora/docs&user=erin", 401, ""}, + } { + resp, body := post(t, tc.who, sharesPath, tc.form) + if resp.StatusCode != tc.status || !strings.Contains(body, tc.detail) { + t.Errorf("%s: %d %q", tc.form, resp.StatusCode, body) + } + } + + // To see what is in it. + grant(t, dora, "/home/dora/docs", "erin", "read") + if resp, body := erin.do(t, "GET", "/home/dora/docs/a.txt"); resp.StatusCode != http.StatusOK || body != "alpha" { + t.Errorf("erin reads: %d %q", resp.StatusCode, body) + } + _, body = erin.do(t, "GET", "/home/dora/docs/", html...) + if !strings.Contains(body, "Shared with you by dora") || !strings.Contains(body, "View only") || + !strings.Contains(body, ``) || + strings.Contains(body, `href="/home/"`) || strings.Contains(body, `href="/home/dora/"`) || strings.Contains(body, "Parent folder") || + strings.Contains(body, `
`) || strings.Contains(body, `