Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 38 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
94 changes: 93 additions & 1 deletion internal/auth/authtest/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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.
Expand Down Expand Up @@ -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
}

Expand Down
197 changes: 197 additions & 0 deletions internal/auth/people.go
Original file line number Diff line number Diff line change
@@ -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
}
Loading
Loading